Question: Is there an easy way to programmatically determine the number of lines within a text file?

Answer:
Seriously belated edit: If you're using .NET 4.0 or later
The
```
File
```
class has a new
```
ReadLines
```
method which lazily enumerates lines rather than greedily reading them all into an array like
```
ReadAllLines
```
. So now you can have both efficiency and conciseness with:
```
```
var lineCount = File.ReadLines(@"C:\file.txt").Count();
```
```
Original Answer
If you're not too bothered about efficiency, you can simply write:
```
```
var lineCount = File.ReadAllLines(@"C:\file.txt").Length;
```
```
For a more efficient method you could do:
```
```
var lineCount = 0;
using (var reader = File.OpenText(@"C:\file.txt"))
{
    while (reader.ReadLine() != null)
    {
        lineCount++;
    }
}
```
```
Edit: In response to questions about efficiency
The reason I said the second was more efficient was regarding memory usage, not necessarily speed. The first one loads the entire contents of the file into an array which means it must allocate at least as much memory as the size of the file. The second merely loops one line at a time so it never has to allocate more than one line's worth of memory at a time. This isn't that important for small files, but for larger files it could be an issue (if you try and find the number of lines in a 4GB file on a 32-bit system, for example, where there simply isn't enough user-mode address space to allocate an array this large).
In terms of speed I wouldn't expect there to be a lot in it. It's possible that ReadAllLines has some internal optimisations, but on the other hand it may have to allocate a massive chunk of memory. I'd guess that ReadAllLines might be faster for small files, but significantly slower for large files; though the only way to tell would be to measure it with a Stopwatch or code profiler.


Question: How can I fetch data in a Winforms application or ASP.NET form from a SAP database? The .NET framework used is 2.0. , language is C# and SAP version is 7.10.

Answer:
Why don't you contact CA and ask them to tell them what they're searching for, for that virus?
Or, you could copy the file and change each individual byte until the warning disappeared (may take a while depending on the size).
It's possible the virus detection may be a lot more complicated than simply looking for a fixed string.


Question: Having just witnessed Sound Load technology on the Nintendo DS game Bangai-O Spritis. I was curious as to how this technology works? Does anyone have any links, documentation or sample code on implementing such a feature, that would allow the state of an application to be saved and loaded via audio?

Answer:
Its the same old thing used in ZX Spectrum era. You load programs/games from tape.Only the sound quality and the filters are probably better.
In my opinion something like Bluetooth or WiFi is better. You can also send files that can be put on some storage and then load them. I find these methods much easier than sound because if there is a lot of noise around you cannot do much.
It is just a conversion of data to audio and then back from audio to data.
Search for Zotyocopy and Copy86M on google - these are the utilities used for saving a game to tape after loading it into memory on zx spectrum.


Question:
We've got dozens of versions of an SWF modified for different customers of a big Flash project, and now would have to replace some strings embedded in scripts in each copy. The FLA file for some of these is very difficult to locate or even missing (I inherited this mess and refactoring it is currently not an option).

Is there a (free) tool to replace strings used inside ActionScript? I tried swfmill to convert the files to XML and back but it can't handle international characters contained in the strings so I could get them only partially converted. Most of the strings were correctly extracted so another tool might do the job.

Answer:
tricky - it might not be any easier, but you could load the 'locked' swf into one you control, then spider through its objects until you hit TextBox, using some for...in loops - it'd be a long, arduous process to map them out then change them, especially if the previous developer didn't name things in a helpful way, but if it's a fairly simple .swf then it might be too bad...
Also, there's a mac-only utility for decompiling swfs that I remember a coworker swearing by, but I don't recall the name... anybody?


Question:
Developing websites are time-consuming. To improve productivity, I would code a prototype to show to our clients. I don't worry about making the prototype comform to the standard. Most of the time, our clients would approve the prototype and give an unreasonable deadline. I usually end up using the prototype in production (hey, the prototype works. No need to make my job harder.)

I could refactor the code to output valid HTML. But is it worth the effort to output valid HTML?

Answer:
Yes. It's hard enough trying to deal with how different browsers will render valid HTML, never mind trying to predict what they'll do with invalid code. Same goes for search engines - enough problems in the HTML may lead to the site not being indexed properly or at all.
I guess the real answer is "it depends on what is invalid about the HTML". If the invalid parts relate to accessibility issues, you might even find your customer has legal problems if they use the site on a commercial basis.


Question:
I have a VARCHAR column in a SQL Server 2000 database that can contain either letters or numbers. It depends on how the application is configured on the front-end for the customer.

When it does contain numbers, I want it to be sorted numerically, e.g. as "1", "2", "10" instead of "1", "10", "2". Fields containing just letters, or letters and numbers (such as 'A1') can be sorted alphabetically as normal. For example, this would be an acceptable sort order.

1
2
10
A
B
B1

What is the best way to achieve this?

Answer:
There are a few possible ways to do this.
One would be
```
```
SELECT
 ...
ORDER BY
  CASE
    WHEN ISNUMERIC(value) = 1 THEN CONVERT(INT, value)
    ELSE 9999999 -- or something huge
  END,
  value
```
```
the first part of the ORDER BY converts everything to an int (with a huge value for non-numerics, to sort last) then the last part takes care of alphabetics.
Note that the performance of this query is probably at least moderately ghastly on large amounts of data.


Question: When using feature descriptors [like SIFT, SURF] - is Approximate Nearest Neighbour the fastest method to do matching between images?

Answer:
I'd say that Euclidean distnace based nearest neighbor would be the easiest to implement, but not necessarily the fastest.
I'd agree that approximate nearest neighbor or 'best bin first' would be the quickest at identifying which image in your background set most closely resembles the probe image.
If your trying to identify a single object in the image, things will be a little more difficult.


Question:
I've got an ASP.NET app using NHibernate to transactionally update a few tables upon a user action. There is a date range involved whereby only one entry to a table 'Booking' can be made such that exclusive dates are specified.

My problem is how to prevent a race condition whereby two user actions occur almost simultaneously and cause mutliple entries into 'Booking' for >1 date. I can't check just prior to calling .Commit() because I think that will still leave be with a race condition?

All I can see is to do a check AFTER the commit and roll the change back manually, but that leaves me with a very bad taste in my mouth! :)

booking_ref (INT) PRIMARY_KEY AUTOINCREMENT

booking_start (DATETIME)

booking_end (DATETIME)

Answer:
make the isolation level of your transaction SERIALIZABLE (
```
session.BeginTransaction(IsolationLevel.Serializable
```
) and check and insert in the same transaction. You should not in general set the isolationlevel to serializable, just in situations like this.
or
lock the table before you check and eventually insert. You can do this by firing a SQL query through nhibernate:
session.CreateSQLQuery("SELECT null as dummy FROM Booking WITH (tablockx, holdlock)").AddScalar("dummy", NHibernateUtil.Int32);
This will lock only that table for selects / inserts for the duration of that transaction.
Hope it helped


Question:
Before moving on to use SVN, I used to manage my project by simply keeping a /develop/ directory and editing and testing files there, then moving them to the /main/ directory. When I decided to move to SVN, I needed to be sure that the directories were indeed in sync.

So, what is a good way to write a shell script [ bash ] to recursively compare files with the same name in two different directories?

Note: The directory names used above are for sample only. I do not recommend storing your code in the top level :).

Answer:
The diff command has a -r option to recursively compare directories:
```
```
diff -r /develop /main
```
```


Question:
I've got a Subversion repository, backed by the berkeley DB. Occasionally it breaks down due to some locks and such not being released, but this morning it was impossible to recover it using the 'svnadmin recover' command. Instead it failed with the following error:

svnadmin: Berkeley DB error for filesystem 'db' while opening 'nodes' table:
Invalid argument
svnadmin: bdb: file nodes (meta pgno = 0) has LSN [1083][429767].
svnadmin: bdb: end of log is [1083][354707]
svnadmin: bdb: db/nodes: unexpected file type or format

I'm going to restore the repository from the last known good backup, but it would be good to know if there is a way this repository could be fixed.

edit: even the db_recover utility does not make a difference. It shows recovery is completed, but the same error persists when verifying the repository using svnadmin.

Answer:
I've got a Subversion repository, backed by the berkeley DB.
Sorry to hear that. I would suggest that at your earliest convenience, you dump that repository (
```
svnadmin dump
```
) and reload it into a new one backed by FSFS (
```
svnadmin load
```
).


Question:
I need to cleanup the HTML of pasted text into TinyMCE by passing it to a webservice and then getting it back into the textarea.
So I need to override the Ctrl+V in TinyMCE to caputre the text, do a background request, and on return continue with whatever the paste handler was for TinyMCE.
First off, where is TinyMCE's Ctrl+V handler, and is there a non-destructive way to override it? (instead of changing the source code)

Answer:
You could write a plug-in that handles the ctrl+v event and passes it through or modify the paste plug-in. The following code is found at
plugins/paste/editor_plugin.js
and it handles the ctrl+v event.
```
```
handleEvent : function(e) {
          // Force paste dialog if non IE browser
          if (!tinyMCE.isRealIE && tinyMCE.getParam("paste_auto_cleanup_on_paste", false) && e.ctrlKey && e.keyCode == 86 && e.type == "keydown") {
             window.setTimeout('tinyMCE.selectedInstance.execCommand("mcePasteText",true)', 1);
             return tinyMCE.cancelEvent(e);
          }

          return true;
       },
```
```
Here is some
more information about creating plug-ins for tinyMCE
.


Question: Please suggest some good resources to start writing Java Web services.

Answer:
If you're using the Spring Framework, I suggest
Spring-WS
.
There is a very helpful
reference guide
which should get you started.


Question: Is there such a thing as having the most prefered design pattern for building applications in TDD or the iterative mode?

Answer:
Use a dynamic language like Python or Ruby to develop: You don't have to fight with many of the problems other languages have which are the reason for "design patterns" in the first place.
Dynamic languages in combination with automated testing will give results really quick so you know which direction to take. If you realize then that you should use a static language for performance reasons or whatever you can translate the dynamic software you have already built.


Question:
I am reading image files in Java using

java.awt.Image img = Toolkit.getDefaultToolkit().createImage(filePath);

On some systems this doesn't work, it instead throws an AWTError complaining about sun/awt/motif/MToolkit.

How else can you create a java.awt.Image object from an image file?

Answer:
I read images using
ImageIO
.
```
```
Image i = ImageIO.read(InputStream in);
```
```
The javadoc will offer more info as well.


