qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
106,963 | <p>I'm building the world's simplest library application. All I want to be able to do is scan in a book's UPC (barcode) using a typical scanner (which just types the numbers of the barcode into a field) and then use it to look up data about the book... at a minimum, title, author, year published, and either the Dewey Decimal or Library of Congress catalog number.</p>
<p>The goal is to print out a tiny sticker ("spine label") with the card catalog number that I can stick on the spine of the book, and then I can sort the books by card catalog number on the shelves in our company library. That way books on similar subjects will tend to be near each other, for example, if you know you're looking for a book about accounting, all you have to do is find SOME book about accounting and you'll see the other half dozen that we have right next to it which makes it convenient to browse the library.</p>
<p>There seem to be lots of web APIs to do this, including Amazon and the Library of Congress. But those are all extremely confusing to me. What I really just want is a single higher level function that takes a UPC barcode number and returns some basic data about the book.</p>
| [
{
"answer_id": 106987,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Edit</strong> It would be pretty easy if you had ISBN. but converting from UPC to ISBN is not as easy as ... | 2008/09/20 | [
"https://Stackoverflow.com/questions/106963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4/"
] | I'm building the world's simplest library application. All I want to be able to do is scan in a book's UPC (barcode) using a typical scanner (which just types the numbers of the barcode into a field) and then use it to look up data about the book... at a minimum, title, author, year published, and either the Dewey Decimal or Library of Congress catalog number.
The goal is to print out a tiny sticker ("spine label") with the card catalog number that I can stick on the spine of the book, and then I can sort the books by card catalog number on the shelves in our company library. That way books on similar subjects will tend to be near each other, for example, if you know you're looking for a book about accounting, all you have to do is find SOME book about accounting and you'll see the other half dozen that we have right next to it which makes it convenient to browse the library.
There seem to be lots of web APIs to do this, including Amazon and the Library of Congress. But those are all extremely confusing to me. What I really just want is a single higher level function that takes a UPC barcode number and returns some basic data about the book. | There's a very straightforward web based solution over at ISBNDB.com that you may want to look at.
**Edit:** Updated API documentation link, now there's version 2 available as well
[Link to prices and tiers here](https://isbndb.com/isbn-database)
You can be up and running in just a few minutes (these examples are from API v1):
* register on the site and get a key to use the API
* try a URL like:
`http://isbndb.com/api/books.xml?access_key=`*{yourkey}*`&index1=isbn&results=details&value1=9780143038092`
The results=details gets additional details including the card catalog number.
As an aside, generally the barcode is the isbn in either isbn10 or isbn13. You just have to delete the last 5 numbers if you are using a scanner and you pick up 18 numbers.
Here's a sample response:
```
<ISBNdb server_time="2008-09-21T00:08:57Z">
<BookList total_results="1" page_size="10" page_number="1" shown_results="1">
<BookData book_id="the_joy_luck_club_a12" isbn="0143038095">
<Title>The Joy Luck Club</Title>
<TitleLong/>
<AuthorsText>Amy Tan, </AuthorsText>
<PublisherText publisher_id="penguin_non_classics">Penguin (Non-Classics)</PublisherText>
<Details dewey_decimal="813.54" physical_description_text="288 pages" language="" edition_info="Paperback; 2006-09-21" dewey_decimal_normalized="813.54" lcc_number="" change_time="2006-12-11T06:26:55Z" price_time="2008-09-20T23:51:33Z"/>
</BookData>
</BookList>
</ISBNdb>
``` |
106,965 | <p>Is there a way to read a locked file across a network given that you are the machine admin on the remote machine? I haven't been able to read the locked file locally, and attempting it over the network adds another layer of difficulty.</p>
| [
{
"answer_id": 106987,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Edit</strong> It would be pretty easy if you had ISBN. but converting from UPC to ISBN is not as easy as ... | 2008/09/20 | [
"https://Stackoverflow.com/questions/106965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2712/"
] | Is there a way to read a locked file across a network given that you are the machine admin on the remote machine? I haven't been able to read the locked file locally, and attempting it over the network adds another layer of difficulty. | There's a very straightforward web based solution over at ISBNDB.com that you may want to look at.
**Edit:** Updated API documentation link, now there's version 2 available as well
[Link to prices and tiers here](https://isbndb.com/isbn-database)
You can be up and running in just a few minutes (these examples are from API v1):
* register on the site and get a key to use the API
* try a URL like:
`http://isbndb.com/api/books.xml?access_key=`*{yourkey}*`&index1=isbn&results=details&value1=9780143038092`
The results=details gets additional details including the card catalog number.
As an aside, generally the barcode is the isbn in either isbn10 or isbn13. You just have to delete the last 5 numbers if you are using a scanner and you pick up 18 numbers.
Here's a sample response:
```
<ISBNdb server_time="2008-09-21T00:08:57Z">
<BookList total_results="1" page_size="10" page_number="1" shown_results="1">
<BookData book_id="the_joy_luck_club_a12" isbn="0143038095">
<Title>The Joy Luck Club</Title>
<TitleLong/>
<AuthorsText>Amy Tan, </AuthorsText>
<PublisherText publisher_id="penguin_non_classics">Penguin (Non-Classics)</PublisherText>
<Details dewey_decimal="813.54" physical_description_text="288 pages" language="" edition_info="Paperback; 2006-09-21" dewey_decimal_normalized="813.54" lcc_number="" change_time="2006-12-11T06:26:55Z" price_time="2008-09-20T23:51:33Z"/>
</BookData>
</BookList>
</ISBNdb>
``` |
106,979 | <p>I have two threads, one needs to poll a bunch of separate static resources looking for updates. The other one needs to get the data and store it in the database. How can thread 1 tell thread 2 that there is something to process?</p>
| [
{
"answer_id": 106982,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 3,
"selected": false,
"text": "<p>I use Monitor.Wait / Pulse on a Queue of work items.</p>\n"
},
{
"answer_id": 106994,
"author": "1800 INFORM... | 2008/09/20 | [
"https://Stackoverflow.com/questions/106979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14101/"
] | I have two threads, one needs to poll a bunch of separate static resources looking for updates. The other one needs to get the data and store it in the database. How can thread 1 tell thread 2 that there is something to process? | If the pieces of data are independant then treat the pieces of data as work items to be processed by a pool of threads. Use the thread pool and `QueueUserWorkItem` to post the data to the thread(s). You should get better scalability using a pool of symmetric threads and limiting the amount of synchronisation that has to occur between the producer and consumer(s).
For example (from [MSDN](http://msdn.microsoft.com/en-us/library/4yd16hza.aspx)):
```
TaskInfo ti = new TaskInfo("This report displays the number {0}.", 42);
// Queue the task and data.
if (ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti)) {
Console.WriteLine("Main thread does some work, then sleeps.");
// If you comment out the Sleep, the main thread exits before
// the ThreadPool task has a chance to run. ThreadPool uses
// background threads, which do not keep the application
// running. (This is a simple example of a race condition.)
Thread.Sleep(1000);
Console.WriteLine("Main thread exits.");
}
else {
Console.WriteLine("Unable to queue ThreadPool request.");
}
// The thread procedure performs the independent task, in this case
// formatting and printing a very simple report.
//
static void ThreadProc(Object stateInfo) {
TaskInfo ti = (TaskInfo) stateInfo;
Console.WriteLine(ti.Boilerplate, ti.Value);
}
``` |
107,018 | <p>There are a couple of different .NET XSLT functions that I see used in the out of the box SharePoint web parts (RSS Viewer and Data View web part).</p>
<pre><code><xsl:stylesheet
xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
xmlns:rssaggwrt="http://schemas.microsoft.com/WebParts/v3/rssagg/runtime"
...>
...
<xsl:value-of select="rssaggwrt:MakeSafe($Html)"/>
<a href="{ddwrt:EnsureAllowedProtocol(string(link))}">More...</a>
...
</xsl:stylesheet>
</code></pre>
<p>Where can I find a reference that describes all of the extension functions that SharePoint provides?</p>
| [
{
"answer_id": 107021,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 1,
"selected": false,
"text": "<p>Here is some documentation I found that describes the ddwrt (<a href=\"http://schemas.microsoft.com/WebParts/v2/D... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] | There are a couple of different .NET XSLT functions that I see used in the out of the box SharePoint web parts (RSS Viewer and Data View web part).
```
<xsl:stylesheet
xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
xmlns:rssaggwrt="http://schemas.microsoft.com/WebParts/v3/rssagg/runtime"
...>
...
<xsl:value-of select="rssaggwrt:MakeSafe($Html)"/>
<a href="{ddwrt:EnsureAllowedProtocol(string(link))}">More...</a>
...
</xsl:stylesheet>
```
Where can I find a reference that describes all of the extension functions that SharePoint provides? | I have been wanting more info on ddwrt as well. The most information I have been able to find is from Serge van den Oever that was later turned into the MSDN article referenced in the previous answer.
<http://weblogs.asp.net/soever/archive/2005/01/03/345535.aspx>
As he noted in his blog post, this article contains some info that was censored in the MSDN article.
Other than this article, there is very little written on the topic. It unfortunately appears that scouring existing generated code (such as the xsl in DataForm web parts) is the best technique to learn more at present. |
107,049 | <p>We have a rather simple site (minimal JS) with plain html and CSS. It is a simple mobile interface for our main application.</p>
<p>We are running into trouble because we have more than one column and several browsers seem to force single columns.</p>
<p>Through some searching I ran into 2 meta tags.</p>
<pre><code><meta name="MobileOptimized" content="220" />
<meta name="viewport" content="width=320" />
</code></pre>
<p>With these we have a good 'scaled' view for IE Mobile and the iPhone. We have not run into any problems with palm's Blazer. But Blackberry is another matter.</p>
<p>Does the Blackberry have a simple way to control the view of the browser as well? By simple I mean without making a special page for that device.</p>
| [
{
"answer_id": 107366,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>My recommendation would be to create two or three versions of the site:</p>\n\n<ul>\n<li>Full blown site for modern desktop... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4923/"
] | We have a rather simple site (minimal JS) with plain html and CSS. It is a simple mobile interface for our main application.
We are running into trouble because we have more than one column and several browsers seem to force single columns.
Through some searching I ran into 2 meta tags.
```
<meta name="MobileOptimized" content="220" />
<meta name="viewport" content="width=320" />
```
With these we have a good 'scaled' view for IE Mobile and the iPhone. We have not run into any problems with palm's Blazer. But Blackberry is another matter.
Does the Blackberry have a simple way to control the view of the browser as well? By simple I mean without making a special page for that device. | I wouldn't bother making a "medium" version for the iPhone etc, iPhone users can just look at your real web page easily enough. Have your full version and a single column version, and you'll reach the largest audience with minimal work.
To answer your question though, there's no good way to make the Blackberry do anything other than 1 column views. You can get it to look fairly professional, as CSS and simple javascript still apply, but you'll have to lose a lot of your horizontal real estate. |
107,054 | <p>I'm trying to implement an outdent of the first letter of the first paragraph of the body text. Where I'm stuck is in getting consistent spacing between the first letter and the rest of the paragraph. </p>
<p>For example, there is a huge difference in spacing between a "W" and an "I"</p>
<p><img src="https://i.stack.imgur.com/2TsvYm.png" alt="'I' Outdent"><br>
<img src="https://i.stack.imgur.com/DnZVSm.png" alt="'W' Outdent"></p>
<p>Anyone have any ideas about how to mitigate the differences? I'd prefer a pure CSS solution, but will resort to JavaScript if need be.</p>
<p><strong>PS</strong>: I don't necessarily need compatibility in IE or Opera</p>
| [
{
"answer_id": 107111,
"author": "Matthew Rapati",
"author_id": 15000,
"author_profile": "https://Stackoverflow.com/users/15000",
"pm_score": 0,
"selected": false,
"text": "<p>I tried using a fix-width font like 'courier new' and since the characters are more or less the same width it ma... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11577/"
] | I'm trying to implement an outdent of the first letter of the first paragraph of the body text. Where I'm stuck is in getting consistent spacing between the first letter and the rest of the paragraph.
For example, there is a huge difference in spacing between a "W" and an "I"


Anyone have any ideas about how to mitigate the differences? I'd prefer a pure CSS solution, but will resort to JavaScript if need be.
**PS**: I don't necessarily need compatibility in IE or Opera | Apply this to `p.outdent:first-letter`:
```
margin-left: -800px;
padding-right: 460px;
float: right;
```
This will position the first letter on the right edge of the paragraph, then shove it left it by more or less the width of the paragraph, then move both the letter and all the padding into the float's large negative margin so the paragraph fits in the margin and doesn't try to wrap around. |
107,117 | <p>I noticed that you can call Queue.Synchronize to get a thread-safe queue object, but the same method isn't available on Queue<T>. Does anyone know why? Seems kind of weird.</p>
| [
{
"answer_id": 107133,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 0,
"selected": false,
"text": "<p>(I assume you mean Queue<T> for the second one.)</p>\n\n<p>I can't specifically answer the question, except that the Is... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14101/"
] | I noticed that you can call Queue.Synchronize to get a thread-safe queue object, but the same method isn't available on Queue<T>. Does anyone know why? Seems kind of weird. | **Update** - in .NET 4, there now is `ConcurrentQueue<T>` in System.Collections.Concurrent, as documented here <http://msdn.microsoft.com/en-us/library/dd267265.aspx>. It's interesting to note that its IsSynchronized method (rightly) returns false.
`ConcurrentQueue<T>` is a complete ground up rewrite, creating copies of the queue to enumerate, and using advanced no-lock techniques like `Interlocked.CompareExchange()` and `Thread.SpinWait()`.
The rest of this answer is still relevant insofar as it relates to the demise of the old Synchronize() and SyncRoot members, and why they didn't work very well from an API perspective.
---
As per Zooba's comment, the BCL team decided that too many developers were misunderstanding the purpose of Synchronise (and to a lesser extent, SyncRoot)
Brian Grunkemeyer described this on the BCL team blog a couple of years back:
<http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx>
The key issue is getting the correct granularity around locks, where some developers would naively use multiple properties or methods on a "synchronized" collection and believe their code to be thread safe. Brian uses Queue as his example,
```
if (queue.Count > 0) {
object obj = null;
try {
obj = queue.Dequeue();
```
Developers wouldn't realize that Count could be changed by another thread before Dequeue was invoked.
Forcing developers to use an explicit lock statement around the whole operation means preventing this false sense of security.
As Brian mentions, the removal of SyncRoot was partly because it had mainly been introduced to support Synchronized, but also because in many cases there is a better choice of lock object - most of the time, either the Queue instance itself, or a
```
private static object lockObjForQueueOperations = new object();
```
on the class owning the instance of the Queue...
This latter approach is usually safest as it avoids some other common traps:
* [Never lock(this)](https://haacked.com/archive/2006/08/08/threadingneverlockthisredux.aspx/)
* [Don't lock(string) or lock(typeof(A))](http://blogs.msdn.com/ricom/archive/2003/12/06/41779.aspx)
As they say, [threading is hard](http://blogs.msdn.com/jmstall/archive/2008/01/30/why-threading-is-hard.aspx), and making it seem easy can be dangerous. |
107,132 | <p>As a follow up to "<a href="https://stackoverflow.com/questions/105400/what-are-indexes-and-how-can-i-use-them-to-optimize-queries-in-my-database">What are indexes and how can I use them to optimise queries in my database?</a>" where I am attempting to learn about indexes, what columns are good index candidates? Specifically for an MS SQL database?</p>
<p>After some googling, everything I have read suggests that columns that are generally increasing and unique make a good index (things like MySQL's auto_increment), I understand this, but I am using MS SQL and I am using GUIDs for primary keys, so it seems that indexes would not benefit GUID columns...</p>
| [
{
"answer_id": 107142,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 3,
"selected": false,
"text": "<p>In general (I don't use mssql so can't comment specifically), primary keys make good indexes. They are unique and must have a... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | As a follow up to "[What are indexes and how can I use them to optimise queries in my database?](https://stackoverflow.com/questions/105400/what-are-indexes-and-how-can-i-use-them-to-optimize-queries-in-my-database)" where I am attempting to learn about indexes, what columns are good index candidates? Specifically for an MS SQL database?
After some googling, everything I have read suggests that columns that are generally increasing and unique make a good index (things like MySQL's auto\_increment), I understand this, but I am using MS SQL and I am using GUIDs for primary keys, so it seems that indexes would not benefit GUID columns... | Indexes can play an important role in query optimization and searching the results speedily from tables. The most important step is to select which columns are to be indexed. There are two major places where we can consider indexing: columns referenced in the WHERE clause and columns used in JOIN clauses. In short, such columns should be indexed against which you are required to search particular records. Suppose, we have a table named buyers where the SELECT query uses indexes like below:
```
SELECT
buyer_id /* no need to index */
FROM buyers
WHERE first_name='Tariq' /* consider indexing */
AND last_name='Iqbal' /* consider indexing */
```
Since "buyer\_id" is referenced in the SELECT portion, MySQL will not use it to limit the chosen rows. Hence, there is no great need to index it. The below is another example little different from the above one:
```
SELECT
buyers.buyer_id, /* no need to index */
country.name /* no need to index */
FROM buyers LEFT JOIN country
ON buyers.country_id=country.country_id /* consider indexing */
WHERE
first_name='Tariq' /* consider indexing */
AND
last_name='Iqbal' /* consider indexing */
```
According to the above queries first\_name, last\_name columns can be indexed as they are located in the WHERE clause. Also an additional field, country\_id from country table, can be considered for indexing because it is in a JOIN clause. So indexing can be considered on every field in the WHERE clause or a JOIN clause.
The following list also offers a few tips that you should always keep in mind when intend to create indexes into your tables:
* Only index those columns that are required in WHERE and ORDER BY clauses. Indexing columns in abundance will result in some disadvantages.
* Try to take benefit of "index prefix" or "multi-columns index" feature of MySQL. If you create an index such as INDEX(first\_name, last\_name), don’t create INDEX(first\_name). However, "index prefix" or "multi-columns index" is not recommended in all search cases.
* Use the NOT NULL attribute for those columns in which you consider the indexing, so that NULL values will never be stored.
* Use the --log-long-format option to log queries that aren’t using indexes. In this way, you can examine this log file and adjust your queries accordingly.
* The EXPLAIN statement helps you to reveal that how MySQL will execute a query. It shows how and in what order tables are joined. This can be much useful for determining how to write optimized queries, and whether the columns are needed to be indexed.
**Update (23 Feb'15):**
Any index (good/bad) increases insert and update time.
Depending on your indexes (number of indexes and type), result is searched. If your search time is gonna increase because of index then that's bad index.
Likely in any book, "Index Page" could have chapter start page, topic page number starts, also sub topic page starts. Some clarification in Index page helps but more detailed index might confuse you or scare you. Indexes are also having memory.
Index selection should be wise. Keep in mind not all columns would require index. |
107,150 | <p>How do I capture the event of the clicking the Selected Node of a TreeView?
It doesn't fire the <strong>SelectedNodeChanged</strong> since the selection has obviously not changed but then what event can I catch so I know that the Selected Node was clicked?</p>
<p><strong>UPDATE</strong>:
When I have some time, I'm going to have to dive into the bowels of the TreeView control and dig out what and where it handles the click events and subclass the TreeView to expose a new event OnSelectedNodeClicked.</p>
<p>I'll probably do this over the Christmas holidays and I'll report back with the results.</p>
<p><strong>UPDATE</strong>:
I have come up with a solution below that sub-classes the TreeView control.</p>
| [
{
"answer_id": 107298,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 3,
"selected": false,
"text": "<p>Easiest way - if it doesn't interfere with the rest of your code - is to simply set the node as not selected in the Selecte... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19377/"
] | How do I capture the event of the clicking the Selected Node of a TreeView?
It doesn't fire the **SelectedNodeChanged** since the selection has obviously not changed but then what event can I catch so I know that the Selected Node was clicked?
**UPDATE**:
When I have some time, I'm going to have to dive into the bowels of the TreeView control and dig out what and where it handles the click events and subclass the TreeView to expose a new event OnSelectedNodeClicked.
I'll probably do this over the Christmas holidays and I'll report back with the results.
**UPDATE**:
I have come up with a solution below that sub-classes the TreeView control. | Easiest way - if it doesn't interfere with the rest of your code - is to simply set the node as not selected in the SelectedNodeChanged method.
```
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e){
// Do whatever you're doing
TreeView1.SelectedNode.Selected = false;
}
``` |
107,160 | <p>I recently started work on a personal coding project using C++ and KDevelop. Although I started out by just hacking around, I figure it'll be better in the long run if I set up a proper unit test suite before going too much further. I've created a seperate test-runner executable as a sub project, and the tests I've added to it appear to function properly. So far, success.</p>
<p>However, I'd really like to get my unit tests running every time I build, not only when I explicitly run them. This will be especially true as I split up the mess I've made into convenience libraries, each of which will probably have its own test executable. Rather than run them all by hand, I'd like to get them to run as the final step in my build process. I've looked all through the options in the project menu and the automake manager, but I can't figure out how to set this up.</p>
<p>I imagine this could probably be done by editing the makefile by hand. Unfortunately, my makefile-fu is a bit weak, and I'm also afraid that KDevelop might overwrite any changes I make by hand the next time I change something through the IDE. Therefore, if there's an option on how to do this through KDevelop itself, I'd much prefer to go that way.</p>
<p>Does anybody know how I could get KDevelop to run my test executables as part of the build process? Thank you!</p>
<p>(I'm not 100% tied to KDevelop. If KDevelop can't do this, or else if there's an IDE that makes this much easier, I could be convinced to switch.)</p>
| [
{
"answer_id": 108086,
"author": "vog",
"author_id": 19163,
"author_profile": "https://Stackoverflow.com/users/19163",
"pm_score": 3,
"selected": true,
"text": "<p>\nAlthough you <i>could</i> manipulate the default `make` target to run your tests,\nit is generally not recommended, becaus... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19491/"
] | I recently started work on a personal coding project using C++ and KDevelop. Although I started out by just hacking around, I figure it'll be better in the long run if I set up a proper unit test suite before going too much further. I've created a seperate test-runner executable as a sub project, and the tests I've added to it appear to function properly. So far, success.
However, I'd really like to get my unit tests running every time I build, not only when I explicitly run them. This will be especially true as I split up the mess I've made into convenience libraries, each of which will probably have its own test executable. Rather than run them all by hand, I'd like to get them to run as the final step in my build process. I've looked all through the options in the project menu and the automake manager, but I can't figure out how to set this up.
I imagine this could probably be done by editing the makefile by hand. Unfortunately, my makefile-fu is a bit weak, and I'm also afraid that KDevelop might overwrite any changes I make by hand the next time I change something through the IDE. Therefore, if there's an option on how to do this through KDevelop itself, I'd much prefer to go that way.
Does anybody know how I could get KDevelop to run my test executables as part of the build process? Thank you!
(I'm not 100% tied to KDevelop. If KDevelop can't do this, or else if there's an IDE that makes this much easier, I could be convinced to switch.) | Although you *could* manipulate the default `make` target to run your tests,
it is generally not recommended, because every invocation of
```
make
```
would run all the tests.
You should use the "check" target instead,
which is an accepted quasi-standard among software packages.
By doing that,
the tests are only started when you run
```
make check
```
You can then easily configure KDevelop
to run "make check" instead of just "make".
Since you are using automake (through KDevelop),
you don't need to write the "check" target yourself.
Instead, just edit your `Makefile.am` and set some variables:
```
TESTS = ...
```
Please have a look at the
[automake documentation, "Support for test suites"](http://www.gnu.org/software/automake/manual/html_node/Tests.html#Tests)
for further information. |
107,196 | <p>When I do a clean build my C# project, the produced dll is different then the previously built one (which I saved separately). No code changes were made, just clean and rebuild. </p>
<p>Diff shows some bytes in the DLL have changes -- few near the beginning and few near the end, but I can't figure out what these represent. Does anybody have insights on why this is happening and how to prevent it? </p>
<p>This is using Visual Studio 2005 / WinForms.</p>
<p><strong>Update:</strong> Not using automatic version incrementing, or signing the assembly. If it's a timestamp of some sort, how to I prevent VS from writing it? </p>
<p><strong>Update:</strong> After looking in Ildasm/diff, it seems like the following items are different:</p>
<ul>
<li>Two bytes in PE header at the start of the file.</li>
<li><PrivateImplementationDetails>{<em>guid</em>} section </li>
<li>Cryptic part of the string table near the end (wonder why, I did not change the strings)</li>
<li>Parts of assembly info at the end of file.</li>
</ul>
<p>No idea how to eliminate any of these, if at all possible...</p>
| [
{
"answer_id": 107202,
"author": "Slapout",
"author_id": 19072,
"author_profile": "https://Stackoverflow.com/users/19072",
"pm_score": -1,
"selected": false,
"text": "<p>Could be that the build or revision numbers have changed. </p>\n"
},
{
"answer_id": 107435,
"author": "Mag... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] | When I do a clean build my C# project, the produced dll is different then the previously built one (which I saved separately). No code changes were made, just clean and rebuild.
Diff shows some bytes in the DLL have changes -- few near the beginning and few near the end, but I can't figure out what these represent. Does anybody have insights on why this is happening and how to prevent it?
This is using Visual Studio 2005 / WinForms.
**Update:** Not using automatic version incrementing, or signing the assembly. If it's a timestamp of some sort, how to I prevent VS from writing it?
**Update:** After looking in Ildasm/diff, it seems like the following items are different:
* Two bytes in PE header at the start of the file.
* <PrivateImplementationDetails>{*guid*} section
* Cryptic part of the string table near the end (wonder why, I did not change the strings)
* Parts of assembly info at the end of file.
No idea how to eliminate any of these, if at all possible... | My best guess would be the changed bytes you're seeing are the internally-used metadata columns that are automatically generated at build-time.
Some of the Ecma-335 Partition II (CLI Specification Metadata Definition) columns that can change per-build, even if the source code doesn't change at all:
* Module.Mvid: A build-time-generated GUID. Always changes, every build.
* AssemblyRef.HashValue: Could change if you're referencing another assembly that has also been rebuilt since the old build.
If this really, really bothers you, my best tip on finding out exactly what is changing would be to diff the actual metadata tables. The way to get these is to use the ildasm MetaInfo window:
```
View > MetaInfo > Raw:Header,Schema,Rows // important, otherwise you get very basic info from the next step
View > MetaInfo > Show!
``` |
107,292 | <p>We are starting a new SOA project with a lot of shared .net assemblies. The code for these assemblies will be stored in SVN.</p>
<p>In development phase, we would like to be able to code these assemblies as an entire solution with as little SVN 'friction' as possible. </p>
<p>When the project enters more of a maintenance mode, the assemblies will be maintained on an individual level.</p>
<p>Without making Branching, Tagging, and Automated Builds a maintenance nightmare, what's the best way to organize these libraries in SVN that also works well with the VS 2008 IDE?</p>
<p>Do you setup Trunk/Branches/Tags at each library level and try to spaghetti it all together somehow at compile time, or is it better to keep it all as one big project with code replicated here and there for simplicity? Is there a solution using externs?</p>
| [
{
"answer_id": 107308,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 0,
"selected": false,
"text": "<p>What we did with shared assemblies during development phase (in a project which had loads of these), is that we put them on... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6354/"
] | We are starting a new SOA project with a lot of shared .net assemblies. The code for these assemblies will be stored in SVN.
In development phase, we would like to be able to code these assemblies as an entire solution with as little SVN 'friction' as possible.
When the project enters more of a maintenance mode, the assemblies will be maintained on an individual level.
Without making Branching, Tagging, and Automated Builds a maintenance nightmare, what's the best way to organize these libraries in SVN that also works well with the VS 2008 IDE?
Do you setup Trunk/Branches/Tags at each library level and try to spaghetti it all together somehow at compile time, or is it better to keep it all as one big project with code replicated here and there for simplicity? Is there a solution using externs? | What we did at our company was to set up a **tools** repository, and then a **project** repository. The **tools** repository is a Subversion repository, organized as follows:
```
/svn/tools/
vendor1/
too11/
1.0/
1.1/
latest = a copy of vendor1/tool1/1.1
tool2/
1.0/
1.5/
latest = a copy of vendor1/tool2/1.5
vendor2/
foo/
1.0.0/
1.1.0/
1.2.0/
latest = a copy of vendor2/foo/1.2.0
```
Every time we get a new version of a tool from a vendor, it is added under its vendor, name, and version number, and the 'latest' tag is updated.
**[Clarification:** this is NOT a typical source respository -- it's intended to store specific versions of 'installed' images. Thus /svn/tools/nunit/nunit2/2.4 would be the top of a directory tree containing the results of installing NUnit 2.4 to a directory and importing it into the tools repository. Source and examples may be present, but the primary focus is on executables and libraries that are necessary to use the tool. If we needed to modify a vendor tool, we'd do that in a separate repository, and release the result to this repository.**]**
One of the vendors is my company, and has a separate section for each tool, assembly, whatever that we release internally.
---
The **projects** repository is a standard Subversion repository, with trunks, tags, and branches as you normally expect. Any given project will look like:
```
/svn/
branches/
tags/
trunk/
foo/
source/
tools/
publish/
foo-build.xml (for NAnt)
foo.build (for MSBuild)
```
The tools directory has a Subversion **svn:externals** property set, that links in the appropriate version (either a specific version or 'latest') of each tool or assembly that is needed by that project. When the 'foo' project is built by CruiseControl.NET, the publish task will populate the 'publish' directory as the 'foo' assembly is intended to be deployed, and then executes the following subversion commands:
```
svn import publish /svn/tools/vendor2/foo/1.2.3
svn delete /svn/tools/vendor2/foo/latest
svn copy /svn/tools/vendor2/foo/1.2.3 /svn/tools/vendor2/foo/latest
```
Developers work on their projects as normal, and let the build automation take care of the details. A normal subversion update will pull the latest versions of external tools as well as as project updates.
If you've got a lot of tool interdependency, you can configure CruiseControl.NET (by hand) to trigger builds for subordinate projects when their dependencies change, but we haven't needed to go that far yet.
>
> Note: All of the Subversion repository paths have been shortened for clarity. We actually use Apache+SVN, and two separate servers, but you should adapt this as you see fit.
>
>
> |
107,294 | <p>I understand the overall meaning of pointers and references(or at least I think i do), I also understand that when I use <b>new</b> I am dynamically allocating memory.</p>
<p>My question is the following:</p>
<p>If i were to use <code>cout << &p</code>, it would display the "virtual memory location" of <code>p</code>.
Is there a way in which I could manipulate this "virtual memory location?"</p>
<p>For example, the following code shows an array of <code>int</code>s.</p>
<p>If I wanted to show the value of <code>p[1]</code> and I knew the "virtual memory location" of <code>p</code>, could I somehow do "<code>&p + 1</code>" and obtain the value of <code>p[1]</code> with <code>cout << *p</code>, which will now point to the second element in the array?</p>
<pre><code>int *p;
p = new int[3];
p[0] = 13;
p[1] = 54;
p[2] = 42;
</code></pre>
| [
{
"answer_id": 107301,
"author": "KTC",
"author_id": 12868,
"author_profile": "https://Stackoverflow.com/users/12868",
"pm_score": 4,
"selected": true,
"text": "<p>Sure, you can manipulate the pointer to access the different elements in the array, but you will need to manipulate the cont... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17162/"
] | I understand the overall meaning of pointers and references(or at least I think i do), I also understand that when I use **new** I am dynamically allocating memory.
My question is the following:
If i were to use `cout << &p`, it would display the "virtual memory location" of `p`.
Is there a way in which I could manipulate this "virtual memory location?"
For example, the following code shows an array of `int`s.
If I wanted to show the value of `p[1]` and I knew the "virtual memory location" of `p`, could I somehow do "`&p + 1`" and obtain the value of `p[1]` with `cout << *p`, which will now point to the second element in the array?
```
int *p;
p = new int[3];
p[0] = 13;
p[1] = 54;
p[2] = 42;
``` | Sure, you can manipulate the pointer to access the different elements in the array, but you will need to manipulate the content of the pointer (i.e. the address of what p is pointing to), rather than the address of the pointer itself.
```
int *p = new int[3];
p[0] = 13;
p[1] = 54;
p[2] = 42;
cout << *p << ' ' << *(p+1) << ' ' << *(p+2);
```
Each addition (or subtraction) mean the subsequent (prior) element in the array. If p points to a 4 byte variable (e.g. *int* on typical 32-bits PCs) at address say 12345, p+1 will point to 12349, and not 12346. Note you want to change the value of what p contains before dereferencing it to access what it points to. |
107,314 | <p>We've been using selenium with great success to handle high-level website testing (in addition to extensive python doctests at a module level). However now we're using extjs for a lot of pages and its proving difficult to incorporate Selenium tests for the complex components like grids. </p>
<p>Has anyone had success writing automated tests for extjs-based web pages? Lots of googling finds people with similar problems, but few answers. Thanks!</p>
| [
{
"answer_id": 107369,
"author": "Ryan Guest",
"author_id": 1811,
"author_profile": "https://Stackoverflow.com/users/1811",
"pm_score": 2,
"selected": false,
"text": "<p>Can you provide more insight into the types of problems you're having with extjs testing?</p>\n\n<p>One Selenium exten... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19506/"
] | We've been using selenium with great success to handle high-level website testing (in addition to extensive python doctests at a module level). However now we're using extjs for a lot of pages and its proving difficult to incorporate Selenium tests for the complex components like grids.
Has anyone had success writing automated tests for extjs-based web pages? Lots of googling finds people with similar problems, but few answers. Thanks! | The biggest hurdle in testing ExtJS with Selenium is that ExtJS doesn't render standard HTML elements and the Selenium IDE will naively (and rightfully) generate commands targeted at elements that just act as decor -- superfluous elements that help ExtJS with the whole desktop-look-and-feel. Here are a few tips and tricks that I've gathered while writing automated Selenium test against an ExtJS app.
General Tips
============
Locating Elements
-----------------
When generating Selenium test cases by recording user actions with Selenium IDE on Firefox, Selenium will base the recorded actions on the ids of the HTML elements. However, for most clickable elements, ExtJS uses generated ids like "ext-gen-345" which are likely to change on a subsequent visit to the same page, even if no code changes have been made. After recording user actions for a test, there needs to be a manual effort to go through all such actions that depend on generated ids and to replace them. There are two types of replacements that can be made:
Replacing an Id Locator with a CSS or XPath Locator
---------------------------------------------------
CSS locators begin with "css=" and XPath locators begin with "//" (the "xpath=" prefix is optional). CSS locators are less verbose and are easier to read and should be preferred over XPath locators. However, there can be cases where XPath locators need to be used because a CSS locator simply can't cut it.
Executing JavaScript
--------------------
Some elements require more than simple mouse/keyboard interactions due to the complex rendering carried out by ExtJS. For example, a Ext.form.CombBox is not really a `<select>` element but a text input with a detached drop-down list that's somewhere at the bottom of the document tree. In order to properly simulate a ComboBox selection, it's possible to first simulate a click on the drop-down arrow and then to click on the list that appears. However, locating these elements through CSS or XPath locators can be cumbersome. An alternative is to locate the ComoBox component itself and call methods on it to simulate the selection:
```
var combo = Ext.getCmp('genderComboBox'); // returns the ComboBox components
combo.setValue('female'); // set the value
combo.fireEvent('select'); // because setValue() doesn't trigger the event
```
In Selenium the `runScript` command can be used to perform the above operation in a more concise form:
```
with (Ext.getCmp('genderComboBox')) { setValue('female'); fireEvent('select'); }
```
Coping with AJAX and Slow Rendering
-----------------------------------
Selenium has "\*AndWait" flavors for all commands for waiting for page loads when a user action results in page transitions or reloads. However, since AJAX fetches don't involve actual page loads, these commands can't be used for synchronization. The solution is to make use of visual clues like the presence/absence of an AJAX progress indicator or the appearance of rows in a grid, additional components, links etc. For example:
```
Command: waitForElementNotPresent
Target: css=div:contains('Loading...')
```
Sometimes an element will appear only after a certain amount of time, depending on how fast ExtJS renders components after a user action results in a view change. Instead of using arbitary delays with the `pause` command, the ideal method is to wait until the element of interest comes within our grasp. For example, to click on an item after waiting for it to appear:
```
Command: waitForElementPresent
Target: css=span:contains('Do the funky thing')
Command: click
Target: css=span:contains('Do the funky thing')
```
Relying on arbitrary pauses is not a good idea since timing differences that result from running the tests in different browsers or on different machines will make the test cases flaky.
Non-clickable Items
-------------------
Some elements can't be triggered by the `click` command. It's because the event listener is actually on the container, watching for mouse events on its child elements, that eventually bubble up to the parent. The tab control is one example. To click on the a tab, you have to simulate a `mouseDown` event at the tab label:
```
Command: mouseDownAt
Target: css=.x-tab-strip-text:contains('Options')
Value: 0,0
```
Field Validation
----------------
Form fields (Ext.form.\* components) that have associated regular expressions or vtypes for validation will trigger validation with a certain delay (see the `validationDelay` property which is set to 250ms by default), after the user enters text or immediately when the field loses focus -- or blurs (see the `validateOnDelay` property). In order to trigger field validation after issuing the type Selenium command to enter some text inside a field, you have to do either of the following:
* **Triggering Delayed Validation**
ExtJS fires off the validation delay timer when the field receives keyup events. To trigger this timer, simply issue a dummy keyup event (it doesn't matter which key you use as ExtJS ignores it), followed by a short pause that is longer than the validationDelay:
```
Command: keyUp
Target: someTextArea
Value: x
Command: pause
Target: 500
```
* **Triggering Immediate Validation**
You can inject a blur event into the field to trigger immediate validation:
```
Command: runScript
Target: someComponent.nameTextField.fireEvent("blur")
```
Checking for Validation Results
-------------------------------
Following validation, you can check for the presence or absence of an error field:
```
Command: verifyElementNotPresent
Target: //*[@id="nameTextField"]/../*[@class="x-form-invalid-msg" and not(contains(@style, "display: none"))]
Command: verifyElementPresent
Target: //*[@id="nameTextField"]/../*[@class="x-form-invalid-msg" and not(contains(@style, "display: none"))]
```
Note that the "display: none" check is necessary because once an error field is shown and then it needs to be hidden, ExtJS will simply hide error field instead of entirely removing it from the DOM tree.
Element-specific Tips
=====================
Clicking an Ext.form.Button
---------------------------
* **Option 1**
Command: click
Target: css=button:contains('Save')
Selects the button by its caption
* **Option 2**
Command: click
Target: css=#save-options button
Selects the button by its id
Selecting a Value from an Ext.form.ComboBox
-------------------------------------------
```
Command: runScript
Target: with (Ext.getCmp('genderComboBox')) { setValue('female'); fireEvent('select'); }
```
First sets the value and then explicitly fires the select event in case there are observers. |
107,382 | <p>I am wondering if it is possible to extract the index position in a given string where a Regex failed when trying to match it? </p>
<p>For example, if my regex was "abc" and I tried to match that with "abd" the match would fail at index 2.</p>
<p>Edit for clarification. The reason I need this is to allow me to simplify the parsing component of my application. The application is an Assmebly language teaching tool which allows students to write, compile, and execute assembly like programs. </p>
<p>Currently I have a tokenizer class which converts input strings into Tokens using regex's. This works very well. For example:</p>
<p>The tokenizer would produce the following tokens given the following input = "INP :x:"<br>:</p>
<pre><code>Token.OPCODE, Token.WHITESPACE, Token.LABEL, Token.EOL
</code></pre>
<p>These tokens are then analysed to ensure they conform to a syntax for a given statement. Currently this is done using IF statements and is proving cumbersome. The upside of this approach is that I can provide detailed error messages. I.E</p>
<pre><code>if(token[2] != Token.LABEL) { throw new SyntaxError("Expected label");}
</code></pre>
<p>I want to use a regular expression to define a syntax instead of the annoying IF statements. But in doing so I lose the ability to return detailed error reports. I therefore would at least like to inform the user of WHERE the error occurred.</p>
| [
{
"answer_id": 107410,
"author": "Max Galkin",
"author_id": 2351099,
"author_profile": "https://Stackoverflow.com/users/2351099",
"pm_score": 1,
"selected": false,
"text": "<p>I guess such an index would only have meaning in some simple case, like in your example.</p>\n\n<p>If you'll tak... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15075/"
] | I am wondering if it is possible to extract the index position in a given string where a Regex failed when trying to match it?
For example, if my regex was "abc" and I tried to match that with "abd" the match would fail at index 2.
Edit for clarification. The reason I need this is to allow me to simplify the parsing component of my application. The application is an Assmebly language teaching tool which allows students to write, compile, and execute assembly like programs.
Currently I have a tokenizer class which converts input strings into Tokens using regex's. This works very well. For example:
The tokenizer would produce the following tokens given the following input = "INP :x:"
:
```
Token.OPCODE, Token.WHITESPACE, Token.LABEL, Token.EOL
```
These tokens are then analysed to ensure they conform to a syntax for a given statement. Currently this is done using IF statements and is proving cumbersome. The upside of this approach is that I can provide detailed error messages. I.E
```
if(token[2] != Token.LABEL) { throw new SyntaxError("Expected label");}
```
I want to use a regular expression to define a syntax instead of the annoying IF statements. But in doing so I lose the ability to return detailed error reports. I therefore would at least like to inform the user of WHERE the error occurred. | I agree with Colin Younger, I don't think it is possible with the existing Regex class. However, I think it is doable if you are willing to sweat a little:
1. Get the Regex class source code
(e.g.
<http://www.codeplex.com/NetMassDownloader>
to download the .Net source).
2. Change the code to have a readonly
property with the failure index.
3. Make sure your code uses that Regex
rather than Microsoft's. |
107,405 | <p>What I'm trying to do here is get the headers of a given URL so I can determine the MIME type. I want to be able to see if <code>http://somedomain/foo/</code> will return an HTML document or a JPEG image for example. Thus, I need to figure out how to send a HEAD request so that I can read the MIME type without having to download the content. Does anyone know of an easy way of doing this?</p>
| [
{
"answer_id": 107427,
"author": "Eevee",
"author_id": 17875,
"author_profile": "https://Stackoverflow.com/users/17875",
"pm_score": 8,
"selected": true,
"text": "<p><strong>edit</strong>: This answer works, but nowadays you should just use the <a href=\"http://docs.python-requests.org/e... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
] | What I'm trying to do here is get the headers of a given URL so I can determine the MIME type. I want to be able to see if `http://somedomain/foo/` will return an HTML document or a JPEG image for example. Thus, I need to figure out how to send a HEAD request so that I can read the MIME type without having to download the content. Does anyone know of an easy way of doing this? | **edit**: This answer works, but nowadays you should just use the [requests](http://docs.python-requests.org/en/latest/index.html) library as mentioned by other answers below.
---
Use [httplib](https://docs.python.org/2/library/httplib.html).
```
>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.com")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> print res.status, res.reason
200 OK
>>> print res.getheaders()
[('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]
```
There's also a `getheader(name)` to get a specific header. |
107,414 | <p>As a base SAS programmer, you know the drill:</p>
<p>You submit your SAS code, which contains an unbalanced quote, so now you've got not only and unclosed quote, but also unclosed comments, macro function definitions, and a missing run; or quit; statement.</p>
<p>What's your best trick for not having those unbalanced quotes bother you?</p>
| [
{
"answer_id": 107443,
"author": "Martin Bøgelund",
"author_id": 18968,
"author_profile": "https://Stackoverflow.com/users/18968",
"pm_score": 3,
"selected": false,
"text": "<p>As for myself, I usually <a href=\"http://www.google.dk/search?q=sas+unbalanced+quote&ie=utf-8&oe=utf-8... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18968/"
] | As a base SAS programmer, you know the drill:
You submit your SAS code, which contains an unbalanced quote, so now you've got not only and unclosed quote, but also unclosed comments, macro function definitions, and a missing run; or quit; statement.
What's your best trick for not having those unbalanced quotes bother you? | enterprise guide 3 used to put the following line at the top of its automatically generated code:
```
*';*";*/;run;
```
however, the only way to really "reset" from all kinds of something unbalanced problems is to quit the sas session, and balance whatever is unbalanced before re-submitting the code. Using this kind of quick (cheap?) hacks does not address the root cause.
by the way, `ods _all_ close;` closes *all* the ods destinations, including the default, results destination. in an interactive session, you should open it again with `ods results;` or `ods results on;` at least according to the documention. but when i tested it on my 9.2, it did not work, as shown below:
```
%put sysvlong=&sysvlong sysscpl=&sysscpl;
/* sysvlong=9.02.01M0P020508 sysscpl=X64_VSPRO */
ods _all_ close;
proc print data=sashelp.class;
run;
/* on log
WARNING: No output destinations active.
*/
ods results on;
proc print data=sashelp.class;
run;
/* on log
WARNING: No output destinations active.
*/
``` |
107,464 | <p>There have been some questions about whether or not JavaScript is an object-oriented language. Even a statement, "just because a language has objects doesn't make it OO."</p>
<p>Is JavaScript an object-oriented language?</p>
| [
{
"answer_id": 107470,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 5,
"selected": false,
"text": "<p>The short answer is Yes. For more information:</p>\n\n<p>From <a href=\"http://en.wikipedia.org/wiki/Javascript\" r... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1538/"
] | There have been some questions about whether or not JavaScript is an object-oriented language. Even a statement, "just because a language has objects doesn't make it OO."
Is JavaScript an object-oriented language? | IMO (and it is only an opinion) **the** key characteristic of an object orientated language would be that it would support [*polymorphism*](http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming). Pretty much all dynamic languages do that.
The next characteristic would be [*encapsulation*](http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29) and that is pretty easy to do in Javascript also.
However in the minds of many it is [*inheritance*](http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29) (specifically implementation inheritance) which would tip the balance as to whether a language qualifies to be called object oriented.
Javascript does provide a fairly easy means to inherit implementation via prototyping but this is at the expense of encapsulation.
So if your criteria for object orientation is the classic threesome of polymorphism, encapsulation and inheritance then Javascript doesn't pass.
**Edit**: The supplementary question is raised "how does prototypal inheritance sacrifice encapsulation?" Consider this example of a non-prototypal approach:-
```
function MyClass() {
var _value = 1;
this.getValue = function() { return _value; }
}
```
The \_value attribute is encapsulated, it cannot be modified directly by external code. We might add a mutator to the class to modify it in a way entirely controlled by code that is part of the class. Now consider a prototypal approach to the same class:-
```
function MyClass() {
var _value = 1;
}
MyClass.prototype.getValue = function() { return _value; }
```
Well this is broken. Since the function assigned to getValue is no longer in scope with \_value it can't access it. We would need to promote \_value to an attribute of `this` but that would make it accessable outside of the control of code written for the class, hence encapsulation is broken.
Despite this my vote still remains that Javascript is object oriented. Why? Because given an [OOD](http://en.wikipedia.org/wiki/Object-oriented_design) I can implement it in Javascript. |
107,546 | <p>I need to implement auto-capitalization inside of a Telerik RadEditor control on an ASPX page as a user types.</p>
<p>This can be an IE specific solution (IE6+).</p>
<p>I currently capture every keystroke (down/up) as the user types to support a separate feature called "macros" that are essentially short keywords that expand into formatted text. i.e. the macro "so" could auto expand upon hitting spacebar to "stackoverflow".</p>
<p>That said, I have access to the keyCode information, as well I am using the TextRange methods to select a word ("so") and expanding it to "stackoverflow". Thus, I have some semblence of context.</p>
<p>However, I need to check this context to know whether I should auto-capitalize. This also needs to work regardless of whether a macro is involved.</p>
<p>Since I'm monitoring keystrokes for the macros, should I just monitor for punctuation (it's more than just periods that signal a capital letter) and auto-cap the next letter typed, or should I use TextRange and analyze context?</p>
| [
{
"answer_id": 107632,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 3,
"selected": false,
"text": "<p>Have you tried to apply the <a href=\"http://www.w3.org/TR/CSS2/text.html#caps-prop\" rel=\"noreferrer\">text-transform</a> CSS... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2742/"
] | I need to implement auto-capitalization inside of a Telerik RadEditor control on an ASPX page as a user types.
This can be an IE specific solution (IE6+).
I currently capture every keystroke (down/up) as the user types to support a separate feature called "macros" that are essentially short keywords that expand into formatted text. i.e. the macro "so" could auto expand upon hitting spacebar to "stackoverflow".
That said, I have access to the keyCode information, as well I am using the TextRange methods to select a word ("so") and expanding it to "stackoverflow". Thus, I have some semblence of context.
However, I need to check this context to know whether I should auto-capitalize. This also needs to work regardless of whether a macro is involved.
Since I'm monitoring keystrokes for the macros, should I just monitor for punctuation (it's more than just periods that signal a capital letter) and auto-cap the next letter typed, or should I use TextRange and analyze context? | I'm not sure if this is what you're trying to do, but here is a function ([reference](http://individed.com/code/to-title-case/js/to-title-case.js)) to convert a given string to title case:
```
function toTitleCase(str) {
return str.replace(/([\w&`'‘’"“.@:\/\{\(\[<>_]+-? *)/g, function(match, p1, index, title){ // ' fix syntax highlighting
if (index > 0 && title.charAt(index - 2) != ":" &&
match.search(/^(a(nd?|s|t)?|b(ut|y)|en|for|i[fn]|o[fnr]|t(he|o)|vs?\.?|via)[ -]/i) > -1)
return match.toLowerCase();
if (title.substring(index - 1, index + 1).search(/['"_{([]/) > -1)
return match.charAt(0) + match.charAt(1).toUpperCase() + match.substr(2);
if (match.substr(1).search(/[A-Z]+|&|[\w]+[._][\w]+/) > -1 ||
title.substring(index - 1, index + 1).search(/[\])}]/) > -1)
return match;
return match.charAt(0).toUpperCase() + match.substr(1);
});
}
``` |
107,549 | <p>When we compile a dll using __stdcall inside visual studio 2008 the compiled function names inside the dll are.</p>
<p>FunctionName</p>
<p>Though when we compile the same dll using GCC using wx-dev-cpp GCC appends the number of paramers the function has, so the name of the function using Dependency walker looks like.</p>
<p>FunctionName@numberOfParameters or == FunctionName@8</p>
<p>How do you tell GCC compiler to remove @nn from exported symbols in the dll?</p>
| [
{
"answer_id": 107564,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 4,
"selected": true,
"text": "<p>__stdcall decorates the function name by adding an underscore to the start, and the number of bytes of parameters ... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17382/"
] | When we compile a dll using \_\_stdcall inside visual studio 2008 the compiled function names inside the dll are.
FunctionName
Though when we compile the same dll using GCC using wx-dev-cpp GCC appends the number of paramers the function has, so the name of the function using Dependency walker looks like.
FunctionName@numberOfParameters or == FunctionName@8
How do you tell GCC compiler to remove @nn from exported symbols in the dll? | \_\_stdcall decorates the function name by adding an underscore to the start, and the number of bytes of parameters to the end (separated by @).
So, a function:
```
void __stdcall Foo(int a, int b);
```
...would become \_Foo@8.
If you list the function name (undecorated) in the EXPORTS section of your .DEF file, it is exported undecorated.
Perhaps this is the difference? |
107,562 | <p>I'm trying to install faac and am running into errors. Here are the errors I get when trying to build it:</p>
<hr>
<pre><code>[root@test faac]# ./bootstrap
configure.in:11: warning: underquoted definition of MY_DEFINE
run info '(automake)Extending aclocal'
or see http://sources.redhat.com/automake/automake.html#Extending-aclocal
aclocal:configure.in:17: warning: macro `AM_PROG_LIBTOOL' not found in library
common/mp4v2/Makefile.am:5: Libtool library used but `LIBTOOL' is undefined
common/mp4v2/Makefile.am:5:
common/mp4v2/Makefile.am:5: The usual way to define `LIBTOOL' is to add `AC_PROG_LIBTOOL'
common/mp4v2/Makefile.am:5: to `configure.in' and run `aclocal' and `autoconf' again.
libfaac/Makefile.am:1: Libtool library used but `LIBTOOL' is undefined
libfaac/Makefile.am:1:
libfaac/Makefile.am:1: The usual way to define `LIBTOOL' is to add `AC_PROG_LIBTOOL'
libfaac/Makefile.am:1: to `configure.in' and run `aclocal' and `autoconf' again.
configure.in:17: error: possibly undefined macro: AM_PROG_LIBTOOL
If this token and others are legitimate, please use m4_pattern_allow.
See the Autoconf documentation.
</code></pre>
<hr>
<p>Does anyone know what this means? I was unable to find anything about this so I figured I'd ask you guys. Thank you for your help.</p>
<p>EDIT:
Here's my versions of linux, libtool, automake and autoconf:</p>
<pre><code>[root@test faac]# libtool --version
ltmain.sh (GNU libtool) 2.2
Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[root@test faac]# autoconf --version
autoconf (GNU Autoconf) 2.59
Written by David J. MacKenzie and Akim Demaille.
Copyright (C) 2003 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[root@test faac]# automake --version
automake (GNU automake) 1.9.2
Written by Tom Tromey <tromey@redhat.com>.
Copyright 2004 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[root@test faac]# cat /etc/redhat-release
Red Hat Enterprise Linux WS release 4 (Nahant)
</code></pre>
| [
{
"answer_id": 107592,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 2,
"selected": false,
"text": "<p>I think the first thing to check is that you have libtool installed.</p>\n\n<p>Edit:</p>\n\n<p>This is what I get ... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm trying to install faac and am running into errors. Here are the errors I get when trying to build it:
---
```
[root@test faac]# ./bootstrap
configure.in:11: warning: underquoted definition of MY_DEFINE
run info '(automake)Extending aclocal'
or see http://sources.redhat.com/automake/automake.html#Extending-aclocal
aclocal:configure.in:17: warning: macro `AM_PROG_LIBTOOL' not found in library
common/mp4v2/Makefile.am:5: Libtool library used but `LIBTOOL' is undefined
common/mp4v2/Makefile.am:5:
common/mp4v2/Makefile.am:5: The usual way to define `LIBTOOL' is to add `AC_PROG_LIBTOOL'
common/mp4v2/Makefile.am:5: to `configure.in' and run `aclocal' and `autoconf' again.
libfaac/Makefile.am:1: Libtool library used but `LIBTOOL' is undefined
libfaac/Makefile.am:1:
libfaac/Makefile.am:1: The usual way to define `LIBTOOL' is to add `AC_PROG_LIBTOOL'
libfaac/Makefile.am:1: to `configure.in' and run `aclocal' and `autoconf' again.
configure.in:17: error: possibly undefined macro: AM_PROG_LIBTOOL
If this token and others are legitimate, please use m4_pattern_allow.
See the Autoconf documentation.
```
---
Does anyone know what this means? I was unable to find anything about this so I figured I'd ask you guys. Thank you for your help.
EDIT:
Here's my versions of linux, libtool, automake and autoconf:
```
[root@test faac]# libtool --version
ltmain.sh (GNU libtool) 2.2
Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[root@test faac]# autoconf --version
autoconf (GNU Autoconf) 2.59
Written by David J. MacKenzie and Akim Demaille.
Copyright (C) 2003 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[root@test faac]# automake --version
automake (GNU automake) 1.9.2
Written by Tom Tromey <tromey@redhat.com>.
Copyright 2004 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[root@test faac]# cat /etc/redhat-release
Red Hat Enterprise Linux WS release 4 (Nahant)
``` | I think the first thing to check is that you have libtool installed.
Edit:
This is what I get on Ubuntu 8.04:
```
$ ./bootstrap
configure.in:11: warning: underquoted definition of MY_DEFINE
configure.in:11: run info '(automake)Extending aclocal'
configure.in:11: or see http://sources.redhat.com/automake/automake.html#Extending-aclocal
configure.in:4: installing `./install-sh'
configure.in:4: installing `./missing'
common/mp4v2/Makefile.am: installing `./depcomp'
$ libtool --version
ltmain.sh (GNU libtool) 1.5.26 Debian 1.5.26-1ubuntu1 (1.1220.2.493 2008/02/01 16:58:18)
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ autoconf --version
autoconf (GNU Autoconf) 2.61
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software. You may redistribute copies of it under the terms of
the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.
There is NO WARRANTY, to the extent permitted by law.
Written by David J. MacKenzie and Akim Demaille.
$ automake --version
automake (GNU automake) 1.10.1
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Tom Tromey <tromey@redhat.com>
and Alexandre Duret-Lutz <adl@gnu.org>.
``` |
107,611 | <p>I need to load some fonts temporarily in my program. Preferably from a dll resource file.</p>
| [
{
"answer_id": 107702,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 2,
"selected": false,
"text": "<p>I found <a href=\"http://www.eggheadcafe.com/software/aspnet/30018713/load-font-from-resource.aspx\" rel=\"nofollo... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13219/"
] | I need to load some fonts temporarily in my program. Preferably from a dll resource file. | And here a Delphi version:
```
procedure LoadFontFromDll(const DllName, FontName: PWideChar);
var
DllHandle: HMODULE;
ResHandle: HRSRC;
ResSize, NbFontAdded: Cardinal;
ResAddr: HGLOBAL;
begin
DllHandle := LoadLibrary(DllName);
if DllHandle = 0 then
RaiseLastOSError;
ResHandle := FindResource(DllHandle, FontName, RT_FONT);
if ResHandle = 0 then
RaiseLastOSError;
ResAddr := LoadResource(DllHandle, ResHandle);
if ResAddr = 0 then
RaiseLastOSError;
ResSize := SizeOfResource(DllHandle, ResHandle);
if ResSize = 0 then
RaiseLastOSError;
if 0 = AddFontMemResourceEx(Pointer(ResAddr), ResSize, nil, @NbFontAdded) then
RaiseLastOSError;
end;
```
to be used like:
```
var
FontName: PChar;
FontHandle: THandle;
...
FontName := 'DEJAVUSANS';
LoadFontFromDll('Project1.dll' , FontName);
FontHandle := CreateFont(0, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH,
FontName);
if FontHandle = 0 then
RaiseLastOSError;
``` |
107,660 | <p>What is the best (regarding performance) way to compute the critical path of a directional acyclic graph when the nodes of the graph have weight?</p>
<p>For example, if I have the following structure:</p>
<pre><code> Node A (weight 3)
/ \
Node B (weight 4) Node D (weight 7)
/ \
Node E (weight 2) Node F (weight 3)
</code></pre>
<p>The critical path should be A->B->F (total weight: 10)</p>
| [
{
"answer_id": 107680,
"author": "Aleksandar Dimitrov",
"author_id": 11797,
"author_profile": "https://Stackoverflow.com/users/11797",
"pm_score": 3,
"selected": true,
"text": "<p>I have no clue about \"critical paths\", but I assume you mean <a href=\"http://en.wikipedia.org/wiki/Critic... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19331/"
] | What is the best (regarding performance) way to compute the critical path of a directional acyclic graph when the nodes of the graph have weight?
For example, if I have the following structure:
```
Node A (weight 3)
/ \
Node B (weight 4) Node D (weight 7)
/ \
Node E (weight 2) Node F (weight 3)
```
The critical path should be A->B->F (total weight: 10) | I have no clue about "critical paths", but I assume you mean [this](http://en.wikipedia.org/wiki/Critical_path_method).
Finding the longest path in an acyclic graph with weights is only possible by traversing the whole tree and then comparing the lengths, as you never really know how the rest of the tree is weighted. You can find more about tree traversal at [Wikipedia](https://secure.wikimedia.org/wikipedia/en/wiki/Tree_traversal). I suggest, you go with pre-order traversal, as it's easy and straight forward to implement.
If you're going to query often, you may also wish to augment the edges between the nodes with information about the weight of their subtrees at insertion. This is relatively cheap, while repeated traversal can be extremely expensive.
But there's nothing to really save you from a full traversal if you don't do it. The order doesn't really matter, as long as you do a *traversal* and never go the same path twice. |
107,674 | <p>I'd like to build a real quick and dirty administrative backend for a Ruby on Rails application I have been attached to at the last minute. I've looked at activescaffold and streamlined and think they are both very attractive and they should be simple to get running, but I don't quite understand how to set up either one as a backend administration page. They seem designed to work like standard Ruby on Rails generators/scaffolds for creating visible front ends with model-view-controller-table name correspondence.</p>
<p>How do you create a admin_players interface when players is already in use and you want to avoid, as much as possible, affecting any of its related files?</p>
<p>The show, edit and index of the original resource are not usuable for the administrator.</p>
| [
{
"answer_id": 107715,
"author": "Toby Hede",
"author_id": 14971,
"author_profile": "https://Stackoverflow.com/users/14971",
"pm_score": 3,
"selected": false,
"text": "<p>I have used Streamlined pretty extensively.</p>\n\n<p>To get Streamline working you create your own controllers - so ... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6805/"
] | I'd like to build a real quick and dirty administrative backend for a Ruby on Rails application I have been attached to at the last minute. I've looked at activescaffold and streamlined and think they are both very attractive and they should be simple to get running, but I don't quite understand how to set up either one as a backend administration page. They seem designed to work like standard Ruby on Rails generators/scaffolds for creating visible front ends with model-view-controller-table name correspondence.
How do you create a admin\_players interface when players is already in use and you want to avoid, as much as possible, affecting any of its related files?
The show, edit and index of the original resource are not usuable for the administrator. | I think namespaces is the solution to the problem you have here:
```
map.namespace :admin do |admin|
admin.resources :customers
end
```
Which will create routes `admin_customers`, `new_admin_customers`, etc.
Then inside the `app/controller` directory you can have an `admin` directory. Inside your admin directory, create an admin controller:
```
./script/generate rspec_controller admin/admin
class Admin::AdminController < ApplicationController
layout "admin"
before_filter :login_required
end
```
Then create an admin customers controller:
```
./script/generate rspec_controller admin/customers
```
And make this inhert from your ApplicationController:
```
class Admin::CustomersController < Admin::AdminController
```
This will look for views in `app/views/admin/customers`
and will expect a layout in `app/views/layouts/admin.html.erb`.
You can then use whichever plugin or code you like to actually do your administration, streamline, ActiveScaffold, whatever personally I like to use `resourcecs_controller`, as it saves you a lot of time if you use a [REST](http://en.wikipedia.org/wiki/Representational_State_Transfer) style architecture, and forcing yourself down that route can save a lot of time elsewhere. Though if you inherited the application that's a moot point by now. |
107,675 | <p>I'd like to unit test responses from the Google App Engine webapp.WSGIApplication, for example request the url '/' and test that the responses status code is 200, using <a href="http://code.google.com/p/gaeunit" rel="noreferrer">GAEUnit</a>. How can I do this? </p>
<p>I'd like to use the webapp framework and GAEUnit, which runs within the App Engine sandbox (unfortunately <a href="http://pythonpaste.org/webtest/" rel="noreferrer">WebTest</a> does not work within the sandbox).</p>
| [
{
"answer_id": 107753,
"author": "David Coffin",
"author_id": 13049,
"author_profile": "https://Stackoverflow.com/users/13049",
"pm_score": 2,
"selected": false,
"text": "<p>Actually WebTest does work within the sandbox, as long as you comment out </p>\n\n<pre><code>import webbrowser\n</... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13049/"
] | I'd like to unit test responses from the Google App Engine webapp.WSGIApplication, for example request the url '/' and test that the responses status code is 200, using [GAEUnit](http://code.google.com/p/gaeunit). How can I do this?
I'd like to use the webapp framework and GAEUnit, which runs within the App Engine sandbox (unfortunately [WebTest](http://pythonpaste.org/webtest/) does not work within the sandbox). | I have added a [sample application](http://code.google.com/p/gaeunit/source/browse/#svn/trunk/sample_app) to the GAEUnit project which demonstrates how to write and execute a web test using GAEUnit. The sample includes a slightly modified version of the '[webtest](http://pythonpaste.org/webtest/index.html)' module ('import webbrowser' is commented out, as recommended by David Coffin).
Here's the 'web\_tests.py' file from the sample application 'test' directory:
```
import unittest
from webtest import TestApp
from google.appengine.ext import webapp
import index
class IndexTest(unittest.TestCase):
def setUp(self):
self.application = webapp.WSGIApplication([('/', index.IndexHandler)], debug=True)
def test_default_page(self):
app = TestApp(self.application)
response = app.get('/')
self.assertEqual('200 OK', response.status)
self.assertTrue('Hello, World!' in response)
def test_page_with_param(self):
app = TestApp(self.application)
response = app.get('/?name=Bob')
self.assertEqual('200 OK', response.status)
self.assertTrue('Hello, Bob!' in response)
``` |
107,693 | <p>I'm having trouble with global variables in php. I have a <code>$screen</code> var set in one file, which requires another file that calls an <code>initSession()</code> defined in yet another file. The <code>initSession()</code> declares <code>global $screen</code> and then processes $screen further down using the value set in the very first script.</p>
<p>How is this possible?</p>
<p>To make things more confusing, if you try to set $screen again then call the <code>initSession()</code>, it uses the value first used once again. The following code will describe the process. Could someone have a go at explaining this?</p>
<pre><code>$screen = "list1.inc"; // From model.php
require "controller.php"; // From model.php
initSession(); // From controller.php
global $screen; // From Include.Session.inc
echo $screen; // prints "list1.inc" // From anywhere
$screen = "delete1.inc"; // From model2.php
require "controller2.php"
initSession();
global $screen;
echo $screen; // prints "list1.inc"
</code></pre>
<p>Update:<br>
If I declare <code>$screen</code> global again just before requiring the second model, $screen is updated properly for the <code>initSession()</code> method. Strange.</p>
| [
{
"answer_id": 107698,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 3,
"selected": false,
"text": "<p>You need to put \"global $screen\" in every function that references it, not just at the top of each file.</p>\n"
},
... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10583/"
] | I'm having trouble with global variables in php. I have a `$screen` var set in one file, which requires another file that calls an `initSession()` defined in yet another file. The `initSession()` declares `global $screen` and then processes $screen further down using the value set in the very first script.
How is this possible?
To make things more confusing, if you try to set $screen again then call the `initSession()`, it uses the value first used once again. The following code will describe the process. Could someone have a go at explaining this?
```
$screen = "list1.inc"; // From model.php
require "controller.php"; // From model.php
initSession(); // From controller.php
global $screen; // From Include.Session.inc
echo $screen; // prints "list1.inc" // From anywhere
$screen = "delete1.inc"; // From model2.php
require "controller2.php"
initSession();
global $screen;
echo $screen; // prints "list1.inc"
```
Update:
If I declare `$screen` global again just before requiring the second model, $screen is updated properly for the `initSession()` method. Strange. | `Global` DOES NOT make the variable global. I know it's tricky :-)
`Global` says that a local variable will be used *as if it was a variable with a higher scope*.
E.G :
```
<?php
$var = "test"; // this is accessible in all the rest of the code, even an included one
function foo2()
{
global $var;
echo $var; // this print "test"
$var = 'test2';
}
global $var; // this is totally useless, unless this file is included inside a class or function
function foo()
{
echo $var; // this print nothing, you are using a local var
$var = 'test3';
}
foo();
foo2();
echo $var; // this will print 'test2'
?>
```
Note that global vars are rarely a good idea. You can code 99.99999% of the time without them and your code is much easier to maintain if you don't have fuzzy scopes. Avoid `global` if you can. |
107,701 | <p>How can I remove those annoying Mac OS X <code>.DS_Store</code> files from a Git repository?</p>
| [
{
"answer_id": 107703,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 3,
"selected": false,
"text": "<p>This will work:</p>\n\n<pre><code>find . -name \"*.DS_Store\" -type f -exec git-rm {} \\;\n</code></pre>\n\n<p>It del... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450/"
] | How can I remove those annoying Mac OS X `.DS_Store` files from a Git repository? | Remove existing `.DS_Store` files from the repository:
```
find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch
```
Add this line:
```
.DS_Store
```
to the file `.gitignore`, which can be found at the top level of your repository (or create the file if it isn't there already). You can do this easily with this command in the top directory:
```
echo .DS_Store >> .gitignore
```
Then commit the file to the repo:
```
git add .gitignore
git commit -m '.DS_Store banished!'
``` |
107,705 | <p>Is output buffering enabled by default in Python's interpreter for <code>sys.stdout</code>?</p>
<p>If the answer is positive, what are all the ways to disable it?</p>
<p>Suggestions so far:</p>
<ol>
<li>Use the <code>-u</code> command line switch</li>
<li>Wrap <code>sys.stdout</code> in an object that flushes after every write</li>
<li>Set <code>PYTHONUNBUFFERED</code> env var</li>
<li><code>sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)</code></li>
</ol>
<p>Is there any other way to set some global flag in <code>sys</code>/<code>sys.stdout</code> programmatically during execution?</p>
| [
{
"answer_id": 107717,
"author": "Seb",
"author_id": 189,
"author_profile": "https://Stackoverflow.com/users/189",
"pm_score": 10,
"selected": true,
"text": "<p>From <a href=\"http://mail.python.org/pipermail/tutor/2003-November/026645.html\" rel=\"nofollow noreferrer\">Magnus Lycka answ... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206/"
] | Is output buffering enabled by default in Python's interpreter for `sys.stdout`?
If the answer is positive, what are all the ways to disable it?
Suggestions so far:
1. Use the `-u` command line switch
2. Wrap `sys.stdout` in an object that flushes after every write
3. Set `PYTHONUNBUFFERED` env var
4. `sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)`
Is there any other way to set some global flag in `sys`/`sys.stdout` programmatically during execution? | From [Magnus Lycka answer on a mailing list](http://mail.python.org/pipermail/tutor/2003-November/026645.html):
>
> You can skip buffering for a whole
> python process using `python -u`
> or by
> setting the environment variable
> PYTHONUNBUFFERED.
>
>
> You could also replace sys.stdout with
> some other stream like wrapper which
> does a flush after every call.
>
>
>
> ```
> class Unbuffered(object):
> def __init__(self, stream):
> self.stream = stream
> def write(self, data):
> self.stream.write(data)
> self.stream.flush()
> def writelines(self, datas):
> self.stream.writelines(datas)
> self.stream.flush()
> def __getattr__(self, attr):
> return getattr(self.stream, attr)
>
> import sys
> sys.stdout = Unbuffered(sys.stdout)
> print 'Hello'
>
> ```
>
> |
107,772 | <p>From my understanding the XMPP protocol is based on an always-on connection where you have no, immediate, indication of when an XML message ends.</p>
<p>This means you have to evaluate the stream as it comes. This also means that, probably, you have to deal with asynchronous connections since the socket can block in the middle of an XML message, either due to message length or a connection being slow.</p>
<p>I would appreciate one source per answer so we can mod them up and see what's the favourite.</p>
| [
{
"answer_id": 107820,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Igniterealtime.org provides an open source XMPP-server and client written in java</p>\n"
},
{
"answer_id": 108307,
... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8167/"
] | From my understanding the XMPP protocol is based on an always-on connection where you have no, immediate, indication of when an XML message ends.
This means you have to evaluate the stream as it comes. This also means that, probably, you have to deal with asynchronous connections since the socket can block in the middle of an XML message, either due to message length or a connection being slow.
I would appreciate one source per answer so we can mod them up and see what's the favourite. | Are you wanting to deal with multiple connections at once? Good asynch socket processing is a must in that case, to avoid one thread per connection.
Otherwise, you just need an XML parser that can deal with a chunk of bytes at a time. [Expat](http://expat.sourceforge.net/) is the canonical example; if you're in Java, try [XP](http://www.jclark.com/xml/xp/). These types of XML parsers will fire events as possible, and buffer partial stanzas until the rest arrives.
Now, to address your assertion that there is no notification when a *stanza* ends, that's not really true. The important thing is not to process the XML stream as if it is a sequence of documents. Use the following pseudo-code:
```
stanza = null
while parser has more:
switch on token type:
START_TAG:
elem = create element from parser state
if stanza is not null:
add elem as child of stanza
stanza = elem
END_TAG:
parent = parent of stanza
if parent is not null:
fire OnStanza event
stanza = parent
```
This approach should work with an event-based or pull parser. It only requires holding on to one pointer worth of state. Obviously, you'll also need to handle attributes, character data, entity references (like & and the like), and special-purpose the stream:stream tag, but this should get you started. |
107,823 | <p>(Jeopardy-style question, I wish the answer had been online when I had this issue)</p>
<p>Using Java 1.4, I have a method that I want to run as a thread some of the time, but not at others. So I declared it as a subclass of Thread, then either called start() or run() depending on what I needed.</p>
<p>But I found that my program would leak memory over time. What am I doing wrong?</p>
| [
{
"answer_id": 107832,
"author": "slim",
"author_id": 7512,
"author_profile": "https://Stackoverflow.com/users/7512",
"pm_score": 7,
"selected": true,
"text": "<p>This is a known bug in Java 1.4:\n<a href=\"http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=5869e03fee226ffffffffc40d4... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7512/"
] | (Jeopardy-style question, I wish the answer had been online when I had this issue)
Using Java 1.4, I have a method that I want to run as a thread some of the time, but not at others. So I declared it as a subclass of Thread, then either called start() or run() depending on what I needed.
But I found that my program would leak memory over time. What am I doing wrong? | This is a known bug in Java 1.4:
<http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=5869e03fee226ffffffffc40d4fa881a86e3:WuuT?bug_id=4533087>
It's fixed in Java 1.5 but Sun doesn't intend to fix it in 1.4.
The issue is that, at construction time, a `Thread` is added to a list of references in an internal thread table. It won't get removed from that list until its start() method has completed. As long as that reference is there, it won't get garbage collected.
So, never create a thread unless you're definitely going to call its `start()` method. A `Thread` object's `run()` method should not be called directly.
A better way to code it is to implement the `Runnable` interface rather than subclass `Thread`. When you don't need a thread, call
```
myRunnable.run();
```
When you do need a thread:
```
Thread myThread = new Thread(myRunnable);
myThread.start();
``` |
107,828 | <p>I don't want <code>PHP</code> errors to display /html, but I want them to display in <code>/html/beta/usercomponent</code>. Everything is set up so that errors do not display at all. How can I get errors to just show up in that one folder (and its subfolders)?</p>
| [
{
"answer_id": 107841,
"author": "Internet Friend",
"author_id": 18037,
"author_profile": "https://Stackoverflow.com/users/18037",
"pm_score": 0,
"selected": false,
"text": "<p><strike>I don't believe there's a simple answer to this</strike>, but I'd certainly want to be proven wrong.</... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I don't want `PHP` errors to display /html, but I want them to display in `/html/beta/usercomponent`. Everything is set up so that errors do not display at all. How can I get errors to just show up in that one folder (and its subfolders)? | In `.htaccess`:
```none
php_value error_reporting 2147483647
```
This number, according to documentation should enable 'all' errors irrespective of version, if you want a more granular setting, manually OR the values together, or run
```bash
php -r 'echo E_ALL | E_STRICT ;'
```
to let php compute the value for you.
You need
```none
AllowOverride All
```
in apaches master configuration to enable .htaccess files.
More Reading on this can be found here:
* [Php/Error Reporting Flag](http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting)
* [Php/Error Reporting values](http://php.net/manual/en/errorfunc.constants.php)
* [Php/Different Ways of Tuning Settings](http://php.net/manual/en/configuration.changes.php)
---
**Notice** If you are using Php-CGI instead of mod\_php, this may not work as advertised, and all you will get is an internal server error, and you will be left without much option other than enabling it either site-wide on a per-script basis with
```php
error_reporting( E_ALL | E_STRICT );
```
or similar constructs before the error occurs.
My advice is to **disable** displaying errors to the user, and utilize heavily php's error\_log feature.
```ini
display_errors = 0
error_logging = E_ALL | E_STRICT
error_log = /var/log/php
```
If you have problems with this being too noisy, this is not a sign you need to just take error reporting off selectively, this is a sign somebody should fix the code.
---
@Roger
Yes, you can use it in a `<Directory>` construct in apaches configuration too, however, the .htaccess in this case is equivalent, and makes it more portable especially if you have multiple working checkout copies of the same codebase and you want to distribute this change to all of them.
If you have multiple virtual hosts, you'll want the construct in the respective virtual hosts definition, otherwise, yes
```xml
<Directory /path/to/wherever/on/filesystem>
<IfModule mod_php5.c>
php_value error_reporting 214748364
</IfModule>
</Directory>
```
The Additional "ifmodule" commands are just a safety net so the above problem with apache dying if you don't have mod\_php won't occur. |
107,872 | <p>I have <a href="http://laconi.ca/trac/" rel="nofollow noreferrer">Laconica</a> (self hosted <a href="http://twitter.com/home" rel="nofollow noreferrer">twitter</a>) configured on my local intranet and would like to integrate the public stream into SharePoint site with a web part. How can I do this?</p>
| [
{
"answer_id": 107874,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 4,
"selected": true,
"text": "<p>You can point an RSS Viewer web part at the laconi.ca public stream RSS feed and use this XSLT to ensure attractiv... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] | I have [Laconica](http://laconi.ca/trac/) (self hosted [twitter](http://twitter.com/home)) configured on my local intranet and would like to integrate the public stream into SharePoint site with a web part. How can I do this? | You can point an RSS Viewer web part at the laconi.ca public stream RSS feed and use this XSLT to ensure attractive output.
**Result screen shot:**
[](https://i.stack.imgur.com/dMlja.jpg)
**XSL transform:**
```
<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema" version="1.0" exclude-result-prefixes="xsl ddwrt msxsl rssaggwrt"
xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
xmlns:rssaggwrt="http://schemas.microsoft.com/WebParts/v3/rssagg/runtime"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:rssFeed="urn:schemas-microsoft-com:sharepoint:RSSAggregatorWebPart"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:rss="http://purl.org/rss/1.0/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"
xmlns:atom2="http://purl.org/atom/ns#"
xmlns:ddwrt2="urn:frontpage:internal"
xmlns:laconica="http://laconi.ca/ont/">
<xsl:param name="rss_FeedLimit">5</xsl:param>
<xsl:param name="rss_ExpandFeed">false</xsl:param>
<xsl:param name="rss_LCID">1033</xsl:param>
<xsl:param name="rss_WebPartID">RSS_Viewer_WebPart</xsl:param>
<xsl:param name="rss_alignValue">left</xsl:param>
<xsl:param name="rss_IsDesignMode">True</xsl:param>
<xsl:template match="rdf:RDF">
<xsl:call-template name="RDFMainTemplate"/>
</xsl:template>
<xsl:template name="RDFMainTemplate" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<xsl:variable name="Rows" select="rss:item"/>
<xsl:variable name="RowCount" select="count($Rows)"/>
<div class="slm-layout-main" >
<xsl:call-template name="RDFMainTemplate.body">
<xsl:with-param name="Rows" select="$Rows"/>
<xsl:with-param name="RowCount" select="count($Rows)"/>
</xsl:call-template>
</div>
</xsl:template>
<xsl:template name="RDFMainTemplate.body" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<xsl:param name="Rows"/>
<xsl:param name="RowCount"/>
<xsl:for-each select="$Rows">
<xsl:variable name="CurPosition" select="position()" />
<xsl:variable name="RssFeedLink" select="$rss_WebPartID" />
<xsl:variable name="CurrentElement" select="concat($RssFeedLink,$CurPosition)" />
<xsl:if test="($CurPosition <= $rss_FeedLimit)">
<xsl:element name="div">
<xsl:if test="($CurPosition mod 2 = 1)">
<xsl:attribute name="style"><![CDATA[background-color:#F9F9F9;]]></xsl:attribute>
</xsl:if>
<xsl:element name="table">
<xsl:attribute name="cellpadding">0</xsl:attribute>
<xsl:attribute name="border">0</xsl:attribute>
<xsl:attribute name="style"><![CDATA[margin:0px;padding:0px;border-spacing:0px;background-color:transparent;]]></xsl:attribute>
<xsl:element name="tr">
<xsl:element name="td">
<xsl:attribute name="style"><![CDATA[vertical-align:top;padding:0px;background-color:transparent;]]></xsl:attribute>
<xsl:attribute name="rowspan">2</xsl:attribute>
<xsl:element name="img">
<xsl:attribute name="src"><xsl:value-of select="laconica:postIcon/@rdf:resource"/></xsl:attribute>
<xsl:attribute name="style"><![CDATA[margin:3px;height:48px;width:48px;]]></xsl:attribute>
</xsl:element>
</xsl:element>
<xsl:element name="td">
<xsl:attribute name="style"><![CDATA[vertical-align:top;padding:0px;background-color:transparent;]]></xsl:attribute>
<div>
<strong><xsl:value-of select="substring-before(rss:title, ':')"/></strong>
</div>
<div style="width:300px;overflow-x:hidden;">
<div>
<xsl:value-of select="substring-after(rss:title, ':')"/>
</div>
</div>
</xsl:element>
</xsl:element>
<xsl:element name="tr">
<xsl:element name="td">
<xsl:attribute name="style"><![CDATA[padding:0px;background-color:transparent;]]></xsl:attribute>
<xsl:element name="a">
<xsl:attribute name="href"><xsl:value-of select="rss:link"/></xsl:attribute>
<xsl:value-of select="ddwrt:FormatDate(dc:date,number($rss_LCID),15)"/>
</xsl:element>
</xsl:element>
</xsl:element>
</xsl:element>
</xsl:element>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
``` |
107,903 | <p>On Mac OS X, you can create a zip archive from the Finder by selecting some files and selecting "Compress" from the contextual menu or the File menu. Unfortunately, the resulting file is not identical to the archive created by the <code>zip</code> command (with the default options).</p>
<p>This distinction matters to at least one service operated by Apple, which fails to accept archives created with the <code>zip</code> command. Having to create archives manually is preventing me from fully automating my release build process.</p>
<p>How can I create a zip archive in the correct format within a shell script?</p>
<p>EDIT: Since writing this question long ago, I've figured out that the key difference between <code>ditto</code> and <code>zip</code> is how they handle symbolic links: because the code signature inside an app bundle contains a symlink, it needs to be preserved as a link and not stored as a regular file. <code>ditto</code> does this by default, but <code>zip</code> does not (option <code>-y</code> is required).</p>
| [
{
"answer_id": 107920,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The clue's in the tag 'automation'.</p>\n\n<p>Create an action in Automator.app that uses the 'Create Archive' action, invo... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10947/"
] | On Mac OS X, you can create a zip archive from the Finder by selecting some files and selecting "Compress" from the contextual menu or the File menu. Unfortunately, the resulting file is not identical to the archive created by the `zip` command (with the default options).
This distinction matters to at least one service operated by Apple, which fails to accept archives created with the `zip` command. Having to create archives manually is preventing me from fully automating my release build process.
How can I create a zip archive in the correct format within a shell script?
EDIT: Since writing this question long ago, I've figured out that the key difference between `ditto` and `zip` is how they handle symbolic links: because the code signature inside an app bundle contains a symlink, it needs to be preserved as a link and not stored as a regular file. `ditto` does this by default, but `zip` does not (option `-y` is required). | Use the ditto command-line tool as follows:
```
ditto -ck --rsrc --sequesterRsrc folder file.zip
```
See the [ditto man page](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/ditto.1.html) for more. |
107,936 | <p>Is there a way to add some custom font on a website without using images, <a href="http://en.wikipedia.org/wiki/Adobe_Flash" rel="noreferrer">Flash</a> or some other graphics?</p>
<p>For example, I was working on a wedding website, and I found a lot of nice fonts for that subject. But I can't find the right way to add that font on the server. And how do I include that font with CSS into the HTML? Is this possible to do without graphics?</p>
| [
{
"answer_id": 107945,
"author": "Casper",
"author_id": 18729,
"author_profile": "https://Stackoverflow.com/users/18729",
"pm_score": 3,
"selected": false,
"text": "<p>Or you could try <a href=\"http://en.wikipedia.org/wiki/Scalable_Inman_Flash_Replacement\" rel=\"nofollow noreferrer\">s... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16039/"
] | Is there a way to add some custom font on a website without using images, [Flash](http://en.wikipedia.org/wiki/Adobe_Flash) or some other graphics?
For example, I was working on a wedding website, and I found a lot of nice fonts for that subject. But I can't find the right way to add that font on the server. And how do I include that font with CSS into the HTML? Is this possible to do without graphics? | This could be done via CSS:
```
<style type="text/css">
@font-face {
font-family: "My Custom Font";
src: url(http://www.example.org/mycustomfont.ttf) format("truetype");
}
p.customfont {
font-family: "My Custom Font", Verdana, Tahoma;
}
</style>
<p class="customfont">Hello world!</p>
```
It is [supported for all of the regular browsers](http://www.w3schools.com/cssref/css3_pr_font-face_rule.asp) if you use TrueType-Fonts (TTF), the Web Open Font Format (WOFF) or Embedded Opentype (EOT). |
107,964 | <p>I am using YUI reset/base, after the reset it sets the <code>ul</code> and <code>li</code> tags to list-style: disc outside;</p>
<p>My markup looks like this:</p>
<pre><code><div id="nav">
<ul class="links">
<li><a href="">Testing</a></li>
</ul>
</div>
</code></pre>
<p>My CSS is:</p>
<pre><code>#nav {}
#nav ul li {
list-style: none;
}
</code></pre>
<p>Now that makes the small disc beside each li disappear.</p>
<p>Why doesn't this work though?</p>
<pre><code> #nav {}
#nav ul.links
{
list-style: none;
}
</code></pre>
<p>It works if I remove the link to the base.css file, why?.</p>
<p>Updated: <code>sidenav</code> -> <code>nav</code></p>
| [
{
"answer_id": 107965,
"author": "Matt",
"author_id": 17759,
"author_profile": "https://Stackoverflow.com/users/17759",
"pm_score": 1,
"selected": false,
"text": "<p>shouldn't it be:</p>\n\n<pre><code>#nav ul.links\n</code></pre>\n"
},
{
"answer_id": 107969,
"author": "unexis... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] | I am using YUI reset/base, after the reset it sets the `ul` and `li` tags to list-style: disc outside;
My markup looks like this:
```
<div id="nav">
<ul class="links">
<li><a href="">Testing</a></li>
</ul>
</div>
```
My CSS is:
```
#nav {}
#nav ul li {
list-style: none;
}
```
Now that makes the small disc beside each li disappear.
Why doesn't this work though?
```
#nav {}
#nav ul.links
{
list-style: none;
}
```
It works if I remove the link to the base.css file, why?.
Updated: `sidenav` -> `nav` | I think that Dan was close with his answer, but this isn't an issue of specificity. **You can set the list-style on the list (the UL) but you can also override that list-style for individual list items (the LIs).**
You are telling the browser to not use bullets on the list, but YUI tells the browser to use them on individual list items (YUI wins):
```
ul li{ list-style: disc outside; } /* in YUI base.css */
#nav ul.links {
list-style: none; /* doesn't override styles for LIs, just the UL */
}
```
What you want is to tell the browser not to use them on the list items:
```
ul li{ list-style: disc outside; } /* in YUI base.css */
#nav ul.links li {
list-style: none;
}
``` |
107,971 | <p>I'm using the following JavaScript code:</p>
<pre><code><script language="JavaScript1.2" type="text/javascript">
function CreateBookmarkLink(title, url) {
if (window.sidebar) {
window.sidebar.addPanel(title, url,"");
} else if( window.external ) {
window.external.AddFavorite( url, title); }
else if(window.opera && window.print) {
return true; }
}
</script>
</code></pre>
<p>This will create a bookmark for Firefox and IE. But the link for Firefox will show up in the sidepanel of the browser, instead of being displayed in the main screen. I personally find this very annoying and am looking for a better solution. It is of course possible to edit the bookmark manually to have it <em>not</em> show up in the side panel, but that requires extra steps. I just want to be able to have people bookmark a page (that has a lot of GET information in the URL which is used to build a certain scheme) the easy way.</p>
<p>I'm afraid that it might not be possible to have Firefox present the page in the main screen at all (as Googling this subject resulted in practically nothing worth using), but I might have missed something. If anyone has an idea if this is possible, or if there's a workaround, I'd love to hear about it.</p>
| [
{
"answer_id": 107985,
"author": "Per Hornshøj-Schierbeck",
"author_id": 11619,
"author_profile": "https://Stackoverflow.com/users/11619",
"pm_score": 0,
"selected": false,
"text": "<p>You have a special case for </p>\n\n<pre><code>if (window.sidebar) \n</code></pre>\n\n<p>and then a bra... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18922/"
] | I'm using the following JavaScript code:
```
<script language="JavaScript1.2" type="text/javascript">
function CreateBookmarkLink(title, url) {
if (window.sidebar) {
window.sidebar.addPanel(title, url,"");
} else if( window.external ) {
window.external.AddFavorite( url, title); }
else if(window.opera && window.print) {
return true; }
}
</script>
```
This will create a bookmark for Firefox and IE. But the link for Firefox will show up in the sidepanel of the browser, instead of being displayed in the main screen. I personally find this very annoying and am looking for a better solution. It is of course possible to edit the bookmark manually to have it *not* show up in the side panel, but that requires extra steps. I just want to be able to have people bookmark a page (that has a lot of GET information in the URL which is used to build a certain scheme) the easy way.
I'm afraid that it might not be possible to have Firefox present the page in the main screen at all (as Googling this subject resulted in practically nothing worth using), but I might have missed something. If anyone has an idea if this is possible, or if there's a workaround, I'd love to hear about it. | I think that's the only solution for Firefox... I have a better function for that action, it works even for Opera and shows a message for other "unsupported" browsers.
```
<script type="text/javascript">
function addBookmark(url,name){
if(window.sidebar && window.sidebar.addPanel) {
window.sidebar.addPanel(name,url,''); //obsolete from FF 23.
} else if(window.opera && window.print) {
var e=document.createElement('a');
e.setAttribute('href',url);
e.setAttribute('title',name);
e.setAttribute('rel','sidebar');
e.click();
} else if(window.external) {
try {
window.external.AddFavorite(url,name);
}
catch(e){}
}
else
alert("To add our website to your bookmarks use CTRL+D on Windows and Linux and Command+D on the Mac.");
}
</script>
``` |
107,972 | <p>Is it possible under any set of circumstances to be able to accomplish this?</p>
<p>My current circumstances are this:</p>
<pre><code>public class CustomForm : Form
{
public class CustomGUIElement
{
...
public event MouseEventHandler Click;
// etc, and so forth.
...
}
private List<CustomGUIElement> _elements;
...
public void CustomForm_Click(object sender, MouseEventArgs e)
{
// we might want to call one of the _elements[n].Click in here
// but we can't because we aren't in the same class.
}
}
</code></pre>
<p>My first thought was to have a function similar to:</p>
<pre><code>internal enum GUIElementHandlers { Click, ... }
internal void CustomGUIElement::CallHandler(GUIElementHandler h, object[] args) {
switch (h) {
case Click:
this.Click(this, (EventArgs)args[0]);
break;
... // etc and so forth
}
}
</code></pre>
<p>It's a horribly ugly kludge, but it should work... There must be a more elegant solution though? The .NET library does this all the time with message handlers and calling events in Control's. Does anyone else have any other/better ideas?</p>
| [
{
"answer_id": 107978,
"author": "Per Hornshøj-Schierbeck",
"author_id": 11619,
"author_profile": "https://Stackoverflow.com/users/11619",
"pm_score": 1,
"selected": false,
"text": "<p>You really should wrap the code you want to be able to execute from the outside in a method. That metho... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] | Is it possible under any set of circumstances to be able to accomplish this?
My current circumstances are this:
```
public class CustomForm : Form
{
public class CustomGUIElement
{
...
public event MouseEventHandler Click;
// etc, and so forth.
...
}
private List<CustomGUIElement> _elements;
...
public void CustomForm_Click(object sender, MouseEventArgs e)
{
// we might want to call one of the _elements[n].Click in here
// but we can't because we aren't in the same class.
}
}
```
My first thought was to have a function similar to:
```
internal enum GUIElementHandlers { Click, ... }
internal void CustomGUIElement::CallHandler(GUIElementHandler h, object[] args) {
switch (h) {
case Click:
this.Click(this, (EventArgs)args[0]);
break;
... // etc and so forth
}
}
```
It's a horribly ugly kludge, but it should work... There must be a more elegant solution though? The .NET library does this all the time with message handlers and calling events in Control's. Does anyone else have any other/better ideas? | You just need to add a public method for invoking the event. Microsoft already does this for some events such as *PerformClick* for controls that expose a *Click* event.
```
public class CustomGUIElement
{
public void PerformClick()
{
OnClick(EventArgs.Empty);
}
protected virtual void OnClick(EventArgs e)
{
if (Click != null)
Click(this, e);
}
}
```
You would then do the following inside your example event handler...
```
public void CustomForm_Click(object sender, MouseEventArgs e)
{
_elements[0].PerformClick();
}
``` |
107,984 | <p>In toad, I can see unicode characters that are coming from oracle db. But when I click one of the fields in the data grid into the edit mode, the unicode characters are converted to meaningless symbols, but this is not the big issue.</p>
<p>While editing this field, the unicode characters are displayed correctly as I type. But as soon as I press enter and exit edit mode, they are converted to the nearest (most similar) non-unicode character. So I cannot type unicode characters on data grids. Copy & pasting one of the unicode characters also does not work.</p>
<p>How can I solve this?</p>
<p>Edit: I am using toad 9.0.0.160.</p>
| [
{
"answer_id": 107978,
"author": "Per Hornshøj-Schierbeck",
"author_id": 11619,
"author_profile": "https://Stackoverflow.com/users/11619",
"pm_score": 1,
"selected": false,
"text": "<p>You really should wrap the code you want to be able to execute from the outside in a method. That metho... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] | In toad, I can see unicode characters that are coming from oracle db. But when I click one of the fields in the data grid into the edit mode, the unicode characters are converted to meaningless symbols, but this is not the big issue.
While editing this field, the unicode characters are displayed correctly as I type. But as soon as I press enter and exit edit mode, they are converted to the nearest (most similar) non-unicode character. So I cannot type unicode characters on data grids. Copy & pasting one of the unicode characters also does not work.
How can I solve this?
Edit: I am using toad 9.0.0.160. | You just need to add a public method for invoking the event. Microsoft already does this for some events such as *PerformClick* for controls that expose a *Click* event.
```
public class CustomGUIElement
{
public void PerformClick()
{
OnClick(EventArgs.Empty);
}
protected virtual void OnClick(EventArgs e)
{
if (Click != null)
Click(this, e);
}
}
```
You would then do the following inside your example event handler...
```
public void CustomForm_Click(object sender, MouseEventArgs e)
{
_elements[0].PerformClick();
}
``` |
107,995 | <p>The <code>unzip</code> command doesn't have an option for recursively unzipping archives.</p>
<p>If I have the following directory structure and archives:</p>
<pre>
/Mother/Loving.zip
/Scurvy/Sea Dogs.zip
/Scurvy/Cures/Limes.zip
</pre>
<p>And I want to unzip all of the archives into directories with the same name as each archive:</p>
<pre>
/Mother/Loving/1.txt
/Mother/Loving.zip
/Scurvy/Sea Dogs/2.txt
/Scurvy/Sea Dogs.zip
/Scurvy/Cures/Limes/3.txt
/Scurvy/Cures/Limes.zip
</pre>
<p>What command or commands would I issue?</p>
<p>It's important that this doesn't choke on filenames that have spaces in them.</p>
| [
{
"answer_id": 107999,
"author": "chuckrector",
"author_id": 10645,
"author_profile": "https://Stackoverflow.com/users/10645",
"pm_score": 5,
"selected": false,
"text": "<p>Here's one solution that extracts all zip files to the <em>working directory</em> and involves the find command and... | 2008/09/20 | [
"https://Stackoverflow.com/questions/107995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10645/"
] | The `unzip` command doesn't have an option for recursively unzipping archives.
If I have the following directory structure and archives:
```
/Mother/Loving.zip
/Scurvy/Sea Dogs.zip
/Scurvy/Cures/Limes.zip
```
And I want to unzip all of the archives into directories with the same name as each archive:
```
/Mother/Loving/1.txt
/Mother/Loving.zip
/Scurvy/Sea Dogs/2.txt
/Scurvy/Sea Dogs.zip
/Scurvy/Cures/Limes/3.txt
/Scurvy/Cures/Limes.zip
```
What command or commands would I issue?
It's important that this doesn't choke on filenames that have spaces in them. | If you want to extract the files to the respective folder you can try this
```
find . -name "*.zip" | while read filename; do unzip -o -d "`dirname "$filename"`" "$filename"; done;
```
A multi-processed version for systems that can handle high I/O:
```
find . -name "*.zip" | xargs -P 5 -I fileName sh -c 'unzip -o -d "$(dirname "fileName")/$(basename -s .zip "fileName")" "fileName"'
``` |
108,005 | <p>first question here. I'm developing a program in C# (.NET 3.5) that displays files in a listview. I'd like to have the "large icon" view display the icon that Windows Explorer uses for that filetype, otherwise I'll have to use some existing code like this:</p>
<pre><code> private int getFileTypeIconIndex(string fileName)
{
string fileLocation = Application.StartupPath + "\\Quarantine\\" + fileName;
FileInfo fi = new FileInfo(fileLocation);
switch (fi.Extension)
{
case ".pdf":
return 1;
case ".doc": case ".docx": case ".docm": case ".dotx":case ".dotm": case ".dot":case ".wpd": case ".wps":
return 2;
default:
return 0;
}
}
</code></pre>
<p>The above code returns an integer that is used to select an icon from an imagelist that I populated with some common icons. It works fine but I'd need to add every extension under the sun! Is there a better way? Thanks!</p>
| [
{
"answer_id": 108015,
"author": "blowdart",
"author_id": 2525,
"author_profile": "https://Stackoverflow.com/users/2525",
"pm_score": 3,
"selected": false,
"text": "<p>The file icons are held in the registry. It's a little convoluted but it works something like</p>\n\n<ul>\n<li>Take the ... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14333/"
] | first question here. I'm developing a program in C# (.NET 3.5) that displays files in a listview. I'd like to have the "large icon" view display the icon that Windows Explorer uses for that filetype, otherwise I'll have to use some existing code like this:
```
private int getFileTypeIconIndex(string fileName)
{
string fileLocation = Application.StartupPath + "\\Quarantine\\" + fileName;
FileInfo fi = new FileInfo(fileLocation);
switch (fi.Extension)
{
case ".pdf":
return 1;
case ".doc": case ".docx": case ".docm": case ".dotx":case ".dotm": case ".dot":case ".wpd": case ".wps":
return 2;
default:
return 0;
}
}
```
The above code returns an integer that is used to select an icon from an imagelist that I populated with some common icons. It works fine but I'd need to add every extension under the sun! Is there a better way? Thanks! | You might find the use of [Icon.ExtractAssociatedIcon](http://msdn.microsoft.com/en-us/library/system.drawing.icon.extractassociatedicon.aspx) a much simpler (an managed) approach than using SHGetFileInfo. But watch out: two files with the same extension may have different icons. |
108,009 | <p>I'm writing a C parser using PLY, and recently ran into a problem.
This code:</p>
<pre><code>typedef int my_type;
my_type x;
</code></pre>
<p>Is correct C code, because my_type is defined as a type previously to
being used as such. I handle it by filling a type symbol table in the
parser that gets used by the lexer to differentiate between types and
simple identifiers.</p>
<p>However, while the type declaration rule ends with SEMI (the ';' token), PLY shifts the token <code>my_type</code> from the second line before deciding it's done with the first one. Because of this, I have no chance to pass the update in the type symbol table to the lexer and it
sees my_type as an identifier and not a type.</p>
<p>Any ideas for a fix ?</p>
<p>The full code is at: <a href="http://code.google.com/p/pycparser/source/browse/trunk/src/c_parser.py" rel="nofollow noreferrer">http://code.google.com/p/pycparser/source/browse/trunk/src/c_parser.py</a>
Not sure how I can create a smaller example out of this. </p>
<p><strong>Edit:</strong></p>
<p>Problem solved. See my solution below.</p>
| [
{
"answer_id": 108033,
"author": "Mike G.",
"author_id": 18901,
"author_profile": "https://Stackoverflow.com/users/18901",
"pm_score": 1,
"selected": false,
"text": "<p>I think you need to move the check for whether an ID is a TYPEID from c_lexer.py to c_parser.py.</p>\n\n<p>As you said,... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206/"
] | I'm writing a C parser using PLY, and recently ran into a problem.
This code:
```
typedef int my_type;
my_type x;
```
Is correct C code, because my\_type is defined as a type previously to
being used as such. I handle it by filling a type symbol table in the
parser that gets used by the lexer to differentiate between types and
simple identifiers.
However, while the type declaration rule ends with SEMI (the ';' token), PLY shifts the token `my_type` from the second line before deciding it's done with the first one. Because of this, I have no chance to pass the update in the type symbol table to the lexer and it
sees my\_type as an identifier and not a type.
Any ideas for a fix ?
The full code is at: <http://code.google.com/p/pycparser/source/browse/trunk/src/c_parser.py>
Not sure how I can create a smaller example out of this.
**Edit:**
Problem solved. See my solution below. | With [some help](http://groups.google.com/group/ply-hack/tree/browse_frm/thread/cf31e8334801eabd/b9cdf4a6682635c1?rnum=1&_done=%2Fgroup%2Fply-hack%2Fbrowse_frm%2Fthread%2Fcf31e8334801eabd%3F#doc_5c415da045e77a6e) from Dave Beazley (PLY's creator), my problem was solved.
The idea is to use special sub-rules and do the actions in them. In my case, I split the `declaration` rule to:
```
def p_decl_body(self, p):
""" decl_body : declaration_specifiers init_declarator_list_opt
"""
# <<Handle the declaration here>>
def p_declaration(self, p):
""" declaration : decl_body SEMI
"""
p[0] = p[1]
```
`decl_body` is always reduced before the token after SEMI is shifted in, so my action gets executed at the correct time. |
108,010 | <p>Greetings.</p>
<p>I'm looking for a way to parse a number of XML files in a particular directory with ASP.NET (C#). I'd like to be able to return content from particular elements, but before that, need to find those that have a certain value between an element.</p>
<p>Example XML file 1:</p>
<pre><code><file>
<title>Title 1</title>
<someContent>Content</someContent>
<filter>filter</filter>
</file>
</code></pre>
<p>Example XML file 2:</p>
<pre><code><file>
<title>Title 2</title>
<someContent>Content</someContent>
<filter>filter, different filter</filter>
</file>
</code></pre>
<p>Example case 1:</p>
<p>Give me all XML that has a filter of 'filter'.</p>
<p>Example case 2:</p>
<p>Give me all XML that has a title of 'Title 1'.</p>
<p>Looking, it seems this should be possible with LINQ, but I've only seen examples on how to do this when there is one XML file, not when there are multiples, such as in this case.</p>
<p>I would prefer that this be done on the server-side, so that I can cache on that end.</p>
<p>Functionality from any version of the .NET Framework can be used.</p>
<p>Thanks!</p>
<p>~James</p>
| [
{
"answer_id": 108012,
"author": "Per Hornshøj-Schierbeck",
"author_id": 11619,
"author_profile": "https://Stackoverflow.com/users/11619",
"pm_score": 1,
"selected": false,
"text": "<p>Use XPath?<br>\n<a href=\"http://www.w3schools.com/XPath/default.asp\" rel=\"nofollow noreferrer\">http... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11912/"
] | Greetings.
I'm looking for a way to parse a number of XML files in a particular directory with ASP.NET (C#). I'd like to be able to return content from particular elements, but before that, need to find those that have a certain value between an element.
Example XML file 1:
```
<file>
<title>Title 1</title>
<someContent>Content</someContent>
<filter>filter</filter>
</file>
```
Example XML file 2:
```
<file>
<title>Title 2</title>
<someContent>Content</someContent>
<filter>filter, different filter</filter>
</file>
```
Example case 1:
Give me all XML that has a filter of 'filter'.
Example case 2:
Give me all XML that has a title of 'Title 1'.
Looking, it seems this should be possible with LINQ, but I've only seen examples on how to do this when there is one XML file, not when there are multiples, such as in this case.
I would prefer that this be done on the server-side, so that I can cache on that end.
Functionality from any version of the .NET Framework can be used.
Thanks!
~James | If you are using .Net 3.5, this is extremely easy with LINQ:
```
//get the files
XElement xe1 = XElement.Load(string_file_path_1);
XElement xe2 = XElement.Load(string_file_path_2);
//Give me all XML that has a filter of 'filter'.
var filter_elements1 = from p in xe1.Descendants("filter") select p;
var filter_elements2 = from p in xe2.Descendants("filter") select p;
var filter_elements = filter_elements1.Union(filter_elements2);
//Give me all XML that has a title of 'Title 1'.
var title1 = from p in xe1.Descendants("title") where p.Value.Equals("Title 1") select p;
var title2 = from p in xe2.Descendants("title") where p.Value.Equals("Title 1") select p;
var titles = title1.Union(title2);
```
This can all be written shorthand and get you your results in just 4 lines total:
```
XElement xe1 = XElement.Load(string_file_path_1);
XElement xe2 = XElement.Load(string_file_path_2);
var _filter_elements = (from p1 in xe1.Descendants("filter") select p1).Union(from p2 in xe2.Descendants("filter") select p2);
var _titles = (from p1 in xe1.Descendants("title") where p1.Value.Equals("Title 1") select p1).Union(from p2 in xe2.Descendants("title") where p2.Value.Equals("Title 1") select p2);
```
These will all be IEnumerable lists, so they are super easy to work with:
```
foreach (var v in filter_elements)
Response.Write("value of filter element" + v.Value + "<br />");
```
LINQ rules! |
108,081 | <p>Are there any good, cross platform (SBCL and CLISP at the very least) easy to install GUI libraries?</p>
| [
{
"answer_id": 108142,
"author": "Matthias Benkard",
"author_id": 15517,
"author_profile": "https://Stackoverflow.com/users/15517",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://www.peter-herth.de/ltk/\" rel=\"noreferrer\">Ltk</a> is quite popular, very portable, and reas... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7780/"
] | Are there any good, cross platform (SBCL and CLISP at the very least) easy to install GUI libraries? | [Ltk](http://www.peter-herth.de/ltk/) is quite popular, very portable, and reasonably well documented through the Tk docs. Installation on SBCL is as easy as saying:
```
(require :asdf-install)
(asdf-install:install :ltk)
```
There's also [Cells-Gtk](http://common-lisp.net/project/cells-gtk/), which is reported to be quite usable but may have a slightly steeper learning curve because of its reliance on Cells.
EDIT: Note that ASDF-INSTALL is integrated this well with SBCL *only*. Installing libraries from within other Lisp implementations may prove harder. (Personally, I always install my libraries from within SBCL and then use them from all implementations.) Sorry about any confusion this may have caused. |
108,094 | <p>Is there anyway to disable the rather annoying feature that Visual Studio (2008 in my case) has of copying the line (with text on it) the cursor is on when <kbd>CTRL</kbd>-<kbd>C</kbd> is pressed and no selection is made?</p>
<p>I know of the option to disable copying blank lines. But this is driving me crazy as well.</p>
<p>ETA: I'm not looking to customize the keyboard shortcut.</p>
<p>ETA-II: I am NOT looking for "Tools->Options->Text Editor->All Languages->Apply cut or copy to blank lines...".</p>
| [
{
"answer_id": 108139,
"author": "devinmoore",
"author_id": 15950,
"author_profile": "https://Stackoverflow.com/users/15950",
"pm_score": 1,
"selected": false,
"text": "<p>I'm pretty sure the way to do it in 2008 is the same as the way in 2005... check out this tutorial on 'customizing k... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4192/"
] | Is there anyway to disable the rather annoying feature that Visual Studio (2008 in my case) has of copying the line (with text on it) the cursor is on when `CTRL`-`C` is pressed and no selection is made?
I know of the option to disable copying blank lines. But this is driving me crazy as well.
ETA: I'm not looking to customize the keyboard shortcut.
ETA-II: I am NOT looking for "Tools->Options->Text Editor->All Languages->Apply cut or copy to blank lines...". | If you aren't willing to customize the keyboard settings, then `Ctrl`+`C` will always be Edit.Copy, which will copy the current line if nothing is selected. If you aren't willing to use the tools VS provides to customize the interface, then you can't do it.
However, the following works:
Assign this macro to `Ctrl`+`C`:
```
Sub CopyOnlyIfSelection()
Dim s As String = DTE.ActiveDocument.Selection.Text
Dim n As Integer = Len(s)
If n > 0 Then
DTE.ActiveDocument.Selection.Copy()
End If
End Sub
``` |
108,104 | <p>Once again one of those: "Is there an easier built-in way of doing things instead of my helper method?"</p>
<p>So it's easy to get the underlying type from a nullable type, but how do I get the nullable version of a .NET type?</p>
<p>So I have</p>
<pre><code>typeof(int)
typeof(DateTime)
System.Type t = something;
</code></pre>
<p>and I want</p>
<pre><code>int?
DateTime?
</code></pre>
<p>or</p>
<pre><code>Nullable<int> (which is the same)
if (t is primitive) then Nullable<T> else just T
</code></pre>
<p>Is there a built-in method?</p>
| [
{
"answer_id": 108122,
"author": "Alex Lyman",
"author_id": 5897,
"author_profile": "https://Stackoverflow.com/users/5897",
"pm_score": 8,
"selected": true,
"text": "<p>Here is the code I use:</p>\n\n<pre><code>Type GetNullableType(Type type) {\n // Use Nullable.GetUnderlyingType() to... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5790/"
] | Once again one of those: "Is there an easier built-in way of doing things instead of my helper method?"
So it's easy to get the underlying type from a nullable type, but how do I get the nullable version of a .NET type?
So I have
```
typeof(int)
typeof(DateTime)
System.Type t = something;
```
and I want
```
int?
DateTime?
```
or
```
Nullable<int> (which is the same)
if (t is primitive) then Nullable<T> else just T
```
Is there a built-in method? | Here is the code I use:
```
Type GetNullableType(Type type) {
// Use Nullable.GetUnderlyingType() to remove the Nullable<T> wrapper if type is already nullable.
type = Nullable.GetUnderlyingType(type) ?? type; // avoid type becoming null
if (type.IsValueType)
return typeof(Nullable<>).MakeGenericType(type);
else
return type;
}
``` |
108,134 | <p>I am using <code>pyexcelerator</code> Python module to generate Excel files.
I want to apply bold style to part of cell text, but not to the whole cell.
How to do it?</p>
| [
{
"answer_id": 108204,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<p>This is an example from Excel documentation:</p>\n\n<pre><code>With Worksheets(\"Sheet1\").Range(\"B1\")\n .Value = \"New... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19607/"
] | I am using `pyexcelerator` Python module to generate Excel files.
I want to apply bold style to part of cell text, but not to the whole cell.
How to do it? | This is an example from Excel documentation:
```
With Worksheets("Sheet1").Range("B1")
.Value = "New Title"
.Characters(5, 5).Font.Bold = True
End With
```
So the Characters property of the cell you want to manipulate is the answer to your question. It's used as Characters(*start*, *length*).
PS: I've never used the module in question, but I've used Excel COM automation in python scripts. The Characters property is available using win32com. |
108,169 | <p>Given a list, how would I select a new list, containing a slice of the original list (Given offset and number of elements) ?</p>
<h3>EDIT:</h3>
<p>Good suggestions so far. Isn't there something specified in one of the SRFI's? This appears to be a very fundamental thing, so I'm surprised that I need to implement it in user-land.</p>
| [
{
"answer_id": 108248,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 4,
"selected": true,
"text": "<p>The following code will do what you want:</p>\n\n<pre><code>(define get-n-items\n (lambda (lst num)\n (if (> num ... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18180/"
] | Given a list, how would I select a new list, containing a slice of the original list (Given offset and number of elements) ?
### EDIT:
Good suggestions so far. Isn't there something specified in one of the SRFI's? This appears to be a very fundamental thing, so I'm surprised that I need to implement it in user-land. | The following code will do what you want:
```
(define get-n-items
(lambda (lst num)
(if (> num 0)
(cons (car lst) (get-n-items (cdr lst) (- num 1)))
'()))) ;'
(define slice
(lambda (lst start count)
(if (> start 1)
(slice (cdr lst) (- start 1) count)
(get-n-items lst count))))
```
Example:
```
> (define l '(2 3 4 5 6 7 8 9)) ;'
()
> l
(2 3 4 5 6 7 8 9)
> (slice l 2 4)
(3 4 5 6)
>
``` |
108,183 | <p>I have a small server program that accepts connections on a TCP or local UNIX socket, reads a simple command and (depending on the command) sends a reply.</p>
<p>The problem is that the client may have no interest in the answer and sometimes exits early. So writing to that socket will cause a <code>SIGPIPE</code> and make my server crash.</p>
<p>What's the best practice to prevent the crash here? Is there a way to check if the other side of the line is still reading? (<code>select()</code> doesn't seem to work here as it always says the socket is writable). Or should I just catch the <code>SIGPIPE</code> with a handler and ignore it?</p>
| [
{
"answer_id": 108190,
"author": "Sam Reynolds",
"author_id": 9192,
"author_profile": "https://Stackoverflow.com/users/9192",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Or should I just catch the SIGPIPE with a handler and ignore it?</p>\n</blockquote>\n\n<p>I believe ... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12523/"
] | I have a small server program that accepts connections on a TCP or local UNIX socket, reads a simple command and (depending on the command) sends a reply.
The problem is that the client may have no interest in the answer and sometimes exits early. So writing to that socket will cause a `SIGPIPE` and make my server crash.
What's the best practice to prevent the crash here? Is there a way to check if the other side of the line is still reading? (`select()` doesn't seem to work here as it always says the socket is writable). Or should I just catch the `SIGPIPE` with a handler and ignore it? | You generally want to ignore the `SIGPIPE` and handle the error directly in your code. This is because signal handlers in C have many restrictions on what they can do.
The most portable way to do this is to set the `SIGPIPE` handler to `SIG_IGN`. This will prevent any socket or pipe write from causing a `SIGPIPE` signal.
To ignore the `SIGPIPE` signal, use the following code:
```
signal(SIGPIPE, SIG_IGN);
```
If you're using the `send()` call, another option is to use the `MSG_NOSIGNAL` option, which will turn the `SIGPIPE` behavior off on a per call basis. Note that not all operating systems support the `MSG_NOSIGNAL` flag.
Lastly, you may also want to consider the `SO_SIGNOPIPE` socket flag that can be set with `setsockopt()` on some operating systems. This will prevent `SIGPIPE` from being caused by writes just to the sockets it is set on. |
108,193 | <pre><code>class Tag(models.Model):
name = models.CharField(maxlength=100)
class Blog(models.Model):
name = models.CharField(maxlength=100)
tags = models.ManyToManyField(Tag)
</code></pre>
<p>Simple models just to ask my question.</p>
<p>I wonder how can i query blogs using tags in two different ways.</p>
<ul>
<li>Blog entries that are tagged with "tag1" or "tag2":
<code>Blog.objects.filter(tags_in=[1,2]).distinct()</code></li>
<li>Blog objects that are tagged with "tag1" and "tag2" : <strong>?</strong></li>
<li>Blog objects that are tagged with exactly "tag1" and "tag2" and nothing else : <strong>??</strong></li>
</ul>
<hr>
<p>Tag and Blog is just used for an example.</p>
| [
{
"answer_id": 108404,
"author": "Clint Ecker",
"author_id": 13668,
"author_profile": "https://Stackoverflow.com/users/13668",
"pm_score": 6,
"selected": true,
"text": "<p>You could use Q objects for #1:</p>\n\n<pre><code># Blogs who have either hockey or django tags.\nfrom django.db.mod... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12785/"
] | ```
class Tag(models.Model):
name = models.CharField(maxlength=100)
class Blog(models.Model):
name = models.CharField(maxlength=100)
tags = models.ManyToManyField(Tag)
```
Simple models just to ask my question.
I wonder how can i query blogs using tags in two different ways.
* Blog entries that are tagged with "tag1" or "tag2":
`Blog.objects.filter(tags_in=[1,2]).distinct()`
* Blog objects that are tagged with "tag1" and "tag2" : **?**
* Blog objects that are tagged with exactly "tag1" and "tag2" and nothing else : **??**
---
Tag and Blog is just used for an example. | You could use Q objects for #1:
```
# Blogs who have either hockey or django tags.
from django.db.models import Q
Blog.objects.filter(
Q(tags__name__iexact='hockey') | Q(tags__name__iexact='django')
)
```
Unions and intersections, I believe, are a bit outside the scope of the Django ORM, but its possible to to these. The following examples are from a Django application called called [django-tagging](http://code.google.com/p/django-tagging/) that provides the functionality. [Line 346 of models.py](http://code.google.com/p/django-tagging/source/browse/trunk/tagging/models.py#346):
For part two, you're looking for a union of two queries, basically
```
def get_union_by_model(self, queryset_or_model, tags):
"""
Create a ``QuerySet`` containing instances of the specified
model associated with *any* of the given list of tags.
"""
tags = get_tag_list(tags)
tag_count = len(tags)
queryset, model = get_queryset_and_model(queryset_or_model)
if not tag_count:
return model._default_manager.none()
model_table = qn(model._meta.db_table)
# This query selects the ids of all objects which have any of
# the given tags.
query = """
SELECT %(model_pk)s
FROM %(model)s, %(tagged_item)s
WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
AND %(model_pk)s = %(tagged_item)s.object_id
GROUP BY %(model_pk)s""" % {
'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
'model': model_table,
'tagged_item': qn(self.model._meta.db_table),
'content_type_id': ContentType.objects.get_for_model(model).pk,
'tag_id_placeholders': ','.join(['%s'] * tag_count),
}
cursor = connection.cursor()
cursor.execute(query, [tag.pk for tag in tags])
object_ids = [row[0] for row in cursor.fetchall()]
if len(object_ids) > 0:
return queryset.filter(pk__in=object_ids)
else:
return model._default_manager.none()
```
For part #3 I believe you're looking for an intersection. See [line 307 of models.py](http://code.google.com/p/django-tagging/source/browse/trunk/tagging/models.py#307)
```
def get_intersection_by_model(self, queryset_or_model, tags):
"""
Create a ``QuerySet`` containing instances of the specified
model associated with *all* of the given list of tags.
"""
tags = get_tag_list(tags)
tag_count = len(tags)
queryset, model = get_queryset_and_model(queryset_or_model)
if not tag_count:
return model._default_manager.none()
model_table = qn(model._meta.db_table)
# This query selects the ids of all objects which have all the
# given tags.
query = """
SELECT %(model_pk)s
FROM %(model)s, %(tagged_item)s
WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
AND %(model_pk)s = %(tagged_item)s.object_id
GROUP BY %(model_pk)s
HAVING COUNT(%(model_pk)s) = %(tag_count)s""" % {
'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
'model': model_table,
'tagged_item': qn(self.model._meta.db_table),
'content_type_id': ContentType.objects.get_for_model(model).pk,
'tag_id_placeholders': ','.join(['%s'] * tag_count),
'tag_count': tag_count,
}
cursor = connection.cursor()
cursor.execute(query, [tag.pk for tag in tags])
object_ids = [row[0] for row in cursor.fetchall()]
if len(object_ids) > 0:
return queryset.filter(pk__in=object_ids)
else:
return model._default_manager.none()
``` |
108,200 | <p>I need to store the timezone an email was sent from. Which is the best way to extract it from the email's 'Date:' header (an RFC822 date)? And what is the recommended format to store it in the database (I'm using hibernate)?</p>
| [
{
"answer_id": 108220,
"author": "Joshua",
"author_id": 6013,
"author_profile": "https://Stackoverflow.com/users/6013",
"pm_score": 0,
"selected": false,
"text": "<p>Extract the data from the header using some sort of substring or regular expression. Parse the date with a SimpleDateForma... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15231/"
] | I need to store the timezone an email was sent from. Which is the best way to extract it from the email's 'Date:' header (an RFC822 date)? And what is the recommended format to store it in the database (I'm using hibernate)? | Probably easiest to parse with JodaTime as it supports ISO8601 see [Date and Time Parsing and Formatting in Java with Joda Time](http://johannburkard.de/blog/programming/java/date-time-parsing-formatting-joda-time.html).
```
DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis();
System.out.println(parser2.parseDateTime(your_date_string));
```
Times must always be stored in UTC (GMT) with a timezone - i.e. after parsing convert from the timezone to GMT and remove daylight savings offset and save the original timezone.
You must store the date with the timezone after converting to UTC.
If you remove or don't handle the timezone it will cause problems when dealing with data that has come from a different timezone. |
108,207 | <p>I want the search box on my web page to display the word "Search" in gray italics. When the box receives focus, it should look just like an empty text box. If there is already text in it, it should display the text normally (black, non-italics). This will help me avoid clutter by removing the label.</p>
<p>BTW, this is an on-page <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> search, so it has no button.</p>
| [
{
"answer_id": 108218,
"author": "levik",
"author_id": 4465,
"author_profile": "https://Stackoverflow.com/users/4465",
"pm_score": 4,
"selected": false,
"text": "<p>You can add and remove a special CSS class and modify the input value <code>onfocus</code>/<code>onblur</code> with JavaScr... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7668/"
] | I want the search box on my web page to display the word "Search" in gray italics. When the box receives focus, it should look just like an empty text box. If there is already text in it, it should display the text normally (black, non-italics). This will help me avoid clutter by removing the label.
BTW, this is an on-page [Ajax](http://en.wikipedia.org/wiki/Ajax_%28programming%29) search, so it has no button. | Another option, if you're happy to have this feature only for newer browsers, is to use the support offered by HTML 5's **placeholder** attribute:
```
<input name="email" placeholder="Email Address">
```
In the absence of any styles, in Chrome this looks like:
[](https://i.stack.imgur.com/tZcmY.png)
You can try demos out [here](http://diveintohtml5.info/examples/input-placeholder.html) and in *[HTML5 Placeholder Styling with CSS](http://davidwalsh.name/html5-placeholder-css)*.
Be sure to check the [browser compatibility of this feature](http://caniuse.com/#feat=input-placeholder). Support in Firefox was added in 3.7. Chrome is fine. Internet Explorer only added support in 10. If you target a browser that does not support input placeholders, you can use a jQuery plugin called [jQuery HTML5 Placeholder](https://github.com/mathiasbynens/jquery-placeholder), and then just add the following JavaScript code to enable it.
```
$('input[placeholder], textarea[placeholder]').placeholder();
``` |
108,211 | <p>I want to add a <em>column</em> to an existing legacy <em>database</em> and write a <em>procedure</em> by which I can assign each record a different value. Something like adding a <em>column</em> and autogenerate the data for it.</p>
<p>Like, if I add a new <em>column</em> called "ID" (number) I want to then initialize a unique value to each of the records. So, my ID <em>column</em> will have records from say <code>1 to 1000</code>.<br>
How do I do that?</p>
| [
{
"answer_id": 108227,
"author": "Simon Johnson",
"author_id": 854,
"author_profile": "https://Stackoverflow.com/users/854",
"pm_score": 9,
"selected": true,
"text": "<p>This will depend on the database but for SQL Server, this could be achieved as follows:</p>\n\n<pre><code>alter table ... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384/"
] | I want to add a *column* to an existing legacy *database* and write a *procedure* by which I can assign each record a different value. Something like adding a *column* and autogenerate the data for it.
Like, if I add a new *column* called "ID" (number) I want to then initialize a unique value to each of the records. So, my ID *column* will have records from say `1 to 1000`.
How do I do that? | This will depend on the database but for SQL Server, this could be achieved as follows:
```
alter table Example
add NewColumn int identity(1,1)
``` |
108,251 | <p>On my VPS server (Fedora 9), mingetty keeps respawning itself because of a "permission denied" error on tty[1-6], even though:</p>
<pre>
root# ls -la /dev/tty1
crw------- 1 root root 4, 1 Sep 19 14:22 /dev/tty1
</pre>
<p>Even weirder, this doesn't work:</p>
<pre>
root# cat </dev/tty1
bash: /dev/tty1: Permission denied
</pre>
<p>I am guessing this has something to do with the VM host, but both my VPS provider and I are out of ideas, and so is Google... Any clue as to why root cannot access a character device with root rw privileges?</p>
<p>Update: I've made sure SELinux has been disabled; yet, the issue is still there....</p>
<p>Update: The strace dump:</p>
<pre>
32399 rt_sigaction(SIGTSTP, {SIG_DFL}, {SIG_DFL}, 8) = 0
32399 rt_sigaction(SIGTTIN, {SIG_DFL}, {SIG_IGN}, 8) = 0
32399 rt_sigaction(SIGTTOU, {SIG_DFL}, {SIG_IGN}, 8) = 0
32399 rt_sigaction(SIGINT, {SIG_IGN}, {SIG_IGN}, 8) = 0
32399 rt_sigaction(SIGQUIT, {SIG_IGN}, {SIG_IGN}, 8) = 0
32399 rt_sigaction(SIGCHLD, {SIG_DFL}, {0x807b990, [], SA_RESTORER, 0xb7e7b708}, 8) = 0
32399 open("/dev/tty1", O_RDONLY|O_LARGEFILE) = -1 EACCES (Permission denied)
32399 open("/dev/tty1", O_RDONLY|O_LARGEFILE) = -1 EACCES (Permission denied)
32399 fstat64(2, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 1), ...}) = 0
32399 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7fe1000
32399 write(2, "bash: /dev/tty1: Permission deni"..., 35) = 35
</pre>
<p>Can't say it's making much sense to me... </p>
| [
{
"answer_id": 108442,
"author": "Martin OConnor",
"author_id": 18233,
"author_profile": "https://Stackoverflow.com/users/18233",
"pm_score": 1,
"selected": false,
"text": "<p>I suspect that SELinux may be the problem. Try temporarily disabling it to see if it works.</p>\n"
},
{
... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19627/"
] | On my VPS server (Fedora 9), mingetty keeps respawning itself because of a "permission denied" error on tty[1-6], even though:
```
root# ls -la /dev/tty1
crw------- 1 root root 4, 1 Sep 19 14:22 /dev/tty1
```
Even weirder, this doesn't work:
```
root# cat </dev/tty1
bash: /dev/tty1: Permission denied
```
I am guessing this has something to do with the VM host, but both my VPS provider and I are out of ideas, and so is Google... Any clue as to why root cannot access a character device with root rw privileges?
Update: I've made sure SELinux has been disabled; yet, the issue is still there....
Update: The strace dump:
```
32399 rt_sigaction(SIGTSTP, {SIG_DFL}, {SIG_DFL}, 8) = 0
32399 rt_sigaction(SIGTTIN, {SIG_DFL}, {SIG_IGN}, 8) = 0
32399 rt_sigaction(SIGTTOU, {SIG_DFL}, {SIG_IGN}, 8) = 0
32399 rt_sigaction(SIGINT, {SIG_IGN}, {SIG_IGN}, 8) = 0
32399 rt_sigaction(SIGQUIT, {SIG_IGN}, {SIG_IGN}, 8) = 0
32399 rt_sigaction(SIGCHLD, {SIG_DFL}, {0x807b990, [], SA_RESTORER, 0xb7e7b708}, 8) = 0
32399 open("/dev/tty1", O_RDONLY|O_LARGEFILE) = -1 EACCES (Permission denied)
32399 open("/dev/tty1", O_RDONLY|O_LARGEFILE) = -1 EACCES (Permission denied)
32399 fstat64(2, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 1), ...}) = 0
32399 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7fe1000
32399 write(2, "bash: /dev/tty1: Permission deni"..., 35) = 35
```
Can't say it's making much sense to me... | I suspect that SELinux may be the problem. Try temporarily disabling it to see if it works. |
108,276 | <p>I have a project with a bunch of external sounds to a SWF. I want to play them, but any time I attempt load a new URL into the sound object it fails with either,</p>
<blockquote>
<p>Error #2068: Invalid Sound</p>
</blockquote>
<p>or raises an ioError with </p>
<blockquote>
<p>Error #2032 Stream Error</p>
</blockquote>
<p>// Tried with path prefixed with "http://.." "file://.." "//.." and "..")</p>
<pre><code>var path:String = "http://../assets/the_song.mp3";
var url:URLRequest = new URLRequest( path );
var sound:Sound = new Sound();
sound.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler);
sound.addEventListener( SecurityErrorEvent.SECURITY_ERROR, secHandler);
sound.load(url);
</code></pre>
| [
{
"answer_id": 108698,
"author": "ZorroDeLaArena",
"author_id": 19696,
"author_profile": "https://Stackoverflow.com/users/19696",
"pm_score": 2,
"selected": false,
"text": "<p>Unless you're going to put a full url, don't use http:// or file://</p>\n\n<p>Sound can load an mp3 file from a ... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14747/"
] | I have a project with a bunch of external sounds to a SWF. I want to play them, but any time I attempt load a new URL into the sound object it fails with either,
>
> Error #2068: Invalid Sound
>
>
>
or raises an ioError with
>
> Error #2032 Stream Error
>
>
>
// Tried with path prefixed with "http://.." "file://.." "//.." and "..")
```
var path:String = "http://../assets/the_song.mp3";
var url:URLRequest = new URLRequest( path );
var sound:Sound = new Sound();
sound.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler);
sound.addEventListener( SecurityErrorEvent.SECURITY_ERROR, secHandler);
sound.load(url);
``` | Well, I've just done a test by putting an mp3 in a directory: `soundTest/assets/song.mp3` then creating a swf that calls the mp3 in another directory: `soundTest/swfs/soundTest.swf` and when I use `var path:String = "../assets/song.mp3";` then it compiles with no errors.
What is your actual directory structure? |
108,281 | <p>I have a table <code>y</code> Which has two columns <code>a</code> and <code>b</code></p>
<p>Entries are:</p>
<pre><code>a b
1 2
1 3
1 4
0 5
0 2
0 4
</code></pre>
<p>I want to get 2,3,4 if I search column <code>a</code> for 1, and 5,2,4 if I search column <code>a</code>.</p>
<p>So, if I search A for something that is in A, (1) I get those rows, and if there are no entries A for given value, give me the 'Defaults' (<code>a</code> = '0')</p>
<p>Here is how I would know how to do it:</p>
<pre><code>$r = mysql_query('SELECT `b` FROM `y` WHERE `a` = \'1\';');
//This gives desired results, 3 rows
$r = mysql_query('SELECT `b` FROM `y` WHERE `a` = \'2\';');
//This does not give desired results yet.
//Get the number of rows, and then get the 'defaults'
if(mysql_num_rows($r) === 0) $r = mysql_query('SELECT `b` FROM `y` WHERE `a` = 0;');
</code></pre>
<p>So, now that it's sufficiently explained, how do I do that in one query, and what about performance concerns? </p>
<p>The most used portion would be the third query, because there would only be values in <code>a</code> for a number IF you stray from the defaults.</p>
| [
{
"answer_id": 108313,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "<p>You can do all this in a single stored procedure with a single parameter.</p>\n\n<p>I have to run out, but I'll try t... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/144/"
] | I have a table `y` Which has two columns `a` and `b`
Entries are:
```
a b
1 2
1 3
1 4
0 5
0 2
0 4
```
I want to get 2,3,4 if I search column `a` for 1, and 5,2,4 if I search column `a`.
So, if I search A for something that is in A, (1) I get those rows, and if there are no entries A for given value, give me the 'Defaults' (`a` = '0')
Here is how I would know how to do it:
```
$r = mysql_query('SELECT `b` FROM `y` WHERE `a` = \'1\';');
//This gives desired results, 3 rows
$r = mysql_query('SELECT `b` FROM `y` WHERE `a` = \'2\';');
//This does not give desired results yet.
//Get the number of rows, and then get the 'defaults'
if(mysql_num_rows($r) === 0) $r = mysql_query('SELECT `b` FROM `y` WHERE `a` = 0;');
```
So, now that it's sufficiently explained, how do I do that in one query, and what about performance concerns?
The most used portion would be the third query, because there would only be values in `a` for a number IF you stray from the defaults. | I think I have it:
```
SELECT b FROM y where a=if(@value IN (select a from y group by a),@value,0);
```
It checks if @value exists in the table, if not, then it uses 0 as a default.
@value can be a php value too.
Hope it helps :) |
108,292 | <p>When developing an application that sends out notification email messages, what are the best practices for </p>
<ol>
<li>not getting flagged as a spammer by your hosting company. (Cover any of:)
<ul>
<li>best technique for not flooding a mail server</li>
<li>best mail server products, if you were to set up your own</li>
<li>sending messages as if from a specific user but still clearly from your application (to ensure complaints, etc come back to you) without breaking good email etiquette</li>
<li>any other lessons learned</li>
</ul></li>
<li>not getting flagged as spam by the receiver's client? (Cover any of:)
<ul>
<li>configuring and using sender-id, domain-keys, SPF, reverse-dns, etc to make sure your emails are properly identified</li>
<li>best SMTP header techniques to avoid getting flagged as spam when sending emails for users (for example, using Sender and From headers together)</li>
<li>any other lessons learned</li>
</ul></li>
</ol>
<p>An additional requirement: this application would be sending a single message to a single recipient based upon an event. So, techniques for sending the same messages to multiple recipients will not apply.</p>
| [
{
"answer_id": 112607,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>best technique for not flooding a mail server</p>\n</blockquote>\n\n<p>not a lot you can do about this beyond... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16099/"
] | When developing an application that sends out notification email messages, what are the best practices for
1. not getting flagged as a spammer by your hosting company. (Cover any of:)
* best technique for not flooding a mail server
* best mail server products, if you were to set up your own
* sending messages as if from a specific user but still clearly from your application (to ensure complaints, etc come back to you) without breaking good email etiquette
* any other lessons learned
2. not getting flagged as spam by the receiver's client? (Cover any of:)
* configuring and using sender-id, domain-keys, SPF, reverse-dns, etc to make sure your emails are properly identified
* best SMTP header techniques to avoid getting flagged as spam when sending emails for users (for example, using Sender and From headers together)
* any other lessons learned
An additional requirement: this application would be sending a single message to a single recipient based upon an event. So, techniques for sending the same messages to multiple recipients will not apply. | >
> best technique for not flooding a mail server
>
>
>
not a lot you can do about this beyond checking with your mail server admin (if it's a shared hosting account / not in your control). but if the requirement is one email to a single recipient per event, that shouldn't be too much of an issue. the things that tend to clog mail systems are emails with hundreds (or more) of recipients.
if you have events firing off all the time, perhaps consider consolidating them and having an email sent that summarizes them periodically.
>
> sending messages as if from a specific user but still clearly from your application (to ensure complaints, etc come back to you) without breaking good email etiquette
>
>
>
you can accomplish this by using the "Reply-To" header, which will then have clients use that address instead of the From address when an email message is being composed.
you should also set the "Return-Path" header of any email, as email without this will often get filtered off.
ex.
```
From: me@me.com
Return-Path: me@me.com
Reply-To: auto@myapp.com
```
>
> configuring and using sender-id, domain-keys, SPF, reverse-dns, etc to make sure your emails are properly identified
>
>
>
this is all highly dependent on how much ownership you have of your mail and DNS servers. spf/sender-id etc... are all DNS issues, so you would need to have access to DNS.
in your example this could present quite the problem. as you are setting mail to be from a specific user, that user would have to have SPF (for example) set in their DNS to allow your mail server as a valid sender. you can imagine how messy (if not outright impossible) this would get with a number of users with various domain names.
as for reverse DNS and the like, it really depends. most client ISP's, etc... will just check to see that reverse DNS is set. (ie, 1.2.3.4 resolves to host.here.domain.com, even if host.here.domain.com doesn't resolve back to 1.2.3.4). this is due to the amount of shared hosting out there (where mail servers will often report themselves as the client's domain name, and not the real mail server).
there are a few stringent networks that require matching reverse DNS, but this requires that you have control over the mail server if it doesn't match in the first place.
if you can be a bit more specific i may be able to provide a bit more advice, but generally, for people who need to send application mail, and don't have a pile of control over their environment, i'd suggest the following:
* make sure to set a "Return-Path"
* it's nice to add your app and abuse info as well in headers ie: "X-Mailer" and "X-Abuse-To" (these are custom headers, for informational purposes only really)
* make sure reverse DNS is set for the IP address of your outgoing mail server |
108,301 | <p>I was going to ask what the best way to do this is, but then decided I should ask whether or not it is even necessary. I have never seen it done in <code>JSP</code> development, but it appears to be common practice in <code>PHP</code>. What is the reasoning behind this, and if I do not protect against this, what else should I be taking into consideration?</p>
| [
{
"answer_id": 108309,
"author": "Issac Kelly",
"author_id": 144,
"author_profile": "https://Stackoverflow.com/users/144",
"pm_score": 1,
"selected": false,
"text": "<p>Well, This is to prevent sensitive includes from being sent to the web-server directly. It's certainly not an all-incl... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I was going to ask what the best way to do this is, but then decided I should ask whether or not it is even necessary. I have never seen it done in `JSP` development, but it appears to be common practice in `PHP`. What is the reasoning behind this, and if I do not protect against this, what else should I be taking into consideration? | The reason this is more common in PHP than other similar languages has to do with PHP's history. Early versions of PHP had the "register\_globals" setting on as a default (in fact, it may not have even been a setting in really early versions). Register\_globals tells PHP to define global variables according to the query string. So if you queried such a script thusly:
```
http://site.com/script.php?hello=world&foo=bar
```
... the script would automatically define a variable $hello with value "world" and $foo with value "bar."
For such a script, if you knew the names of key variables, it was possible to exploit the script by specifying those variables on the query string. The solution? Define some magic string in the core script and then make all the ancilliary scripts check for the magic string and bail out if it's not there.
Thankfully, almost nobody uses register\_variables anymore, but many scripts are still very poorly written and make stupid assumptions that cause them to do damage if they are called out of context.
Personally, I avoid the whole thing by using the Symfony framework, which (at least in its default setup) keeps the controllers and templates out of the web root altogether. The only entry point is the front controller. |
108,318 | <p>I need a function like this:</p>
<pre><code>// return true if 'n' is a power of 2, e.g.
// is_power_of_2(16) => true
// is_power_of_2(3) => false
bool is_power_of_2(int n);
</code></pre>
<p>Can anyone suggest how I could write this?</p>
| [
{
"answer_id": 108329,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 6,
"selected": false,
"text": "<p>A power of two will have just one bit set (for unsigned numbers). Something like</p>\n\n<pre><code>bool powerOfTwo = ... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19641/"
] | I need a function like this:
```
// return true if 'n' is a power of 2, e.g.
// is_power_of_2(16) => true
// is_power_of_2(3) => false
bool is_power_of_2(int n);
```
Can anyone suggest how I could write this? | `(n & (n - 1)) == 0` is best. However, note that it will incorrectly return true for n=0, so if that is possible, you will want to check for it explicitly.
<http://www.graphics.stanford.edu/~seander/bithacks.html> has a large collection of clever bit-twiddling algorithms, including this one. |
108,346 | <p>Something i've never really done before, but what is the best way to make sure that any external assemblies/dll's that my application uses are available, and possibly the correct version.</p>
<p>I wrote an app that relies on the System.Data.SQLite.dll, i went to test it on a machine where that dll was missing, and my app just threw up a runtime exception because the dll was missing. How can i trap this error?</p>
| [
{
"answer_id": 108372,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 0,
"selected": false,
"text": "<p>You should trap the error outside of your main loop.<br>\nOr if you want to ship/locate your own assemblies you can try ... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19638/"
] | Something i've never really done before, but what is the best way to make sure that any external assemblies/dll's that my application uses are available, and possibly the correct version.
I wrote an app that relies on the System.Data.SQLite.dll, i went to test it on a machine where that dll was missing, and my app just threw up a runtime exception because the dll was missing. How can i trap this error? | What you want to do is use reflection to check and see if the assembly can be loaded into memory. Wrap that up in a try..catch block and handle any of the specific exceptions that come from it.
```
Try
Assembly.Load("System.Data.SQLite, Version=1.0.22.0, Culture=neutral, PublicKeyToken=DB937BC2D44FF139");
Catch ex As FileNotFoundException
//do something here
End Try
``` |
108,389 | <pre><code>class MyContainedClass {
};
class MyClass {
public:
MyContainedClass * getElement() {
// ...
std::list<MyContainedClass>::iterator it = ... // retrieve somehow
return &(*it);
}
// other methods
private:
std::list<MyContainedClass> m_contained;
};
</code></pre>
<p>Though msdn says <code>std::list</code> should not perform relocations of elements on deletion or insertion, is it a good and common way to return pointer to a list element?</p>
<p>PS: I know that I can use collection of pointers (and will have to <code>delete</code> elements in destructor), collection of shared pointers (which I don't like), etc.</p>
| [
{
"answer_id": 108409,
"author": "Andrew Queisser",
"author_id": 18321,
"author_profile": "https://Stackoverflow.com/users/18321",
"pm_score": 0,
"selected": false,
"text": "<p>I think the bigger problem is that you're hiding the type of collection so even if you use a collection that do... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14535/"
] | ```
class MyContainedClass {
};
class MyClass {
public:
MyContainedClass * getElement() {
// ...
std::list<MyContainedClass>::iterator it = ... // retrieve somehow
return &(*it);
}
// other methods
private:
std::list<MyContainedClass> m_contained;
};
```
Though msdn says `std::list` should not perform relocations of elements on deletion or insertion, is it a good and common way to return pointer to a list element?
PS: I know that I can use collection of pointers (and will have to `delete` elements in destructor), collection of shared pointers (which I don't like), etc. | I don't see the use of encapsulating this, but that may be just me. In any case, returning a reference instead of a pointer makes a lot more sense to me. |
108,396 | <p>I am using Fluent NHibernate and having some issues getting a many to many relationship setup with one of my classes. It's probably a stupid mistake but I've been stuck for a little bit trying to get it working. Anyways, I have a couple classes that have Many-Many relationships. </p>
<pre><code>public class Person
{
public Person()
{
GroupsOwned = new List<Groups>();
}
public virtual IList<Groups> GroupsOwned { get; set; }
}
public class Groups
{
public Groups()
{
Admins= new List<Person>();
}
public virtual IList<Person> Admins{ get; set; }
}
</code></pre>
<p>With the mapping looking like this</p>
<p>Person: ...</p>
<pre><code>HasManyToMany<Groups>(x => x.GroupsOwned)
.WithTableName("GroupAdministrators")
.WithParentKeyColumn("PersonID")
.WithChildKeyColumn("GroupID")
.Cascade.SaveUpdate();
</code></pre>
<p>Groups: ...</p>
<pre><code> HasManyToMany<Person>(x => x.Admins)
.WithTableName("GroupAdministrators")
.WithParentKeyColumn("GroupID")
.WithChildKeyColumn("PersonID")
.Cascade.SaveUpdate();
</code></pre>
<p>When I run my integration test, basically I'm creating a new person and group. Adding the Group to the Person.GroupsOwned. If I get the Person Object back from the repository, the GroupsOwned is equal to the initial group, however, when I get the group back if I check count on Group.Admins, the count is 0. The Join table has the GroupID and the PersonID saved in it. </p>
<p>Thanks for any advice you may have.</p>
| [
{
"answer_id": 108694,
"author": "emeryc",
"author_id": 3900,
"author_profile": "https://Stackoverflow.com/users/3900",
"pm_score": 0,
"selected": false,
"text": "<p>Are you making sure to add the Person to the Groups.Admin? You have to make both links.</p>\n"
},
{
"answer_id": 1... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385358/"
] | I am using Fluent NHibernate and having some issues getting a many to many relationship setup with one of my classes. It's probably a stupid mistake but I've been stuck for a little bit trying to get it working. Anyways, I have a couple classes that have Many-Many relationships.
```
public class Person
{
public Person()
{
GroupsOwned = new List<Groups>();
}
public virtual IList<Groups> GroupsOwned { get; set; }
}
public class Groups
{
public Groups()
{
Admins= new List<Person>();
}
public virtual IList<Person> Admins{ get; set; }
}
```
With the mapping looking like this
Person: ...
```
HasManyToMany<Groups>(x => x.GroupsOwned)
.WithTableName("GroupAdministrators")
.WithParentKeyColumn("PersonID")
.WithChildKeyColumn("GroupID")
.Cascade.SaveUpdate();
```
Groups: ...
```
HasManyToMany<Person>(x => x.Admins)
.WithTableName("GroupAdministrators")
.WithParentKeyColumn("GroupID")
.WithChildKeyColumn("PersonID")
.Cascade.SaveUpdate();
```
When I run my integration test, basically I'm creating a new person and group. Adding the Group to the Person.GroupsOwned. If I get the Person Object back from the repository, the GroupsOwned is equal to the initial group, however, when I get the group back if I check count on Group.Admins, the count is 0. The Join table has the GroupID and the PersonID saved in it.
Thanks for any advice you may have. | The fact that it is adding two records to the table looks like you are missing an [inverse attribute](http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#example-many-to-many-mapping-file). Since both the person and the group are being changed, NHibernate is persisting the relation twice (once for each object). The inverse attribute is specifically for avoiding this.
I'm not sure about how to add it in mapping in code, but the link shows how to do it in XML. |
108,403 | <p>Assume a table structure of <code>MyTable(KEY, datafield1, datafield2...)</code>.</p>
<p>Often I want to either update an existing record, or insert a new record if it doesn't exist.</p>
<p>Essentially:</p>
<pre><code>IF (key exists)
run update command
ELSE
run insert command
</code></pre>
<p>What's the best performing way to write this?</p>
| [
{
"answer_id": 108408,
"author": "Clint Ecker",
"author_id": 13668,
"author_profile": "https://Stackoverflow.com/users/13668",
"pm_score": -1,
"selected": false,
"text": "<p>Do a select, if you get a result, update it, if not, create it.</p>\n"
},
{
"answer_id": 108410,
"auth... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18907/"
] | Assume a table structure of `MyTable(KEY, datafield1, datafield2...)`.
Often I want to either update an existing record, or insert a new record if it doesn't exist.
Essentially:
```
IF (key exists)
run update command
ELSE
run insert command
```
What's the best performing way to write this? | don't forget about transactions. Performance is good, but simple (IF EXISTS..) approach is very dangerous.
When multiple threads will try to perform Insert-or-update you can easily
get primary key violation.
Solutions provided by @Beau Crawford & @Esteban show general idea but error-prone.
To avoid deadlocks and PK violations you can use something like this:
```
begin tran
if exists (select * from table with (updlock,serializable) where key = @key)
begin
update table set ...
where key = @key
end
else
begin
insert into table (key, ...)
values (@key, ...)
end
commit tran
```
or
```
begin tran
update table with (serializable) set ...
where key = @key
if @@rowcount = 0
begin
insert into table (key, ...) values (@key,..)
end
commit tran
``` |
108,439 | <p>I'm looking to get the result of a command as a variable in a Windows batch script (see <a href="https://stackoverflow.com/questions/58207/using-the-result-of-a-command-as-an-argument-in-bash#58214">how to get the result of a command in bash</a> for the bash scripting equivalent). A solution that will work in a .bat file is preferred, but other common windows scripting solutions are also welcome. </p>
| [
{
"answer_id": 108462,
"author": "Jack B Nimble",
"author_id": 3800,
"author_profile": "https://Stackoverflow.com/users/3800",
"pm_score": -1,
"selected": false,
"text": "<p>Please refer to this <a href=\"http://technet.microsoft.com/en-us/library/bb490982.aspx\" rel=\"nofollow noreferre... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535/"
] | I'm looking to get the result of a command as a variable in a Windows batch script (see [how to get the result of a command in bash](https://stackoverflow.com/questions/58207/using-the-result-of-a-command-as-an-argument-in-bash#58214) for the bash scripting equivalent). A solution that will work in a .bat file is preferred, but other common windows scripting solutions are also welcome. | If you have to capture all the command output you can use a batch like this:
```
@ECHO OFF
IF NOT "%1"=="" GOTO ADDV
SET VAR=
FOR /F %%I IN ('DIR *.TXT /B /O:D') DO CALL %0 %%I
SET VAR
GOTO END
:ADDV
SET VAR=%VAR%!%1
:END
```
All output lines are stored in VAR separated with "!".
But if only a single-line console-output is expected, try:
```
@ECHO off
@SET MY_VAR=
FOR /F %%I IN ('npm prefix') DO @SET "MY_VAR=%%I"
@REM Do something with MY_VAR variable...
```
@John: is there any practical use for this? I think you should watch PowerShell or any other programming language capable to perform scripting tasks easily (Python, Perl, PHP, Ruby) |
108,443 | <p>I'm planning to create a data structure optimized to hold assembly code. That way I can be totally responsible for the optimization algorithms that will be working on this structure. If I can compile while running. It will be kind of dynamic execution. Is this possible? Have any one seen something like this?</p>
<p>Should I use structs to link the structure into a program flow. Are objects better?</p>
<pre><code>struct asm_code {
int type;
int value;
int optimized;
asm_code *next_to_execute;
} asm_imp;
</code></pre>
<p>Update: I think it will turn out, like a linked list.</p>
<p>Update: I know there are other compilers out there. But this is a military top secret project. So we can't trust any code. We have to do it all by ourselves.</p>
<p>Update: OK, I think I will just generate basic i386 machine code. But how do I jump into my memory blob when it is finished?</p>
| [
{
"answer_id": 108493,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 3,
"selected": false,
"text": "<p>It is possible. Dynamic code generation is even mainstream in some areas like software rendering and graphics.... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15054/"
] | I'm planning to create a data structure optimized to hold assembly code. That way I can be totally responsible for the optimization algorithms that will be working on this structure. If I can compile while running. It will be kind of dynamic execution. Is this possible? Have any one seen something like this?
Should I use structs to link the structure into a program flow. Are objects better?
```
struct asm_code {
int type;
int value;
int optimized;
asm_code *next_to_execute;
} asm_imp;
```
Update: I think it will turn out, like a linked list.
Update: I know there are other compilers out there. But this is a military top secret project. So we can't trust any code. We have to do it all by ourselves.
Update: OK, I think I will just generate basic i386 machine code. But how do I jump into my memory blob when it is finished? | It is possible. Dynamic code generation is even mainstream in some areas like software rendering and graphics. You find a lot of use in all kinds of script languages, in dynamic compilation of byte-code in machine code (.NET, Java, as far as I know Perl. Recently JavaScript joined the club as well).
You also find it used in very math-heavy applications as well, It makes a difference if you for example remove all multiplication with zero out of a matrix multiplication if you plan to do such a multiplication several thousand times.
I strongly suggest that you read on the SSA representation of code. That's a representation where each primitive is turned into the so called three operand form, and each variable is only assigned once (hence the same Static Single Assignment form).
You can run high order optimizations on such code, and it's straight forward to turn that code into executable code. You won't write that code-generation backend on a weekend though...
To get a feeling how the SSA looks like you can try out the LLVM compiler. On their web-site they have a little "Try Out" widget to play with. You paste C code into a window and you get something out that is close to the SSA form.
Little example how it looks like:
Lets take this integer square root algorithm in C. (arbitrary example, I just took something simple yet non-trivial):
```
unsigned int isqrt32 (unsigned int value)
{
unsigned int g = 0;
unsigned int bshift = 15;
unsigned int b = 1<<bshift;
do {
unsigned int temp = (g+g+b)<<bshift;
if (value >= temp) {
g += b;
value -= temp;
}
b>>=1;
} while (bshift--);
return g;
}
```
LLVM turns it into:
```
define i32 @isqrt32(i32 %value) nounwind {
entry:
br label %bb
bb: ; preds = %bb, %entry
%indvar = phi i32 [ 0, %entry ], [ %indvar.next, %bb ]
%b.0 = phi i32 [ 32768, %entry ], [ %tmp23, %bb ]
%g.1 = phi i32 [ 0, %entry ], [ %g.0, %bb ]
%value_addr.1 = phi i32 [ %value, %entry ], [ %value_addr.0, %bb ]
%bshift.0 = sub i32 15, %indvar
%tmp5 = shl i32 %g.1, 1
%tmp7 = add i32 %tmp5, %b.0
%tmp9 = shl i32 %tmp7, %bshift.0
%tmp12 = icmp ult i32 %value_addr.1, %tmp9
%tmp17 = select i1 %tmp12, i32 0, i32 %b.0
%g.0 = add i32 %tmp17, %g.1
%tmp20 = select i1 %tmp12, i32 0, i32 %tmp9
%value_addr.0 = sub i32 %value_addr.1, %tmp20
%tmp23 = lshr i32 %b.0, 1
%indvar.next = add i32 %indvar, 1
%exitcond = icmp eq i32 %indvar.next, 16
br i1 %exitcond, label %bb30, label %bb
bb30: ; preds = %bb
ret i32 %g.0
}
```
I know it looks horrible at first. It's not even pure SSA-Form. The more you read on that representation the more sense it will make. And you will also find out why this representation is so widely used these days.
Encapsulating all the info you need into a data-structure is easy. In the end you have to decide if you want to use enums or strings for opcode names ect.
Btw - I know I didn't gave you a data-structure but more a formal yet practical language and the advice where to look further.
It's a very nice and interesting research field.
Edit: And before I forget it: Don't overlook the built in features of .NET and Java. These languates allow you to compile from byte-code or source code from within the program and execute the result.
Cheers,
Nils
---
Regarding your edit: How to execute a binary blob with code:
Jumping into your binary blob is OS and platform dependent. In a nutshell you have invalide the instruction cache, *maybe* you have to writeback the data-cache and you may have to enable execution rights on the memory-region you've wrote your code into.
On win32 it's relative easy as instruction cache flushing seems to be sufficient if you place your code on the heap.
You can use this stub to get started:
```
typedef void (* voidfunc) (void);
void * generate_code (void)
{
// reserve some space
unsigned char * buffer = (unsigned char *) malloc (1024);
// write a single RET-instruction
buffer[0] = 0xc3;
return buffer;
}
int main (int argc, char **args)
{
// generate some code:
voidfunc func = (voidfunc) generate_code();
// flush instruction cache:
FlushInstructionCache(GetCurrentProcess(), func, 1024);
// execute the code (it does nothing atm)
func();
// free memory and exit.
free (func);
}
``` |
108,461 | <p>I have a small gallery of thumbnails. When I place my mouse pointer over a thumbnail image I'd like to have a full size image pop up in a div in the top right of the screen. I've seen this done using just CSS and I'd like to go down that route rather than use javascript if possible.</p>
| [
{
"answer_id": 108479,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 0,
"selected": false,
"text": "<p>Eric Meyer's <a href=\"http://meyerweb.com/eric/css/edge/popups/demo2.html\" rel=\"nofollow noreferrer\">Pure CSS Po... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18748/"
] | I have a small gallery of thumbnails. When I place my mouse pointer over a thumbnail image I'd like to have a full size image pop up in a div in the top right of the screen. I've seen this done using just CSS and I'd like to go down that route rather than use javascript if possible. | [Pure CSS Popups2](http://meyerweb.com/eric/css/edge/popups/demo2.html), from the same site that brings us Complexspiral. Note that this example is using actual navigational links as the rolled-over element. If you don't want that, it may cause some stickiness regarding versions of IE.
The basic technique is to stick each image inside a link tag with an actual href (Otherwise some IE versions will neglect :hover)
```
<a href="#">Text <img class="popup" src="pic.gif" /></a>
```
and position it cleverly using absolute position. Hide the image initially
```
a img.popup { display: none }
```
and then on the link rollover, set it up to appear.
```
a:hover img.popup { display: block }
```
That's the basic technique, but there are always going to be major positioning limitations since the image tag dwells inside the link tag. See the link for details; he uses something a little more tricky than display: none to hide the image. |
108,523 | <p>I've been using a small class to emulate Enums in some Python projects. Is there a better way or does this make the most sense for some situations?</p>
<p>Class code here:</p>
<pre><code>class Enum(object):
'''Simple Enum Class
Example Usage:
>>> codes = Enum('FOO BAR BAZ') # codes.BAZ will be 2 and so on ...'''
def __init__(self, names):
for number, name in enumerate(names.split()):
setattr(self, name, number)
</code></pre>
| [
{
"answer_id": 108547,
"author": "Ycros",
"author_id": 10495,
"author_profile": "https://Stackoverflow.com/users/10495",
"pm_score": 3,
"selected": false,
"text": "<p>Enums have been proposed for inclusion into the language before, but were rejected (see <a href=\"http://www.python.org/d... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9127/"
] | I've been using a small class to emulate Enums in some Python projects. Is there a better way or does this make the most sense for some situations?
Class code here:
```
class Enum(object):
'''Simple Enum Class
Example Usage:
>>> codes = Enum('FOO BAR BAZ') # codes.BAZ will be 2 and so on ...'''
def __init__(self, names):
for number, name in enumerate(names.split()):
setattr(self, name, number)
``` | There's a lot of good discussion [here](https://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python). |
108,558 | <p>Can a cookie be shared between two sites on the same top level domain? Say <code>www.example.com</code> and <code>secure.example.com</code> ?
We are looking into implementing a cache for non-secure content, and need to segregate secure content to another domain.
What parameters does the cookie need? I'm using asp.net</p>
| [
{
"answer_id": 108569,
"author": "Rich Bradshaw",
"author_id": 16511,
"author_profile": "https://Stackoverflow.com/users/16511",
"pm_score": 6,
"selected": true,
"text": "<p>Yes, you can. Use:</p>\n\n<pre><code>Response.Cookies(\"UID\").Domain = \".myserver.com\"\n</code></pre>\n"
},
... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7277/"
] | Can a cookie be shared between two sites on the same top level domain? Say `www.example.com` and `secure.example.com` ?
We are looking into implementing a cache for non-secure content, and need to segregate secure content to another domain.
What parameters does the cookie need? I'm using asp.net | Yes, you can. Use:
```
Response.Cookies("UID").Domain = ".myserver.com"
``` |
108,567 | <p>I have a SVN structure like this:</p>
<pre><code>/Projects
/Project1
/Project2
/someFolder
/Project3
/Project4
</code></pre>
<p>I would like to move all the projects into the /Projects folder, which means I want to move Projects 3 and 4 from /someFolder into the /projects folder.</p>
<p>The caveat: I'd like to keep the full history. I assume that every client would have to check out the stuff from the new location again, which is fine, but I still wonder what the simplest approach is to move directories without completely destroying the history?</p>
<p>Subversion 1.5 if that matters.</p>
| [
{
"answer_id": 108571,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 2,
"selected": false,
"text": "<p>Moving directories in Subversion doesn't destroy history, AFAIK.</p>\n"
},
{
"answer_id": 108573,
"auth... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | I have a SVN structure like this:
```
/Projects
/Project1
/Project2
/someFolder
/Project3
/Project4
```
I would like to move all the projects into the /Projects folder, which means I want to move Projects 3 and 4 from /someFolder into the /projects folder.
The caveat: I'd like to keep the full history. I assume that every client would have to check out the stuff from the new location again, which is fine, but I still wonder what the simplest approach is to move directories without completely destroying the history?
Subversion 1.5 if that matters. | ```
svn help rename
```
Moving/renaming in subversion keeps history intact. |
108,586 | <p>Data: a dependency list, already verified to be acyclic. So here, 'a' depends on 'b','c' (c depends on d), etc... </p>
<pre><code>A = { 'a' : dict(b=1, c=1),
'c' : dict(d=1),
'd' : dict(e=1,f=1,g=1),
'h' : dict(j=1)
}
</code></pre>
<p>I'd like to have a top-down, recursive solution to let's say, find the chain starting at
'a': a, c, d, e, g, f, b</p>
<p>So, right now (a non-generator solution):</p>
<pre><code>def get_all(D,k):
L = []
def get2(D,k):
L.append(k)
for ii in D.get(k,[]):
get2(D, ii)
get2(D,k)
return L
</code></pre>
<p>Obviously, this is pretty weak :) I've been banging my head about how to how to get yields inside there, and I'd appreciate any py-foo y'all can bring to this.</p>
| [
{
"answer_id": 108606,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 3,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code>#!/usr/bin/env python\n\ndef get_all(D, k):\n yield k\n for ii in D.get(k, []):\n ... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15842/"
] | Data: a dependency list, already verified to be acyclic. So here, 'a' depends on 'b','c' (c depends on d), etc...
```
A = { 'a' : dict(b=1, c=1),
'c' : dict(d=1),
'd' : dict(e=1,f=1,g=1),
'h' : dict(j=1)
}
```
I'd like to have a top-down, recursive solution to let's say, find the chain starting at
'a': a, c, d, e, g, f, b
So, right now (a non-generator solution):
```
def get_all(D,k):
L = []
def get2(D,k):
L.append(k)
for ii in D.get(k,[]):
get2(D, ii)
get2(D,k)
return L
```
Obviously, this is pretty weak :) I've been banging my head about how to how to get yields inside there, and I'd appreciate any py-foo y'all can bring to this. | Try this:
```
#!/usr/bin/env python
def get_all(D, k):
yield k
for ii in D.get(k, []):
for jj in get_all(D, ii):
yield jj
A = { 'a' : dict(b=1, c=1),
'c' : dict(d=1),
'd' : dict(e=1,f=1,g=1),
'h' : dict(j=1)
}
for ii in get_all(A,'a'):
print ii
```
Gives me
```
steve@rei:~/code/tmp
$ python recur.py
a
c
d
e
g
f
b
``` |
108,598 | <p>Considering the following architecture:</p>
<ul>
<li>a base object 'Entity'</li>
<li>a derived object 'Entry:Base'</li>
<li>and a further derived object 'CancelledEntry:Entry'</li>
</ul>
<p>In EntitySQL I can write the following: </p>
<pre><code>[...] where it is of (only MyEntities.Entry) [...]
</code></pre>
<p>to return only objects of type Entry and no Entity or CancelledEntry.</p>
<p>In linq to sql, the following command will return objects of type Entry and CancelledEntry. </p>
<pre><code>EntityContext.EntitySet.OfType<Entry>()
</code></pre>
<p>What is the syntax/function to use to return only objects of type Entry?</p>
| [
{
"answer_id": 108644,
"author": "ADB",
"author_id": 3610,
"author_profile": "https://Stackoverflow.com/users/3610",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, I have found a partial solution:</p>\n\n<pre><code>EntityContext.EntitySet.OfType<Entry>().Where( obj => !(obj i... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3610/"
] | Considering the following architecture:
* a base object 'Entity'
* a derived object 'Entry:Base'
* and a further derived object 'CancelledEntry:Entry'
In EntitySQL I can write the following:
```
[...] where it is of (only MyEntities.Entry) [...]
```
to return only objects of type Entry and no Entity or CancelledEntry.
In linq to sql, the following command will return objects of type Entry and CancelledEntry.
```
EntityContext.EntitySet.OfType<Entry>()
```
What is the syntax/function to use to return only objects of type Entry? | Why don't you apply an extension method on IQueryable< Entry > called ApplyBaseEntryFilter() which would apply this filter and return an IQueryable< Entry >.
This is an example of how to reuse linq query fragments. Using extension methods on IQueryable< Entity > is a great way to re-use queries as you should neve rneed to copy and paste query fragments around your application, hope that helps. |
108,682 | <p><a href="http://svnbook.red-bean.com/nightly/en/svn.tour.importing.html#svn.tour.importing.layout" rel="nofollow noreferrer"><em>Version Control with Subversion</em></a> recommends the following layout for (single-project) repositories (complemented by <a href="https://stackoverflow.com/questions/49356/what-is-a-good-repository-layout-for-releases-and-projects-in-subversion"><em>this question</em></a>):</p>
<pre><code>/trunk
/tags
/rel.1 (approximately)
...
/branches
/rel1fixes
</code></pre>
<p>What are the relative merits of this arrangement when compared with a (perhaps) more process-oriented one?:</p>
<pre><code>/development
/current
/stable
/qa (maybe)
...
/production
/stable
/Prod.2
/Prod.1
/vendor
/Rel.5.1
/Rel.5.2
</code></pre>
<p>Please note that I'm thinking of in-house deployment, rather than building a product.</p>
<p>Disclaimer: although I'm a Subversion user, I've never had to deploy with it in a real live environment. </p>
| [
{
"answer_id": 108700,
"author": "neu242",
"author_id": 13365,
"author_profile": "https://Stackoverflow.com/users/13365",
"pm_score": 0,
"selected": false,
"text": "<p>Whenever you deal with real live environments, you would want your developers to be able to understand your repository a... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9634/"
] | [*Version Control with Subversion*](http://svnbook.red-bean.com/nightly/en/svn.tour.importing.html#svn.tour.importing.layout) recommends the following layout for (single-project) repositories (complemented by [*this question*](https://stackoverflow.com/questions/49356/what-is-a-good-repository-layout-for-releases-and-projects-in-subversion)):
```
/trunk
/tags
/rel.1 (approximately)
...
/branches
/rel1fixes
```
What are the relative merits of this arrangement when compared with a (perhaps) more process-oriented one?:
```
/development
/current
/stable
/qa (maybe)
...
/production
/stable
/Prod.2
/Prod.1
/vendor
/Rel.5.1
/Rel.5.2
```
Please note that I'm thinking of in-house deployment, rather than building a product.
Disclaimer: although I'm a Subversion user, I've never had to deploy with it in a real live environment. | The main difference between the recommended layout and your proposed layout is that the recommended layout is somewhat self-documenting as to where to commit things, and how it behaves.
For example, in the recommended layout, it's obvious that all new development is committed to trunk, and most branches are made from trunk. Also, it's obvious that you should never commit anything into /tags. Finally, it's safe to assume that branches are truly branches, which may contain changes specific to that particular branch purpose.
With the proposed layout, some of these things are less certain. Is /development/stable branched from /current? What's the relation between /development/stable and /production/stable? Which of these directories are tags, and which ones can I actually check stuff into?
Certainly this behavior can be documented, but by sticking to the accepted layout that everybody uses, you'll have an easier time getting new hires up to speed on how it works. |
108,687 | <p>I want to create a box shape and I am having trouble.
I want the box to have a background color, and then different color inside the box.<br>
The box will then have a list of items using ul and li, and each list item will have a background of white, and the list item's background color is too stretch the entire distance of the inner box.
Also, the list items should have a 1 px spacing between each one, so that the background color of the inside box color is visible.</p>
<p>Here is a rough sketch of what I am trying to do:</p>
<p><a href="https://i.stack.imgur.com/aZ2W7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aZ2W7.png" alt=""></a></p>
| [
{
"answer_id": 108708,
"author": "Mike Tunnicliffe",
"author_id": 13956,
"author_profile": "https://Stackoverflow.com/users/13956",
"pm_score": 2,
"selected": false,
"text": "<p>So if you have source:</p>\n\n<pre><code><div class=\"panel\">\n <div>Some other stuff</div>... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] | I want to create a box shape and I am having trouble.
I want the box to have a background color, and then different color inside the box.
The box will then have a list of items using ul and li, and each list item will have a background of white, and the list item's background color is too stretch the entire distance of the inner box.
Also, the list items should have a 1 px spacing between each one, so that the background color of the inside box color is visible.
Here is a rough sketch of what I am trying to do:
[](https://i.stack.imgur.com/aZ2W7.png) | You can do this pretty cleanly with this css:
```
.box {
width: 100px;
border: solid #884400;
border-width: 8px 3px 8px 3px;
background-color: #ccaa77;
}
.box ul {
margin: 0px;
padding: 0px;
padding-top: 50px; /* presuming the non-list header space at the top of
your box is desirable */
}
.box ul li {
margin: 0px 2px 2px 2px; /* reduce to 1px if you find the separation
sufficiently visible */
background-color: #ffffff;
list-style-type: none;
padding-left: 2px;
}
```
and this html:
```
<div class="box">
<ul>
<li>Lorem</li>
<li>Ipsum</li>
</ul>
</div>
```
[DEMO](http://jsfiddle.net/0b7w65qv/) |
108,768 | <p>I got a comment to my answer on this thread:</p>
<p><a href="https://stackoverflow.com/questions/105477">Malloc inside a function call appears to be getting freed on return?</a></p>
<p>In short I had code like this:</p>
<pre><code>int * somefunc (void)
{
int * temp = (int*) malloc (sizeof (int));
temp[0] = 0;
return temp;
}
</code></pre>
<p>I got this comment:</p>
<blockquote>
<p>Can I just say, please don't cast the
return value of malloc? It is not
required and can hide errors.</p>
</blockquote>
<p>I agree that the cast is not required in C. It is mandatory in C++, so I usually add them just in case I have to port the code in C++ one day.</p>
<p>However, I wonder how casts like this can hide errors. Any ideas?</p>
<h1>Edit:</h1>
<p>Seems like there are very good and valid arguments on both sides. Thanks for posting, folks.</p>
| [
{
"answer_id": 108780,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 0,
"selected": false,
"text": "<p>Casting a function which returns (void *) to instead be an (int *) is harmless: you're casting one type of pointer to ano... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15955/"
] | I got a comment to my answer on this thread:
[Malloc inside a function call appears to be getting freed on return?](https://stackoverflow.com/questions/105477)
In short I had code like this:
```
int * somefunc (void)
{
int * temp = (int*) malloc (sizeof (int));
temp[0] = 0;
return temp;
}
```
I got this comment:
>
> Can I just say, please don't cast the
> return value of malloc? It is not
> required and can hide errors.
>
>
>
I agree that the cast is not required in C. It is mandatory in C++, so I usually add them just in case I have to port the code in C++ one day.
However, I wonder how casts like this can hide errors. Any ideas?
Edit:
=====
Seems like there are very good and valid arguments on both sides. Thanks for posting, folks. | It seems fitting I post an answer, since I left the comment :P
Basically, if you forget to include `stdlib.h` the compiler will assume `malloc` returns an `int`. Without casting, you will get a warning. With casting you won't.
So by casting you get nothing, and run the risk of suppressing legitimate warnings.
Much is written about this, a quick google search will turn up more detailed explanations.
edit
----
It has been argued that
```
TYPE * p;
p = (TYPE *)malloc(n*sizeof(TYPE));
```
makes it obvious when you accidentally don't allocate enough memory because say, you thought `p` was `TYPe` not `TYPE`, and thus we should cast malloc because the advantage of this method overrides the smaller cost of accidentally suppressing compiler warnings.
I would like to point out 2 things:
1. you should write `p = malloc(sizeof(*p)*n);` to always ensure you malloc the right amount of space
2. with the above approach, you need to make changes in 3 places if you ever change the type of `p`: once in the declaration, once in the `malloc`, and once in the cast.
In short, I still personally believe there is no need for casting the return value of `malloc` and it is certainly not best practice. |
108,813 | <p>How can I Handler 404 errors without the framework throwing an Exception 500 error code?</p>
| [
{
"answer_id": 108830,
"author": "dave",
"author_id": 14355,
"author_profile": "https://Stackoverflow.com/users/14355",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://jason.whitehorn.ws/2008/06/17/Friendly-404-Errors-In-ASPNET-MVC.aspx\" rel=\"noreferrer\">http://jason.whi... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19710/"
] | How can I Handler 404 errors without the framework throwing an Exception 500 error code? | <http://jason.whitehorn.ws/2008/06/17/Friendly-404-Errors-In-ASPNET-MVC.aspx> gives the following explanation:
Add a wildcard routing rule as your final rule:
```
routes.MapRoute("Error",
"{*url}",
new { controller = "Error", action = "Http404" });
```
Any request that doesn't match another rule gets routed to the Http404 action of the Error controller, which you also need to configure:
```
public ActionResult Http404(string url) {
Response.StatusCode = 404;
ViewData["url"] = url;
return View();
}
``` |
108,819 | <p>What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I'd like to create a new <code>Array</code> with the same strings but in a random order.</p>
<p>Please include a C# example in your answer.</p>
| [
{
"answer_id": 108828,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 1,
"selected": false,
"text": "<p>Generate an array of random floats or ints of the same length. Sort that array, and do corresponding swaps on your target a... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16440/"
] | What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I'd like to create a new `Array` with the same strings but in a random order.
Please include a C# example in your answer. | If you're on .NET 3.5, you can use the following IEnumerable coolness:
```
Random rnd=new Random();
string[] MyRandomArray = MyArray.OrderBy(x => rnd.Next()).ToArray();
```
Edit: and here's the corresponding VB.NET code:
```
Dim rnd As New System.Random
Dim MyRandomArray = MyArray.OrderBy(Function() rnd.Next()).ToArray()
```
Second edit, in response to remarks that System.Random "isn't threadsafe" and "only suitable for toy apps" due to returning a time-based sequence: as used in my example, Random() is perfectly thread-safe, unless you're allowing the routine in which you randomize the array to be re-entered, in which case you'll need something like `lock (MyRandomArray)` anyway in order not to corrupt your data, which will protect `rnd` as well.
Also, it should be well-understood that System.Random as a source of entropy isn't very strong. As noted in the [MSDN documentation](http://msdn.microsoft.com/en-us/library/system.random.aspx), you should use something derived from `System.Security.Cryptography.RandomNumberGenerator` if you're doing anything security-related. For example:
```
using System.Security.Cryptography;
```
...
```
RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
string[] MyRandomArray = MyArray.OrderBy(x => GetNextInt32(rnd)).ToArray();
```
...
```
static int GetNextInt32(RNGCryptoServiceProvider rnd)
{
byte[] randomInt = new byte[4];
rnd.GetBytes(randomInt);
return Convert.ToInt32(randomInt[0]);
}
``` |
108,853 | <p>I have some code in a javascript file that needs to send queries back to the server. The question is, how do I find the url for the script that I am in, so I can build a proper request url for ajax.</p>
<p>I.e., the same script is included on <code>/</code>, <code>/help</code>, <code>/whatever</code>, and so on, while it will always need to request from <code>/data.json</code>. Additionally, the same site is run on different servers, where the <code>/</code>-folder might be placed differently. I have means to resolve the relative url where I include the Javascript (ez-publish template), but not within the javascript file itself.</p>
<p>Are there small scripts that will work on all browsers made for this?</p>
| [
{
"answer_id": 108860,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 2,
"selected": false,
"text": "<p><code>document.location.href</code> will give you the current URL, which you can then manipulate using JavaScript's s... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355/"
] | I have some code in a javascript file that needs to send queries back to the server. The question is, how do I find the url for the script that I am in, so I can build a proper request url for ajax.
I.e., the same script is included on `/`, `/help`, `/whatever`, and so on, while it will always need to request from `/data.json`. Additionally, the same site is run on different servers, where the `/`-folder might be placed differently. I have means to resolve the relative url where I include the Javascript (ez-publish template), but not within the javascript file itself.
Are there small scripts that will work on all browsers made for this? | For this I like to put `<link>` elements in the page's `<head>`, containing the URLs to use for requests. They can be generated by your server-side language so they always point to the right view:
```
<link id="link-action-1" href="${reverse_url ('action_1')}"/>
```
becomes
```
<link id="link-action-1" href="/my/web/root/action-1/"/>
```
and can be retrieved by Javascript with:
```
document.getElementById ('link-action-1').href;
``` |
108,866 | <p>Is there a version of memset() which sets a value that is larger than 1 byte (char)? For example, let's say we have a memset32() function, so using it we can do the following:</p>
<pre><code>int32_t array[10];
memset32(array, 0xDEADBEEF, sizeof(array));
</code></pre>
<p>This will set the value 0xDEADBEEF in all the elements of array. Currently it seems to me this can only be done with a loop.</p>
<p>Specifically, I am interested in a 64 bit version of memset(). Know anything like that?</p>
| [
{
"answer_id": 108876,
"author": "Alex M",
"author_id": 9652,
"author_profile": "https://Stackoverflow.com/users/9652",
"pm_score": 3,
"selected": false,
"text": "<p><code>wmemset(3)</code> is the wide (16-bit) version of memset. I think that's the closest you're going to get in C, witho... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7748/"
] | Is there a version of memset() which sets a value that is larger than 1 byte (char)? For example, let's say we have a memset32() function, so using it we can do the following:
```
int32_t array[10];
memset32(array, 0xDEADBEEF, sizeof(array));
```
This will set the value 0xDEADBEEF in all the elements of array. Currently it seems to me this can only be done with a loop.
Specifically, I am interested in a 64 bit version of memset(). Know anything like that? | ```
void memset64( void * dest, uint64_t value, uintptr_t size )
{
uintptr_t i;
for( i = 0; i < (size & (~7)); i+=8 )
{
memcpy( ((char*)dest) + i, &value, 8 );
}
for( ; i < size; i++ )
{
((char*)dest)[i] = ((char*)&value)[i&7];
}
}
```
(Explanation, as requested in the comments: when you assign to a pointer, the compiler assumes that the pointer is aligned to the type's natural alignment; for uint64\_t, that is 8 bytes. memcpy() makes no such assumption. On some hardware unaligned accesses are impossible, so assignment is not a suitable solution unless you know unaligned accesses work on the hardware with small or no penalty, or know that they will never occur, or both. The compiler will replace small memcpy()s and memset()s with more suitable code so it is not as horrible is it looks; but if you do know enough to guarantee assignment will always work and your profiler tells you it is faster, you can replace the memcpy with an assignment. The second for() loop is present in case the amount of memory to be filled is not a multiple of 64 bits. If you know it always will be, you can simply drop that loop.) |
108,892 | <p>Basically, growl notifications (or other callbacks) when tests break or pass. <strong>Does anything like this exist?</strong></p>
<p>If not, it should be pretty easy to write.. Easiest way would be to..</p>
<ol>
<li>run <code>python-autotest myfile1.py myfile2.py etc.py</code>
<ul>
<li>Check if files-to-be-monitored have been modified (possibly just if they've been saved).</li>
<li>Run any tests in those files.</li>
<li>If a test fails, but in the previous run it passed, generate a growl alert. Same with tests that fail then pass.</li>
<li>Wait, and repeat steps 2-5.</li>
</ul></li>
</ol>
<p>The problem I can see there is if the tests are in a different file. The simple solution would be to run all the tests after each save.. but with slower tests, this might take longer than the time between saves, and/or could use a lot of CPU power etc..</p>
<p>The best way to do it would be to actually see what bits of code have changed, if function abc() has changed, only run tests that interact with this.. While this would be great, I think it'd be extremely complex to implement?</p>
<p>To summarise:</p>
<ul>
<li>Is there anything like the Ruby tool <code>autotest</code> (part of the <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" rel="noreferrer">ZenTest package</a>), but for Python code?</li>
<li>How do you check which functions have changed between two revisions of a script?</li>
<li>Is it possible to determine which functions a command will call? (Somewhat like a reverse traceback)</li>
</ul>
| [
{
"answer_id": 108911,
"author": "macarthy",
"author_id": 17232,
"author_profile": "https://Stackoverflow.com/users/17232",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe buildbot would be useful <a href=\"http://buildbot.net/trac\" rel=\"nofollow noreferrer\">http://buildbot.net/tr... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] | Basically, growl notifications (or other callbacks) when tests break or pass. **Does anything like this exist?**
If not, it should be pretty easy to write.. Easiest way would be to..
1. run `python-autotest myfile1.py myfile2.py etc.py`
* Check if files-to-be-monitored have been modified (possibly just if they've been saved).
* Run any tests in those files.
* If a test fails, but in the previous run it passed, generate a growl alert. Same with tests that fail then pass.
* Wait, and repeat steps 2-5.
The problem I can see there is if the tests are in a different file. The simple solution would be to run all the tests after each save.. but with slower tests, this might take longer than the time between saves, and/or could use a lot of CPU power etc..
The best way to do it would be to actually see what bits of code have changed, if function abc() has changed, only run tests that interact with this.. While this would be great, I think it'd be extremely complex to implement?
To summarise:
* Is there anything like the Ruby tool `autotest` (part of the [ZenTest package](http://www.zenspider.com/ZSS/Products/ZenTest/)), but for Python code?
* How do you check which functions have changed between two revisions of a script?
* Is it possible to determine which functions a command will call? (Somewhat like a reverse traceback) | I found [autonose](https://github.com/gfxmonk/autonose) to be pretty unreliable but [sniffer](http://pypi.python.org/pypi/sniffer/0.2.3) seems to work very well.
```
$ pip install sniffer
$ cd myproject
```
Then instead of running "nosetests", you run:
```
$ sniffer
```
Or instead of `nosetests --verbose --with-doctest`, you run:
```
$ sniffer -x--verbose -x--with-doctest
```
As described in the [readme](http://pypi.python.org/pypi/sniffer/0.2.3), it's a good idea to install one of the platform-specific filesystem-watching libraries, `pyinotify`, `pywin32` or `MacFSEvents` (all installable via `pip` etc) |
108,900 | <p>How do I go about programmatically updating the FILEVERSION string in an MFC app? I have a build process that I use to generate a header file which contains the SVN rev for a given release. I'm using SvnRev from <a href="http://www.compuphase.com/svnrev.htm" rel="nofollow noreferrer">http://www.compuphase.com/svnrev.htm</a> to update a header file which I use to set the caption bar of my MFC app. Now I want to use this #define for my FILEVERION info. </p>
<p>What's the best way to proceed?</p>
| [
{
"answer_id": 108963,
"author": "Aaron Fischer",
"author_id": 5618,
"author_profile": "https://Stackoverflow.com/users/5618",
"pm_score": 1,
"selected": false,
"text": "<p>In your application.rc file there is a version block. This block controls the version info displayed in the filesy... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17259/"
] | How do I go about programmatically updating the FILEVERSION string in an MFC app? I have a build process that I use to generate a header file which contains the SVN rev for a given release. I'm using SvnRev from <http://www.compuphase.com/svnrev.htm> to update a header file which I use to set the caption bar of my MFC app. Now I want to use this #define for my FILEVERION info.
What's the best way to proceed? | An `.rc` file can `#include` header files just like `.c` files can. I have an auto-generated `version.h` file, which defines things like:
```
#define MY_PRODUCT_VERSION "0.47"
#define MY_PRODUCT_VERSION_NUM 0,47,0,0
```
Then I just have my `.rc` file `#include "version.h"` and use those defines.
```
VS_VERSION_INFO VERSIONINFO
FILEVERSION MY_PRODUCT_VERSION_NUM
PRODUCTVERSION MY_PRODUCT_VERSION_NUM
...
VALUE "FileVersion", MY_PRODUCT_VERSION "\0"
VALUE "ProductVersion", MY_PRODUCT_VERSION "\0"
...
```
I haven't tried this technique with an MFC project. It might be necessary to move your `VS_VERSION_INFO` resource to your `.rc2` file (which won't get edited by Visual Studio). |
108,938 | <p>Rails comes with a handy session hash into which we can cram stuff to our heart's content. I would, however, like something like ASP's application context, which instead of sharing data only within a single session, will share it with all sessions in the same application. I'm writing a simple dashboard app, and would like to pull data every 5 minutes, rather than every 5 minutes for each session.</p>
<p>I could, of course, store the cache update times in a database, but so far haven't needed to set up a database for this app, and would love to avoid that dependency if possible.</p>
<p>So, is there any way to get (or simulate) this sort of thing? If there's no way to do it without a database, is there any kind of "fake" database engine that comes with Rails, runs in memory, but doesn't bother persisting data between restarts?</p>
| [
{
"answer_id": 108948,
"author": "p3t0r",
"author_id": 16685,
"author_profile": "https://Stackoverflow.com/users/16685",
"pm_score": 2,
"selected": false,
"text": "<p>You should have a look at memcached: <a href=\"http://wiki.rubyonrails.org/rails/pages/MemCached\" rel=\"nofollow norefer... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2041950/"
] | Rails comes with a handy session hash into which we can cram stuff to our heart's content. I would, however, like something like ASP's application context, which instead of sharing data only within a single session, will share it with all sessions in the same application. I'm writing a simple dashboard app, and would like to pull data every 5 minutes, rather than every 5 minutes for each session.
I could, of course, store the cache update times in a database, but so far haven't needed to set up a database for this app, and would love to avoid that dependency if possible.
So, is there any way to get (or simulate) this sort of thing? If there's no way to do it without a database, is there any kind of "fake" database engine that comes with Rails, runs in memory, but doesn't bother persisting data between restarts? | **Right answer**: memcached . Fast, clean, supports multiple processes, integrates **very** cleanly with Rails these days. Not even that bad to set up, but it is one more thing to keep running.
**90% Answer**: There are probably multiple Rails processes running around -- one for each Mongrel you have, for example. Depending on the specifics of your caching needs, its quite possible that having one cache per Mongrel isn't the worst thing in the world. For example, supposing you were caching the results of a long-running query which
* gets fresh data every 8 hours
* is used every page load, 20,000 times a day
* needs to be accessed in 4 processes (Mongrels)
then you can drop that 20,000 requests down to 12 with about a single line of code
```
@@arbitrary_name ||= Model.find_by_stupidly_long_query(param)
```
The double at-mark, a Ruby symbol you might not be familiar with, is a global variable. ||= is the commonly used Ruby idiom to execute the assignment if and only if the variable is currently nil or otherwise evaluates to false. It will stay good until you explicitly empty it OR until the process stops, for any reason -- server restart, explicitly killed, what have you.
And after you go down from 20k calculations a day to 12 in about 15 seconds (OK, two minutes -- you need to wrap it in a trivial if block which stores the cache update time in a different global), you might find that there is no need to spend additional engineering assets on getting it down to 4 a day.
I actually use this in one of my production sites, for caching a few expensive queries which literally only need to be evaluated once in the life of the process (i.e. they change only at deployment time -- I suppose I could precalculate the results and write them to disk or DB but why do that when SQL can do the work for me).
You don't get any magic expiry syntax, reliability is pretty slim, and it can't be shared across processes -- but its 90% of what you need in a line of code. |
108,940 | <p>I am trying to evaluate the answer <a href="https://stackoverflow.com/questions/108081/are-there-any-high-level-easy-to-install-gui-libraries-for-common-lisp">provided here</a>, and am getting the error: <code>"A file with name ASDF-INSTALL does not exist"</code> when using clisp:</p>
<pre><code>dsm@localhost:~$ clisp -q
[1]> (require :asdf-install)
*** - LOAD: A file with name ASDF-INSTALL does not exist
The following restarts are available:
ABORT :R1 ABORT
Break 1 [2]> :r1
[3]> (quit)
dsm@localhost:~$
</code></pre>
<p>cmucl throws a similar error:</p>
<pre><code>dsm@localhost:~$ cmucl -q
Warning: #<Command Line Switch "q"> is an illegal switch
CMU Common Lisp CVS release-19a 19a-release-20040728 + minimal debian patches, running on crap-pile
With core: /usr/lib/cmucl/lisp.core
Dumped on: Sat, 2008-09-20 20:11:54+02:00 on localhost
For support see http://www.cons.org/cmucl/support.html Send bug reports to the debian BTS.
or to pvaneynd@debian.org
type (help) for help, (quit) to exit, and (demo) to see the demos
Loaded subsystems:
Python 1.1, target Intel x86
CLOS based on Gerd's PCL 2004/04/14 03:32:47
* (require :asdf-install)
Error in function REQUIRE: Don't know how to load ASDF-INSTALL
[Condition of type SIMPLE-ERROR]
Restarts:
0: [ABORT] Return to Top-Level.
Debug (type H for help)
(REQUIRE :ASDF-INSTALL NIL)
Source:
; File: target:code/module.lisp
(ERROR "Don't know how to load ~A" MODULE-NAME)
0] (quit)
dsm@localhost:~$
</code></pre>
<p>But sbcl works perfectly:</p>
<pre><code>dsm@localhost:~$ sbcl -q
This is SBCL 1.0.11.debian, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.
SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses. See the CREDITS and COPYING files in the
distribution for more information.
* (require :asdf-install)
; loading system definition from
; /usr/lib/sbcl/sb-bsd-sockets/sb-bsd-sockets.asd into #<PACKAGE "ASDF0">
; registering #<SYSTEM SB-BSD-SOCKETS {AB01A89}> as SB-BSD-SOCKETS
; registering #<SYSTEM SB-BSD-SOCKETS-TESTS {AC67181}> as SB-BSD-SOCKETS-TESTS
("SB-BSD-SOCKETS" "ASDF-INSTALL")
* (quit)
</code></pre>
<p>Any ideas on how to fix this? I found <a href="https://bugs.launchpad.net/ubuntu/+source/common-lisp-controller/+bug/37208" rel="nofollow noreferrer">this post</a> on the internet, but using that didn't work either.</p>
| [
{
"answer_id": 109028,
"author": "Attila Lendvai",
"author_id": 14464,
"author_profile": "https://Stackoverflow.com/users/14464",
"pm_score": 2,
"selected": false,
"text": "<p>try this before anything else:</p>\n\n<pre><code>(require :asdf)\n</code></pre>\n\n<p>you can steal some ideas f... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7780/"
] | I am trying to evaluate the answer [provided here](https://stackoverflow.com/questions/108081/are-there-any-high-level-easy-to-install-gui-libraries-for-common-lisp), and am getting the error: `"A file with name ASDF-INSTALL does not exist"` when using clisp:
```
dsm@localhost:~$ clisp -q
[1]> (require :asdf-install)
*** - LOAD: A file with name ASDF-INSTALL does not exist
The following restarts are available:
ABORT :R1 ABORT
Break 1 [2]> :r1
[3]> (quit)
dsm@localhost:~$
```
cmucl throws a similar error:
```
dsm@localhost:~$ cmucl -q
Warning: #<Command Line Switch "q"> is an illegal switch
CMU Common Lisp CVS release-19a 19a-release-20040728 + minimal debian patches, running on crap-pile
With core: /usr/lib/cmucl/lisp.core
Dumped on: Sat, 2008-09-20 20:11:54+02:00 on localhost
For support see http://www.cons.org/cmucl/support.html Send bug reports to the debian BTS.
or to pvaneynd@debian.org
type (help) for help, (quit) to exit, and (demo) to see the demos
Loaded subsystems:
Python 1.1, target Intel x86
CLOS based on Gerd's PCL 2004/04/14 03:32:47
* (require :asdf-install)
Error in function REQUIRE: Don't know how to load ASDF-INSTALL
[Condition of type SIMPLE-ERROR]
Restarts:
0: [ABORT] Return to Top-Level.
Debug (type H for help)
(REQUIRE :ASDF-INSTALL NIL)
Source:
; File: target:code/module.lisp
(ERROR "Don't know how to load ~A" MODULE-NAME)
0] (quit)
dsm@localhost:~$
```
But sbcl works perfectly:
```
dsm@localhost:~$ sbcl -q
This is SBCL 1.0.11.debian, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.
SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses. See the CREDITS and COPYING files in the
distribution for more information.
* (require :asdf-install)
; loading system definition from
; /usr/lib/sbcl/sb-bsd-sockets/sb-bsd-sockets.asd into #<PACKAGE "ASDF0">
; registering #<SYSTEM SB-BSD-SOCKETS {AB01A89}> as SB-BSD-SOCKETS
; registering #<SYSTEM SB-BSD-SOCKETS-TESTS {AC67181}> as SB-BSD-SOCKETS-TESTS
("SB-BSD-SOCKETS" "ASDF-INSTALL")
* (quit)
```
Any ideas on how to fix this? I found [this post](https://bugs.launchpad.net/ubuntu/+source/common-lisp-controller/+bug/37208) on the internet, but using that didn't work either. | use clc:clc-require in clisp. Refer to 'man common-lisp-controller'. I had the same error in clisp and resolved it by using clc:clc-require. sbcl works fine with just require though. |
108,971 | <p>We have two versions of a managed C++ assembly, one for x86 and one for x64. This assembly is called by a .net application complied for AnyCPU. We are deploying our code via a file copy install, and would like to continue to do so.</p>
<p>Is it possible to use a Side-by-Side assembly manifest to loading a x86 or x64 assembly respectively when an application is dynamically selecting it's processor architecture? Or is there another way to get this done in a file copy deployment (e.g. not using the GAC)?</p>
| [
{
"answer_id": 108998,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/ms164699(VS.80).aspx\" rel=\"nofollow noreferrer\">c... | 2008/09/20 | [
"https://Stackoverflow.com/questions/108971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6156/"
] | We have two versions of a managed C++ assembly, one for x86 and one for x64. This assembly is called by a .net application complied for AnyCPU. We are deploying our code via a file copy install, and would like to continue to do so.
Is it possible to use a Side-by-Side assembly manifest to loading a x86 or x64 assembly respectively when an application is dynamically selecting it's processor architecture? Or is there another way to get this done in a file copy deployment (e.g. not using the GAC)? | I created a simple solution that is able to load platform-specific assembly from an executable compiled as AnyCPU. The technique used can be summarized as follows:
1. Make sure default .NET assembly loading mechanism ("Fusion" engine) can't find either x86 or x64 version of the platform-specific assembly
2. Before the main application attempts loading the platform-specific assembly, install a custom assembly resolver in the current AppDomain
3. Now when the main application needs the platform-specific assembly, Fusion engine will give up (because of step 1) and call our custom resolver (because of step 2); in the custom resolver we determine current platform and use directory-based lookup to load appropriate DLL.
To demonstrate this technique, I am attaching a short, command-line based tutorial. I tested the resulting binaries on Windows XP x86 and then Vista SP1 x64 (by copying the binaries over, just like your deployment).
**Note 1**: "csc.exe" is a C-sharp compiler. This tutorial assumes it is in your path (my tests were using "C:\WINDOWS\Microsoft.NET\Framework\v3.5\csc.exe")
**Note 2**: I recommend you create a temporary folder for the tests and run command line (or powershell) whose current working directory is set to this location, e.g.
```
(cmd.exe)
C:
mkdir \TEMP\CrossPlatformTest
cd \TEMP\CrossPlatformTest
```
**Step 1**: The platform-specific assembly is represented by a simple C# class library:
```
// file 'library.cs' in C:\TEMP\CrossPlatformTest
namespace Cross.Platform.Library
{
public static class Worker
{
public static void Run()
{
System.Console.WriteLine("Worker is running");
System.Console.WriteLine("(Enter to continue)");
System.Console.ReadLine();
}
}
}
```
**Step 2**: We compile platform-specific assemblies using simple command-line commands:
```
(cmd.exe from Note 2)
mkdir platform\x86
csc /out:platform\x86\library.dll /target:library /platform:x86 library.cs
mkdir platform\amd64
csc /out:platform\amd64\library.dll /target:library /platform:x64 library.cs
```
**Step 3**: Main program is split into two parts. "Bootstrapper" contains main entry point for the executable and it registers a custom assembly resolver in current appdomain:
```
// file 'bootstrapper.cs' in C:\TEMP\CrossPlatformTest
namespace Cross.Platform.Program
{
public static class Bootstrapper
{
public static void Main()
{
System.AppDomain.CurrentDomain.AssemblyResolve += CustomResolve;
App.Run();
}
private static System.Reflection.Assembly CustomResolve(
object sender,
System.ResolveEventArgs args)
{
if (args.Name.StartsWith("library"))
{
string fileName = System.IO.Path.GetFullPath(
"platform\\"
+ System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")
+ "\\library.dll");
System.Console.WriteLine(fileName);
if (System.IO.File.Exists(fileName))
{
return System.Reflection.Assembly.LoadFile(fileName);
}
}
return null;
}
}
}
```
"Program" is the "real" implementation of the application (note that App.Run was invoked at the end of Bootstrapper.Main):
```
// file 'program.cs' in C:\TEMP\CrossPlatformTest
namespace Cross.Platform.Program
{
public static class App
{
public static void Run()
{
Cross.Platform.Library.Worker.Run();
}
}
}
```
**Step 4**: Compile the main application on command line:
```
(cmd.exe from Note 2)
csc /reference:platform\x86\library.dll /out:program.exe program.cs bootstrapper.cs
```
**Step 5**: We're now finished. The structure of the directory we created should be as follows:
```
(C:\TEMP\CrossPlatformTest, root dir)
platform (dir)
amd64 (dir)
library.dll
x86 (dir)
library.dll
program.exe
*.cs (source files)
```
If you now run program.exe on a 32bit platform, platform\x86\library.dll will be loaded; if you run program.exe on a 64bit platform, platform\amd64\library.dll will be loaded. Note that I added Console.ReadLine() at the end of the Worker.Run method so that you can use task manager/process explorer to investigate loaded DLLs, or you can use Visual Studio/Windows Debugger to attach to the process to see the call stack etc.
When program.exe is run, our custom assembly resolver is attached to current appdomain. As soon as .NET starts loading the Program class, it sees a dependency on 'library' assembly, so it tries loading it. However, no such assembly is found (because we've hidden it in platform/\* subdirectories). Luckily, our custom resolver knows our trickery and based on the current platform it tries loading the assembly from appropriate platform/\* subdirectory. |
109,000 | <p>My C application uses 3rd libraries, which do their own memory management.
In order to be robust, my application has code to deal with failures of library functions due to lack of free memory.</p>
<p>I would like to test this code, and for this, I need to simulate failures due to lack of memory.</p>
<p>What tool/s are recommended for this?
My environment is Linux/gcc.</p>
| [
{
"answer_id": 109004,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "<p>Create your own malloc wrapper which will randomly return null instead of a valid pointer. Well, or which fails c... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11886/"
] | My C application uses 3rd libraries, which do their own memory management.
In order to be robust, my application has code to deal with failures of library functions due to lack of free memory.
I would like to test this code, and for this, I need to simulate failures due to lack of memory.
What tool/s are recommended for this?
My environment is Linux/gcc. | You can use `ulimit` to limit the amount of resources a user can use, including memory. So you create a test user, limit their memory use to something just enough to launch your program, and watch it die :)
Example:
```
ulimit -m 64
```
Sets a memory limit of 64kb. |
109,023 | <p>8 bits representing the number 7 look like this:</p>
<pre><code>00000111
</code></pre>
<p>Three bits are set.</p>
<p>What are the algorithms to determine the number of set bits in a 32-bit integer?</p>
| [
{
"answer_id": 109025,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 11,
"selected": true,
"text": "<p>This is known as the '<a href=\"https://en.wikipedia.org/wiki/Hamming_weight\" rel=\"nofollow noreferrer\">Hamming... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16881/"
] | 8 bits representing the number 7 look like this:
```
00000111
```
Three bits are set.
What are the algorithms to determine the number of set bits in a 32-bit integer? | This is known as the '[Hamming Weight](https://en.wikipedia.org/wiki/Hamming_weight)', 'popcount' or 'sideways addition'.
Some CPUs have a single built-in instruction to do it and others have parallel instructions which act on bit vectors. Instructions like x86's [`popcnt`](https://www.felixcloutier.com/x86/popcnt) (on CPUs where it's supported) will almost certainly be fastest for a single integer. Some other architectures may have a slow instruction implemented with a microcoded loop that tests a bit per cycle (*citation needed* - hardware popcount is normally fast if it exists at all.).
The 'best' algorithm really depends on which CPU you are on and what your usage pattern is.
Your compiler may know how to do something that's good for the specific CPU you're compiling for, e.g. [C++20 `std::popcount()`](https://en.cppreference.com/w/cpp/numeric/popcount), or C++ [`std::bitset<32>::count()`](https://en.cppreference.com/w/cpp/utility/bitset/count), as a portable way to access builtin / intrinsic functions (see [another answer](https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer/109069#109069) on this question). But your compiler's choice of fallback for target CPUs that don't have hardware popcnt might not be optimal for your use-case. Or your language (e.g. C) might not expose any portable function that could use a CPU-specific popcount when there is one.
---
### Portable algorithms that don't need (or benefit from) any HW support
A pre-populated table lookup method can be very fast if your CPU has a large cache and you are doing lots of these operations in a tight loop. However it can suffer because of the expense of a 'cache miss', where the CPU has to fetch some of the table from main memory. (Look up each byte separately to keep the table small.) If you want popcount for a contiguous range of numbers, only the low byte is changing for groups of 256 numbers, [making this very good](https://stackoverflow.com/questions/66520106/count-integers-in-1-n-with-k-zero-bits-below-the-leading-1-popcount-for-a-c/66532113#66532113).
If you know that your bytes will be mostly 0's or mostly 1's then there are efficient algorithms for these scenarios, e.g. clearing the lowest set with a bithack in a loop until it becomes zero.
I believe a very good general purpose algorithm is the following, known as 'parallel' or 'variable-precision SWAR algorithm'. I have expressed this in a C-like pseudo language, you may need to adjust it to work for a particular language (e.g. using uint32\_t for C++ and >>> in Java):
GCC10 and clang 10.0 can recognize this pattern / idiom and compile it to a hardware popcnt or equivalent instruction when available, giving you the best of both worlds. (<https://godbolt.org/z/qGdh1dvKK>)
```c
int numberOfSetBits(uint32_t i)
{
// Java: use int, and use >>> instead of >>. Or use Integer.bitCount()
// C or C++: use uint32_t
i = i - ((i >> 1) & 0x55555555); // add pairs of bits
i = (i & 0x33333333) + ((i >> 2) & 0x33333333); // quads
i = (i + (i >> 4)) & 0x0F0F0F0F; // groups of 8
return (i * 0x01010101) >> 24; // horizontal sum of bytes
}
```
For JavaScript: [coerce to integer](https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer/109025#comment103845611_109025) with `|0` for performance: change the first line to `i = (i|0) - ((i >> 1) & 0x55555555);`
This has the best worst-case behaviour of any of the algorithms discussed, so will efficiently deal with any usage pattern or values you throw at it. (Its performance is not data-dependent on normal CPUs where all integer operations including multiply are constant-time. It doesn't get any faster with "simple" inputs, but it's still pretty decent.)
References:
* [https://graphics.stanford.edu/~seander/bithacks.html](https://graphics.stanford.edu/%7Eseander/bithacks.html#CountBitsSetParallel)
* <https://catonmat.net/low-level-bit-hacks> for bithack basics, like how subtracting 1 flips contiguous zeros.
* <https://en.wikipedia.org/wiki/Hamming_weight>
* <http://gurmeet.net/puzzles/fast-bit-counting-routines/>
* <http://aggregate.ee.engr.uky.edu/MAGIC/#Population%20Count%20(Ones%20Count)>
---
### How this SWAR bithack works:
```
i = i - ((i >> 1) & 0x55555555);
```
The first step is an optimized version of masking to isolate the odd / even bits, shifting to line them up, and adding. This effectively does 16 separate additions in 2-bit accumulators ([SWAR = SIMD Within A Register](https://en.wikipedia.org/wiki/SWAR)). Like `(i & 0x55555555) + ((i>>1) & 0x55555555)`.
The next step takes the odd/even eight of those 16x 2-bit accumulators and adds again, producing 8x 4-bit sums. The `i - ...` optimization isn't possible this time so it does just mask before / after shifting. Using the same `0x33...` constant both times instead of `0xccc...` before shifting is a good thing when compiling for ISAs that need to construct 32-bit constants in registers separately.
The final shift-and-add step of `(i + (i >> 4)) & 0x0F0F0F0F` widens to 4x 8-bit accumulators. It masks *after* adding instead of before, because the maximum value in any 4-bit accumulator is `4`, if all 4 bits of the corresponding input bits were set. 4+4 = 8 which still fits in 4 bits, so carry between nibble elements is impossible in `i + (i >> 4)`.
So far this is just fairly normal SIMD using SWAR techniques with a few clever optimizations. Continuing on with the same pattern for 2 more steps can widen to 2x 16-bit then 1x 32-bit counts. But there is a more efficient way on machines with fast hardware multiply:
Once we have few enough "elements", **a multiply with a magic constant can sum all the elements into the top element**. In this case byte elements. Multiply is done by left-shifting and adding, so **a multiply of `x * 0x01010101` results in `x + (x<<8) + (x<<16) + (x<<24)`.** Our 8-bit elements are wide enough (and holding small enough counts) that this doesn't produce carry *into* that top 8 bits.
**A 64-bit version of this** can do 8x 8-bit elements in a 64-bit integer with a 0x0101010101010101 multiplier, and extract the high byte with `>>56`. So it doesn't take any extra steps, just wider constants. This is what GCC uses for `__builtin_popcountll` on x86 systems when the hardware `popcnt` instruction isn't enabled. If you can use builtins or intrinsics for this, do so to give the compiler a chance to do target-specific optimizations.
---
### With full SIMD for wider vectors (e.g. counting a whole array)
This bitwise-SWAR algorithm could parallelize to be done in multiple vector elements at once, instead of in a single integer register, for a speedup on CPUs with SIMD but no usable popcount instruction. (e.g. x86-64 code that has to run on any CPU, not just Nehalem or later.)
However, the best way to use vector instructions for popcount is usually by using a variable-shuffle to do a table-lookup for 4 bits at a time of each byte in parallel. (The 4 bits index a 16 entry table held in a vector register).
On Intel CPUs, the hardware 64bit popcnt instruction can outperform an [SSSE3 `PSHUFB` bit-parallel implementation](http://wm.ite.pl/articles/sse-popcount.html) by about a factor of 2, but only [if your compiler gets it just right](http://danluu.com/assembly-intrinsics/). Otherwise SSE can come out significantly ahead. Newer compiler versions are aware of the [popcnt false dependency](https://stackoverflow.com/a/25089720/224132) [problem on Intel](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=62011).
* <https://github.com/WojciechMula/sse-popcount> state-of-the-art x86 SIMD popcount for SSSE3, AVX2, AVX512BW, AVX512VBMI, or AVX512 VPOPCNT. Using Harley-Seal across vectors to defer popcount within an element. (Also ARM NEON)
* [Counting 1 bits (population count) on large data using AVX-512 or AVX-2](https://stackoverflow.com/questions/50081465/counting-1-bits-population-count-on-large-data-using-avx-512-or-avx-2)
* related: <https://github.com/mklarqvist/positional-popcount> - separate counts for each bit-position of multiple 8, 16, 32, or 64-bit integers. (Again, x86 SIMD including AVX-512 which is really good at this, with `vpternlogd` making Harley-Seal *very* good.) |
109,044 | <p>I have an ASP.NET MVC-application which I want deployable on both IIS6 and IIS7 and as we all know, IIS6 needs the ".mvc"-naming in the URL.</p>
<p>Will this code work to make sure it works on all IIS-versions? Without having to make special adjustments in code, global.asax or config-files for the different IIS-versions.</p>
<pre><code>bool usingIntegratedPipeline = HttpRuntime.UsingIntegratedPipeline;
routes.MapRoute(
"Default",
usingIntegratedPipeline ?
"{controller}/{action}/{id}" : "{controller}.mvc/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
</code></pre>
<p><strong>Update</strong>: Forgot to mention. No ISAPI. Hosted website, no control over the IIS-server.</p>
| [
{
"answer_id": 109103,
"author": "alex",
"author_id": 19268,
"author_profile": "https://Stackoverflow.com/users/19268",
"pm_score": 0,
"selected": false,
"text": "<p>You can use an ISAPI filter to rewrite URLs which will allow you to have the nice URLs while still on IIS 6. </p>\n\n<p>Lo... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429/"
] | I have an ASP.NET MVC-application which I want deployable on both IIS6 and IIS7 and as we all know, IIS6 needs the ".mvc"-naming in the URL.
Will this code work to make sure it works on all IIS-versions? Without having to make special adjustments in code, global.asax or config-files for the different IIS-versions.
```
bool usingIntegratedPipeline = HttpRuntime.UsingIntegratedPipeline;
routes.MapRoute(
"Default",
usingIntegratedPipeline ?
"{controller}/{action}/{id}" : "{controller}.mvc/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
```
**Update**: Forgot to mention. No ISAPI. Hosted website, no control over the IIS-server. | That should fix the .mvc problem since the integrated pipeline is IIS7 strictly.
But remember to change settings on the IIS7 website to use "2.0 Integrated Pipeline" otherwhise it will return false aswell.
Also ofcouse setup the mapping of .mvc to the asp.net isapi dll, but Im guessing that you already know this.
Some small suggestions on other things you might need to remember when deploying MVC applications on IIS6 that I found useful:
<http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx> |
109,064 | <p>Could you recommend me a way to place a coundown timer on ASP.NET page?</p>
<p>Now I use this code:</p>
<p><strong>Default.aspx</strong></p>
<pre><code><asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server">60</asp:Label>
<asp:Timer ID="Timer1" runat="server" Interval="1000"
ontick="Timer1_Tick">
</asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
</code></pre>
<p><strong>Default.aspx.cs</strong></p>
<pre><code>protected void Timer1_Tick(object sender, EventArgs e)
{
int seconds = int.Parse(Label1.Text);
if (seconds > 0)
Label1.Text = (seconds - 1).ToString();
else
Timer1.Enabled = false;
}
</code></pre>
<p>But it is traffic expensive. I would prefer pure client-side method. Is it possible in ASP.NET? </p>
| [
{
"answer_id": 109096,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 2,
"selected": false,
"text": "<p>You might add something like this in your .aspx page</p>\n\n<pre><code><form name=\"counter\"><input type=\"text... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
] | Could you recommend me a way to place a coundown timer on ASP.NET page?
Now I use this code:
**Default.aspx**
```
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server">60</asp:Label>
<asp:Timer ID="Timer1" runat="server" Interval="1000"
ontick="Timer1_Tick">
</asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
```
**Default.aspx.cs**
```
protected void Timer1_Tick(object sender, EventArgs e)
{
int seconds = int.Parse(Label1.Text);
if (seconds > 0)
Label1.Text = (seconds - 1).ToString();
else
Timer1.Enabled = false;
}
```
But it is traffic expensive. I would prefer pure client-side method. Is it possible in ASP.NET? | OK, finally I ended with
```
<span id="timerLabel" runat="server"></span>
<script type="text/javascript">
function countdown()
{
seconds = document.getElementById("timerLabel").innerHTML;
if (seconds > 0)
{
document.getElementById("timerLabel").innerHTML = seconds - 1;
setTimeout("countdown()", 1000);
}
}
setTimeout("countdown()", 1000);
</script>
```
Really simple. Like old good plain HTML with JavaScript. |
109,066 | <p>I found this guide for using the flash parameters, thought it might be useful to post here, since Flash CS3 lacks a usage example for reading these parameters.</p>
<p>See answers for the link</p>
| [
{
"answer_id": 109067,
"author": "Eliram",
"author_id": 18790,
"author_profile": "https://Stackoverflow.com/users/18790",
"pm_score": 1,
"selected": false,
"text": "<pre><code>var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;\n</code></pre>\n\n<p>The entire article is at... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18790/"
] | I found this guide for using the flash parameters, thought it might be useful to post here, since Flash CS3 lacks a usage example for reading these parameters.
See answers for the link | Not sure why [his example](http://blogs.adobe.com/pdehaan/2006/07/using_flashvars_with_actionscr.html) calls LoaderInfo. The [DisplayObject](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/DisplayObject.html) class has its own (readonly) [loaderinfo](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/DisplayObject.html#loaderInfo) property. As long as your main class extends a DisplayObject, you can call the property directly
```
package {
import flash.display.Sprite;
public class Main extends Sprite {
public function Main() {
var test1:String = '';
if (this.loaderInfo.parameters.test1 !== undefined) {
test1 = this.loaderInfo.parameters.test1;
}
}
}
}
```
From the doc:
>
> Returns a LoaderInfo object containing
> information about loading the file to
> which this display object belongs. The
> loaderInfo property is defined only
> for the root display object of a SWF
> file or for a loaded Bitmap (not for a
> Bitmap that is drawn with
> ActionScript). To find the loaderInfo
> object associated with the SWF file
> that contains a display object named
> myDisplayObject, use
> myDisplayObject.root.loaderInfo.
>
>
> |
109,086 | <p>I am using <code>setInterval(fname, 10000);</code> to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event? </p>
<p>I want the user to be able to stop the repeated refresh of data.</p>
| [
{
"answer_id": 109091,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 12,
"selected": true,
"text": "<p><code>setInterval()</code> returns an interval ID, which you can pass to <code>clearInterval()</code>:</p>\n<pre><c... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | I am using `setInterval(fname, 10000);` to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?
I want the user to be able to stop the repeated refresh of data. | `setInterval()` returns an interval ID, which you can pass to `clearInterval()`:
```
var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
```
See the docs for [`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) and [`clearInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval). |
109,087 | <p>Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code:</p>
<pre><code>class hi:
def __init__(self):
self.ii = "foo"
self.kk = "bar"
</code></pre>
<p>Is there a way for me to do this:</p>
<pre><code>>>> mystery_method(hi)
["ii", "kk"]
</code></pre>
<p>Edit: I originally had asked for class variables erroneously.</p>
| [
{
"answer_id": 109106,
"author": "cnu",
"author_id": 1448,
"author_profile": "https://Stackoverflow.com/users/1448",
"pm_score": 9,
"selected": true,
"text": "<p>Every object has a <code>__dict__</code> variable containing all the variables and its values in it.</p>\n<p>Try this</p>\n<pr... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] | Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code:
```
class hi:
def __init__(self):
self.ii = "foo"
self.kk = "bar"
```
Is there a way for me to do this:
```
>>> mystery_method(hi)
["ii", "kk"]
```
Edit: I originally had asked for class variables erroneously. | Every object has a `__dict__` variable containing all the variables and its values in it.
Try this
```
>>> hi_obj = hi()
>>> hi_obj.__dict__.keys()
```
Output
```
dict_keys(['ii', 'kk'])
``` |
109,134 | <p>How do I change the style (color) of a div such as the following? </p>
<pre><code>"<div id=foo class="ed" style="display: <%= ((foo.isTrue) ? string.Empty : "none") %>">
<%= ((foo.isTrue) ? foo.Name: "false foo") %>"`
</code></pre>
| [
{
"answer_id": 109140,
"author": "unexist",
"author_id": 18179,
"author_profile": "https://Stackoverflow.com/users/18179",
"pm_score": 0,
"selected": false,
"text": "<p>That code fragment doesn't say much - if the code is server-side why don't you change e.g. the class of the HTML elemen... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15059/"
] | How do I change the style (color) of a div such as the following?
```
"<div id=foo class="ed" style="display: <%= ((foo.isTrue) ? string.Empty : "none") %>">
<%= ((foo.isTrue) ? foo.Name: "false foo") %>"`
``` | If you want to alter the color of the div with client side code (javascript) running in the browser, you do something like the following:
```
<script>
var fooElement = document.getElementById("foo");
fooElement.style.color = "red"; //to change the font color
</script>
``` |
109,232 | <p>What is the best way (performance wise) to paginate results in SQL Server 2000, 2005, 2008, 2012 if you also want to get the total number of results (before paginating)?</p>
| [
{
"answer_id": 109258,
"author": "Horcrux7",
"author_id": 12631,
"author_profile": "https://Stackoverflow.com/users/12631",
"pm_score": -1,
"selected": false,
"text": "<p>You didn't specify the language nor which driver you are using. Therefore I'm describing it abstractly.</p>\n\n<ul>\n... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19331/"
] | What is the best way (performance wise) to paginate results in SQL Server 2000, 2005, 2008, 2012 if you also want to get the total number of results (before paginating)? | Getting the total number of results and paginating are two different operations. For the sake of this example, let's assume that the query you're dealing with is
```
SELECT * FROM Orders WHERE OrderDate >= '1980-01-01' ORDER BY OrderDate
```
In this case, you would determine the total number of results using:
```
SELECT COUNT(*) FROM Orders WHERE OrderDate >= '1980-01-01'
```
...which may seem inefficient, but is actually pretty performant, assuming all indexes etc. are properly set up.
Next, to get actual results back in a paged fashion, the following query would be most efficient:
```
SELECT *
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY OrderDate ) AS RowNum, *
FROM Orders
WHERE OrderDate >= '1980-01-01'
) AS RowConstrainedResult
WHERE RowNum >= 1
AND RowNum < 20
ORDER BY RowNum
```
This will return rows 1-19 of the original query. The cool thing here, especially for web apps, is that you don't have to keep any state, except the row numbers to be returned. |
109,249 | <p>Why doesn't have the c standard a memswap function, which would probably look like:</p>
<pre><code>int memswap(void *ptr1, void *ptr2, size_t nbytes)?
</code></pre>
<p>I know it'd be easy to write, but i think the libc could do some awesome tricks to speed it up like some implementations do it for memcpy.</p>
| [
{
"answer_id": 109259,
"author": "Colen",
"author_id": 13500,
"author_profile": "https://Stackoverflow.com/users/13500",
"pm_score": 2,
"selected": false,
"text": "<p>Probably because it's not needed very often - I memset and memcpy reasonably often, but I don't know that I'd ever have u... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18687/"
] | Why doesn't have the c standard a memswap function, which would probably look like:
```
int memswap(void *ptr1, void *ptr2, size_t nbytes)?
```
I know it'd be easy to write, but i think the libc could do some awesome tricks to speed it up like some implementations do it for memcpy. | This isn't something that is routinely required.
The ideas may have been considered and discarded because it is quite difficult to come up with an algorithm that is general purpose. Don't forget that C is an old language and extensions need to be generally useful.
Possible error conditions :-
* behaviour when the ranges being swapped overlap
* length of zero
* running out of memory (an optimal implementation might allocate memory to do this)
* null pointer
The **best** algorithm might also depend upon what you are doing, and so *could* be better coded directly by you.
* swapping structures likely to be quicker using a temp structure and assignment
* small lengths - may be better allocating temporary memory
* long lengths - 'section' by section swap (where section is some optimal length)
* use of hardware copy functions |
109,284 | <p>Is it possible to test the use of a given layout using RSpec with Rails, for example I'd like a matcher that does the following:</p>
<pre><code>response.should use_layout('my_layout_name')
</code></pre>
<p>I found a use_layout matcher when Googling but it doesn't work as neither the response or controller seem to have a layout property that matcher was looking for.</p>
| [
{
"answer_id": 110301,
"author": "Otto",
"author_id": 9594,
"author_profile": "https://Stackoverflow.com/users/9594",
"pm_score": 4,
"selected": true,
"text": "<p>I found an example of <a href=\"http://rubyforge.org/pipermail/rspec-users/2007-May/001816.html\" rel=\"noreferrer\">how to w... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6432/"
] | Is it possible to test the use of a given layout using RSpec with Rails, for example I'd like a matcher that does the following:
```
response.should use_layout('my_layout_name')
```
I found a use\_layout matcher when Googling but it doesn't work as neither the response or controller seem to have a layout property that matcher was looking for. | I found an example of [how to write a `use_layout` matcher](http://rubyforge.org/pipermail/rspec-users/2007-May/001816.html) that will do just that. Here's the code in case that link goes away:
```
# in spec_helper.rb
class UseLayout
def initialize(expected)
@expected = 'layouts/' + expected
end
def matches?(controller)
@actual = controller.layout
#@actual.equal?(@expected)
@actual == @expected
end
def failure_message
return "use_layout expected #{@expected.inspect}, got #
{@actual.inspect}", @expected, @actual
end
def negeative_failure_message
return "use_layout expected #{@expected.inspect} not to equal #
{@actual.inspect}", @expected, @actual
end
end
def use_layout(expected)
UseLayout.new(expected)
end
# in controller spec
response.should use_layout("application")
``` |
109,305 | <p>I have an ASP.Net GridView control that I need to remain a fixed size whether there are 0 records or <em>n</em> records in the grid. The header and the footer should remain in the same position regardless of the amount of data in the grid. Obviously, I need to implement paging for larger datasets but how would I achieve this fixed sized GridView? Ideally I would like this to be a reusable control.</p>
| [
{
"answer_id": 109496,
"author": "Tim C",
"author_id": 7585,
"author_profile": "https://Stackoverflow.com/users/7585",
"pm_score": 1,
"selected": false,
"text": "<p>You may have to drop the headers and footers from the GridView altogether and add them to the page as separate table elemen... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7215/"
] | I have an ASP.Net GridView control that I need to remain a fixed size whether there are 0 records or *n* records in the grid. The header and the footer should remain in the same position regardless of the amount of data in the grid. Obviously, I need to implement paging for larger datasets but how would I achieve this fixed sized GridView? Ideally I would like this to be a reusable control. | You may have to drop the headers and footers from the GridView altogether and add them to the page as separate table elements. You will need to make sure each table cell in the header and footer tables have fixed widths that correspond to the widths of the cells in your GridView.
The GridView itself would probably be nested in a DIV tag of a fixed height. Something like as follows.
```
<table><tr><td style="width:100px">Header 1</td><td style="width:200px">Header 2</td></table>
<div style="width:300px;height:400px">
<asp:GridView>.....</asp:GridView>
</div>
<table><tr><td style="width:100px">Footer 1</td><td style="width:200px">Footer 2</td></table>
```
You will probably have to tweak the margin and padding value to get it all to line up exactly though. |
109,325 | <p>How do you perform the equivalent of Oracle's <code>DESCRIBE TABLE</code> in PostgreSQL (using the psql command)?</p>
| [
{
"answer_id": 109329,
"author": "Mr. Muskrat",
"author_id": 2657951,
"author_profile": "https://Stackoverflow.com/users/2657951",
"pm_score": 5,
"selected": false,
"text": "<p>The psql equivalent of <code>DESCRIBE TABLE</code> is <code>\\d table</code>.</p>\n\n<p>See the psql portion of... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2657951/"
] | How do you perform the equivalent of Oracle's `DESCRIBE TABLE` in PostgreSQL (using the psql command)? | Try this (in the `psql` command-line tool):
```
\d+ tablename
```
See [the manual](http://www.postgresql.org/docs/current/interactive/app-psql.html#APP-PSQL-META-COMMANDS) for more info. |
109,343 | <p>With web services it is considered a good practice to batch several service calls into one message to reduce a number of remote calls. Is there any way to do this with RESTful services?</p>
| [
{
"answer_id": 109479,
"author": "Aaron Jensen",
"author_id": 11229,
"author_profile": "https://Stackoverflow.com/users/11229",
"pm_score": -1,
"selected": false,
"text": "<p>Of course there is a way but it would require server-side support. There is no magical one size fits all methodol... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19268/"
] | With web services it is considered a good practice to batch several service calls into one message to reduce a number of remote calls. Is there any way to do this with RESTful services? | I don't see how batching requests makes any sense in REST. Since the URL in a REST-based service represents the operation to perform and the data on which to perform it, making batch requests would seriously break the conceptual model.
An exception would be if you were performing the same operation on the same data multiple times. In this case you can either pass in multiple values for a request parameter or encode this repetition in the body (however this would only really work for PUT or POST). The Gliffy REST API supports adding multiple users to the same folder via
```
POST /folders/ROOT/the/folder/name/users?userId=56&userId=87&userId=45
```
which is essentially:
```
PUT /folders/ROOT/the/folder/name/users/56
PUT /folders/ROOT/the/folder/name/users/87
PUT /folders/ROOT/the/folder/name/users/45
```
As the other commenter pointed out, paging results from a GET can be done via request parameters:
```
GET /some/list/of/resources?startIndex=10&pageSize=50
```
**if** the REST service supports it. |
109,383 | <p>I am relatively new to Java, and often find that I need to sort a <code>Map<Key, Value></code> on the values.</p>
<p>Since the values are not unique, I find myself converting the <code>keySet</code> into an <code>array</code>, and sorting that array through <strong>array sort</strong> with a <strong>custom comparator</strong> that sorts on the value associated with the key.</p>
<p>Is there an easier way?</p>
| [
{
"answer_id": 109389,
"author": "devinmoore",
"author_id": 15950,
"author_profile": "https://Stackoverflow.com/users/15950",
"pm_score": 8,
"selected": false,
"text": "<p>From <a href=\"http://www.programmersheaven.com/download/49349/download.aspx\" rel=\"noreferrer\">http://www.program... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9466/"
] | I am relatively new to Java, and often find that I need to sort a `Map<Key, Value>` on the values.
Since the values are not unique, I find myself converting the `keySet` into an `array`, and sorting that array through **array sort** with a **custom comparator** that sorts on the value associated with the key.
Is there an easier way? | Here's a generic-friendly version:
```
public class MapUtil {
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
List<Entry<K, V>> list = new ArrayList<>(map.entrySet());
list.sort(Entry.comparingByValue());
Map<K, V> result = new LinkedHashMap<>();
for (Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
}
``` |
109,417 | <p>I populated a datagridview from a datatable. How do I read from the datagridview when the application is running?</p>
| [
{
"answer_id": 109452,
"author": "Hamish Smith",
"author_id": 15572,
"author_profile": "https://Stackoverflow.com/users/15572",
"pm_score": 3,
"selected": true,
"text": "<p>how did you populate it? is the DataSource something useful like a BindlingList? \nIf it is then something like:</p... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I populated a datagridview from a datatable. How do I read from the datagridview when the application is running? | how did you populate it? is the DataSource something useful like a BindlingList?
If it is then something like:
```
BindingSource bindingSource = this.dataGridView1.DataSource as BindingSource;
//substitute your business object type for T
T entity = bindingSource.Current as T;
```
would get you the entity bound to the row.
Otherwise there is always the datagridview.Columns[n].Cells[n].Value but really I'd look at using the objects in the DataSource
Edit: Ah... a datatable... righto:
```
var table = dataGridView1.DataSource as DataTable;
foreach(DataRow row in table.Rows)
{
foreach(DataColumn column in table.Columns)
{
Console.WriteLine(row[column]);
}
}
``` |
109,444 | <p>Okay so im working on this php image upload system but for some reason internet explorer turns my basepath into the same path, but with double backslashes instead of one; ie:</p>
<pre><code>C:\\Documents and Settings\\kasper\\Bureaublad\\24.jpg
</code></pre>
<p>This needs to become C:\Documents and Settings\kasper\Bureaublad\24.jpg.</p>
| [
{
"answer_id": 109454,
"author": "The.Anti.9",
"author_id": 2128,
"author_profile": "https://Stackoverflow.com/users/2128",
"pm_score": 3,
"selected": true,
"text": "<p>Use the <a href=\"http://us.php.net/manual/en/function.stripslashes.php\" rel=\"nofollow noreferrer\"><code>stripslashe... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18671/"
] | Okay so im working on this php image upload system but for some reason internet explorer turns my basepath into the same path, but with double backslashes instead of one; ie:
```
C:\\Documents and Settings\\kasper\\Bureaublad\\24.jpg
```
This needs to become C:\Documents and Settings\kasper\Bureaublad\24.jpg. | Use the [`stripslashes`](http://us.php.net/manual/en/function.stripslashes.php) function.
That should make them all single slashes. |
109,449 | <p>Is there a (cross-platform) way to get a C FILE* handle from a C++ std::fstream ?</p>
<p>The reason I ask is because my C++ library accepts fstreams and in one particular function I'd like to use a C library that accepts a FILE*.</p>
| [
{
"answer_id": 109476,
"author": "Mike G.",
"author_id": 18901,
"author_profile": "https://Stackoverflow.com/users/18901",
"pm_score": 2,
"selected": false,
"text": "<p>Well, you can get the file descriptor - I forget whether the method is fd() or getfd(). <em>The implementations I've u... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Is there a (cross-platform) way to get a C FILE\* handle from a C++ std::fstream ?
The reason I ask is because my C++ library accepts fstreams and in one particular function I'd like to use a C library that accepts a FILE\*. | The short answer is no.
The reason, is because the `std::fstream` is not required to use a `FILE*` as part of its implementation. So even if you manage to extract file descriptor from the `std::fstream` object and manually build a FILE object, then you will have other problems because you will now have two buffered objects writing to the same file descriptor.
The real question is why do you want to convert the `std::fstream` object into a `FILE*`?
Though I don't recommend it, you could try looking up `funopen()`.
Unfortunately, this is **not** a POSIX API (it's a BSD extension) so its portability is in question. Which is also probably why I can't find anybody that has wrapped a `std::stream` with an object like this.
```
FILE *funopen(
const void *cookie,
int (*readfn )(void *, char *, int),
int (*writefn)(void *, const char *, int),
fpos_t (*seekfn) (void *, fpos_t, int),
int (*closefn)(void *)
);
```
This allows you to build a `FILE` object and specify some functions that will be used to do the actual work. If you write appropriate functions you can get them to read from the `std::fstream` object that actually has the file open. |