Question: Using Visual Studio 2008 Team Edition, is it possible to assign a shortcut key that switches between markup and code? If not, is it possible to assign a shortcut key that goes from code to markup?

Answer:
The following is a macro taken from a comment by Lozza on
https://blog.codinghorror.com/visual-studio-net-2003-and-2005-keyboard-shortcuts/
. You just need to bind it to a shortcut of your choice:
```
```
Sub SwitchToMarkup()
  Dim FileName

  If (DTE.ActiveWindow.Caption().EndsWith(".cs")) Then
    ' swith from .aspx.cs to .aspx
    FileName = DTE.ActiveWindow.Document.FullName.Replace(".cs", "")
    If System.IO.File.Exists(FileName) Then
      DTE.ItemOperations.OpenFile(FileName)
    End If
  ElseIf (DTE.ActiveWindow.Caption().EndsWith(".aspx")) Then
    ' swith from .aspx to .aspx.cs
    FileName = DTE.ActiveWindow.Document.FullName.Replace(".aspx", ".aspx.cs")
    If System.IO.File.Exists(FileName) Then
      DTE.ItemOperations.OpenFile(FileName)
    End If
  ElseIf (DTE.ActiveWindow.Caption().EndsWith(".ascx")) Then
    FileName = DTE.ActiveWindow.Document.FullName.Replace(".ascx", ".ascx.cs")
    If System.IO.File.Exists(FileName) Then
      DTE.ItemOperations.OpenFile(FileName)
    End If
  End If
End Sub
```
```


Question:
Can someone give me some working examples of how you can create, add messages, read from, and destroy a private message queue from C++ APIs? I tried the MSDN pieces of code but i can't make them work properly.

Thanks

Answer:
Not quite sure how you'd go about creating or destroying message queues. Windows should create one per thread.
If you're using MFC, any CWinThread and CWnd derived class has a message queue that's trivial to access (using PostMessage or PostThreadMessage and the ON_COMMAND macro). To do something similar with the windows API, I think you need to write your own message pump, something like CWinApp's run method.
```
```
MSG msg;
BOOL bRet;
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}
```
```
...is the example from the MSDN documentation. Is this what you're using? What doesn't work?


Question:
We have been looking at g++ versions 3.2.3 and 4.2.4.  With 4.2.4, the performance improvements on some of our code base is significant.

I've tried searching the gcc buzilla database to find hints as to what bugs may have had such a dramatic improvement but I didn't find any individual bug that stood out as being a candidate.

Are the improvements the result of many small changes that have slowly had an affect?  Or was there say a top 5 set of improvements that may have made a difference?

For some background, our code base does make good use of STL containers and algorithms, as well as C++ features such as the 'inline' keyword.

Answer:
In my experience, 3.4 is where the performance basically peaked; 4.2 is actually slower than 3.4 on my project, with 4.3 being the first to roughly equal 3.4's performance.  4.4 is slightly faster than 3.4.
There are a specific few cases I've found where older versions of gcc did some unbelievably retarded things in code--there was a particular function that went from 128 to 21 clocks from 3.4 to 4.3, but that was obviously a special case (it was a short loop where the addition of just a few unnecessary instructions massively hurt performance).
I personally use 3.4 just because it compiles so much faster, making testing much quicker.  I also try to avoid the latest versions because they seem to have nasty habits of miscompiling code; --march core2 on recent gcc versions causes segfaults in my program, for example, because it emits autovectorized code that tries to perform aligned accesses on unaligned addresses.
Overall though the differences are rarely large; 3-5% is the absolute
most
I've seen in terms of performance change.
Now, note this is C; things may be different in C++.


Question:
Using The loader class of Adobe Flex, I load an external SWF file. However, the loaded SWF file has a different frameRate than my application.

Is it possible to have both the parent app and the loaded child app playing at different framerates? If so, how?

Answer:
It's not possible.
Flash Player or Adobe AIR only uses a single frame rate for all loaded SWF files at any one time, and this frame rate is determined by the nominal frame rate of the main SWF file
There are two ways around this, change the framerate of the main swf to match the loaded one (this can be done during runtime) or decouple the animation from actual frames and use events to step it forward.


Question:
I want to create variables inside function from dictionary.

Lets say I have a dictionary

bar = {'a': 1, 'b': 2, 'c': 3}

and function

def foo():
  pass

What I want to do is to create inside function "foo" variables with names of each dictionary item name and values as dictionary item values

So in the end it should be similar to

def foo():
  a = 1
  b = 2
  c = 3

Is it possible at all? And if it does, how to do such thing?

Answer:
Why would you want to do such a thing?  Unless you actually do anything with the variables inside the function, a function that just assigns several variables and then discards them is indistinguishable to def foo(): pass   (An optimiser would be justified in generating exactly the same bytecode).
If you also want to dynamically append code that uses the values, then you could do this by using exec (though unless this is really user-input code, there are almost certainly better ways to do what you want).  eg:
```
```
some_code = '  return a+b+c'
exec "def foo():\n  " + '\n  '.join('%s = %s' for k,v in bar.items()) + '\n' + some_code
```
```
(Note that your code must be indented to the same level.)
On the other hand, if you want to actually assign these values to the function
object
(so you can do foo.a and get 1 - note that your sample code doesn't do this), you can do this by:
```
```
for key, val in bar.items():
    setattr(foo, key, val)
```
```


Question:
I am currently working on a project that has been in production for over two years. The project makes extensive use of unit testing and scripted UI tests. Initialy unit tests covered the system framework, business rules and state transitions (or workflow). Test scripts are used for black box testing. However, over time the cost of maintaining our full set of unit tests has become increasingly expensive especially those relating to state.

After a bit of investigation we have found that test scripts are more effective (that is, provide better coverage) and are cheaper to maintain than unit tests relating to workflow. This isn't to say the value of unit tests has been completely negated but it does raise this question whether some classes of unit tests can be dropped in favour of test scripts.

Our project is run on an iterative incremental model.

Answer:
One of the answers on SO to the question of 'the limitations of Unit Testing' was that a unit testing becomes convoluted when it's used to test anything to do with INTEGRATION rather than function. Connecting to and using external services (database, SSH'ing to a another server, etc.) and User Interfaces were two of the examples used.
It's not that you CANT use Unit Testing for these things, its just that the difficulty involved in covering all the bases makes using this method of testing not worth it except in cases where reliability is paramount.
I use "script tests" for all my custom JavaScript UI code (template engine, effects and animations, etc.) and I find it quick and reliable if done right.


Question: Would anyone recommend a particular JavaScript charting library - specifically one that doesn't use flash at all?

Answer:
If you're using jQuery I've found
flot
to be very good - try out the
examples
to see if they suit your needs, but I've found them to do most of what I need for my current project.
Additionally
ExtJS 4.0
has introduced a great set of charts - very powerful, and is designed to work with live data.


Question:
Is there a javascript function I can use to detect whether a specific silverlight version is installed in the current browser?

I'm particularly interested in the Silverlight 2 Beta 2 version. I don't want to use the default method of having an image behind the silverlight control which is just shown if the Silverlight plugin doesn't load.

Edit: From link provided in accepted answer:

Include Silverlight.js (from Silverlight SDK)

Silverlight.isInstalled("2.0");

Answer:
Include Silverlight.js (from Silverlight SDK)
```
Silverlight.isInstalled("4.0")
```
Resource:
http://msdn.microsoft.com/en-us/library/cc265155(vs.95).aspx


Question: I am looking for a free tool to load Excel data sheet into an Oracle database. I tried the Oracle SQL developer, but it keeps throwing a NullPointerException. Any ideas?

Answer:
Excel -> CSV -> Oracle
Save the Excel spreadsheet as file type 'CSV' (Comma-Separated Values).
Transfer the .csv file to the Oracle server.
Create the Oracle table, using the SQL
```
CREATE TABLE
```
statement to define the table's column lengths and types.
Use sqlload to load the .csv file into the Oracle table. Create a sqlload control file like this:
```
```
load data
infile theFile.csv
replace
into table theTable
fields terminated by ','
(x,y,z)
```
```
Invoke sqlload to read the .csv file into the new table, creating one row in the table for each line in the .csv file. This is done as a Unix command:
```
```
% sqlload userid=username/password control=<filename.ctl> log=<filename>.log
```
```
OR
If you just want a tool, use
QuickLoad


Question:
I have been given a requirement where I need to support multiple databases in the same instance, to support multi-tenancy. Each DB has an identical schema. The user logs into a specific database by choosing from a list, and all subsequent calls will go to that DB until they log out.

I want to hot swap the session factory inside a single HibernateDaoTemplate based on a parameter supplied by the client.

I can find lots of stuff on hot-swapping data sources (and all the transaction issues associated with that) but I want to hot swap session factories - retaining all the caching for each.

What's the easiest way to do this? Configure a HotSwappableTarget for the DaoTemplate? Can anyone point me to samples on how to do this?

Answer:
If all the databases are identical, then I can suggest using a single SessionFactory and providing your own implementations for the DataSource and Cache that are actually "tenant-aware". (Implementing these is fairly trivial: just maintain a map of tenant id -> real cache/real datasource and then delegate all calls to the appropriate one). Configure the single SessionFactory to use your tenant-aware Cache and DataSource. A ThreadLocal can be used to make the tenant ID of the current request available to any code that needs to know about it.
I have used this approach before successfully to support multi-tenancy.


Question: Just found this out the hard way. I wanted to pop up a FontDialog to allow the user to choose a font.. one of those familiar dialogs..

Answer:
Not all of them have equivalents.
The FontDialog for instance doesnt.. (grumble grumble). This page has the complete lowdown.. posting since it may be useful just as a mental note.
http://msdn.microsoft.com/en-us/library/ms750559.aspx
Update:
The Programming WPF book had this covered. Apparently some of the dialogs didn't make the RTM bus. The FontDialog that will included into the next update is available here.. as is the ColorPicker dialog. Also you shuoldn't blindly use Win32 dialogs, because the corresponding types in WPF (e.g. Font and Color are "bigger and better" now.)
http://blogs.msdn.com/wpfsdk/archive/2006/10/26/Uncommon-Dialogs--Font-Chooser-and-Color-Picker-Dialogs.aspx


Question:
I try to fetch a Wikipedia article with Python's urllib:

f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes")
s = f.read()
f.close()

However instead of the html page I get the following response: Error - Wikimedia Foundation:

Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to ()
Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT

Wikipedia seems to block request which are not from a standard browser.

Anybody know how to work around this?

Answer:
Try changing the user agent header you are sending in your request to something like:
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008072820 Ubuntu/8.04 (hardy) Firefox/3.0.1 (Linux Mint)


Question:
I have a string of arbitrary length, and starting at position p0, I need to find the first occurrence of one of three 3-letter patterns.

Assume the string contain only letters. I need to find the count of triplets starting at position p0 and jumping forward in triplets until the first occurrence of either 'aaa' or 'bbb' or 'ccc'.

Is this even possible using just a regex?

Answer:
```
```
$string=~/^   # from the start of the string
            (?:.{$p0}) # skip (don't capture) "$p0" occurrences of any character
            (?:...)*?  # skip 3 characters at a time,
                       # as few times as possible (non-greedy)
            (aaa|bbb|ccc) # capture aaa or bbb or ccc as $1
         /x;
```
```
(Assuming p0 is 0-based).
Of course, it's probably more efficient to use substr on the string to skip forward:
```
```
substr($string, $p0)=~/^(?:...)*?(aaa|bbb|ccc)/;
```
```


Question:
I am using the open source Javascript WYSIWYG from OpenWebWare and Asp.Net RequiredFieldValidator on the TextBox which I am calling the WYSIWYG for.  Everything works fine, but the first time I try to submit the form, I get the server-side RFV ErrorMessage "Required", but if I submit a second time, it goes through.

Am I missing something?  I would like to have the client-side validation... how can I get the text to register as not empty?

Answer:
the textarea HTML tag is one of the most unpleasent tags to work with and I'm not 100% sure if the client-side validator will support it, regardless of whether it's a WYSIWYG or not.
I think you'd be best off using a CustomValidator and writing the JavaScript which does the checking manually.
Alternatively you can debug though the JavaScript which is used with FireBug or VS 2008.


Question: Is there a way to alter the precision of an existing decimal column in Microsoft SQL Server?

Answer:
```
```
ALTER TABLE Testing ALTER COLUMN TestDec decimal(16,1)
```
```
Just put
```
decimal(precision, scale)
```
, replacing the precision and scale with your desired values.
I haven't done any testing with this with data in the table, but if you alter the precision, you would be subject to losing data if the new precision is lower.


Question:
I am using following PHP code to connect to MS Access database:

$odb_conn = new COM("ADODB.Connection");
$connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". $db_path.";";
$odb_conn->open($connstr);

How can I retrieve database catalog/metadata from the mdb file?

FOUND THE SOLUTION

$rs_meta = $odb_conn->OpenSchema(20, array(Null, Null, Null, "TABLE"));

Answer:
The
```
MSysObjects
```
table can be used to query metadata in Access:
```
```
SELECT NAME
FROM MSysObjects
WHERE Type In (1,4,6) AND Left([Name],4)<>"MSYS"
```
```


Question: What's the difference between failover and disaster recovery?

Answer:
Failover: When one machine fails, another machine (usually in the same location) takes over and resumes service
Disaster recovery: When Godzilla destroys your data center, you do have alternative locations to keep providing your service and protocols/means for the other location to know how to keep delivering the service
Depending on the particular needs of each service, disaster recovery might just be a backup tape in a safe in a different location. In other words, it's just having a defined protocol to recover from disaster. Likewise, failover might just be having a spare backup machine which makes you go to the data center for it to take over the place of the failed one, that is, having a defined protocol about what to do in case of machine failure.
Summing up, failover answers the question 'what do I do in case a single machine fails?', disaster recovery answers 'what do I do in case a disaster happens (fire, floods, war, ISP goes bankrupt, whatever)?'
High Availability Deployment Architecture


Question:
I'm doing some testing on Firefox toolbars for the sake of learning and I can't find out any information on how to store the contents of a "search" drop-down inside the user's profile.

Is there any tutorial on how to sort this out?

Answer:
Since it's taking quite a bit to get an answer I went and investigate it myself.
Here is what I've got now. Not all is clear to me but it works.
Let's assume you have a <textbox> like this, on your .xul:
```
```
<textbox id="search_with_history" />
```
```
You now have to add some other attributes to enable history.
```
```
<textbox id="search_with_history" type="autocomplete"
    autocompletesearch="form-history"
    autocompletesearchparam="Search-History-Name"
    ontextentered="Search_Change(param);"
    enablehistory="true"
 />
```
```
This gives you the minimum to enable a history on that textbox.
For some reason, and here is where my ignorance shows, the onTextEntered event function has to have the param to it called "param". I tried "event" and it didn't work.
But that alone will not do work by itself. One has to add some Javascript to help with the job.
```
```
// This is the interface to store the history
const HistoryObject = Components.classes["@mozilla.org/satchel/form-history;1"]
    .getService(
        Components.interfaces.nsIFormHistory2 || Components.interfaces.nsIFormHistory
    );
// The above line was broken into 4 for clearness.
// If you encounter problems please use only one line.

// This function is the one called upon the event of pressing <enter>
// on the text box
function Search_Change(event) {
    var terms = document.getElementById('search_with_history').value;
    HistoryObject.addEntry('Search-History-Name', terms);
}
```
```
This is the absolute minimum to get a history going on.


Question:
I am using VMware Server 1.0.7 on Windows XP SP3 at the moment to test software in virtual machines.

I have also tried Microsoft Virtual PC (do not remeber the version, could be 2004 or 2007) and VMware was way faster at the time.

I have heard of Parallels and VirtualBox but I did not have the time to try them out. Anybody has some benchmarks how fast is each of them (or some other)?

I searched for benchmarks on the web, but found nothing useful.

I am looking primarily for free software, but if it is really better than free ones I would pay for it.

Also, if you are using (or know of) a good virtualization software but have no benchmarks for it, please let me know.

Answer:
The
```
/dev/random
```
device is intended to be a source of cryptographically secure bits.


Question:
I have a site on my webhotel I would like to run some scheduled tasks on. What methods of achieving this would you recommend?

What I’ve thought out so far is having a script included in the top of every page and then let this script check whether it’s time to run this job or not.

This is just a quick example of what I was thinking about:

if ($alreadyDone == 0 && time() > $timeToRunMaintainance) {
   runTask();
   $timeToRunMaintainance = time() + $interval;
}

Anything else I should take into consideration or is there a better method than this?

Answer:
That's what cronjobs are made for.
```
man crontab
```
assuming you are running a linux server.  If you don't have shell access or no way to setup cronjobs, there are free services that setup cronjobs on external servers and ping one of your URLs.


Question:
I am trying to optimize some stored procedures on a SQL Server 2000 database and when I try to use SQL Profiler I get an error message "In order to run a trace against SQL Server you have to be a member of sysadmin fixed server role.". It seems that only members of the sysadmin role can run traces on the server (something that was fixed in SQL Server 2005) and there is no way in hell that I will be granted that server role (company policies)

What I'm doing now is inserting the current time minus the time the procedure started at various stages of the code but I find this very tedious

I was also thinking of replicating the database to a local installation of SQL Server but the stored procedure is using data from many different databases that i will spend a lot of time copying data locally

So I was wondering if there is some other way of profiling SQL code? (Third party tools,  different practices, something else )

Answer:
That's what cronjobs are made for.
```
man crontab
```
assuming you are running a linux server.  If you don't have shell access or no way to setup cronjobs, there are free services that setup cronjobs on external servers and ping one of your URLs.


Question:
I'm trying to put together a selector in SASS that will operate on the visted, hovered state of a link, but I can't quite seem to get the markup right, can someone enlighten me?
I was writing it like this:

 &:visited:hover
     attribute: foo

Answer:
```
```
a
 &:visited:hover
    :attribute foo
```
```
Try that - note that identation is two spaces, and the colon goes before attribute not after.


Question:
Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory.

So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')?

Answer:
Nope.  But you can use short integers in arrays:
```
```
from array import array
a = array("h") # h = signed short, H = unsigned short
```
```
As long as the value stays in that array it will be a short integer.
documentation for the
array module


Question:
Say for instance I was writing a function that was designed to accept multiple argument types:

var overloaded = function (arg) {
    if (is_dom_element(arg)) {
        // Code for DOM Element argument...
    }
};

What's the best way to implement is_dom_element so that it works in a cross-browser, fairly accurate way?

Answer:
Probably this one here:
```
```
node instanceof HTMLElement
```
```
That should work in most browsers.  Otherwise you have to duck-type it (eg.
```
typeof x.nodeType != 'undefined'
```
)


Question: I'm looking for non-web-based tools to view IIS logs.  I've been using LogParser but I was hoping for something with an interface.  It doesn't need to do any fancy reports or charts -- just a list with some search filters is plenty.  I need something lightweight that I can run directly on the web server, preferably without a complex install process.

Answer:
I find that command-line tools are often enough. For example, to list all log entries with a 404 response:
```
```
findstr "404" logfilename > out.txt
```
```
Findstr supports regular expressions in the search term and wildcards in the filename, so it is quite flexible for dealing with logfiles.


Question: I am putting together a proposal for a large multinational company for our licenced solution. Problem is I've never put together something this big before and so I don't know what is acceptable.  Ignoring hosting or support (or even the functionality of the app) for the moment and just concentrating the licence - do you think it's more usual to do it on a per user basis - and if so would the company mind when prices fluctuate as more users come on board?  Or is it more normal to do bands of users: 1-1000, 1000-5000, 5000-10000, 10000-25000, 25000-50000, 50000-100k, 100k+ (probably maximum usage).  Does anyone know of any good links about this kind of thing?  Has anyone here procured a complex, multilingual web app for 30000 users and how much is acceptable?

Answer: It's going to depend on your situation I suppose, is this licensed solution already complete, or is it going to be created specifically for this company. If it's the first, I'd suggest using previous offers as basis. If it's going to be developped, it's going to depend on how you want to recoup your money for developing it. Over what period of time do you want to recoup your costs etc. I'd say that bands of users is probably the most common solution, as people probably don't want to relicense for every individual user.


Question: How do I iterate over a set of records in RPG(LE) with embedded SQL?

Answer:
Usually I'll create a cursor and fetch each record.
```
```
//***********************************************************************
   // Main - Main Processing Routine
   begsr Main;

     exsr BldSqlStmt;

     if OpenSqlCursor() = SQL_SUCCESS;

       dow FetchNextRow() = SQL_SUCCESS;
         exsr ProcessRow;
       enddo;

       if sqlStt = SQL_NO_MORE_ROWS;
         CloseSqlCursor();
       endif;

     endif;

     CloseSqlCursor();

   endsr;    // Main
```
```
I have added more detail to this answer
in a post on my website
.


Question: What's the difference between "Layers" and "Tiers"?

Answer:
Read Scott Hanselman's post on the issue:
A reminder on "Three/Multi Tier/Layer Architecture/Design"
:
Remember though, that in "Scott World" (which is hopefully your world also :) ) a "Tier" is a unit of deployment, while a "Layer" is a logical separation of responsibility within code.  You may say you have a "3-tier" system, but be running it on one laptop.  You may say your have a "3-layer" system, but have only ASP.NET pages that talk to a database.  There's power in precision, friends.


Question:
I've noticed that Internet Explorer adds a number in square brackets to files downloaded from the internet (usually [1]). This creates a big problem with downloading Excel spreadsheets as square brackets are not a valid filename character inside Excel worksheet name. That problem is IE specific, others browsers are keeping same file name.

So, if you have a pivot table auto-refreshed on file opening for example, you'll get an error message saying the name "file[1].yourPivotTableName" is not valid.

Is there any solution to that problem ?

EDIT : It seems that whatever the filename suggested by HTTP directives, IE adds [1] in all cases, which cause the problem ! (So, answers about filenames aren't helpful in that case)

EDIT : I've tried some VBA code to save file under another name when it'll open. However, it doesn't work (same error message than before). Do you think there's a way to fix that with VBA ?

Answer:
Actually, the correct .NET-code is as following:
```
```
Response.AppendHeader("content-disposition", "attachment;filename=file.xls");
Response.ContentType = "application/vnd.ms-excel";
```
```
Note:
AppendHeader
, not
AddHeader
, which I think only works in debug web-server and IIS7.


Question:
I'm trying to populate a TDBGrid with the results of the following TQuery against the file Journal.db:

select * from Journal
where  Journal.where = "RainPump"

I've tried both Journal."Where" and Journal.[Where] to no avail.

I've also tried: select Journal.[Where] as "Location" with the same result.

Journal.db is a file created by a third party and I am unable to change the field names.

The problem is that the field I'm interested in is called 'where' and understandably causes the above error. How do I reference this field without causing the BDE (presumably) to explode?

Answer:
```
```
select * from Journal where Journal."where" = "RainPump"
```
```


Question: I need to know where i can get a free version of C and C++ compilers for Windows Vista. Many of the versions i have tried are not working in fullscreen mode.

Answer:
Please take a look at
visual studio 2008 express edition
.
It is a freeware IDE and compiler from Microsoft for C#, VB.Net, C++, SQL, and web.
The Express line is a lightweight version of Microsoft Visual Studio 2008 product.
I believe it has full screen support in the IDE.
See the
wikipedia page for further reading
.


Question:
We have a vxWorks design which requires one task to process both high and low priority messages sent over two message queues.

The messages for a given priority have to be processed in FIFO order.

For example, process all the high priority messages in the order they were received, then process the low priority messages.  If there is no high priority message, then process the low priority message immediately.

Is there a way to do this?

Answer:
In vxWorks, you can't wait directly on multiple queues.  You can however use the OS events (from eventLib) to achieve this result.
Here is a simple code snippet:
```
```
MSG_Q_ID lowQ, hiQ;

void Init() {
// Task Initialization Code.  This should be called from the task that will
// be receiving the messages
...
hiQ = msgQCreate(...);
lowQ = msgQCreate(...);
msgQEvStart(hiQ, VX_EV01);  // Event 1 sent when hiQ receives message
msgQEvStart(loQ, VX_EV02);  // Event 2 sent when loQ receives message
...
}
void RxMessages() {
...
  UINT32 ev;   // Event received

   // Blocks until we receive Event 1 or 2
   eventReceive(VX_EV01 | VX_EV02, EVENT_WAIT_ANY, WAIT_FOREVER, &ev);
   if(ev & VX_EV01) {
      msgQReceive(hiQ, ...);
   }
   if(ev & VX_EV02) {
      msgQReceive(loQ, ...);
   }
}
```
```
Note that you need to modify that code to make sure you drain all your queues in case there is more than one message that was received.
The same mechanism can also be applied to Binary semaphores using the semEvStart() function.


Question: What would be the best way to expose certain functionality in a Dotnet VSTO Excel add-in to VBA, without requiring the user to be a local administrator (i.e. no COM registration, no HttpListener)? Would it be possible to use Microsoft Message Queues from VBA?

Answer:
If I may interpret your question as broadly as "How do I expose functionality in a .Net assembly to Excel without COM registration" then an excellent solution is to use Excel's XLL interface.
Basically one deploys an xll shim and an associated .Net dll. When the xll is loaded it reflects over the dll and exposes the functions therein to Excel.
An open source implementation can be found here
http://exceldna.typepad.com/blog/2006/01/introducing_exc.html
A commercial, closed source, but more feature rich one here
http://www.managedxll.com/


Question:
I would like to trash the mail received by a single qmail alias.  I don't want any mail delivery errors, and I want qmail to be happy about having delivered the mail.

How can I do this, preferably without adding another local email account?

Answer:
Create an alias by creating a file /var/qmail/aliases/.qmail-
blackhole
with this content:
```
```
|cat >/dev/null
```
```
Then redirect whatever you want to this ‘blackhole’ alias (or use whatever you want in place of ‘blackhole’). Merely using /dev/null won’t work (
```
Unable_to_write_/dev/null
```
).
The messages will still be logged, however. Though it’s more of a feature than a bug.


Question: Is Eclipse at all theme-able? I would like to install a dark color scheme for it, since I much prefer white text on dark background than the other way around.

Answer:
Here's a guy that posted his Eclipse preferences for changing the colors like a theme:
http://blog.codefront.net/2006/09/28/vibrant-ink-textmate-theme-for-eclipse/
And here's more about how to set the colors in the
Ganymede Eclipse version
(v. 3.4, mid 2008):
http://help.eclipse.org/ganymede/index.jsp?topic=/org.eclipse.platform.doc.user/concepts/accessibility/fontsandcolors.htm


Question:
I got this error when I checked out my database from source control. It might sounds weird to check in the sql server database, but this was what I have done because this is just a personal project.

Anyone knows how to fix this?

Answer:
You really don't want to be checking database files into and out of source control - in SQL Server you have to detach the files for this to even work and you run all kinds of risks.
If you absolutely have to do this, you should version backups.
I recommend versioning a script which creates the entire database (tables, sprocs, views, etc.)
You can try creating a database attaching from that data file and using
Create Database
the
```
ATTACH_REBUILD_LOG
```
option, but I'm not confident it's going to work since they probably weren't detached properly.


Question:
This is a real issue that applies on tagging items in general (and yes, this applies to StackOverflow too, and no, it is not a question about StackOverflow).

The whole tagging issue helps cluster similar items, whatever items they may be (jokes, blog posts, so questions etc). However, there (usually but not strictly) is a hierarchy of tags, meaning that some tags imply other tags too. To use a familiar example, the "c#" so tag implies also ".net"; another example, in a jokes database, a "blondes" tag implies the "derisive" tag, similarly to "irish" or "belge" or "canadian" etc depending on the joke's country origin.

How have you handled this, if you have, in your projects? I will supply an answer describing two different methods I have used in two separate cases (actually, the same mechanism but implemented in two different environments), but I am also interested not only on similar mechanisms, but also on your opinion on the hierarchy issue.

Answer:
The mechanism I have implemented was to not use the tags given themselves, but an indirect lookup table (not strictly DBMS terms) which links a tag to many implied tags (obviously, a tag is linked with itself for this to work).
In a python project, the lookup table is a dictionary keyed on tags, with values sets of tags (where tags are plain strings).
In a database project (indifferent which RDBMS engine it was), there were the following tables:
```
```
[Tags]
tagID integer primary key
tagName text

[TagRelations]
tagID integer # first part of two-field key
tagID_parent integer # second part of key
trlValue float
```
```
where the trlValue was a value in the (0, 1] space, used to give a gravity for the each linked tag; a self-to-self tag relation always carries 1.0 in the trlValue, while the rest are algorithmically calculated (it's not important how exactly). Think the example jokes database I gave; a ['blonde', 'derisive', 0.5] record would correlate to a ['pondian', 'derisive', 0.5] and therefore suggest all derisive jokes given another.


Question:
In the past I've worked with a number of programmers who have worked exclusively writing GUI applications.

And I've been given the impression that they have almost universally minimised the use of multiple threads in their applications. In some cases they seem to have gone to extreme lengths to ensure that they use a single thread.

Is this common? Is this the generally accepted philosophy for gui application design?

And if so, why?

[edit]

There are a number of answers saying that thread usage should be minimised to reduce complexity. Reducing complexity in general is a good thing.

But if you look at any number of applications where response to external events is of paramount importance (eg. web servers, any number of embedded applications) there seems to be a world of difference in the attitude toward thread usage.

Answer:
I think in terms of windows you are limited to all GUI operations happening on a single thread - because of the way the windows message pump works, to increase responsivness most apps add at least one additional worker thread for longer running tasks that would otherwise block and make the ui unresponsive.
Threading is fundamentally hard and so thinking in terms or more than a couple threads can often result in a lot of debugging effort - there is a quote that escapes me right now that goes something like - "if you think you understand threading then you really dont"


Question: If you call javascript window.open and pass a url to a .xls file it open on some machines in the browser window.  How can you force it into Excel?

Answer:
Only the users machine can "force" it into Excel.  That said, 99% of the time if you send the correct mime-type and a user has Excel, then it will open in Excel assuming they approve.
And only the server can send the correct mime-type.  The document type you pass to a JavaScript window.open call will have no effect on this.  In fact, calling window.open will at best just open a superfluous window.
It's best to just link to the document with
```
<a href="foo.xls">
```
.  And provided your server is sending a mime-type of
```
application/x-excel
```
or
```
application/x-msexcel
```
this will almost always nudge the browser into opening a new window with the Excel document.


Question: How do I get a list of all files (and directories) in a given directory in Python?

Answer:
You can use
```
```
os.listdir(path)
```
```
For reference and more os functions look here:
Python 2 docs:
https://docs.python.org/2/library/os.html#os.listdir
Python 3 docs:
https://docs.python.org/3/library/os.html#os.listdir


Question:
Will Subclipse 1.4.4 work safely with Subversion 1.3.2?

I am confused because its changelog says

NOTE: As of Subclipse 1.3.0, the minimum Subversion JavaHL requirement is 1.5.0.

Answer: Do you mean whether Subclipse 1.4.4 will work with a server that is 1.3.2?  If so, probably yes since clients tend to be updated more often than the servers, and thus they try to be backwards compatible. 1.3.2 is starting to get old though, if the client is based on subversion 1.5.


Question: I have the .net framework 3.5 on my development machine and also am using the AJAX toolkit  in my code.  In order to publish this code to a server for my users, do I need anything on the server in order for my AJAX code to operate correctly?

Answer:
You need only the .NET framework 3.5.
If you publish your project, the AJAX Toolkit used will be also copied over. If you only reference the AJAX Toolkit via file, not via project, then be sure you set the dll to "Copy always" in the properties window.


Question:
Are there any decent tutorials for setting up F# in Visual Studio 2005? Everything I have found points at VS2008.

ie: 'F# projects' under projects, etc.

Answer:
Installing F# Editing for Microsoft Visual Studio 2005
That page also links to
Don Syme's F# blog
, which has a lot of useful stuff on working with F# in VS, including a demo of
F# intellisense in VS2005
.


Question:
I have several <li> elements with different id's on ASP.NET page:

<li id="li1" class="class1">
<li id="li2" class="class1">
<li id="li3" class="class1">

and can change their class using JavaScript like this:

li1.className="class2"

But is there a way to change <li> element class using ASP.NET? It could be something like:

WebControl control = (WebControl)FindControl("li1");
control.CssClass="class2";

But FindControl() doesn't work as I expected. Any suggestions?

Thanks in advance!

Answer:
you must set runat="server" like:
```
```

stuff

```
```


Question: How to show google maps in mobile application using .net2.0

Answer:
There is various controls available to integrate Google Maps into an ASP.net website. Since the Sockets and Net libraries are available on Windows Mobile, you could possibly integrate using the Google Maps API, however will have to build your own controls to display the maps. The API can be found
here
.


Question:
I am a bit confused in what the application controller should do? Because I see the functionality will also exists in your MVP pattern to make the decisions which form should be shown when a button is clicked? Are there any good examples for Windows Forms that uses  the application controller pattern?

There is a difference in the MVC(ontroler) and the Application Controller. I know the MVC(ontroller), I am not sure what is the responsibilities for an Application Controller, and how does it fit into a WinForms application. Martin Fowler also calls this the Application Controller pattern, surely it is not the same thing as the MVC(ontroller)?

Answer:
Personally I have no experience with MVP or winforms, but I have worked with MVC. I hope this is what you're asking, otherwise ignore my answer completely.
The C in MVC is responsible for more than just choosing the next view to be presented to the client. It holds most, preferably
all
, business-logic of the application, including performance of system tasks (such as logging and enforcement of permissions upon the flow of data from the model and to it).
Its primary task is, naturally, to serve the presentation layer above it and separate it from the model layer below while mediating between them. I guess you can think of it as the brain of the application.
Hope this helps,
Yuval =8-)


Question:
Many times, a Java app needs to connect to the Internet. The most common example happens when it is reading an XML file and needs to download its schema.

I am behind a proxy server. How can I set my JVM to use the proxy ?

Answer:
From the Java documentation (
not
the javadoc API):
http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html
Set the JVM flags
```
http.proxyHost
```
and
```
http.proxyPort
```
when starting your JVM on the command line.
This is usually done in a shell script (in Unix) or bat file (in Windows). Here's the example with the Unix shell script:
```
```
JAVA_FLAGS=-Dhttp.proxyHost=10.0.0.100 -Dhttp.proxyPort=8800
java ${JAVA_FLAGS} ...
```
```
When using containers such as JBoss or WebLogic, my solution is to edit the start-up scripts supplied by the vendor.
Many developers are familiar with the Java API (javadocs), but many times the rest of the documentation is overlooked. It contains a lot of interesting information:
http://download.oracle.com/javase/6/docs/technotes/guides/
Update :
If you do not want to use proxy to resolve some local/intranet hosts, check out the comment from @Tomalak:
Also don't forget the http.nonProxyHosts property!
```
```
-Dhttp.nonProxyHosts="localhost|127.0.0.1|10.*.*.*|*.example.com|etc"
```
```


Question: What is the average time that it would take a complete novice, whose background is mostly Windows XP, to go through the FreeBSD handbook and get sufficient mastery to setup a server from the ground up?

Answer:
It would depend on how much knowledge you have of unix, and from the sounds of things, you probably do not have a whole lot.
Assuming you have little knowledge of unix at all, I would say that it will probably take a few days to get a grasp of what is going on, and possibly a week to have something working.
The FreeBSD handbook is pretty detailed though, and does provide you with a good grounding of everything you need to do to get things to work.
I know that this sounds like an awful lot of time, but in my experience, they really are quite different OS paradigms.


Question: How can one load custom (not an image, nor a sound file) resource file from /res within .jar using MIDP 2.0?

Answer:
I'm working with MIDP 2.1, but I hope this is in 2.0 too.
Class.getResource(path_to_resource) should give you an InputStream to the file.


Question: We are creating an XBAP application that we need to have rounded corners in various locations in a single page and we would like to have a WPF Rounded Corner container to place a bunch of other elements within.  Does anyone have some suggestions or sample code on how we can best accomplish this?   Either with styles on a  or with creating a custom control?

Answer:
You don't need a custom control, just put your container in a border element:
```
```
<Border BorderBrush="#FF000000" BorderThickness="1" CornerRadius="8">
   <Grid/>
</Border>
```
```
You can replace the
```
<Grid/>
```
with any of the layout containers...


Question:
Is it possible to, for instance, replace and free a TEdit with a subclassed component instantiated (conditionally) at runtime? If so, how and when it should be done? I've tried to set the parent to nil and to call free() in the form constructor and AfterConstruction methods but in both cases I got a runtime error.

Being more specific, I got an Access violation error (EAccessViolation). It seems François is right when he says that freeing components at frame costruction messes with Form controls housekeeping.

Answer:
You have to call RemoveControl of the TEdit's parent to remove the control. Use InsertControl to add the new control.
```
```
var Edit2: TEdit;
begin
  Edit2 := TEdit.Create(self);
  Edit2.Left := Edit1.Left;
  Edit2.Top := Edit2.Top;
  Edit1.Parent.Insertcontrol(Edit2);
  TWinControl(Edit1.parent).RemoveControl(Edit1);
  Edit1.Free;
end;
```
```
Replace TEdit.Create to the class you want to use, and copy all properties you need like I did with Left and Top.


Question:
What are the C++ rules for calling the base class constructor from a derived class?

For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).

Answer:
Base class constructors are automatically called for you if they have no argument.  If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list.  Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".
```
```
class SuperClass
{
    public:

        SuperClass(int foo)
        {
            // do something with foo
        }
};

class SubClass : public SuperClass
{
    public:

        SubClass(int foo, int bar)
        : SuperClass(foo)    // Call the superclass constructor in the subclass' initialization list.
        {
            // do something with bar
        }
};
```
```
More info on the constructor's initialization list
here
and
here
.


Question:
Suppose we have an iterator (an infinite one) that returns lists (or finite iterators), for example one returned by

infinite = itertools.cycle([[1,2,3]])

What is a good Python idiom to get an iterator (obviously infinite) that will return each of the elements from the first iterator, then each from the second one, etc. In the example above it would return 1,2,3,1,2,3,.... The iterator is infinite, so itertools.chain(*infinite) will not work.

Related

Flattening a shallow list in python

Answer:
Use a generator:
```
```
(item for it in infinite for item in it)
```
```
The * construct unpacks into a tuple in order to pass the arguments, so there's no way to use it.


Question:
I'm working on databases that have moving tables auto-generated by some obscure tools. By the way, we have to track information changes in the table via some triggers. And, of course, it occurs that some changes in the table structure broke some triggers, by removing a column or changing its type, for example.

So, the question is: Is there a way to query the Oracle metadata to check is some triggers are broken, in order to send a report to the support team?

The user_triggers give all the triggers and tells if they are enable or not, but does not indicate if they are still valid.

Answer:
```
```
SELECT *
FROM   ALL_OBJECTS
WHERE  OBJECT_NAME = trigger_name
AND    OBJECT_TYPE = 'TRIGGER'
AND    STATUS <> 'VALID'
```
```


Question:
I try to open and excel reference in LabVIEW and then close it after sometime. But the LabVIEW keeps holding the reference and does not release it unless I close the VI. Why is this happening? Is there anyway to force it to release the Reference?

I am checking the error out for any errors. But it is not throwing up any errors.

Answer:
This might get you started. It will need some refinement
```
```
Table Product ( id PK, name, price, units_per_package)
Table Product_Attribs (id FK ref Product, AttribName, AttribValue)
```
```
Which would allow you to attach a list of attributes to the products. -- This is essentially your option 3
If you know a max number of attributes, You could go
```
```
Table Product (id PK, name, price, units_per_package, attrName_1, attrValue_1 ...)
```
```
Which would of course de-normalize the database, but make queries easier.
I prefer the first option because
It supports an arbitrary number of attributes.
Attribute names can be stored in another table, and referential integrity enforced so that those damn Canadians don't stick a "colour" in there and break reporting.


Question: How to create a database using T SQL script on a specified location? Let's say, I want to create a SQL server database on D:\temp\dbFolder. How to do this?

Answer:
When you create the new database you specify the location. For example:
```
```
USE [master]
GO

    CREATE DATABASE [AdventureWorks] ON  PRIMARY
    ( NAME = N'AdventureWorks_Data', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Data.mdf' , SIZE = 167872KB , MAXSIZE = UNLIMITED, FILEGROWTH = 16384KB )
     LOG ON
    ( NAME = N'AdventureWorks_Log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Log.ldf' , SIZE = 2048KB , MAXSIZE = 2048GB , FILEGROWTH = 16384KB )
    GO
```
```


Question:
I see on Stack Overflow and PEP 8 that the recommendation is to use spaces only for indentation in Python programs.  I can understand the need for consistent indentation and I have felt that pain.

Is there an underlying reason for spaces to be preferred?  I would have thought that tabs were far easier to work with.

Answer:
The problem with tabs is that they are invisible, and people can never agree on the width of tabs. When you mix tabs and spaces, and you set tabstops at something other than Python (which uses tabstops every 8 spaces) you will be seeing the code in a different layout than Python sees it. And because the layout determines blocks, you will be seeing different logic. It leads to subtle bugs.
If you insist on defying PEP 8 and using tabs -- or worse, mixing tabs and spaces -- at least always run python with the '-tt' argument, which makes
inconsistent
indentation (sometimes a tab, sometimes a space for the same indentation level) an error. Also, if possible, set your editor to display tabs differently. But really, the best approach is not to use tabs, period.


Question:
I can add custom version strings to a C++ DLL in Visual Studio by editing the .rc file by hand.  For example, if I add to the VersionInfo section of the .rc file

VALUE "BuildDate", "2008/09/19 15:42:52"

Then that date is visible in the file explorer, in the DLL's properties, under the Version tab.

Can I do the same for a C# DLL?  Not just for build date, but for other version information (such as source control information)

UPDATE: I think there may be a way to do this by embedding a windows resource, so I've asked how to do that.

Answer:
In AssemblyInfo.cs, you can put:
```
```
[assembly: System.Reflection.AssemblyInformationalVersion("whatever you want")]
```
```
It's a compiler warning if it's not a number like 1.2.3.4, but I'm fairly sure everything will work.


Question: Have any of you ever tried to run from sharepoint? I've worked with sharepoint enough to know that it is not something that interests me. My interests are more along the lines of APIs / backend / distributed development. Have any of you found ways, as consultants, to move away from sharepoint and keep learning other things of interest? I'm currently in a position where sharepoint is in huge demand and I can't quite find a way to simply step aside from it. any suggestions ?

Answer:
Learn Java, or Ruby.
The Microsoft sales model of "attach" whereby they sell a solution comprised of multiple technologies and then sell the next solution on the basis of "well you have already invested in SharePoint so you already have the skills in place and the infrastructure for this new bit of technology we have" is here to stay... it's very successful.
SharePoint is cloud computing for business who have MS shops... you avoid it by not doing C#. If you're doing C# then given enough time, your apps will need to run in the corporate cloud and you should be looking after your career by embracing it.
Just my 2p. Sorry if it's not quite the answer you wanted.


Question:
I'd like to know do I normalize a URL in python.

For example, If I have a url string like : "http://www.example.com/foo goo/bar.html"

I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.

Answer:
Py3
```
```
from urllib.parse import urlparse, urlunparse, quote
def myquote(url):
    parts = urlparse(url)
    return urlunparse(parts._replace(path=quote(parts.path)))

>>> myquote('https://www.example.com/~user/with space/index.html?a=1&b=2')
'https://www.example.com/~user/with%20space/index.html?a=1&b=2'
```
```
Py2
```
```
import urlparse, urllib
def myquote(url):
    parts = urlparse.urlparse(url)
    return urlparse.urlunparse(parts[:2] + (urllib.quote(parts[2]),) + parts[3:])

>>> myquote('https://www.example.com/~user/with space/index.html?a=1&b=2')
'https://www.example.com/%7Euser/with%20space/index.html?a=1&b=2'
```
```
This quotes only the path component.


Question:
I understand the mantra of "don't roll your own" when it comes to site security frameworks.

For most cases anyway.

I'm going to be collaborating on a site that integrates text-messaging into the system.

I'd like to use an existing, well-tested security framework to protect the users data, but I need it to also protect a users phone number as well.

I wouldn't want to be the one responsible for a list of users cell phone numbers getting jacked and spammed.

What suggestions can the community offer?

Answer:
Since you need to be able to retrieve the phone numbers, the only thing you can really do to protect them (beyond the normal things you would do to protecting your db) is encrypt them. This means that you need to:
Make sure the key doesn't leak when you inadvertently leak a database dump.
Make sure your system doesn't helpfully decrypt the phone numbers when someone manages to SQL inject your system.
Of course the recommendation of not rolling your own still applies, use AES or some other well respected cipher with a reasonable key length.


Question:
I'm just getting started with Custom User Controls in C# and I'm wondering if there are any examples out there of how to write one which accepts nested tags?

For example, when you create an asp:repeater you can add a nested tag for itemtemplate.

Answer:
I wrote a
blog post
about this some time ago. In brief, if you had a control with the following markup:
```
```
<Abc:CustomControlUno runat="server" ID="Control1">
    <Children>
        <Abc:Control1Child IntegerProperty="1" />
    </Children>
</Abc:CustomControlUno>
```
```
You'd need the code in the control to be along the lines of:
```
```
[ParseChildren(true)]
[PersistChildren(true)]
[ToolboxData("<{0}:CustomControlUno runat=server></{0}:CustomControlUno>")]
public class CustomControlUno : WebControl, INamingContainer
{
    private Control1ChildrenCollection _children;

    [PersistenceMode(PersistenceMode.InnerProperty)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public Control1ChildrenCollection Children
    {
        get
        {
            if (_children == null)
            {
                _children = new Control1ChildrenCollection();
            }
            return _children;
        }
    }
}

public class Control1ChildrenCollection : List<Control1Child>
{
}

public class Control1Child
{
    public int IntegerProperty { get; set; }
}
```
```


Question: How do I get the modified date/time of a file in Python?

Answer:
```
```
os.path.getmtime(filepath)
```
```
or
```
```
os.stat(filepath).st_mtime
```
```


Question: What is the best way to divide a 32 bit integer into four (unsigned) chars in C#.

Answer:
It's not clear if this is really what you want, but:
```
```
int x = yourNumber();
char a = (char)(x & 0xff);
char b = (char)((x >> 8) & 0xff);
char c = (char)((x >> 16) & 0xff);
char d = (char)((x >> 24) & 0xff);
```
```
This assumes you want the bytes interpreted as the lowest range of Unicode characters.


Question:
I've recently acquired a second monitor and now run VS2008 SP1 maximized on my secondary (and bigger) monitor. This theoretically has the benefit of opening the application under development on the primary monitor, where -- as it seems to me -- all newly started applications go. So far, so good. The problem though is now, that the exception helper popup is not opened on the secondary monitor. Even worse, it is only shown when the Studio window is far enough on the primary monitor! If I drag the studio with an opened exception helper from the primary to the secondary monitor, the helper is dragged with the window until it hits the border between the two monitors, where it suddenly disappears.

Has somebody experienced this too? Is there any workaround? Anything else I should try?

Answer:
It's not clear if this is really what you want, but:
```
```
int x = yourNumber();
char a = (char)(x & 0xff);
char b = (char)((x >> 8) & 0xff);
char c = (char)((x >> 16) & 0xff);
char d = (char)((x >> 24) & 0xff);
```
```
This assumes you want the bytes interpreted as the lowest range of Unicode characters.


Question:
I want to attach a click event to a button element and then later remove it, but I can't get unclick() or unbind() event(s) to work as expected.  In the code below, the button is tan colour and the click event works.

window.onload = init;
function init() {
    $("#startButton").css('background-color', 'beige').click(process_click);
    $("#startButton").css('background-color', 'tan').unclick();
}

How can I remove events from my elements?

Answer:
unbind is your friend.
```
```
$("#startButton").unbind('click')
```
```


Question: Changing a value prompt to a multi-select value prompt in Report studio, provide single select functionality. How can i get multi-select functionality?

Answer:
Look at the parameter associated with the prompt. Now go look and see how you use that parameter to filter the queries in your report. If you have the filter set as:-
[namespace].[table].[column] = ?MyParameter?
... then it doesn't matter that your prompt is a multi-select prompt, it will still run as a single selection prompt. Modify your filters so they are of the form:-
[namespace].[table].[column] in ?MyParameter?
This tells Cognos that your parameter can contain multiple values, and it will display the prompt accordingly.


Question:
I have a legacy application that is written in C# and it displays a very complex treeview with 10 to 20 thousand elements.

In the past I encountered a similar problem (but in C++) that i solved with the OWNERDATA capability offered by the Win32 API.

Is there a similar mechanism in C#?

EDIT: The plan is to optimize the creation time as well as browsing time. The method available through Win32 API is excellent in both of these cases as it reduce initialization time to nothing and the number of requests for elements are limited to only the ones visible at any one time.
Joshl: We are actually doing exactly what you suggest already, but we still need more efficiency.

Answer:
One technique for improving performance is to load TreeNodes as the user expands the treeview. Normally a user will not require 20,000 nodes to be open on their screen at once. Only load the level that the user needs to see, along with whatever child information you need to properly display affordances to the user (expand icon if children exist, counts, icons, etc). As the user expands nodes, load children just in time.
Helpful hint from Keith: With the winforms TreeView you need to have at least one child node or it won't show the expand [+], but then you handle the TreeNodeExpanded event to remove that dummy node and populate the children.


Question: I have a managed DLL (written in C++/CLI) that contains a class used by a C# executable. In the constructor of the class, I need to get access to the full path of the executable referencing the DLL. In the actual app I know I can use the Application object to do this, but how can I do it from a managed DLL?

Answer:
```
```
Assembly.GetCallingAssembly()
```
```
or
```
```
Assembly.GetExecutingAssembly()
```
```
or
```
```
Assembly.GetEntryAssembly()
```
```
Depending on your need.
Then use Location or CodeBase property (I never remember which one).


Question: I have a Web Service (ASMX) with a few Web methods on our production Web server.  On a separate internal Web server (which isn't publicly exposed) I have another Web site that will use the ASMX's public web methods.  What are some of the best ways to secure the Web service such that only the internal Web server can access the Web Services running on the publicly exposed Web server?

Answer:
Assuming you don't have the option of using WCF, I'd advocate using WSE 3 (Web Service Enhancements).  You can get the toolkit / SDK thingummy at
MS's site
To limit the access to only internal machines (as I think your question asked), I'd set up a separate web site in IIS and set it to only respond to the internal IP address of your server.


Question: What does the explicit keyword mean in C++?

Answer:
The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a
single parameter
to convert from one type to another in order to get the right type for a parameter.
Here's an example class with a constructor that can be used for implicit conversions:
```
```
class Foo
{
private:
  int m_foo;

public:
  // single parameter constructor, can be used as an implicit conversion
  Foo (int foo) : m_foo (foo) {}

  int GetFoo () { return m_foo; }
};
```
```
Here's a simple function that takes a
```
Foo
```
object:
```
```
void DoBar (Foo foo)
{
  int i = foo.GetFoo ();
}
```
```
and here's where the
```
DoBar
```
function is called:
```
```
int main ()
{
  DoBar (42);
}
```
```
The argument is not a
```
Foo
```
object, but an
```
int
```
. However, there exists a constructor for
```
Foo
```
that takes an
```
int
```
so this constructor can be used to convert the parameter to the correct type.
The compiler is allowed to do this once for each parameter.
Prefixing the
```
explicit
```
keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call
```
DoBar (42)
```
.  It is now necessary to call for conversion explicitly with
```
DoBar (Foo (42))
```
The reason you might want to do this is to avoid accidental construction that can hide bugs.
Contrived example:
You have a
```
MyString
```
class with a constructor that constructs a string of the given size.  You have a function
```
print(const MyString&)
```
(as well as an overload
```
print (char *string)
```
), and you call
```
print(3)
```
(when you
actually
intended to call
```
print("3")
```
).  You expect it to print "3", but it prints an empty string of length 3 instead.


Question:
What are some of the lesser-known but useful features and techniques that people are using in their Greasemonkey scripts?

(Please, just one feature per answer.)

Similar threads:

Hidden Features of JavaScript

Hidden Features of Java

Hidden Features of C++

Hidden Features of C#

Answer:
Data can be persisted across page loads by storing it as a mozilla preference value via
```
GM_setValue(keyname, value)
```
.
Here is a simple example that tallys the number of times your script has been executed - by a given browser:
```
var od = GM_getValue("odometer", 0);
od++;
GM_setValue("odometer", od);
GM_log("odometer=" + od);
```
GM values are analogous to cookies in that cookie values can only be accessed by the originated domain, GM values can only be accessed by the script that created them.


Question: What are the compelling features of MFC? Why would you select it for a new project?

Answer:
Quick Tour Of New MFC Functionality
I hear they have a new ribbon control. If you're into this sort of complexity. Here's a screenshot of a newly generated app:
(source:
msdn.com
)
Really, it's just a widget update. So do we need more widgets?


Question: I work with quite a bit of multi-platform C/C++ code, separated by common #defines (#if WIN, #if UNIX, etc).  It would be nice if I could have vim automatically fold the sections I'm currently not interested in when I open a file.  I've searched through the vim script archives, but I haven't found anything useful.  Any suggestions?  Places to start?

Answer:
Just add a folding region to your syntax
http://vim.wikia.com/wiki/Syntax_folding_of_Vim_scripts#Syntax_definitions
```
```
:syn region myFold start="\#IF" end="\#ENDIF" transparent fold
:syn sync fromstart
:set foldmethod=syntax
```
```


Question: Is it legal to add support for a 3rd party file format in my application by reverse engineer a unencrypted binary file format from another application, and reading the contents?

Answer:
Depends on your location.
In the EU it is specifically permitted (article 6 EU software convention) to "reverse engineer file formats for the purpose of interoperability"
In general it's hard to prevent someone reading a file format, there have been examples where you are prohibeted from writing a file because the format contains patented technology (if software patents are allowed in your country). This was the case with GIF for a number of years.


Question:
I would like to convert a string into a node. I have a method that is defined to take a node, but the value I have is a string (it is hard coded). How do I turn that string into a node?

So, given an XQuery method:

define function foo($bar as node()*) as node() {
  (: unimportant details :)
}

I have a string that I want to pass to the foo method. How do I convert the string to a node so that the method will accept the string.

Answer:
MarkLogic solutions:
The best way to convert a string into a node is to use:
```
```
xdmp:unquote($string).
```
```
Conversely if you want to convert a node into a string you would use:
```
```
xdmp:quote($node).
```
```
Language agnostic solutions:
Node to string is:
```
```
fn:string($node)
```
```


Question:
What is the best (cleanest, most efficient) way to write saturating addition in C?

The function or macro should add two unsigned inputs (need both 16- and 32-bit versions) and return all-bits-one (0xFFFF or 0xFFFFFFFF) if the sum overflows.

Target is x86 and ARM using gcc (4.1.2) and Visual Studio (for simulation only, so a fallback implementation is OK there).

Answer:
```
```
uint32_t saturate_add32(uint32_t a, uint32_t b)
{
    uint32_t sum = a + b;
    if ((sum < a) || (sum < b))
        return ~((uint32_t)0);
    else
        return sum;
} /* saturate_add32 */

uint16_t saturate_add16(uint16_t a, uint16_t b)
{
    uint16_t sum = a + b;
    if ((sum < a) || (sum < b))
        return ~((uint16_t)0);
    else
        return sum;
} /* saturate_add16 */
```
```
Edit:
Now that you've posted your version, I'm not sure mine is any cleaner/better/more efficient/more studly.


Question:
My quick search reveals the reference implementation (http://stax.codehaus.org), the Woodstox implementation (http://woodstox.codehaus.org), and Sun's SJSXP implementation (https://sjsxp.dev.java.net/).

Please comment on the relative merits of these, and fill me in on any other implementations I should consider.

Answer:
Interesting to note that:
SJSXP performance is consistently faster than BEA, Oracle and RI for all
      of the documents described here in this study. However, it lags behind
      Woodstox and XPP3 in some document sizes and in the best cases, exhibits
      similar performance compared to these two parsers.
Article from Sun:
Streaming APIs for XML parsers


Question:
I'm currently looking for ways to create automated tests for a JAX-RS (Java API for RESTful Web Services) based web service.

I basically need a way to send it certain inputs and verify that I get the expected responses. I'd prefer to do this via JUnit, but I'm not sure how that can be achieved.

What approach do you use to test your web-services?

Update: As entzik pointed out, decoupling the web service from the business logic allows me to unit test the business logic. However, I also want to test for the correct HTTP status codes etc.

Answer:
You probably wrote some java code that implements your business logic and then you have generated the web services end point for it.
An important thing to do is to independently test your business logic. Since it's pure java code you can do that with regular JUnit tests.
Now, since the web services part is just an end point, what you want to make sure is that the generated plumbing (stubs, etc) are in sync with your java code. you can do that by writing JUnit tests that invoke the generated web service java clients. This will let you know when you change your java signatures without updating the web services stuff.
If your web services plumbing is automatically generated by your build system at every build, then it may not be necessary to test the end points (assuming it's all properly generated). Depends on your level of paranoia.


Question:
How would I go about binding the following object, Car, to a gridview?

public class Car
{
   long Id {get; set;}
   Manufacturer Maker {get; set;}
}

public class Manufacturer
{
   long Id {get; set;}
   String Name {get; set;}
}

The primitive types get bound easy but I have found no way of displaying anything for Maker. I would like for it to display the Manufacturer.Name. Is it even possible?

What would be a way to do it? Would I have to store ManufacturerId in Car as well and then setup an lookupEditRepository with list of Manufacturers?

Answer:
```
```
public class Manufacturer
    {
       long Id {get; set;}
       String Name {get; set;}

       public override string ToString()
       {
          return Name;
       }
    }
```
```
Override the to string method.


Question: I have a web application that is becoming rather large. I want to separate it into smaller more logical projects, but the smaller projects are still going to need to access some of the classes in the app_code of the main project. What are some good methods to accomplish this?

Answer:
Add a class library project with the common classes and add a reference to this project to each of the new projects.
So you'll have the following Solution layout
```
```
/webapp1
   /default.aspx
   /....
/webapp2
   /default.aspx
   /....
/lib
   /Utils.cs
```
```


Question:
Is it worth designing a system to expect test accounts and products to be present and active in production, or should there be no contamination of production databases with test entities, even if your shipping crew knows not to ship any box addressed to "Test Customer"?

I've implemented messaging protocols that have a test="True" attribute in the spec, and wondered if a modern schema should include metadata for tagging orders, accounts, transactions, etc. as test entities that get processed just like any other entity--but just short of the point where money gets spent. Ie: it fakes charging an imaginary credit card and fakes the shipment of a package.

This isn't expected to be a substitute for a fully separated testing, development, and QA database, but even with those, we've always had the well-known Test SKU and Test Customer in the production system. Harmless?

Answer: Having testing accounts in production is something I usually frown upon because it opens up a potential security hole.  One should strive to duplicate as much of the production environment in testing as possible but there are obviously cases where that isn't possible.  Expensive production only hardware is a prime example.  I would say as a general practice it should be discouraged but as with all things if you can provide a reason which makes sense to you then you might overlook a hard and fast rule.


Question:
I need to have a script read the files coming in and check information for verification.

On the first line of the files to be read is a date but in numeric form.  eg: 20080923
But before the date is other information, I need to read it from position 27. Meaning line 1 position 27, I need to get that number and see if it’s greater then another number.

I use the grep command to check other information but I use special characters to search, in this case the information before the date is always different, so I can’t use a character to search on.  It has to be done by line 1 position 27.

Answer:
```
```
sed 1q $file | cut -c27-34
```
```
The
```
sed
```
command reads the first line of the file and the
```
cut
```
command chops out characters 27-34 of the one line, which is where you said the date is.
Added later:
For the more general case - where you need to read line 24, for example, instead of the first line, you need a slightly more complex
```
sed
```
command:
```
```
sed -n -e 24p -e 24q | cut -c27-34
sed -n '24p;24q' | cut -c27-34
```
```
The
```
-n
```
option means 'do not print lines by default'; the
```
24p
```
means print line 24; the
```
24q
```
means quit after processing line 24.  You could leave that out, in which case
```
sed
```
would continue processing the input, effectively ignoring it.
Finally, especially if you are going to validate the date, you might want to use Perl for the whole job (or Python, or Ruby, or Tcl, or any scripting language of your choice).


Question:
I have a large ADO.Net dataset and two database schemas (Oracle) with different constraints.  The dataset will work with either schema, but I want to be able to tell the dataset which schema to use (via connection string) at runtime.

Is that even possible?

Answer: In the .Net 2.0 world, you can change your connection string on your table adapters at run-time.  You just have to be sure the Connnection property is public, which can be set from the dataset designer.


Question: Is there a way to comment out markup in an .ASPX page so that it isn't delivered to the client? I have tried the standard comments <!-- --> but this just gets delivered as a comment and doesn't prevent the control from rendering.

Answer:
Another way assuming it's not server side code you want to comment out is...
```
```
<asp:panel runat="server" visible="false">
    html here
</asp:panel>
```
```


Question:
Table:

UserId, Value, Date.

I want to get the UserId, Value for the max(Date) for each UserId. That is, the Value for each UserId that has the latest date. Is there a way to do this simply in SQL? (Preferably Oracle)

Update: Apologies for any ambiguity: I need to get ALL the UserIds. But for each UserId, only that row where that user has the latest date.

Answer:
I think something like this. (Forgive me for any syntax mistakes; I'm used to using HQL at this point!)
EDIT: Also misread the question! Corrected the query...
```
```
SELECT UserId, Value
FROM Users AS user
WHERE Date = (
    SELECT MAX(Date)
    FROM Users AS maxtest
    WHERE maxtest.UserId = user.UserId
)
```
```


Question: Has anyone been successful in getting the grails plugin for eclipse to work? How about grails plugin with netbeans?

Answer:
Unfortunately, there hasn't been much progress on the Eclipse plugin for Grails, we have started using
IntelliJ IDEA
for Grails development, the
JetGroovy
plugin is excellent and keeps getting better!


Question:
When you call the object.__repr__() method in Python you get something like this back:

<__main__.Test object at 0x2aba1c0cf890>

Is there any way to get a hold of the memory address if you overload __repr__(), other then calling super(Class, obj).__repr__() and regexing it out?

Answer:
Just use
```
```
id(object)
```
```


Question:
I need to store items with a calendar date (just the day, no time) in a sqlite database.  What's the best way to represent the date in the column?  Julian days and unix seconds come to mind as reasonable alternatives.  If I go with a unit other than days at what clock time should it be?

Update: I am aware of ISO8601 and actually used it to store the date as a string in YYYY-MM-DD format for the prototype.  But for various arithmetic I have to convert it to some number internally, so I'd prefer to store a number and just convert to string for display.  What units should this number be in, with what origin, and if the units is more precise than days what time of day should be used?

Answer:
If you expect to be handing the date to an external tool or library, you should use whatever format it expects. Unix time seems to be the lingua franca of digital horography, so it's a good default if external circumstances don't make the choice for you.
ISO 8601
may be of interest.
Edit:
But for various arithmetic I have to convert it to some number internally, so I'd prefer to store a number and just convert to string for display.
Ah, that makes sense. If your environment (.NET? Python? C++?) has time-handling tools, it would be best to use their native unit and epoch. There's no reason to re-write all those date-manipulation functions; they're trickier than they look. Otherwise, I'd use days in the local (Gregorian?) calendar since a reasonable epoch for your application. Be generous, you don't want a reverse Y2K bug when you suddenly need to handle a date earlier than you ever expected.
The time of day is entirely a matter of taste. Midnight seems like the cleanest choice (all zeros in the hour, minute, second fields), but since it never reaches the user there's no practical implications. It would be a good spot for an easter egg, in fact.


Question: There is a way to know the flash player version installed on the computer that runs our SWF file with Action Script 3.0?

Answer:
It's in
flash.system.Capabilities.version


Question:
I have inherited a poorly written web application that seems to have errors when it tries to read in an xml document stored in the database that has an "&" in it.  For example there will be a tag with the contents: "Prepaid & Charge".  Is there some secret simple thing to do to have it not get an error parsing that character, or am I missing something obvious?

EDIT:
Are there any other characters that will cause this same type of parser error for not being well formed?

Answer:
You can replace & with
```
&
```
Or you might also be able to use
CDATA
sections.


Question:
I use the on-demand (hosted) version of FogBugz.  I would like to start using Mercurial for source control.  I would like to integrate FogBugz and a BitBucket repository.
I gave it a bit of a try but things weren't going very well.

FogBugz requires that you hook up your Mercurial client to a fogbugz.py python script.  TortoiseHg doesn't seem to have the hgext directory that they refer to in instructions.

So has anyone successfully done something similar?

Answer:
From the sounds of it you are wanting to run the hook on your local machine. The hook and directions are intended for use on the central server.
If you are the only one working in your repository or don't mind commit not showing up in FB until after you do a pull, then you can add the hook locally to your primary clone, If you are using your primary clone then you need to do something slightly different from what they say here:
http://bugs.movabletype.org/help/topics/sourcecontrol/setup/Mercurial.html
You can put your fogbugz.py anywhere you want, just add a path line to your [fogbugz] section of that repositories hgrc file:
```
```
[fogbugz]
path=C:\Program Files\TortoiseHg\scripts\fogbugz.py
```
```
Just make sure you have python installed. you may also wish to add a commit hook so that local commits to the repository also get into FB.
```
```
[hooks]
commit=python:hgext.fogbugz.hook
incoming=python:hgext.fogbugz.hook
```
```
On the Fogbugz install you will want change put the following in your for your logs url:
```
```
^REPO/log/^R2/^FILE
```
```
and the following for your diff url:
```
```
^REPO/diff/^R2/^FILE
```
```
When the hook script runs it connects to your FB install and sends it a few parameters. These parameters are stored in the DB and used to generate urls for diffs and log informaiton. The script sends the url of repo, this is in your baseurl setting in the [web] section. You want this url to be the url to your bitbucket repository. This will be used to replace
^REPO
from the url templates above. The hook script also passes the revision id and the file name to FB. These will replace ^R2 and ^FILE. So in summary this is the stuff you want to add to the hgrc file in your .hg directory:
```
```
[extensions]
hgext.fogbugz=

[fogbugz]
path=C:\Program Files\TortoiseHg\scripts\fogbugz.py
host=https://<YOURACCOUNT>.fogbugz.com/
script=cvsSubmit.asp

[hooks]
commit=python:hgext.fogbugz.hook
incoming=python:hgext.fogbugz.hook

[web]
baseurl=http://www.bitbucket.org/<YOURBITBUCKETACCOUNT>/<YOURPROJECT>/
```
```
One thing to remember is that FB may get notified of a checkin before you actually push those changes to bitbucket. If this is the cause do a push and things will work.
EDIT: added section about the FB server and the summary.


Question: In SQL Server what is the simplest/cleanest way to make a datetime representing the first of the month based on another datetime? eg I have a variable or column with 3-Mar-2005 14:23 and I want to get 1-Mar-2005 00:00 (as a datetime, not as varchar)

Answer:
```
```
SELECT DATEADD(mm, DATEDIFF(mm, 0, @date), 0)
```
```


Question:
We're looking at CouchdDB for a CMS-ish application. What are some common patterns, best practices and workflow advice surrounding backing up our production database?

I'm particularly interested in the process of cloning the database for use in development and testing.

Is it sufficient to just copy the files on disk out from under a live running instance? Can you clone database data between two live running instances?

Advice and description of the techniques you use will be greatly appreciated.

Answer:
CouchDB supports replication, so just replicate to another instance of CouchDB and backup from there, avoiding disturbing where you write changes to.
https://docs.couchdb.org/en/latest/maintenance/backups.html
You literally send a POST request to your CouchDB instance telling it where to replicate to, and it Works(tm)
EDIT: You can just cp out the .couch files in the data directory from under the running database as long as you can accept the I/O hit.


Question:
What is the best way to reduce the size of the viewstate hidden field in JSF?
I have noticed that my view state is approximately 40k this goes down to the client and back to the server on every request and response espically coming to the server this is a significant slowdown for the user.

My Environment JSF 1.2, MyFaces, Tomcat, Tomahawk, RichFaces

Answer:
If you are using MyFaces you can try this setting to compress the viewstate before sending to the client.
```
```
<context-param>
    <param-name>org.apache.myfaces.COMPRESS_STATE_IN_CLIENT</param-name>
    <param-value>true</param-value>
</context-param> `
```
```


Question:
I have the following string and I would like to remove <bpt *>*</bpt> and <ept *>*</ept> (notice the additional tag content inside them that also needs to be removed)  without using a XML parser (overhead too large for tiny strings).

The big <bpt i="1" x="1" type="bold"><b></bpt>black<ept i="1"></b></ept> <bpt i="2" x="2" type="ulined"><u></bpt>cat<ept i="2"></u></ept> sleeps.

Any regex in VB.NET or C# will do.

Answer:
I presume you want to drop the tag entirely?
```
```
(<bpt .*?>.*?</bpt>)|(<ept .*?>.*?</ept>)
```
```
The ? after the * makes it non-greedy, so it will try to match as few characters as possible.
One problem you'll have is nested tags. stuff would not see the second  because the first matched.


Question:
Ok, so we have clients and those clients get to customize their web facing page. One option we are giving them is to be able to change the color of a graphic (it's like a framish-looking bar) using one of those hex wheels or whatever.

So, I've thought about it, and I don't know where to start. I am sending comps out this week to my xhtml guy and I want to have the implementation done at least in my mind before I send things out.

Something about System.Drawing sounds about right, but I've never worked with that before and it sounds hella complicated. Does anyone have an idea?

UPDATE: The color of an image will be changing. So if I want image 1 to be green, and image 2 to be blue, I go into my admin screen and enter those hex values (probably will give them an interface for it) and then when someone else looks at their page they will see the changes they made. Kind of like customizing a facebook or myspace page (OMFGz soooo Werb 2.0)

Answer:
What exactly will be changing? Depending on what's changing you may be able to overlay a transparent png on top of an html background color. Just change the background color and the logo color will change. Of course this limits what you can change, but you'd be surprised how much you can get away with.
And yes, the alternative is to paint the image on the web server.
Here's a post on it from hanselman
.


Question: How does one invoke a groovy method that prints to stdout, appending the output to a string?

Answer:
This demonstrates how you can do this.  Paste this into a Groovy script file and run it.  You will see the first call functions as normal.  The second call produces no results.  Finally, the last step in the main prints the results of the second call that were redirected to a ByteArrayOutputStream.
Have fun!
```
```
void doSomething() {
  println "i did something"
}

println "normal call\n---------------"
doSomething()
println ""

def buf = new ByteArrayOutputStream()
def newOut = new PrintStream(buf)
def saveOut = System.out

println "redirected call\n---------------"
System.out = newOut
doSomething()
System.out = saveOut
println ""

println "results of call\n---------------"
println buf.toString()
```
```


Question:
I am 90% sure I saw this answer on stackoverflow before, in fact I had never seen the "int?" syntax before seeing it here, but no matter how I search I can't find the previous post, and it's driving me crazy.

It's possible that I've been eating the funny mushrooms by accident, but if I'm not, can someone please point out the previous post if they can find it or re-explain it?  My stackoverflow search-fu is apparently too low....

Answer:
int? is shorthand for
```
Nullable<int>
```
.
This
may be the post you were looking for.