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 |
|---|---|---|---|---|---|---|
137,336 | <p>PHP, as we all know is very loosely typed. The language does not require you to specify any kind of type for function parameters or class variables. This can be a powerful feature.</p>
<p>Sometimes though, it can make debugging your script a painful experience. For example, passing one kind of object into a method that expects a different kind of object can produce error messages complaining that a certain variable/method doesn't exist for the passed object. These situations are mostly annoyances. More onerous problems are when you initialize one object with an object of the wrong class, and that "wrong object" won't be used until later on in the script's execution. In this case you end up getting an error much later than when you passed the original argument.</p>
<p>Instead of complaining that what I passed doesn't have a specific method or variable, or waiting until much later in script execution for my passed in object to be used, <strong><em>I would much rather have an error message, at exactly where I specify an object of the wrong type, complaining about the object's type being incorrect or incompatible.</em></strong> </p>
<p>How do you handle these situations in your code? How do you detect incompatible types? How can I introduce some type-checking into my scripts so that I can get more easily understood error messages? </p>
<p>Also, how can you do all this while accounting for inheritance in Php? Consider:</p>
<pre><code><?php
class InterfaceClass
{
#...
}
class UsesInterfaceClass
{
function SetObject(&$obj)
{
// What do I put here to make sure that $obj either
// is of type InterfaceObject or inherits from it
}
}
?>
</code></pre>
<p>Then a user of this code implements the interface with their own concrete class:</p>
<pre><code><?php
class ConcreteClass extends InterfaceClass
{
}
?>
</code></pre>
<p>I want ConcreteClass instances, and all future, unknown user-defined objects, to also be acceptable to SetObject. How would you make this allowable in checking for the correct type?</p>
| [
{
"answer_id": 137342,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 5,
"selected": true,
"text": "<p>Actually for classes you can provide type hinting in PHP (5+).</p>\n\n<pre><code> <?php\n class UsesBaseClass\n... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123/"
] | PHP, as we all know is very loosely typed. The language does not require you to specify any kind of type for function parameters or class variables. This can be a powerful feature.
Sometimes though, it can make debugging your script a painful experience. For example, passing one kind of object into a method that expects a different kind of object can produce error messages complaining that a certain variable/method doesn't exist for the passed object. These situations are mostly annoyances. More onerous problems are when you initialize one object with an object of the wrong class, and that "wrong object" won't be used until later on in the script's execution. In this case you end up getting an error much later than when you passed the original argument.
Instead of complaining that what I passed doesn't have a specific method or variable, or waiting until much later in script execution for my passed in object to be used, ***I would much rather have an error message, at exactly where I specify an object of the wrong type, complaining about the object's type being incorrect or incompatible.***
How do you handle these situations in your code? How do you detect incompatible types? How can I introduce some type-checking into my scripts so that I can get more easily understood error messages?
Also, how can you do all this while accounting for inheritance in Php? Consider:
```
<?php
class InterfaceClass
{
#...
}
class UsesInterfaceClass
{
function SetObject(&$obj)
{
// What do I put here to make sure that $obj either
// is of type InterfaceObject or inherits from it
}
}
?>
```
Then a user of this code implements the interface with their own concrete class:
```
<?php
class ConcreteClass extends InterfaceClass
{
}
?>
```
I want ConcreteClass instances, and all future, unknown user-defined objects, to also be acceptable to SetObject. How would you make this allowable in checking for the correct type? | Actually for classes you can provide type hinting in PHP (5+).
```
<?php
class UsesBaseClass
{
function SetObject(InterfaceObject $obj)
{
}
}
?>
```
This will also work correctly with inheritance as you would expect it to.
As an aside, don't put the word 'object' in your class names... |
137,359 | <p>I produce a report as an CSV file.
When I try to open the file in Excel, it makes an assumption about the data type based on the contents of the cell, and reformats it accordingly.</p>
<p>For example, if the CSV file contains</p>
<pre><code>...,005,...
</code></pre>
<p>Then Excel shows it as 5.
Is there a way to override this and display 005?</p>
<p>I would prefer to do something to the file itself, so that the user could just double-click on the CSV file to open it.</p>
<p>I use Excel 2003.</p>
| [
{
"answer_id": 137368,
"author": "Ólafur Waage",
"author_id": 22459,
"author_profile": "https://Stackoverflow.com/users/22459",
"pm_score": 2,
"selected": false,
"text": "<p>You can simply format your range as Text.</p>\n\n<p>Also <a href=\"http://peltiertech.com/Excel/NumberFormats.html... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10557/"
] | I produce a report as an CSV file.
When I try to open the file in Excel, it makes an assumption about the data type based on the contents of the cell, and reformats it accordingly.
For example, if the CSV file contains
```
...,005,...
```
Then Excel shows it as 5.
Is there a way to override this and display 005?
I would prefer to do something to the file itself, so that the user could just double-click on the CSV file to open it.
I use Excel 2003. | There isn’t an easy way to control the formatting Excel applies when opening a .csv file. However listed below are three approaches that might help.
My preference is the first option.
**Option 1 – Change the data in the file**
You could change the data in the .csv file as follows ...,**=”005”**,...
This will be displayed in Excel as ...,**005**,...
Excel will have kept the data as a formula, but copying the column and using paste special values will get rid of the formula but retain the formatting
**Option 2** – Format the data
If it is simply a format issue and all your data in that column has a three digits length. Then open the data in Excel and then format the column containing the data with this custom format **000**
**Option 3** – Change the file extension to .dif (Data interchange format)
Change the file extension and use the file import wizard to control the formats.
Files with a .dif extension are automatically opened by Excel when double clicked on.
*Step by step:*
* Change the file extension from **.csv** to **.dif**
* Double click on the file to open it in Excel.
* The 'File Import Wizard' will be launched.
* Set the 'File type' to 'Delimited' and click on the 'Next' button.
* Under Delimiters, tick 'Comma' and click on the 'Next' button.
* Click on each column of your data that is displayed and select a 'Column data format'. The column with the value '005' should be formatted as 'Text'.
* Click on the finish button, the file will be opened by Excel with the formats that you have specified. |
137,375 | <p>I'm teaching/helping a student to program.</p>
<p>I remember the following process always helped me when I started; It looks pretty intuitive and I wonder if someone else have had a similar approach.</p>
<ol>
<li>Read the problem and understand it ( of course ) .</li>
<li>Identify possible "functions" and variables.</li>
<li>Write how would I do it step by step ( algorithm ) </li>
<li>Translate it into code, if there is something you cannot do, create a function that does it for you and keep moving.</li>
</ol>
<p>With the time and practice I seem to have forgotten how hard it was to pass from problem description to a coding solution, but, by applying this method I managed to learn how to program.</p>
<p>So for a project description like: </p>
<blockquote>
<p><em>A system has to calculate the price of an Item based on the following rules ( a description of the rules... client, discounts, availability etc.. etc.etc. )</em></p>
</blockquote>
<p>I first step is to understand what the problem is.</p>
<p>Then identify the item, the rules the variables etc.</p>
<p>pseudo code something like:</p>
<pre><code>function getPrice( itemPrice, quantity , clientAge, hourOfDay ) : int
if( hourOfDay > 18 ) then
discount = 5%
if( quantity > 10 ) then
discount = 5%
if( clientAge > 60 or < 18 ) then
discount = 5%
return item_price - discounts...
end
</code></pre>
<p>And then pass it to the programming language..</p>
<pre><code>public class Problem1{
public int getPrice( int itemPrice, int quantity,hourOdDay ) {
int discount = 0;
if( hourOfDay > 10 ) {
// uh uh.. U don't know how to calculate percentage...
// create a function and move on.
discount += percentOf( 5, itemPriece );
.
.
.
you get the idea..
}
}
public int percentOf( int percent, int i ) {
// ....
}
}
</code></pre>
<p>Did you went on a similar approach?.. Did some one teach you a similar approach or did you discovered your self ( as I did :( ) </p>
| [
{
"answer_id": 137383,
"author": "J.J.",
"author_id": 21204,
"author_profile": "https://Stackoverflow.com/users/21204",
"pm_score": 3,
"selected": true,
"text": "<p>I did something similar. </p>\n\n<ul>\n<li>Figure out the rules/logic. </li>\n<li>Figure out the math. </li>\n<li>Then try ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] | I'm teaching/helping a student to program.
I remember the following process always helped me when I started; It looks pretty intuitive and I wonder if someone else have had a similar approach.
1. Read the problem and understand it ( of course ) .
2. Identify possible "functions" and variables.
3. Write how would I do it step by step ( algorithm )
4. Translate it into code, if there is something you cannot do, create a function that does it for you and keep moving.
With the time and practice I seem to have forgotten how hard it was to pass from problem description to a coding solution, but, by applying this method I managed to learn how to program.
So for a project description like:
>
> *A system has to calculate the price of an Item based on the following rules ( a description of the rules... client, discounts, availability etc.. etc.etc. )*
>
>
>
I first step is to understand what the problem is.
Then identify the item, the rules the variables etc.
pseudo code something like:
```
function getPrice( itemPrice, quantity , clientAge, hourOfDay ) : int
if( hourOfDay > 18 ) then
discount = 5%
if( quantity > 10 ) then
discount = 5%
if( clientAge > 60 or < 18 ) then
discount = 5%
return item_price - discounts...
end
```
And then pass it to the programming language..
```
public class Problem1{
public int getPrice( int itemPrice, int quantity,hourOdDay ) {
int discount = 0;
if( hourOfDay > 10 ) {
// uh uh.. U don't know how to calculate percentage...
// create a function and move on.
discount += percentOf( 5, itemPriece );
.
.
.
you get the idea..
}
}
public int percentOf( int percent, int i ) {
// ....
}
}
```
Did you went on a similar approach?.. Did some one teach you a similar approach or did you discovered your self ( as I did :( ) | I did something similar.
* Figure out the rules/logic.
* Figure out the math.
* Then try and code it.
After doing that for a couple of months it just gets internalized. You don't realize your doing it until you come up against a complex problem that requires you to break it down. |
137,387 | <p>I'm converting an old app that records folder sizes on a daily basis. The legacy app uses the Scripting.FileSystemObject library:</p>
<pre><code>Set fso = CreateObject("Scripting.FileSystemObject")
Set folderObject = fso.GetFolder(folder)
size = folderObject.Size
</code></pre>
<p>There isn't an equivalent mechanism on the System.IO.Directory and System.IO.DirectoryInfo classes.</p>
<p>To achieve the same result in .NET do I actually have to recursively walk the whole folder structure keeping a running total of file sizes?</p>
<p>Update: @Jonathon/Ed - thanks....as I thought. I think I'll just reference the Scripting.FileSystemObject COM library. Works just as well even if breaking the .NET purity of my app. It's for an internal reporting app so it's not such a big deal.</p>
| [
{
"answer_id": 137393,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>Sadly, yes...who knows why.</p>\n\n<pre><code>public static long DirSize(DirectoryInfo d) \n{ \n long Size = 0; ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419/"
] | I'm converting an old app that records folder sizes on a daily basis. The legacy app uses the Scripting.FileSystemObject library:
```
Set fso = CreateObject("Scripting.FileSystemObject")
Set folderObject = fso.GetFolder(folder)
size = folderObject.Size
```
There isn't an equivalent mechanism on the System.IO.Directory and System.IO.DirectoryInfo classes.
To achieve the same result in .NET do I actually have to recursively walk the whole folder structure keeping a running total of file sizes?
Update: @Jonathon/Ed - thanks....as I thought. I think I'll just reference the Scripting.FileSystemObject COM library. Works just as well even if breaking the .NET purity of my app. It's for an internal reporting app so it's not such a big deal. | I think that you already know the answer; you will need to add up all of the files in the directory (as well as its child directories.) I don't know of any built in function for this, but hey, I don't know everything (not even close). |
137,392 | <p>I'm sick of remembering all the passwords for different logins. Lately I found the interesting tool <a href="http://www.xs4all.nl/~jlpoutre/BoT/Javascript/PasswordComposer/" rel="nofollow noreferrer">password composer</a> which lets you generate passwords base on the <strong>hostname</strong> and a secret <strong>master password</strong>. But I don't want to use a website or installing software to generate my passwords.</p>
<p>So I'm looking for a simple one way hashing alogorithm which I can execute without computer aid to generate my passwords. Something in the spirit of the <a href="http://en.wikipedia.org/wiki/Solitaire_(cipher)" rel="nofollow noreferrer">solitare cipher</a> without the need for cards.</p>
<p>Using a PW store is not an option.</p>
| [
{
"answer_id": 137421,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>Why don't you just use the exact same algorithm as the password composer?</p>\n\n<ul>\n<li>Pick a master password... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/720/"
] | I'm sick of remembering all the passwords for different logins. Lately I found the interesting tool [password composer](http://www.xs4all.nl/~jlpoutre/BoT/Javascript/PasswordComposer/) which lets you generate passwords base on the **hostname** and a secret **master password**. But I don't want to use a website or installing software to generate my passwords.
So I'm looking for a simple one way hashing alogorithm which I can execute without computer aid to generate my passwords. Something in the spirit of the [solitare cipher](http://en.wikipedia.org/wiki/Solitaire_(cipher)) without the need for cards.
Using a PW store is not an option. | Why don't you just use the exact same algorithm as the password composer?
* Pick a master password
* Take the application/machine name for which you want a password
* Concatenate the two (or shuffle)
* Apply a code you can do in your head, like [Caesar's cipher](http://en.wikipedia.org/wiki/Caesar%27s_cipher)
* Take the first X characters (15 is usually a good length for secure passwords)
Example:
```
Master Password: kaboom
Machine Name: hal9000
Shuffle: khaablo9o0m00
Transposition table: shift 5 left
abcdefghijklmnopqrstuvwxyz 1234567890
vwxyzabcdefghijklmnopqrstu 6789012345
Result: fcvvwgj4j5h55
```
You could use as complex a substitution as your head can do reliably (with or without a paper). You could also use a different table for each password (say, deduce the table from the first letter of each machine name). As long as your master password is secure, there's nothing to fear about the simplicity of the algorithm. |
137,398 | <p>I have a SQL query (MS Access) and I need to add two columns, either of which may be null. For instance:</p>
<pre><code>SELECT Column1, Column2, Column3+Column4 AS [Added Values]
FROM Table
</code></pre>
<p>where Column3 or Column4 may be null. In this case, I want null to be considered zero (so <code>4 + null = 4, null + null = 0</code>).</p>
<p>Any suggestions as to how to accomplish this?</p>
| [
{
"answer_id": 137410,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 5,
"selected": true,
"text": "<p>Since ISNULL in Access is a boolean function (one parameter), use it like this:</p>\n\n<pre><code>SELECT Column1, Column... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14902/"
] | I have a SQL query (MS Access) and I need to add two columns, either of which may be null. For instance:
```
SELECT Column1, Column2, Column3+Column4 AS [Added Values]
FROM Table
```
where Column3 or Column4 may be null. In this case, I want null to be considered zero (so `4 + null = 4, null + null = 0`).
Any suggestions as to how to accomplish this? | Since ISNULL in Access is a boolean function (one parameter), use it like this:
```
SELECT Column1, Column2, IIF(ISNULL(Column3),0,Column3) + IIF(ISNULL(Column4),0,Column4) AS [Added Values]
FROM Table
``` |
137,399 | <p>Occasionally I come accross a unit test that doesn't Assert anything. The particular example I came across this morning was testing that a log file got written to when a condition was met. The assumption was that if no error was thrown the test passed.</p>
<p>I personally don't have a problem with this, however it seems to be a bit of a "code smell" to write a unit test that doesn't have any assertions associated with it.</p>
<p>Just wondering what people's views on this are?</p>
| [
{
"answer_id": 137409,
"author": "chessguy",
"author_id": 1908025,
"author_profile": "https://Stackoverflow.com/users/1908025",
"pm_score": 2,
"selected": false,
"text": "<p>In some sense, you are making an implicit assertion - that the code doesn't throw an exception. Of course it would... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] | Occasionally I come accross a unit test that doesn't Assert anything. The particular example I came across this morning was testing that a log file got written to when a condition was met. The assumption was that if no error was thrown the test passed.
I personally don't have a problem with this, however it seems to be a bit of a "code smell" to write a unit test that doesn't have any assertions associated with it.
Just wondering what people's views on this are? | This would be the official way to do it:
```
// Act
Exception ex = Record.Exception(() => someCode());
// Assert
Assert.Null(ex);
``` |
137,400 | <p>Looking at the processmodel element in the Web.Config there are two attributes.</p>
<pre><code>maxWorkerThreads="25"
maxIoThreads="25"
</code></pre>
<p>What is the difference between worker threads and I/O threads?</p>
| [
{
"answer_id": 137431,
"author": "chadmyers",
"author_id": 10862,
"author_profile": "https://Stackoverflow.com/users/10862",
"pm_score": 6,
"selected": true,
"text": "<p>Fundamentally not a lot, it's all about how ASP.NET and IIS allocate I/O wait objects and manage the contention and la... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19490/"
] | Looking at the processmodel element in the Web.Config there are two attributes.
```
maxWorkerThreads="25"
maxIoThreads="25"
```
What is the difference between worker threads and I/O threads? | Fundamentally not a lot, it's all about how ASP.NET and IIS allocate I/O wait objects and manage the contention and latency of communicating over the network and transferring data.
I/O threads are set aside as such because they will be doing I/O (as the name implies) and may have to wait for "long" periods of time (hundreds of milliseconds). They also can be optimized and used differently to take advantage of I/O completion port functionality in the Windows kernel. A single I/O thread may be managing multiple completion ports to maintain throughput.
Windows has a lot of capabilities for dealing with I/O blocking whereas ASP.NET/.NET has a plain concept of "Thread". ASP.NET can optimize for I/O by using more of the unmanaged threading capabilities in the OS. You wouldn't want to do this all the time for every thread as you lose a lot of capabilities that .NET gives you which is why there is a distinction between how the threads are intended to be used.
Worker threads are threads upon which regular "work" or just plain code/processing happens. Worker threads are unlikely to block a lot or wait on anything and will be short running and therefore require more aggressive scheduling to maximize processing power and throughput.
[Edit]: I also found this link which is particularly relevant to this question:
<http://blogs.msdn.com/ericeil/archive/2008/06/20/windows-i-o-threads-vs-managed-i-o-threads.aspx> |
137,448 | <p>Take the following snippet:</p>
<pre><code>List<int> distances = new List<int>();
</code></pre>
<p>Was the redundancy intended by the language designers? If so, why?</p>
| [
{
"answer_id": 137455,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 4,
"selected": false,
"text": "<p>You could always say: <br></p>\n\n<pre><code> var distances = new List<int>();\n</code></pre>\n"
},
{
"ans... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] | Take the following snippet:
```
List<int> distances = new List<int>();
```
Was the redundancy intended by the language designers? If so, why? | The reason the code appears to be redundant is because, to a novice programmer, it appears to be defining the same thing twice. But this is not what the code is doing. It is defining two separate things that just happen to be of the same type. It is defining the following:
1. A variable named distances of type `List<int>`.
2. An object on the heap of type `List<int>`.
Consider the following:
```
Person[] coworkers = new Employee[20];
```
Here the non-redundancy is clearer, because the variable and the allocated object are of two different types (a situation that is legal if the object’s type derives from or implements the variable’s type). |
137,449 | <p>I have a draggable div element with a hover style. This works fine, but the div contains some form elements (label, input). The problem is that when the mouse is over these child elements the hover is disabled.</p>
<pre><code><div class="app_setting">
<label">Name</label>
<input type="text" name="name"/>
</div>
.app_setting:hover {
cursor:move;
}
</code></pre>
<p>Any ideas how to get the hover to apply also to the child elements?</p>
| [
{
"answer_id": 137466,
"author": "garrow",
"author_id": 21095,
"author_profile": "https://Stackoverflow.com/users/21095",
"pm_score": 6,
"selected": true,
"text": "<pre><code>.app_setting *:hover { cursor:move }\n</code></pre>\n"
},
{
"answer_id": 137496,
"author": "seanb",
... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14971/"
] | I have a draggable div element with a hover style. This works fine, but the div contains some form elements (label, input). The problem is that when the mouse is over these child elements the hover is disabled.
```
<div class="app_setting">
<label">Name</label>
<input type="text" name="name"/>
</div>
.app_setting:hover {
cursor:move;
}
```
Any ideas how to get the hover to apply also to the child elements? | ```
.app_setting *:hover { cursor:move }
``` |
137,452 | <p>I hate case sensitivity in databases, but I'm developing for a client who uses it. How can I turn on this option on my SQL Server, so I can be sure I've gotten the case right in all my queries?</p>
| [
{
"answer_id": 137460,
"author": "John Hoven",
"author_id": 1907,
"author_profile": "https://Stackoverflow.com/users/1907",
"pm_score": 0,
"selected": false,
"text": "<p>You'll have to change the database collation. You'll also need to alter the table and column level collation. I bele... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] | I hate case sensitivity in databases, but I'm developing for a client who uses it. How can I turn on this option on my SQL Server, so I can be sure I've gotten the case right in all my queries? | How about:
```
ALTER DATABASE database_name COLLATE collation_name
```
See BOL for a [list of collation options](http://msdn.microsoft.com/en-us/library/ms144250(SQL.90).aspx) and pick the case-sensitive one that best fits your needs (i.e. the one your client is using).
Obviously, it's probably a good idea to make a full backup of your database before you try this. I've never personally tried to use a database with a different collation than the server's default collation, so I don't know of any "gotchas". But if you have good backups and test it in your environment before deploying it to your client, I can't imagine that there's much risk involved. |
137,487 | <p>I am told that good developers can spot/utilize the difference between <code>Null</code> and <code>False</code> and <code>0</code> and all the other good "nothing" entities.<br>
What <em>is</em> the difference, specifically in PHP? Does it have something to do with <code>===</code>?</p>
| [
{
"answer_id": 137500,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "<p>The differences between these values always come down to detailed language-specific rules. What you learn for PHP isn'... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615/"
] | I am told that good developers can spot/utilize the difference between `Null` and `False` and `0` and all the other good "nothing" entities.
What *is* the difference, specifically in PHP? Does it have something to do with `===`? | It's language specific, but in PHP :
------------------------------------
**`Null`** means "**nothing**". The var has not been initialized.
**`False`** means "**not true in a boolean context**". Used to explicitly show you are dealing with logical issues.
**`0`** is an **`int`**. Nothing to do with the rest above, used for mathematics.
Now, what is tricky, it's that in dynamic languages like PHP, *all of them have a value in a boolean context*, which (in PHP) is `False`.
If you test it with `==`, it's testing the boolean value, so you will get equality. If you test it with `===`, it will test the type, and you will get inequality.
So why are they useful ?
------------------------
Well, look at the `strrpos()` function. It returns False if it did not found anything, but 0 if it has found something at the beginning of the string !
```
<?php
// pitfall :
if (strrpos("Hello World", "Hello")) {
// never exectuted
}
// smart move :
if (strrpos("Hello World", "Hello") !== False) {
// that works !
}
?>
```
And of course, if you deal with states:
You want to make a difference between `DebugMode = False` (set to off), `DebugMode = True` (set to on) and `DebugMode = Null` (not set at all, will lead to hard debugging ;-)). |
137,497 | <p>In Oracle, is there an easy way to fully unwrap a view? eg: If I have a view which is made up of selects on more views, is there some way to unwrap it to just select directly on real tables?</p>
| [
{
"answer_id": 137750,
"author": "Mark Stock",
"author_id": 19737,
"author_profile": "https://Stackoverflow.com/users/19737",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li><p>Get the query text of your view.</p>\n\n<pre><code>SELECT text FROM dba_views\nWHERE owner = 'the-owner' A... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3839/"
] | In Oracle, is there an easy way to fully unwrap a view? eg: If I have a view which is made up of selects on more views, is there some way to unwrap it to just select directly on real tables? | 1. Get the query text of your view.
```
SELECT text FROM dba_views
WHERE owner = 'the-owner' AND view_name = 'the-view-name';
```
2. Parse. Search for view names within the query text.
3. Get the query text for each view name found. (see item 1.)
4. Replace each view name in the query with the related query text.
5. Do this recursively until there are no more views found.
Easy?
**EDIT:** The above instructions do not do everything required. Thinking about this a little more it gets hairy, grows legs, and maybe another arm. Finding column names, and column names that might be elaborate functions and subqueries. Bringing it all back together with the joins and clauses. The resulting query might look very ugly.
Somewhere within Oracle there may be something that is actually unwrapping a view. I don't know. I am glad I didn't use views that much in Oracle. |
137,521 | <p>My Invoice model has an address_id attribute, and I don't want this address_id to change FOREVER. So I don't want this to happen outside the class:</p>
<pre><code>invoice.address_id = 1
invoice.address = some_address
</code></pre>
<p>Rails automatically adds this address_id attribute to the model from the invoice table, so how can I declare this attribute private/protected? Calling</p>
<pre><code>attr_protected :address_id
</code></pre>
<p>is most likely not the solution since based on the documentation it only prevents mass assignments.</p>
<p>Thanks!</p>
| [
{
"answer_id": 137538,
"author": "ryw",
"author_id": 2477,
"author_profile": "https://Stackoverflow.com/users/2477",
"pm_score": 2,
"selected": false,
"text": "<p>Not as pretty as a one liner, but code below should work (and you could always do some metaprogramming to write an 'immutable... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11082/"
] | My Invoice model has an address\_id attribute, and I don't want this address\_id to change FOREVER. So I don't want this to happen outside the class:
```
invoice.address_id = 1
invoice.address = some_address
```
Rails automatically adds this address\_id attribute to the model from the invoice table, so how can I declare this attribute private/protected? Calling
```
attr_protected :address_id
```
is most likely not the solution since based on the documentation it only prevents mass assignments.
Thanks! | You want [`attr_readonly`](http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001317). |
137,530 | <p>Ok, this is a curly one. I'm working on some Delphi code that I didn't write, and I'm encountering a very strange problem. One of my stored procedures' parameters is coming through as <code>null</code>, even though it's definitely being sent <code>1</code>.</p>
<p>The Delphi code uses a TADOQuery to execute the stored procedure (anonymized):</p>
<pre><code> ADOQuery1.SQL.Text := "exec MyStoredProcedure :Foo,:Bar,:Baz,:Qux,:Smang,:Jimmy";
ADOQuery1.Parameters.ParamByName("Foo").Value := Integer(someFunction());
// other parameters all set similarly
ADOQuery1.ExecSQL;
</code></pre>
<p><code>Integer(SomeFunction())</code> currently always returns 1 - I checked with the debugger.</p>
<p>However, in my stored proc ( altered for debug purposes ):</p>
<pre><code>create procedure MyStoredProcedure (
@Foo int, @Bar int, @Baz int,
@Qux int, @Smang int, @Jimmy varchar(20)
) as begin
-- temp debug
if ( @Foo is null ) begin
insert into TempLog values ( "oh crap" )
end
-- do the rest of the stuff here..
end
</code></pre>
<p><code>TempLog</code> does indeed end up with "oh crap" in it (side question: there must be a better way of debugging stored procs: what is it?).</p>
<p>Here's an example trace from profiler:</p>
<pre><code>exec [MYDB]..sp_procedure_params_rowset N'MyStoredProcedure',1,NULL,NULL
declare @p3 int
set @p3=NULL
exec sp_executesql
N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6',
N'@P1 int OUTPUT,@P2 int,@P3 int,@P4 int,@P5 int,@P6 int',
@p3 output,1,1,1,0,200
select @p3
</code></pre>
<p>This looks a little strange to me. Notice that it's using @p3 <em>and</em> @P3 - could this be causing my issue? </p>
<p>The other strange thing is that it seems to depend on which TADOConnection I use. </p>
<p>The project is a dll which is passed a TADOConnection from another application. It calls all the stored procedures using this connection.</p>
<p>If instead of using this connection, I first do this:</p>
<pre><code>ConnectionNew := TADOQuery.Create(ConnectionOld.Owner);
ConnectionNew.ConnectionString := ConnectionOld.ConnectionString;
TADOQuery1.Connection := ConnectionNew;
</code></pre>
<p>Then the issue does not occur! The trace from this situation is this:</p>
<pre><code>exec [MYDB]..sp_procedure_params_rowset N'MyStoredProcedure',1,NULL,NULL
declare @p1 int
set @p1=64
exec sp_prepare @p1 output,
N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int,@P6 varchar(20)',
N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6',
1
select @p1
SET FMTONLY ON exec sp_execute 64,0,0,0,0,0,' ' SET FMTONLY OFF
exec sp_unprepare 64
SET NO_BROWSETABLE OFF
exec sp_executesql
N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6',
N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int,@P6 varchar(20)',
1,1,1,3,0,'400.00'
</code></pre>
<p>Which is a bit much for lil ol' me to follow, unfortunately. What sort of TADOConnection options could be influencing this?</p>
<p>Does anyone have any ideas?</p>
<p><strong>Edit:</strong> <a href="https://stackoverflow.com/questions/137530/why-is-my-stored-procedure-receiving-a-null-parameter#177214">Update below</a> (didn't want to make this question any longer :P)</p>
| [
{
"answer_id": 137694,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 0,
"selected": false,
"text": "<p>caveat: i don't know delphi, but this issue rings a faint bell and so i'm interested in it</p>\n\n<p>do you get th... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
] | Ok, this is a curly one. I'm working on some Delphi code that I didn't write, and I'm encountering a very strange problem. One of my stored procedures' parameters is coming through as `null`, even though it's definitely being sent `1`.
The Delphi code uses a TADOQuery to execute the stored procedure (anonymized):
```
ADOQuery1.SQL.Text := "exec MyStoredProcedure :Foo,:Bar,:Baz,:Qux,:Smang,:Jimmy";
ADOQuery1.Parameters.ParamByName("Foo").Value := Integer(someFunction());
// other parameters all set similarly
ADOQuery1.ExecSQL;
```
`Integer(SomeFunction())` currently always returns 1 - I checked with the debugger.
However, in my stored proc ( altered for debug purposes ):
```
create procedure MyStoredProcedure (
@Foo int, @Bar int, @Baz int,
@Qux int, @Smang int, @Jimmy varchar(20)
) as begin
-- temp debug
if ( @Foo is null ) begin
insert into TempLog values ( "oh crap" )
end
-- do the rest of the stuff here..
end
```
`TempLog` does indeed end up with "oh crap" in it (side question: there must be a better way of debugging stored procs: what is it?).
Here's an example trace from profiler:
```
exec [MYDB]..sp_procedure_params_rowset N'MyStoredProcedure',1,NULL,NULL
declare @p3 int
set @p3=NULL
exec sp_executesql
N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6',
N'@P1 int OUTPUT,@P2 int,@P3 int,@P4 int,@P5 int,@P6 int',
@p3 output,1,1,1,0,200
select @p3
```
This looks a little strange to me. Notice that it's using @p3 *and* @P3 - could this be causing my issue?
The other strange thing is that it seems to depend on which TADOConnection I use.
The project is a dll which is passed a TADOConnection from another application. It calls all the stored procedures using this connection.
If instead of using this connection, I first do this:
```
ConnectionNew := TADOQuery.Create(ConnectionOld.Owner);
ConnectionNew.ConnectionString := ConnectionOld.ConnectionString;
TADOQuery1.Connection := ConnectionNew;
```
Then the issue does not occur! The trace from this situation is this:
```
exec [MYDB]..sp_procedure_params_rowset N'MyStoredProcedure',1,NULL,NULL
declare @p1 int
set @p1=64
exec sp_prepare @p1 output,
N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int,@P6 varchar(20)',
N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6',
1
select @p1
SET FMTONLY ON exec sp_execute 64,0,0,0,0,0,' ' SET FMTONLY OFF
exec sp_unprepare 64
SET NO_BROWSETABLE OFF
exec sp_executesql
N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6',
N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int,@P6 varchar(20)',
1,1,1,3,0,'400.00'
```
Which is a bit much for lil ol' me to follow, unfortunately. What sort of TADOConnection options could be influencing this?
Does anyone have any ideas?
**Edit:** [Update below](https://stackoverflow.com/questions/137530/why-is-my-stored-procedure-receiving-a-null-parameter#177214) (didn't want to make this question any longer :P) | Ok, progress is made.. sort of.
@Robsoft was correct, setting the parameter direction to `pdInput` fixed the issue.
I traced into the VCL code, and it came down to `TParameters.InternalRefresh.RefreshFromOleDB`. This function is being called when I set the SQL.Text. Here's the (abridged) code:
```
function TParameters.InternalRefresh: Boolean;
procedure RefreshFromOleDB;
// ..
if OLEDBParameters.GetParameterInfo(ParamCount, PDBPARAMINFO(ParamInfo), @NamesBuffer) = S_OK then
for I := 0 to ParamCount - 1 do
with ParamInfo[I] do
begin
// ..
Direction := dwFlags and $F; // here's where the wrong value comes from
// ..
end;
// ..
end;
// ..
end;
```
So, [`OLEDBParameters.GetParameterInfo`](http://msdn.microsoft.com/en-us/library/ms714917(VS.85).aspx) is returning the wrong flags for some reason.
I've verified that with the original connection, `(dwFlags and $F)` is `2` (`DBPARAMFLAGS_ISOUTPUT`), and with the new connection, it's `1` (`DBPARAMFLAGS_ISINPUT`).
I'm not really sure I want to dig any deeper than that, for now at least.
Until I have more time and inclination, I'll just make sure all parameters are set to `pdInput` before I open the query.
Unless anyone has any more bright ideas now..?
Anyway, thanks everyone for your suggestions so far. |
137,580 | <p>I know how to do a HEAD request with httplib, but I have to use mechanize for this site. </p>
<p>Essentially, what I need to do is grab a value from the header (filename) without actually downloading the file.</p>
<p>Any suggestions how I could accomplish this?</p>
| [
{
"answer_id": 137624,
"author": "Michał Kwiatkowski",
"author_id": 21998,
"author_profile": "https://Stackoverflow.com/users/21998",
"pm_score": 4,
"selected": true,
"text": "<p>Mechanize itself only sends GETs and POSTs, but you can easily extend the Request class to send HEAD. Example... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18866/"
] | I know how to do a HEAD request with httplib, but I have to use mechanize for this site.
Essentially, what I need to do is grab a value from the header (filename) without actually downloading the file.
Any suggestions how I could accomplish this? | Mechanize itself only sends GETs and POSTs, but you can easily extend the Request class to send HEAD. Example:
```
import mechanize
class HeadRequest(mechanize.Request):
def get_method(self):
return "HEAD"
request = HeadRequest("http://www.example.com/")
response = mechanize.urlopen(request)
print response.info()
``` |
137,621 | <p>I can't find a reference to it but I remember reading that it wasn't a good idea to call virtual (polymorphic) methods within a destructor or the Dispose() method of IDisposable.</p>
<p>Is this true and if so can someone explain why?</p>
| [
{
"answer_id": 137636,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 1,
"selected": false,
"text": "<p>Virtual methods are discouraged in both constructors and destructors. </p>\n\n<p>The reason is more practical than anyth... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21429/"
] | I can't find a reference to it but I remember reading that it wasn't a good idea to call virtual (polymorphic) methods within a destructor or the Dispose() method of IDisposable.
Is this true and if so can someone explain why? | Calling virtual methods from a finalizer/`Dispose` is unsafe, for the same reasons [it is unsafe to do in a constructor](https://stackoverflow.com/questions/119506/virtual-member-call-in-a-constructor). It is impossible to be sure that the derived class has not already cleaned-up some state that the virtual method requires to execute properly.
Some people are confused by the standard Disposable pattern, and its use of a virtual method, `virtual Dispose(bool disposing)`, and think this makes it Ok to use *any* virtual method durring a dispose. Consider the following code:
```
class C : IDisposable {
private IDisposable.Dispose() {
this.Dispose(true);
}
protected virtual Dispose(bool disposing) {
this.DoSomething();
}
protected virtual void DoSomething() { }
}
class D : C {
IDisposable X;
protected override Dispose(bool disposing) {
X.Dispose();
base.Dispose(disposing);
}
protected override void DoSomething() {
X.Whatever();
}
}
```
Here's what happens when you Dispose and object of type `D`, called `d`:
1. Some code calls `((IDisposable)d).Dispose()`
2. `C.IDisposable.Dispose()` calls the virtual method `D.Dispose(bool)`
3. `D.Dispose(bool)` disposes of `D.X`
4. `D.Dispose(bool)` calls `C.Dispose(bool)` **statically** (the target of the call is known *at compile-time*)
5. `C.Dispose(bool)` calls the virtual methods `D.DoSomething()`
6. `D.DoSomething` calls the method `D.X.Whatever()` on the already disposed `D.X`
7. ?
Now, most people who run this code do one thing to fix it -- they move the `base.Dispose(dispose)` call to before they clean-up their own object. And, yes, that does work. But do you really trust Programmer X, the Ultra-Junior Developer from the company you developed `C` for, assigned to write `D`, to write it in a way that the error is either detected, or has the `base.Dispose(disposing)` call in the right spot?
I'm not saying you should never, **ever** write code that calls a virtual method from Dispose, just that you'll need to **document** that virtual method's *requirement* that it never use any state that's defined in any class derived below `C`. |
137,629 | <p>How do you render primitives as wireframes in OpenGL?</p>
| [
{
"answer_id": 137644,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 6,
"selected": false,
"text": "<p>From <a href=\"https://web.archive.org/web/20090119194513/http://cone3d.gamedev.net/cgi-bin/index.pl?page=tutorials... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How do you render primitives as wireframes in OpenGL? | ```
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
```
to switch on,
```
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
```
to go back to normal.
Note that things like texture-mapping and lighting will still be applied to the wireframe lines if they're enabled, which can look weird. |
137,630 | <p>I was wondering if there was a way to use "find_by_sql" within a named_scope. I'd like to treat custom sql as named_scope so I can chain it to my existing named_scopes. It would also be good for optimizing a sql snippet I use frequently.</p>
| [
{
"answer_id": 137643,
"author": "macarthy",
"author_id": 17232,
"author_profile": "https://Stackoverflow.com/users/17232",
"pm_score": 0,
"selected": false,
"text": "<p>sure why not </p>\n\n<p>:named_scope :conditions => [ your sql ]</p>\n"
},
{
"answer_id": 180440,
"author"... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1227001/"
] | I was wondering if there was a way to use "find\_by\_sql" within a named\_scope. I'd like to treat custom sql as named\_scope so I can chain it to my existing named\_scopes. It would also be good for optimizing a sql snippet I use frequently. | While you can put any SQL you like in the conditions of a named scope, if you then call `find_by_sql` then the 'scopes' get thrown away.
Given:
```
class Item
# Anything you can put in an sql WHERE you can put here
named_scope :mine, :conditions=>'user_id = 12345 and IS_A_NINJA() = 1'
end
```
This works (it just sticks the SQL string in there - if you have more than one they get joined with AND)
```
Item.mine.find :all
=> SELECT * FROM items WHERE ('user_id' = 887 and IS_A_NINJA() = 1)
```
However, this doesn't
```
Items.mine.find_by_sql 'select * from items limit 1'
=> select * from items limit 1
```
So the answer is "No". If you think about what has to happen behind the scenes then this makes a lot of sense. In order to build the SQL rails has to know how it fits together.
When you create normal queries, the `select`, `joins`, `conditions`, etc are all broken up into distinct pieces. Rails knows that it can add things to the conditions without affecting everything else (which is how `with_scope` and `named_scope` work).
With `find_by_sql` however, you just give rails a big string. It doesn't know what goes where, so it's not safe for it to go in and add the things it would need to add for the scopes to work. |
137,660 | <p>In a J2EE application (like one running in WebSphere), when I use <code>System.out.println()</code>, my text goes to standard out, which is mapped to a file by the WebSphere admin console.</p>
<p>In an ASP.NET application (like one running in IIS), where does the output of <code>Console.WriteLine()</code> go? The IIS process must have a stdin, stdout and stderr; but is stdout mapped to the Windows version of /dev/null or am I missing a key concept here?</p>
<p>I'm <strong>not asking</strong> if I should log there (I use log4net), but where does the output go? My best info came from this <a href="http://www.velocityreviews.com/forums/t91075-where-does-consolewriteline-goto.html" rel="noreferrer">discussion</a> where they say <code>Console.SetOut()</code> can change the <code>TextWriter</code>, but it still didn't answer the question on what the initial value of the Console is, or how to set it in config/outside of runtime code.</p>
| [
{
"answer_id": 137704,
"author": "Leon Tayson",
"author_id": 18413,
"author_profile": "https://Stackoverflow.com/users/18413",
"pm_score": -1,
"selected": false,
"text": "<p>In an ASP.NET application, I think it goes to the Output or Console window which is visible during debugging.</p>\... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22514/"
] | In a J2EE application (like one running in WebSphere), when I use `System.out.println()`, my text goes to standard out, which is mapped to a file by the WebSphere admin console.
In an ASP.NET application (like one running in IIS), where does the output of `Console.WriteLine()` go? The IIS process must have a stdin, stdout and stderr; but is stdout mapped to the Windows version of /dev/null or am I missing a key concept here?
I'm **not asking** if I should log there (I use log4net), but where does the output go? My best info came from this [discussion](http://www.velocityreviews.com/forums/t91075-where-does-consolewriteline-goto.html) where they say `Console.SetOut()` can change the `TextWriter`, but it still didn't answer the question on what the initial value of the Console is, or how to set it in config/outside of runtime code. | If you look at the `Console` class in [.NET Reflector](http://en.wikipedia.org/wiki/.NET_Reflector), you'll find that if a process doesn't have an associated console, `Console.Out` and `Console.Error` are backed by `Stream.Null` (wrapped inside a `TextWriter`), which is a dummy implementation of `Stream` that basically ignores all input, and gives no output.
So it is conceptually equivalent to `/dev/null`, but the implementation is more streamlined: there's no actual I/O taking place with the null device.
Also, apart from calling `SetOut`, there is no way to configure the default.
**Update 2020-11-02**: As this answer is still gathering votes in 2020, it should probably be noted that under ASP.NET Core, there usually *is* a console attached. You can configure the [ASP.NET Core IIS Module](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/aspnet-core-module) to redirect all stdout and stderr output to a log file via the `stdoutLogEnabled` and `stdoutLogFile` settings:
```xml
<system.webServer>
<aspNetCore processPath="dotnet"
arguments=".\MyApp.dll"
hostingModel="inprocess"
stdoutLogEnabled="true"
stdoutLogFile=".\logs\stdout" />
<system.webServer>
``` |
137,661 | <p>In C#, I can do this:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
List<Animal> animals = new List<Animal>();
animals.Add(new Dog());
animals.Add(new Cat());
foreach (Animal a in animals)
{
Console.WriteLine(a.MakeNoise());
a.Sleep();
}
}
}
public class Animal
{
public virtual string MakeNoise() { return String.Empty; }
public void Sleep()
{
Console.Writeline(this.GetType().ToString() + " is sleeping.");
}
}
public class Dog : Animal
{
public override string MakeNoise()
{
return "Woof!";
}
}
public class Cat : Animal
{
public override string MakeNoise()
{
return "Meow!";
}
}
</code></pre>
<p>Obviously, the output is (Slightly paraphrased):</p>
<ul>
<li>Woof</li>
<li>Dog is Sleeping</li>
<li>Meow</li>
<li>Cat is Sleeping</li>
</ul>
<p>Since C# is often mocked for its verbose type syntax, how do you handle polymorphism/virtual methods in a duck typed language such as Ruby?</p>
| [
{
"answer_id": 137675,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": true,
"text": "<p>edit: added more code for your updated question</p>\n\n<p>disclaimer: I haven't used Ruby in a year or so, and don't... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | In C#, I can do this:
```
class Program
{
static void Main(string[] args)
{
List<Animal> animals = new List<Animal>();
animals.Add(new Dog());
animals.Add(new Cat());
foreach (Animal a in animals)
{
Console.WriteLine(a.MakeNoise());
a.Sleep();
}
}
}
public class Animal
{
public virtual string MakeNoise() { return String.Empty; }
public void Sleep()
{
Console.Writeline(this.GetType().ToString() + " is sleeping.");
}
}
public class Dog : Animal
{
public override string MakeNoise()
{
return "Woof!";
}
}
public class Cat : Animal
{
public override string MakeNoise()
{
return "Meow!";
}
}
```
Obviously, the output is (Slightly paraphrased):
* Woof
* Dog is Sleeping
* Meow
* Cat is Sleeping
Since C# is often mocked for its verbose type syntax, how do you handle polymorphism/virtual methods in a duck typed language such as Ruby? | edit: added more code for your updated question
disclaimer: I haven't used Ruby in a year or so, and don't have it installed on this machine, so the syntax might be entirely wrong. But the concepts are correct.
---
The exact same way, with classes and overridden methods:
```
class Animal
def MakeNoise
return ""
end
def Sleep
print self.class.name + " is sleeping.\n"
end
end
class Dog < Animal
def MakeNoise
return "Woof!"
end
end
class Cat < Animal
def MakeNoise
return "Meow!"
end
end
animals = [Dog.new, Cat.new]
animals.each {|a|
print a.MakeNoise + "\n"
a.Sleep
}
``` |
137,679 | <p>I setup phpMyID on one of my machines, and I'm trying to get apache to redirect to HTTPS only when a password is being submitted. I am doing this as my original setup of redirecting all openid traffic didn't work stackoverflow doesn't like my self signed certificate. This is the new rule I've written, but its not working:</p>
<pre><code>RewriteRule http://%{SERVER_NAME}/openid/index.php(\?.+)$ https://%{SERVER_NAME}/openid/index.php$1
</code></pre>
| [
{
"answer_id": 137692,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "<p>You need to use a Cond to test for both port (http or httpd) and query string:</p>\n\n<pre><code>RewriteCond %{SER... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
] | I setup phpMyID on one of my machines, and I'm trying to get apache to redirect to HTTPS only when a password is being submitted. I am doing this as my original setup of redirecting all openid traffic didn't work stackoverflow doesn't like my self signed certificate. This is the new rule I've written, but its not working:
```
RewriteRule http://%{SERVER_NAME}/openid/index.php(\?.+)$ https://%{SERVER_NAME}/openid/index.php$1
``` | You need to use a Cond to test for both port (http or httpd) and query string:
```
RewriteCond %{SERVER_PORT} 80
RewriteCond %{QUERY_STRING} (.+)
RewriteRule /openid/index.php https://%{SERVER_NAME}/openid/index.php?%1
```
if on .htaccess you must use instead
```
RewriteCond %{SERVER_PORT} 80
RewriteCond %{QUERY_STRING} (.+)
RewriteRule openid/index.php https://%{SERVER_NAME}/openid/index.php?%1
``` |
137,730 | <p>How to post a username, password and multiple binary files from a single html form and process it using php? I'm not allowed to use ajax.</p>
| [
{
"answer_id": 137751,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "<p>You should use the <code>$_FILES</code> superglobal and <code>move_uploaded_file()</code> function to see which f... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740/"
] | How to post a username, password and multiple binary files from a single html form and process it using php? I'm not allowed to use ajax. | first off check out these pages on PHP.net
1. [file upload info](http://us3.php.net/features.file-upload)
2. [`move_uploaded_file`](http://us3.php.net/manual/en/function.move-uploaded-file.php)
But to get you started here's a couple stub files.
**uploadForm.html**
```
<html>
<body>
<form action="processStuff.php" enctype="multipart/form-data" method="POST">
username: <input type="text" name="username" />
password: <input type="password" name="password" />
<p>
<input type="file" name="uploadFile[]" /><br />
<input type="file" name="uploadFile[]" /><br />
<input type="file" name="uploadFile[]" /><br />
<!-- Add as many of these as you want -->
</p>
<p>
<input type="submit" />
</p>
</form>
</body>
</html>
```
**processStuff.php**
```
<pre>
<?php
echo '<h2>Username & password</h2>'
echo "Username: {$_POST['username']}\nPassword: {$_POST['password']}";
echo '<hr />';
echo '<h2>Uploaded files</h2>'
foreach($_FILES['uploadFile']['tmp_name'] as $i => $tempUploadPath) {
if (empty($tempUploadPath)) {
// this <input type="file" /> was "blank"... no file selected
} else {
// a file was uploaded
echo '<strong>A file named "', $_FILES['uploadFile']['name'][$i], "\" was uploaded</strong>\n";
echo "\ttemporarily stored at: ", $tempUploadPath, "\n";
echo "\tmime type: ", $_FILES['uploadFile']['type'][$i], "\n";
echo "\tsize: ", $_FILES['uploadFile']['size'][$i], " bytes\n";
echo "\terror code",
((empty($_FILES['uploadFile']['size'][$i])
? '<em>no errror</em>'
: $_FILES['uploadFile']['size'][$i])),
"\n\n";
// do something useful with the uploaded file
// access it via $tempUploadPath and use move_uploaded_file() to move
// it out of the temp path before you manipulate it in any way!!!!!
// see http://us3.php.net/features.file-upload
// and http://us3.php.net/manual/en/function.move-uploaded-file.php
}
}
?>
</pre>
```
The HTML file shows how to set the `enctype` of the `<form>` & the second form show you how to access the submitted username & password & finally how to loop thru every uploaded file.
As noted you MUST move the file(s) ASAP. They're uploaded to a temp location and the system will delete them unless you deal with them. So move 'em somewhere first then do whatever you need w/ them.
Hoep this helps
Arin |
137,753 | <p>I'm looking for the most ideal data structure (for performance and ease of use) from which values can be retrieved by string key or index. Dictionary doesn't work because you can't really retrieve by index. Any ideas?</p>
| [
{
"answer_id": 137762,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>Hash based collections (Dictionary, Hashtable, HashSet) are out because you won't have an index, since you want an index,... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] | I'm looking for the most ideal data structure (for performance and ease of use) from which values can be retrieved by string key or index. Dictionary doesn't work because you can't really retrieve by index. Any ideas? | You want the [OrderedDictionary](http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx) class. You will need to include the System.Collections.Specialized namespace:
```
OrderedDictionary od = new OrderedDictionary();
od.Add("abc", 1);
od.Add("def", 2);
od.Add("ghi", 3);
od.Add("jkl", 4);
// Can access via index or key value:
Console.WriteLine(od[1]);
Console.WriteLine(od["def"]);
``` |
137,773 | <p>In our product we ship some linux binaries that dynamically link to system libraries like "libpam". On some customer systems we get the following error on stderr when the program runs:</p>
<pre><code>./authpam: /lib/libpam.so.0: no version information available (required by authpam)
</code></pre>
<p>The application runs fine and executes code from the dynamic library. So this is not a fatal error, it's really just a warning.</p>
<p>I figure that this is error comes from the dynamic linker when the system installed library is missing something our executable expects. I don't know much about the internals of the dynamic linking process ... and googling the topic doesn't help much. :(</p>
<p>Anyone know what causes this error? ... how I can diagnose the cause? ... and how we could change our executables to avoid this problem?</p>
<p>Update: The customer upgraded to the latest version of debian "testing" and the same error occurred. So it's not an out of date libpam library. I guess I'd like to understand what the linker is complaining about? How can I investigate the underlying cause, etc?</p>
| [
{
"answer_id": 137810,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "<p>Have you seen <a href=\"http://answers.google.com/answers/threadview/id/786136.html\" rel=\"nofollow noreferrer\"... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In our product we ship some linux binaries that dynamically link to system libraries like "libpam". On some customer systems we get the following error on stderr when the program runs:
```
./authpam: /lib/libpam.so.0: no version information available (required by authpam)
```
The application runs fine and executes code from the dynamic library. So this is not a fatal error, it's really just a warning.
I figure that this is error comes from the dynamic linker when the system installed library is missing something our executable expects. I don't know much about the internals of the dynamic linking process ... and googling the topic doesn't help much. :(
Anyone know what causes this error? ... how I can diagnose the cause? ... and how we could change our executables to avoid this problem?
Update: The customer upgraded to the latest version of debian "testing" and the same error occurred. So it's not an out of date libpam library. I guess I'd like to understand what the linker is complaining about? How can I investigate the underlying cause, etc? | The "no version information available" means that the library version number is lower on the shared object. For example, if your major.minor.patch number is 7.15.5 on the machine where you build the binary, and the major.minor.patch number is 7.12.1 on the installation machine, ld will print the warning.
You can fix this by compiling with a library (headers and shared objects) that matches the shared object version shipped with your target OS. E.g., if you are going to install to RedHat 3.4.6-9 you don't want to compile on Debian 4.1.1-21. This is one of the reasons that most distributions ship for specific linux distro numbers.
Otherwise, you can statically link. However, you don't want to do this with something like PAM, so you want to actually install a development environment that matches your client's production environment (or at least install and link against the correct library versions.)
Advice you get to rename the .so files (padding them with version numbers,) stems from a time when shared object libraries did not use versioned symbols. So don't expect that playing with the .so.n.n.n naming scheme is going to help (much - it might help if you system has been trashed.)
You last option will be compiling with a library with a different minor version number, using a custom linking script:
<http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/gnu-linker/scripts.html>
To do this, you'll need to write a custom script, and you'll need a custom installer that runs ld against your client's shared objects, using the custom script. This requires that your client have gcc or ld on their production system. |
137,775 | <p>I've wanted this for fluent interfaces. See, for example <a href="http://channel9.msdn.com/forums/Coffeehouse/257556-C-Extension-Properties/" rel="nofollow noreferrer">this</a> Channel9 discussion. Would probably <a href="http://ayende.com/Blog/archive/2007/12/02/Why-C-doesnt-have-extension-properties.aspx" rel="nofollow noreferrer">require</a> also adding indexed properties.</p>
<p>What are your thoughts? Would the advantages outweigh the "language clutter"?</p>
| [
{
"answer_id": 137787,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 5,
"selected": false,
"text": "<p>Since properties are just syntactic sugar for methods, I don't see why C# should have extension methods without ext... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22528/"
] | I've wanted this for fluent interfaces. See, for example [this](http://channel9.msdn.com/forums/Coffeehouse/257556-C-Extension-Properties/) Channel9 discussion. Would probably [require](http://ayende.com/Blog/archive/2007/12/02/Why-C-doesnt-have-extension-properties.aspx) also adding indexed properties.
What are your thoughts? Would the advantages outweigh the "language clutter"? | In my book the #1 most substantial reason for extension properties is implementing fluent interface patterns around unowned code. I built a wrapper around the NHibernate session to make it more intitutive to work with so I can do logic similar to
```
public bool IsInTransaction
{
get { return _session.Is().Not.Null && _session.Is().InTransaction; }
}
```
Which looks very stupid that Is must be a method as there is no way for me to insert the Is as a property unless I directly modify the source on the session object. |
137,783 | <p>Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.</p>
| [
{
"answer_id": 137807,
"author": "Will Hartung",
"author_id": 13663,
"author_profile": "https://Stackoverflow.com/users/13663",
"pm_score": 4,
"selected": false,
"text": "<p>Are homework problems allowed here?</p>\n\n<p>This function does crude \"base 5\" math to generate a number betwee... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22535/"
] | Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7. | There is no (exactly correct) solution which will run in a constant amount of time, since 1/7 is an infinite decimal in base 5. One simple solution would be to use rejection sampling, e.g.:
```
int i;
do
{
i = 5 * (rand5() - 1) + rand5(); // i is now uniformly random between 1 and 25
} while(i > 21);
// i is now uniformly random between 1 and 21
return i % 7 + 1; // result is now uniformly random between 1 and 7
```
This has an expected runtime of 25/21 = 1.19 iterations of the loop, but there is an infinitesimally small probability of looping forever. |
137,784 | <p>I have a report in SSRS 2005 that's based on a query that's similar to this one: </p>
<pre><code>SELECT * FROM MyTable (NOLOCK)
WHERE col1 = 'ABC'
AND col2 LIKE '%XYZ%'
</code></pre>
<p>I need to be able to dynamically include the AND part of the WHERE clause in the query based on whether the user has checked a checkbox. Basically, this is a dynamic SQL statement and that's the problem. I tried several approaches to no avail. Is this possible? Does SSRS 2005 supports dynamic SQL? Thanks!</p>
| [
{
"answer_id": 137856,
"author": "Jason Stevenson",
"author_id": 13368,
"author_profile": "https://Stackoverflow.com/users/13368",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps this would work for you:</p>\n\n<pre><code>if @checked = 1\n select * from mytable (nolock) where co... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11507/"
] | I have a report in SSRS 2005 that's based on a query that's similar to this one:
```
SELECT * FROM MyTable (NOLOCK)
WHERE col1 = 'ABC'
AND col2 LIKE '%XYZ%'
```
I need to be able to dynamically include the AND part of the WHERE clause in the query based on whether the user has checked a checkbox. Basically, this is a dynamic SQL statement and that's the problem. I tried several approaches to no avail. Is this possible? Does SSRS 2005 supports dynamic SQL? Thanks! | Charles almost had the correct answer.
It should be:
```
SELECT * FROM MyTable (NOLOCK)
WHERE col1 = 'ABC'
AND (@checked = 0 OR col2 LIKE '%XYZ%')
```
This is a classic "pattern" in SQL for conditional predicates. If `@checked = 0`, then it will return all rows matching the remainder of the predicate (`col1 = 'ABC'`). SQL Server won't even process the second half of the `OR`.
If `@checked = 1` then it will evaluate the second part of the `OR` and return rows matching `col1 = 'ABC' AND col2 LIKE '%XYZ%'`
If you have multiple conditional predicates they can be chained together using this method (while the IF and CASE methods would quickly become unmanageable).
For example:
```
SELECT * FROM MyTable (NOLOCK)
WHERE col1 = 'ABC'
AND (@checked1 = 0 OR col2 LIKE '%XYZ%')
AND (@checked2 = 0 OR col3 LIKE '%MNO%')
```
Don't use dynamic SQL, don't use IF or CASE. |
137,803 | <p>Does anyone happen to remember the function name used to generate sequential row number built-in SQL Server 2000.</p>
| [
{
"answer_id": 137818,
"author": "FryHard",
"author_id": 231,
"author_profile": "https://Stackoverflow.com/users/231",
"pm_score": 5,
"selected": true,
"text": "<p>If you are making use of GUIDs this should be nice and easy, if you are looking for an integer ID, you will have to wait for... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15396/"
] | Does anyone happen to remember the function name used to generate sequential row number built-in SQL Server 2000. | If you are making use of GUIDs this should be nice and easy, if you are looking for an integer ID, you will have to wait for another answer.
```
SELECT newId() AS ColId, Col1, Col2, Col3 FROM table1
```
The newId() will generate a new GUID for you that you can use as your automatically generated id column. |
137,837 | <p>Does your software handle newline characters from other systems?</p>
<pre><code>Linux/BSD linefeed ^J 10 x0A
Windows/IBM return linefeed ^M^J 13 10 x0D x0A
old Macs return ^M 13 x0D
others?
</code></pre>
<p>For reasons of insanity, I am going with using the Linux version of the newline character in my text files. But, when I bring my text files over to say Windows, some programs do not play nicely with newline characters in my text. How would you deal with this?</p>
| [
{
"answer_id": 137841,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect you will find that most modern Windows programs (with the notable exception of Notepad) handle newline-only ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19737/"
] | Does your software handle newline characters from other systems?
```
Linux/BSD linefeed ^J 10 x0A
Windows/IBM return linefeed ^M^J 13 10 x0D x0A
old Macs return ^M 13 x0D
others?
```
For reasons of insanity, I am going with using the Linux version of the newline character in my text files. But, when I bring my text files over to say Windows, some programs do not play nicely with newline characters in my text. How would you deal with this? | As they say, be strict in what you write and liberal in what you read.
Your application should be able to work properly reading both line endings. If you want to use linefeeds, and potentially upset Windows users, that's fine.
But save for Notepad, most programs I play with seem to be happy with both methods.
(And I use Cygwin on Windows, which just makes everything interesting) |
137,872 | <p>I am using the JQuery form plugin (<a href="http://malsup.com/jquery/form/" rel="noreferrer">http://malsup.com/jquery/form/</a>) to handle the ajax submission of a form. I also have JQuery.Validate (<a href="http://docs.jquery.com/Plugins/Validation" rel="noreferrer">http://docs.jquery.com/Plugins/Validation</a>) plugged in for my client side validation.</p>
<p>What I am seeing is that the validation fails when I expect it to however it does not stop the form from submitting. When I was using a traditional form (i.e. non-ajax) the validation failing prevented the form for submitting at all.... which is my desired behaviour.</p>
<p>I know that the validation is hooked up correctly as the validation messages still appear after the ajax submit has happened.</p>
<p>So what I am I missing that is preventing my desired behaviour? Sample code below....</p>
<pre><code><form id="searchForm" method="post" action="/User/GetDetails">
<input id="username" name="username" type="text" value="user.name" />
<input id="submit" name="submit" type="submit" value="Search" />
</form>
<div id="detailsView">
</div>
<script type="text/javascript">
var options = {
target: '#detailsView'
};
$('#searchForm').ajaxForm(options);
$('#searchForm').validate({
rules: {
username: {required:true}},
messages: {
username: {required:"Username is a required field."}}
});
</script>
</code></pre>
| [
{
"answer_id": 137881,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 1,
"selected": false,
"text": "<p>Just as a first pass, I'm wondering why the line</p>\n\n<pre><code>$(\"form\").validate({\n</code></pre>\n\n<p>doe... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4884/"
] | I am using the JQuery form plugin (<http://malsup.com/jquery/form/>) to handle the ajax submission of a form. I also have JQuery.Validate (<http://docs.jquery.com/Plugins/Validation>) plugged in for my client side validation.
What I am seeing is that the validation fails when I expect it to however it does not stop the form from submitting. When I was using a traditional form (i.e. non-ajax) the validation failing prevented the form for submitting at all.... which is my desired behaviour.
I know that the validation is hooked up correctly as the validation messages still appear after the ajax submit has happened.
So what I am I missing that is preventing my desired behaviour? Sample code below....
```
<form id="searchForm" method="post" action="/User/GetDetails">
<input id="username" name="username" type="text" value="user.name" />
<input id="submit" name="submit" type="submit" value="Search" />
</form>
<div id="detailsView">
</div>
<script type="text/javascript">
var options = {
target: '#detailsView'
};
$('#searchForm').ajaxForm(options);
$('#searchForm').validate({
rules: {
username: {required:true}},
messages: {
username: {required:"Username is a required field."}}
});
</script>
``` | You need to add a callback function for use with the beforeSubmit event when initializing the ajaxForm():
```
var options = {
beforeSubmit: function() {
return $('#searchForm').validate().form();
},
target: '#detailsView'
};
```
Now it knows to check the result of the validation before it will submit the page. |
137,911 | <p>I want to add the link tags to redirect my web-site to my OpenID provider. These tags should go in the head element. What's the best way to add them in Plone?</p>
<p>I understand that filling the head_slot is a way to do it, but that can only happen when you are adding a template to the page and that template is being rendered. In my case I'm not adding any template. Which template should I modify (that is not main_template.pt, which is my current solution, with it's huge drawbacks).</p>
| [
{
"answer_id": 139950,
"author": "Nikki9696",
"author_id": 456669,
"author_profile": "https://Stackoverflow.com/users/456669",
"pm_score": -1,
"selected": false,
"text": "<p>Plone documentation on supporting OpenID can be found here.</p>\n\n<p><a href=\"http://plone.org/documentation/how... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] | I want to add the link tags to redirect my web-site to my OpenID provider. These tags should go in the head element. What's the best way to add them in Plone?
I understand that filling the head\_slot is a way to do it, but that can only happen when you are adding a template to the page and that template is being rendered. In my case I'm not adding any template. Which template should I modify (that is not main\_template.pt, which is my current solution, with it's huge drawbacks). | I couldn't understand how to fill a slot without a product or anything. I understand that you can fill a slot from a template, but if Plone is not picking up that template, then the *filling code* would never be run. I ended up modifying main\_template and putting my code directly in the . This is bad because different skins will have different main\_templates and indeed it bit me because I've modified it for one template when I was using the other. That is not a harmless-nothing-happens experience but a nasty problem because main\_template in on custom and it gets picked up so you have one skin working with the main\_template of the other. End result: UI broken with a hard-to-find problem.
This is the code I added:
```
<head>
...
<link rel="openid.server" href="http://www.myopenid.com/server" />
<link rel="openid.delegate" href="http://pupeno.myopenid.com/" />
<link rel="openid2.local_id" href="http://pupeno.myopenid.com" />
<link rel="openid2.provider" href="http://www.myopenid.com/server" />
<meta http-equiv="X-XRDS-Location" content="http://www.myopenid.com/xrds?username=pupeno.myopenid.com" />
</head>
```
I will probably mark this answer as accepted because it's what I'm currently using (and that's my policy, I mark solutions I end up using as accepted, nothing else is marked as accepted), but if any of the other questions become clear in how to inject this new template, I will use that and revert the acceptance (if StackOverflow allows it). |
137,935 | <p>In Vim editor I opted <code>]I</code> on a function (in C++ code).
This presented a list, which says <em>'Press ENTER or type command to continue'</em>.</p>
<p>Now to jump to an occurrence say 6, I type <code>6</code> - but this is not working.</p>
<p>What commands can I type in such a case, and how do I jump to Nth occurrence from this list?</p>
<p><strong>Update:</strong></p>
<p>Actually I tried <a href="https://stackoverflow.com/questions/137935/how-to-jump-to-an-occurrence-from-vim-search-list#137942">:N</a> (eg :6) - but the moment I type <code>:</code> Vim enters Insert mode, and the colon gets inserted in the code instead.</p>
<p><strong>Update</strong></p>
<p>Assuming <a href="https://stackoverflow.com/questions/137935/how-to-jump-to-an-occurrence-from-vim-search-list#137942">:N</a> approach is correct, still complete uninstall and install of Vim, without any configuration, too did not help - though now typing <code>:</code> does not switch Vim to insert mode.</p>
| [
{
"answer_id": 137942,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": true,
"text": "<p>It should present you a list like:</p>\n\n<pre><code>1: 345 my_func (int var)\n2: 4523 my_func (int var)\n3: 1003... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14803/"
] | In Vim editor I opted `]I` on a function (in C++ code).
This presented a list, which says *'Press ENTER or type command to continue'*.
Now to jump to an occurrence say 6, I type `6` - but this is not working.
What commands can I type in such a case, and how do I jump to Nth occurrence from this list?
**Update:**
Actually I tried [:N](https://stackoverflow.com/questions/137935/how-to-jump-to-an-occurrence-from-vim-search-list#137942) (eg :6) - but the moment I type `:` Vim enters Insert mode, and the colon gets inserted in the code instead.
**Update**
Assuming [:N](https://stackoverflow.com/questions/137935/how-to-jump-to-an-occurrence-from-vim-search-list#137942) approach is correct, still complete uninstall and install of Vim, without any configuration, too did not help - though now typing `:` does not switch Vim to insert mode. | It should present you a list like:
```
1: 345 my_func (int var)
2: 4523 my_func (int var)
3: 10032 my_func (3);
```
The second column is line numbers. Type :345 to jump to line 345. |
137,951 | <p>I have an ASP.NET Datagrid with several text boxes and drop down boxes inside it. I want to read all the values in the grid using a JavaScript function. How do i go about it?</p>
| [
{
"answer_id": 137993,
"author": "Rodrick Chapman",
"author_id": 3927,
"author_profile": "https://Stackoverflow.com/users/3927",
"pm_score": 2,
"selected": false,
"text": "<p>Easily done with jQuery. I don't recall what kind of markup the Datagrid creates but basically something like thi... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have an ASP.NET Datagrid with several text boxes and drop down boxes inside it. I want to read all the values in the grid using a JavaScript function. How do i go about it? | And here's an example using Microsoft AJAX framework:
```
var txts = $get('client_id_of_datagrid').getElementsByTagName('input');
var ddls = $get('client_id_of_datagrid').getElementsByTagName('select');
for(var i=0;i<txts.length;i++){
if(txts[i].type==='text'){
/* do stuff */
}
}
for(var i=0;i<ddls.length;i++){
/* do stuff */
}
```
And for no framework replace $get with document.getElementById.
Really, jQuery is the best idea. |
137,952 | <p>I decide to learn more about vim and its syntax highlighting.
Using examples for others, I am creating my own syntax file for Markdown. I have seen <a href="http://www.vim.org/scripts/script.php?script_id=1242" rel="noreferrer">mkd.vim</a> and it has this problem too.
My issue is between list items and code block highlighting.</p>
<p>Code Block <a href="http://daringfireball.net/projects/markdown/syntax#precode" rel="noreferrer">definition</a>:</p>
<ul>
<li>first line is blank</li>
<li>second line begins with at least 4 spaces or 1 tab</li>
<li>block is finished with a blank line</li>
</ul>
<p>Example:</p>
<pre><code>Regular text
this is code, monospaced and left untouched by markdown
another line of code
Regular Text
</code></pre>
<p>My Vim syntax for code block:</p>
<pre><code>syn match mkdCodeBlock /\(\s\{4,}\|\t\{1,}\).*\n/ contained nextgroup=mkdCodeBlock
hi link mkdCodeBlock comment
</code></pre>
<p>Unorder List item <a href="http://daringfireball.net/projects/markdown/syntax#list" rel="noreferrer">definition</a>:</p>
<ul>
<li>first line is blank</li>
<li>second line begins with a [-+*] followed by a space</li>
<li>the list is finished with a blank line then a normal (non-list) line</li>
<li>in between line items any number of blank lines can be added</li>
<li>a sub list is specified by indenting (4 space or 1 tab)</li>
<li>a line of normal text after a list item is include as a continuation of that list item</li>
</ul>
<p>Example:</p>
<pre><code>Regular text
- item 1
- sub item 1
- sub item 2
- item 2
this is part of item 2
so is this
- item 3, still in the same list
- sub item 1
- sub item 2
Regular text, list ends above
</code></pre>
<p>My Vim syntax for unorder list item definition (I only highlight <code>[-+*]</code>):</p>
<pre><code>syn region mkdListItem start=/\s*[-*+]\s\+/ matchgroup=pdcListText end=".*" contained nextgroup=mkdListItem,mkdListSkipNL contains=@Spell skipnl
syn match mkdListSkipNL /\s*\n/ contained nextgroup=mkdListItem,mkdListSkipNL skipnl
hi link mkdListItem operator
</code></pre>
<p>I cannot get the highlighting to work with the last two rule for list and with a code block.</p>
<p>This is an example that breaks my syntax highlighting:</p>
<pre><code>Regular text
- Item 1
- Item 2
part of item 2
- these 2 line should be highlighted as a list item
- but they are highlighted as a code block
</code></pre>
<p>I currently cannot figure out how to get the highlighting to work the way I want it too</p>
<hr>
<p>Forgot to add a "global" syntax rule used in both rules listed below. It is to ensure a that they start with a blank line.</p>
<pre><code>syn match mkdBlankLine /^\s*\n/ nextgroup=mkdCodeBlock,mkdListItem transparent
</code></pre>
<hr>
<p>Another Note: I should have been more clear. In my syntax file, the List rules appear before the Blockquote Rules</p>
<hr>
| [
{
"answer_id": 138186,
"author": "hcs42",
"author_id": 17916,
"author_profile": "https://Stackoverflow.com/users/17916",
"pm_score": 4,
"selected": true,
"text": "<p>Just make sure that the definition of mkdListItem is after the definition of mkdCodeBlock, like this:</p>\n\n<pre><code>sy... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/873/"
] | I decide to learn more about vim and its syntax highlighting.
Using examples for others, I am creating my own syntax file for Markdown. I have seen [mkd.vim](http://www.vim.org/scripts/script.php?script_id=1242) and it has this problem too.
My issue is between list items and code block highlighting.
Code Block [definition](http://daringfireball.net/projects/markdown/syntax#precode):
* first line is blank
* second line begins with at least 4 spaces or 1 tab
* block is finished with a blank line
Example:
```
Regular text
this is code, monospaced and left untouched by markdown
another line of code
Regular Text
```
My Vim syntax for code block:
```
syn match mkdCodeBlock /\(\s\{4,}\|\t\{1,}\).*\n/ contained nextgroup=mkdCodeBlock
hi link mkdCodeBlock comment
```
Unorder List item [definition](http://daringfireball.net/projects/markdown/syntax#list):
* first line is blank
* second line begins with a [-+\*] followed by a space
* the list is finished with a blank line then a normal (non-list) line
* in between line items any number of blank lines can be added
* a sub list is specified by indenting (4 space or 1 tab)
* a line of normal text after a list item is include as a continuation of that list item
Example:
```
Regular text
- item 1
- sub item 1
- sub item 2
- item 2
this is part of item 2
so is this
- item 3, still in the same list
- sub item 1
- sub item 2
Regular text, list ends above
```
My Vim syntax for unorder list item definition (I only highlight `[-+*]`):
```
syn region mkdListItem start=/\s*[-*+]\s\+/ matchgroup=pdcListText end=".*" contained nextgroup=mkdListItem,mkdListSkipNL contains=@Spell skipnl
syn match mkdListSkipNL /\s*\n/ contained nextgroup=mkdListItem,mkdListSkipNL skipnl
hi link mkdListItem operator
```
I cannot get the highlighting to work with the last two rule for list and with a code block.
This is an example that breaks my syntax highlighting:
```
Regular text
- Item 1
- Item 2
part of item 2
- these 2 line should be highlighted as a list item
- but they are highlighted as a code block
```
I currently cannot figure out how to get the highlighting to work the way I want it too
---
Forgot to add a "global" syntax rule used in both rules listed below. It is to ensure a that they start with a blank line.
```
syn match mkdBlankLine /^\s*\n/ nextgroup=mkdCodeBlock,mkdListItem transparent
```
---
Another Note: I should have been more clear. In my syntax file, the List rules appear before the Blockquote Rules
--- | Just make sure that the definition of mkdListItem is after the definition of mkdCodeBlock, like this:
```
syn match mkdCodeBlock /\(\s\{4,}\|\t\{1,}\).*\n/ contained nextgroup=mkdCodeBlock
hi link mkdCodeBlock comment
syn region mkdListItem start=/\s*[-*+]\s\+/ matchgroup=pdcListText end=".*" contained nextgroup=mkdListItem,mkdListSkipNL contains=@Spell skipnl
syn match mkdListSkipNL /\s*\n/ contained nextgroup=mkdListItem,mkdListSkipNL skipnl
hi link mkdListItem operator
syn match mkdBlankLine /^\s*\n/ nextgroup=mkdCodeBlock,mkdListItem transparent
```
Vim documentation says in `:help :syn-define`:
"In case more than one item matches at the same position, the one that was
defined LAST wins. Thus you can override previously defined syntax items by
using an item that matches the same text. But a keyword always goes before a
match or region. And a keyword with matching case always goes before a
keyword with ignoring case." |
137,998 | <p>I'm a newbie to pgsql. I have few questionss on it:</p>
<p>1) I know it is possible to access columns by <code><schema>.<table_name></code>, but when I try to access columns like <code><db_name>.<schema>.<table_name></code> it throwing error like</p>
<pre><code>Cross-database references are not implemented
</code></pre>
<p>How do I implement it?</p>
<p>2) We have 10+ tables and 6 of have 2000+ rows. Is it fine to maintain all of them in one database? Or should I create dbs to maintain them?</p>
<p>3) From above questions tables which have over 2000+ rows, for a particular process I need a few rows of data. I have created views to get those rows.
For example: a table contains details of employees, they divide into 3 types; manager, architect, and engineer. Very obvious thing this table not getting each every process... process use to read data from it...
I think there are two ways to get data <code>SELECT * FROM emp WHERE type='manager'</code>, or I can create views for manager, architect n engineer and get data <code>SELECT * FROM view_manager</code></p>
<p>Can you suggest any better way to do this?</p>
<p>4) Do views also require storage space, like tables do?</p>
<p>Thanx in advance.</p>
| [
{
"answer_id": 138022,
"author": "Michael Ratanapintha",
"author_id": 1879,
"author_profile": "https://Stackoverflow.com/users/1879",
"pm_score": 0,
"selected": false,
"text": "<p>1: A workaround is to open a connection to the other database, and (if using psql(1)) set that as your curre... | 2008/09/26 | [
"https://Stackoverflow.com/questions/137998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22554/"
] | I'm a newbie to pgsql. I have few questionss on it:
1) I know it is possible to access columns by `<schema>.<table_name>`, but when I try to access columns like `<db_name>.<schema>.<table_name>` it throwing error like
```
Cross-database references are not implemented
```
How do I implement it?
2) We have 10+ tables and 6 of have 2000+ rows. Is it fine to maintain all of them in one database? Or should I create dbs to maintain them?
3) From above questions tables which have over 2000+ rows, for a particular process I need a few rows of data. I have created views to get those rows.
For example: a table contains details of employees, they divide into 3 types; manager, architect, and engineer. Very obvious thing this table not getting each every process... process use to read data from it...
I think there are two ways to get data `SELECT * FROM emp WHERE type='manager'`, or I can create views for manager, architect n engineer and get data `SELECT * FROM view_manager`
Can you suggest any better way to do this?
4) Do views also require storage space, like tables do?
Thanx in advance. | 1. Cross Database exists in PostGreSQL for years now. You must prefix the name of the database by the database name (and, of course, have the right to query on it). You'll come with something like this:
SELECT alias\_1.col1, alias\_2.col3 FROM table\_1 as alias\_1, database\_b.table\_2 as alias\_2 WHERE ...
If your database is on another instance, then you'll need to use the dblink contrib.
2. This question doe not make sens. Please refine.
3. Generally, views are use to simplify the writing of other queries that reuse them. In your case, as you describe it, maybe that stored proceudre would better fits you needs.
4. No, expect the view definition. |
138,000 | <p>When I try to send an HTTP GET request through XMLHttpRequest it works on non-secure HTTP.</p>
<p>But when sent over HTTPS, different browsers gave different results:</p>
<p>On Firefox 3.0.2:
- The GET request doesn't reach the web server.</p>
<p>On IE 7:
- The GET request reached the web server.</p>
<p>Does this have something to do with Firefox 3 getting stricter with untrusted certificates?
Is there a way around this?</p>
<p>I've already added the URL as an exception in Firefox's Certificate Manager.
The error console doesn't report any error.
I've added a try-catch around XMLHttpRequest's open() and send. No exception is thrown.</p>
<p>Using both absolute and relative URL path doesn't work.</p>
<p>Here's the code snippet:</p>
<pre><code> var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return false;
}
}
}
// we won't be handling any HTTP response
xmlHttp.onreadystatechange=function()
{
// do nothing..
}
// send HTTP GET request
try
{
xmlHttp.open("GET", "/[relative path to request]", true);
xmlHttp.send(null);
}
catch (e)
{
alert('Error sending HTTP GET request!');
return false;
}
</code></pre>
<p>Thanks,
Kenneth</p>
| [
{
"answer_id": 138011,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 0,
"selected": false,
"text": "<p>By any chance, are you requesting a non-HTTPS URL in an HTTPS page? Do any messages appear in the error log/console... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16139/"
] | When I try to send an HTTP GET request through XMLHttpRequest it works on non-secure HTTP.
But when sent over HTTPS, different browsers gave different results:
On Firefox 3.0.2:
- The GET request doesn't reach the web server.
On IE 7:
- The GET request reached the web server.
Does this have something to do with Firefox 3 getting stricter with untrusted certificates?
Is there a way around this?
I've already added the URL as an exception in Firefox's Certificate Manager.
The error console doesn't report any error.
I've added a try-catch around XMLHttpRequest's open() and send. No exception is thrown.
Using both absolute and relative URL path doesn't work.
Here's the code snippet:
```
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return false;
}
}
}
// we won't be handling any HTTP response
xmlHttp.onreadystatechange=function()
{
// do nothing..
}
// send HTTP GET request
try
{
xmlHttp.open("GET", "/[relative path to request]", true);
xmlHttp.send(null);
}
catch (e)
{
alert('Error sending HTTP GET request!');
return false;
}
```
Thanks,
Kenneth | Try placing your closure after the open:
```
// send HTTP GET request
try
{
xmlHttp.open("GET", "/[relative path to request]", true);
}
catch (e)
{
alert('Error sending HTTP GET request!');
return false;
}
// we won't be handling any HTTP response
xmlHttp.onreadystatechange=function()
{
// do nothing..
}
// Then send it.
xmlHttp.send(null);
```
A little googling found confirmation:
<http://www.ghastlyfop.com/blog/2007/01/onreadystate-changes-in-firefox.html>
Although that document says to attach the function after .send(null), I've
always attached after open. |
138,029 | <p>After a bind a method to an event of a Tkinter element is there a way to get the method back?</p>
<pre><code>>>> root = Tkinter.Tk()
>>> frame = Tkinter.Frame(root, width=100, height=100)
>>> frame.bind('<Button-1>', lambda e: pprint('Click')) # function needed
>>> frame.pack()
>>> bound_event_method = frame.???
</code></pre>
| [
{
"answer_id": 138039,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 0,
"selected": false,
"text": "<p>Doesn't appear to be... why not just save it yourself if you're going to need it, or use a non-anonymous function?</... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
] | After a bind a method to an event of a Tkinter element is there a way to get the method back?
```
>>> root = Tkinter.Tk()
>>> frame = Tkinter.Frame(root, width=100, height=100)
>>> frame.bind('<Button-1>', lambda e: pprint('Click')) # function needed
>>> frame.pack()
>>> bound_event_method = frame.???
``` | The associated call to do that for the tk C API would be [Get\_GetCommandInfo](http://linux.about.com/library/cmd/blcmdl3_Tcl_GetCommandInfo.htm) which
>
> places information about the command
> in the Tcl\_CmdInfo structure pointed
> to by infoPtr
>
>
>
However this function is not used anywhere in [\_tkinter.c](http://svn.python.org/projects/python/trunk/Modules/_tkinter.c) which is the binding for tk used by python trough [Tkinter.py](http://svn.python.org/projects/python/trunk/Lib/lib-tk/Tkinter.py).
Therefore it is impossible to get the bound function out of tkinter. You need to remember that function yourself. |
138,040 | <p>I have to create a dialog based application, instead of old CFormView type of design. But CDialog produces fixed-size dialogs. How can I create dialog based applications with resizable dialogs?</p>
| [
{
"answer_id": 138052,
"author": "user22044",
"author_id": 22044,
"author_profile": "https://Stackoverflow.com/users/22044",
"pm_score": 2,
"selected": false,
"text": "<p>There is no easy way to do this. Basically, you will need to dynamically layout controls when the window size is chan... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have to create a dialog based application, instead of old CFormView type of design. But CDialog produces fixed-size dialogs. How can I create dialog based applications with resizable dialogs? | In the RC resource file if the dialog has this style similar to this it will be fixed size:
```
IDD_DIALOG_DIALOG DIALOGEX 0, 0, 320, 201
STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
```
If the dialog has this style it will be sizeable:
```
IDD_DIALOG_DIALOG DIALOGEX 0, 0, 320, 201
STYLE WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME
```
With these sizable frame options the dialog will be re-sizeable but you will still need to do a lot of work handling the **WM\_SIZE** message to manage the sizing an positioning of the controls within the dialog. |
138,043 | <p>I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port.</p>
<p>I know that TcpClient will assign a new client side port when I open a connection to a given server.</p>
<p>Is there a simple way to find the next open TCP port in .NET?</p>
<p>I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.</p>
| [
{
"answer_id": 138044,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 5,
"selected": false,
"text": "<p>Use a port number of 0. The TCP stack will allocate the next free one.</p>\n"
},
{
"answer_id": 138220,
"auth... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4829/"
] | I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port.
I know that TcpClient will assign a new client side port when I open a connection to a given server.
Is there a simple way to find the next open TCP port in .NET?
I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel. | Here is what I was looking for:
```
static int FreeTcpPort()
{
TcpListener l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
``` |
138,045 | <p>Is there something like <a href="http://effbot.org/zone/python-getattr.htm" rel="noreferrer">Python's getattr()</a> in C#? I would like to create a window by reading a list which contains the names of controls to put on the window.</p>
| [
{
"answer_id": 138053,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 3,
"selected": false,
"text": "<p>Use reflection for this.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.type.getproperty.aspx... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22562/"
] | Is there something like [Python's getattr()](http://effbot.org/zone/python-getattr.htm) in C#? I would like to create a window by reading a list which contains the names of controls to put on the window. | There is also [Type.InvokeMember](http://msdn.microsoft.com/en-us/library/66btctbe.aspx).
```
public static class ReflectionExt
{
public static object GetAttr(this object obj, string name)
{
Type type = obj.GetType();
BindingFlags flags = BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.GetProperty;
return type.InvokeMember(name, flags, Type.DefaultBinder, obj, null);
}
}
```
Which could be used like:
```
object value = ReflectionExt.GetAttr(obj, "PropertyName");
```
or (as an extension method):
```
object value = obj.GetAttr("PropertyName");
``` |
138,056 | <p>In other words, a block of code like this:</p>
<pre><code>(setq initial-major-mode
(lambda ()
(text-mode)
(font-lock-mode)
))
</code></pre>
<p>... would come out looking like something like this:</p>
<p><img src="https://i.stack.imgur.com/kiaIG.gif" alt="alt text"></p>
<p>If something like this already exists, what is it? And if it doesn't exist, how should I go about writing it?</p>
| [
{
"answer_id": 138357,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 5,
"selected": true,
"text": "<p>I think you are looking for something like <a href=\"http://www.foldr.org/~michaelw/emacs/mwe-color-box.el\" rel=\"noreferrer\... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
] | In other words, a block of code like this:
```
(setq initial-major-mode
(lambda ()
(text-mode)
(font-lock-mode)
))
```
... would come out looking like something like this:

If something like this already exists, what is it? And if it doesn't exist, how should I go about writing it? | I think you are looking for something like [mwe-color-box.el](http://www.foldr.org/~michaelw/emacs/mwe-color-box.el) |
138,071 | <p>The questions says everything, take this example code: </p>
<pre><code><ul id="css-id">
<li>
<something:CustomControl ID="SomeThingElse" runat="server" />
<something:OtherCustomControl runat="server" />
</li>
</ul>
</code></pre>
<p>Now if an error gets thrown somewhere inside these controlls (that are located in a master page) they will take down the entire site, how would one catch these exceptions?</p>
| [
{
"answer_id": 138082,
"author": "Drejc",
"author_id": 6482,
"author_profile": "https://Stackoverflow.com/users/6482",
"pm_score": 4,
"selected": true,
"text": "<p>You can catch all exception not handled elswhere in the Global.asax page / class. \nLook at:</p>\n\n<pre><code>protected voi... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452521/"
] | The questions says everything, take this example code:
```
<ul id="css-id">
<li>
<something:CustomControl ID="SomeThingElse" runat="server" />
<something:OtherCustomControl runat="server" />
</li>
</ul>
```
Now if an error gets thrown somewhere inside these controlls (that are located in a master page) they will take down the entire site, how would one catch these exceptions? | You can catch all exception not handled elswhere in the Global.asax page / class.
Look at:
```
protected void Application_Error(Object sender, EventArgs e)
```
method. |
138,073 | <p><strong>Scenario:</strong> C# apps uses SQL2000. It excecute 3 stored procs within a try catch in the app. In the catch the error is suppressed. Due to some legalities, the c# code cannot be changed and implemented. </p>
<p><strong>Q:</strong> How do I trap the actual SQL error in the stored proc into a log file or other table? @@Error returns an error message to the app but when evaluated in query analyzer it is always 0 although the 'If @@Error <> 0' does fire. I try to store the @@Error number, but it is always 0.</p>
<p>Please help.</p>
| [
{
"answer_id": 138111,
"author": "Matt Lacey",
"author_id": 1755,
"author_profile": "https://Stackoverflow.com/users/1755",
"pm_score": 2,
"selected": false,
"text": "<p>Haven't got an example to hand, but look at using</p>\n\n<pre><code>RAISERROR ... WITH LOG\n</code></pre>\n\n<p>see: <... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | **Scenario:** C# apps uses SQL2000. It excecute 3 stored procs within a try catch in the app. In the catch the error is suppressed. Due to some legalities, the c# code cannot be changed and implemented.
**Q:** How do I trap the actual SQL error in the stored proc into a log file or other table? @@Error returns an error message to the app but when evaluated in query analyzer it is always 0 although the 'If @@Error <> 0' does fire. I try to store the @@Error number, but it is always 0.
Please help. | `@@ERROR` is reset to 0 when you check it. Why? Because it reflects the status of the last statement executed.
```
IF @@ERROR <> 0 ...
```
is a statement, and that statement succeeds, causing `@@ERROR` to be set to 0.
The proper way to examine and operate on `@@ERROR` values is as follows:
```
DECLARE @ErrorCode INT
INSERT INTO Table ...
SET @ErrorCode = @@ERROR
IF @ErrorCode <> 0
BEGIN
INSERT INTO ErrorLog (ErrorCode, Message)
VALUES (@ErrorCode, 'The INSERT operation failed.')
END
``` |
138,096 | <p>I have a Window where I have put a Frame. I would like to add a Page to the Frame when I click a button that is also on the Window but not in the Frame. There are several buttons in the Window and each click on a button should load a different Page in the Frame.</p>
<p>Since I'm a total newbie on this WPF stuff it's quite possible that this approach is not the best and I have thought about replacing the Frame with a Canvas and then make UserControls instead of Pages that will be added to the Canvas. I welcome any ideas and suggestions on how to best solve this. </p>
<p>I aiming for a functionality that is similar to the application Billy Hollis demonstrated in dnrtv episode 115. (<a href="http://dnrtv.com/default.aspx?showID=115" rel="noreferrer">http://dnrtv.com/default.aspx?showID=115</a>). </p>
| [
{
"answer_id": 138315,
"author": "Joachim Kerschbaumer",
"author_id": 20227,
"author_profile": "https://Stackoverflow.com/users/20227",
"pm_score": 5,
"selected": true,
"text": "<p>the Frame class exposes a method named \"Navigate\" that takes the content you want to show in your frame a... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143/"
] | I have a Window where I have put a Frame. I would like to add a Page to the Frame when I click a button that is also on the Window but not in the Frame. There are several buttons in the Window and each click on a button should load a different Page in the Frame.
Since I'm a total newbie on this WPF stuff it's quite possible that this approach is not the best and I have thought about replacing the Frame with a Canvas and then make UserControls instead of Pages that will be added to the Canvas. I welcome any ideas and suggestions on how to best solve this.
I aiming for a functionality that is similar to the application Billy Hollis demonstrated in dnrtv episode 115. (<http://dnrtv.com/default.aspx?showID=115>). | the Frame class exposes a method named "Navigate" that takes the content you want to show in your frame as parameter.
try calling
```
myFrame.Navigate(myPageObject);
```
this should work |
138,097 | <p>I need to find the PID of the current running process on a Linux platform (it can be a system dependent solution). Java does not support getting the process ID, and JRuby currently has a bug with the Ruby method, Process.pid.</p>
<p>Is there another way to obtain the PID?</p>
| [
{
"answer_id": 138098,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 6,
"selected": true,
"text": "<p>If you have <a href=\"http://en.wikipedia.org/wiki/Procfs\" rel=\"nofollow noreferrer\">procfs</a> installed, you can fin... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | I need to find the PID of the current running process on a Linux platform (it can be a system dependent solution). Java does not support getting the process ID, and JRuby currently has a bug with the Ruby method, Process.pid.
Is there another way to obtain the PID? | If you have [procfs](http://en.wikipedia.org/wiki/Procfs) installed, you can find the process id via the /proc/self symlink, which points to a directory whose name is the pid (there are also files here with other pertinent information, including the PID, but the directory is all you need in this case).
Thus, with Java, you can do:
```
String pid = new File("/proc/self").getCanonicalFile().getName();
```
In JRuby, you can use the same solution:
```
pid = java.io.File.new("/proc/self").canonical_file.name
```
Special thanks to the #stackoverflow channel on free node for helping me solve this! (specifically, [Jerub](https://stackoverflow.com/users/14648/jerub), [gregh](https://stackoverflow.com/users/893/greg-hewgill), and [Topdeck](https://stackoverflow.com/users/1057/harley)) |
138,099 | <p>GWT's serializer has limited <code>java.io.Serializable</code> support, but for security reasons there is a whitelist of types it supports. The documentation I've found, for example <a href="http://www.gwtproject.org/doc/latest/FAQ_Server.html#Does_the_GWT_RPC_system_support_the_use_of_java.io.Serializable" rel="noreferrer">this FAQ entry</a> says that any types you want to serialize "must be included in the serialization policy whitelist", and that the list is generated at compile time, but doesn't explain how the compiler decides what goes on the whitelist.</p>
<p>The generated list contains a number of types that are part of the standard library, such as <code>java.lang.String</code> and <code>java.util.HashMap</code>. I get an error when trying to serialize <code>java.sql.Date</code>, which implements the <code>Serializable</code> interface, but is not on the whitelist. How can I add this type to the list?</p>
| [
{
"answer_id": 138965,
"author": "pfranza",
"author_id": 22221,
"author_profile": "https://Stackoverflow.com/users/22221",
"pm_score": 3,
"selected": false,
"text": "<p>The whitelist is generated by the GWT compiler and contains all the entries that are designated by the IsSerializable m... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3562/"
] | GWT's serializer has limited `java.io.Serializable` support, but for security reasons there is a whitelist of types it supports. The documentation I've found, for example [this FAQ entry](http://www.gwtproject.org/doc/latest/FAQ_Server.html#Does_the_GWT_RPC_system_support_the_use_of_java.io.Serializable) says that any types you want to serialize "must be included in the serialization policy whitelist", and that the list is generated at compile time, but doesn't explain how the compiler decides what goes on the whitelist.
The generated list contains a number of types that are part of the standard library, such as `java.lang.String` and `java.util.HashMap`. I get an error when trying to serialize `java.sql.Date`, which implements the `Serializable` interface, but is not on the whitelist. How can I add this type to the list? | Any specific types that you include in your service interface and any types that they reference will be automatically whitelisted, as long as they implement java.io.Serializable, eg:
```
public String getStringForDates(ArrayList<java.util.Date> dates);
```
Will result in ArrayList and Date both being included on the whitelist.
It gets trickier if you try and use java.lang.Object instead of specific types:
```
public Object getObjectForString(String str);
```
Because the compiler doesn't know what to whitelist. In that case if the objects are not referenced anywhere in your service interface, you have to mark them explicitly with the IsSerializable interface, otherwise it won't let you pass them through the RPC mechanism. |
138,117 | <p>how to send rich text message in system.net.mail need code for send a mail as html</p>
| [
{
"answer_id": 138128,
"author": "Vincent McNabb",
"author_id": 16299,
"author_profile": "https://Stackoverflow.com/users/16299",
"pm_score": 2,
"selected": false,
"text": "<pre><code>System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();\nmm.Body = \"<html>...</htm... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | how to send rich text message in system.net.mail need code for send a mail as html | ```
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("me@mycompany.com");
mail.To.Add("you@yourcompany.com");
//set the content
mail.Subject = "This is an email";
mail.Body = "<b>This is bold</b> <font color=#336699>This is blue</font>";
mail.IsBodyHtml = true;
//send the message
SmtpClient smtp = new SmtpClient("127.0.0.1");
smtp.Send(mail);
``` |
138,122 | <p>I'd like to be able to create a large (say 20,000 x 20,000) pixel bitmap in a C++ MFC application, using a CDC derived class to write to the bitmap. I've tried using memory DCs as described in the MSDN docs, but these appear to be restricted to sizes compatible with the current display driver.</p>
<p>I'm currently using a bitmap print driver to do the job, but it is extremely slow and uses very large amounts of intermediate storage due to spooling GDI information.</p>
<p>The solution I'm looking for should not involve metafiles or spooling, as the model that I am drawing takes many millions of GDI calls to render.</p>
<p>I could use a divide and conquer approach via multiple memory DCs, but it seems like a pretty cumborsome and inelegant technique.</p>
<p>any thoughts?</p>
| [
{
"answer_id": 138126,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 1,
"selected": false,
"text": "<p>This is unusual as I often created a DC based on the screen that will be used for a bitmap image that is much larger than the... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22564/"
] | I'd like to be able to create a large (say 20,000 x 20,000) pixel bitmap in a C++ MFC application, using a CDC derived class to write to the bitmap. I've tried using memory DCs as described in the MSDN docs, but these appear to be restricted to sizes compatible with the current display driver.
I'm currently using a bitmap print driver to do the job, but it is extremely slow and uses very large amounts of intermediate storage due to spooling GDI information.
The solution I'm looking for should not involve metafiles or spooling, as the model that I am drawing takes many millions of GDI calls to render.
I could use a divide and conquer approach via multiple memory DCs, but it seems like a pretty cumborsome and inelegant technique.
any thoughts? | CDC and CBitmap appears to only support device dependant bitmaps, you might have more luck creating your bitmap with [::CreateDIBSection](http://msdn.microsoft.com/en-us/library/ms532292(VS.85).aspx), then attaching a CBitmap to that. The raw GDI interfaces are a little hoary, unfortunately.
You probably won't have much luck with 20,000 x 20,000 at 32 BPP, at least in a 32-bit application, as that comes out at about 1.5 GB of memory, but I got a valid HBITMAP back with 16 bpp:
```
BITMAPINFOHEADER bmi = { sizeof(bmi) };
bmi.biWidth = 20000;
bmi.biHeight = 20000;
bmi.biPlanes = 1;
bmi.biBitCount = 16;
HDC hdc = CreateCompatibleDC(NULL);
BYTE* pbData = 0;
HBITMAP hbm = CreateDIBSection(hdc, (BITMAPINFO*)&bmi, DIB_RGB_COLORS, (void**)&pbData, NULL, 0);
DeleteObject(SelectObject(hdc, hbm));
``` |
138,132 | <p><strong>Here's the situation</strong>: I'm trying my hand at some MySpace page customisations. If you've <a href="https://stackoverflow.com/questions/116610/myspace-dom">ever tried</a> [stackoverflow], I'm sure you understand how frustrating it can be.<br>
Basically it can be all customised via CSS, within a certain set of rules (e.g. the '#' character is not allowed...how useful!).<br>
Have a look at this <a href="http://www.mikeindustries.com/blog/archive/2006/04/hacking-myspace-layouts" rel="nofollow noreferrer">blog</a> if you want more info, I used it as the basis for my customisations</p>
<p>So the only problem is with the comments section, where 'friends' post whatever they feel like.
It already has...</p>
<pre><code>max-width:423px;
</code></pre>
<p>...set on the table, but I've discovered if long URLs are posted in the comment section, it blows out the table width, regardless of the max setting!</p>
<p><strong>Question</strong>: Is there a way to manage text that is going to push the width of the table?<br>
Perhaps splitting/chopping the string? Or is there more I should be doing..?<br>
The URLs are posted as text, not hrefs.</p>
<p>Using Firefox and Firebug btw.</p>
<p><strong>Edit</strong>: Also javascript is not allowed ;)</p>
<p><strong>Another edit</strong> Just checked with IE7, and it seems to work.. so firefox is being the hassle in this case..</p>
| [
{
"answer_id": 138145,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried the various values for the \"overflow\" css property? I think that may do what you need in some permut... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] | **Here's the situation**: I'm trying my hand at some MySpace page customisations. If you've [ever tried](https://stackoverflow.com/questions/116610/myspace-dom) [stackoverflow], I'm sure you understand how frustrating it can be.
Basically it can be all customised via CSS, within a certain set of rules (e.g. the '#' character is not allowed...how useful!).
Have a look at this [blog](http://www.mikeindustries.com/blog/archive/2006/04/hacking-myspace-layouts) if you want more info, I used it as the basis for my customisations
So the only problem is with the comments section, where 'friends' post whatever they feel like.
It already has...
```
max-width:423px;
```
...set on the table, but I've discovered if long URLs are posted in the comment section, it blows out the table width, regardless of the max setting!
**Question**: Is there a way to manage text that is going to push the width of the table?
Perhaps splitting/chopping the string? Or is there more I should be doing..?
The URLs are posted as text, not hrefs.
Using Firefox and Firebug btw.
**Edit**: Also javascript is not allowed ;)
**Another edit** Just checked with IE7, and it seems to work.. so firefox is being the hassle in this case.. | Have you tried the various values for the "overflow" css property? I think that may do what you need in some permutation. |
138,133 | <p>Is there a standard framework (maybe part of Enterprise Library... or .NET itself) that allows you to do common parameter validation in method attributes?</p>
| [
{
"answer_id": 138152,
"author": "Fredrik Kalseth",
"author_id": 1710,
"author_profile": "https://Stackoverflow.com/users/1710",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.codeplex.com/aspnet/Wiki/View.aspx?title=Dynamic%20Data&referringTitle=Home\" rel=\"nofo... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] | Is there a standard framework (maybe part of Enterprise Library... or .NET itself) that allows you to do common parameter validation in method attributes? | [Microsoft Code Contracts](http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx), which are part of .NET Framework since 4.0 CTP and are available for earlier .NET Framework versions as a stand-alone package, allow to specify coding assumptions. This includes specifying pre-conditions which can verify parameters.
An example use for parameter checking would be (copied from [Code Contracts documentation](http://download.microsoft.com/download/C/2/7/C2715F76-F56C-4D37-9231-EF8076B7EC13/userdoc.pdf)):
```
public Rational(int numerator, int denominator)
{
Contract.Requires(denominator ! = 0);
this.numerator = numerator;
this.denominator = denominator;
}
```
The benefit of using Code Contracts is that it is a library which will be part of future .NET Framework releases, so sooner or later you will have one dependency less in your application.
**EDIT:** Just noticed that your specifically asking for a library that uses Attributes for argument checking... that Code Contracts does not. The reason why Code Contracts does not use attributes is listed in their [FAQ](http://research.microsoft.com/en-us/projects/contracts/faq.aspx):
>
> The advantage of using custom attributes is that they do not impact the code at all. However, the benefits of using method calls far outweigh the seemingly natural first choice of attributes:
>
>
> **Runtime support:** Without depending on a binary rewriter, contracts expressed with attributes cannot be enforced at runtime. This means that if there are preconditions (or other contracts) that you want enforced at runtime, you need to either duplicate the contracts in the code or else include a binary rewriter in your build process. Contract.RequiresAlways serves both as a declarative contract and as a runtime-checked validation.
>
>
> **Need for parsing:** Since the values that can be used with custom attributes are limited, conditions end up being encoded as strings. This requires defining a new language that is appropriate for all source languages, requires the strings to be parsed, duplicating all of the functionality the compiler already possesses.
>
>
> **Lack of IDE support:** Expressed as strings, there is no support for Intellisense, type checking, or refactoring, all of which are available for authoring contracts as code.
>
>
> |
138,144 | <p>What essential things (functions, aliases, start up scripts) do you have in your profile?</p>
| [
{
"answer_id": 138224,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 2,
"selected": false,
"text": "<pre><code>############################################################################## \n# Get an XPath Navigator obje... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20911/"
] | What essential things (functions, aliases, start up scripts) do you have in your profile? | I often find myself needing needing some basic agregates to count/sum some things., I've defined these functions and use them often, they work really nicely at the end of a pipeline :
```
#
# useful agregate
#
function count
{
BEGIN { $x = 0 }
PROCESS { $x += 1 }
END { $x }
}
function product
{
BEGIN { $x = 1 }
PROCESS { $x *= $_ }
END { $x }
}
function sum
{
BEGIN { $x = 0 }
PROCESS { $x += $_ }
END { $x }
}
function average
{
BEGIN { $max = 0; $curr = 0 }
PROCESS { $max += $_; $curr += 1 }
END { $max / $curr }
}
```
To be able to get time and path with colors in my prompt :
```
function Get-Time { return $(get-date | foreach { $_.ToLongTimeString() } ) }
function prompt
{
# Write the time
write-host "[" -noNewLine
write-host $(Get-Time) -foreground yellow -noNewLine
write-host "] " -noNewLine
# Write the path
write-host $($(Get-Location).Path.replace($home,"~").replace("\","/")) -foreground green -noNewLine
write-host $(if ($nestedpromptlevel -ge 1) { '>>' }) -noNewLine
return "> "
}
```
The following functions are stolen from a blog and modified to fit my taste, but ls with colors is very nice :
```
# LS.MSH
# Colorized LS function replacement
# /\/\o\/\/ 2006
# http://mow001.blogspot.com
function LL
{
param ($dir = ".", $all = $false)
$origFg = $host.ui.rawui.foregroundColor
if ( $all ) { $toList = ls -force $dir }
else { $toList = ls $dir }
foreach ($Item in $toList)
{
Switch ($Item.Extension)
{
".Exe" {$host.ui.rawui.foregroundColor = "Yellow"}
".cmd" {$host.ui.rawui.foregroundColor = "Red"}
".msh" {$host.ui.rawui.foregroundColor = "Red"}
".vbs" {$host.ui.rawui.foregroundColor = "Red"}
Default {$host.ui.rawui.foregroundColor = $origFg}
}
if ($item.Mode.StartsWith("d")) {$host.ui.rawui.foregroundColor = "Green"}
$item
}
$host.ui.rawui.foregroundColor = $origFg
}
function lla
{
param ( $dir=".")
ll $dir $true
}
function la { ls -force }
```
And some shortcuts to avoid really repetitive filtering tasks :
```
# behave like a grep command
# but work on objects, used
# to be still be allowed to use grep
filter match( $reg )
{
if ($_.tostring() -match $reg)
{ $_ }
}
# behave like a grep -v command
# but work on objects
filter exclude( $reg )
{
if (-not ($_.tostring() -match $reg))
{ $_ }
}
# behave like match but use only -like
filter like( $glob )
{
if ($_.toString() -like $glob)
{ $_ }
}
filter unlike( $glob )
{
if (-not ($_.tostring() -like $glob))
{ $_ }
}
``` |
138,162 | <p>I want to setup my local development machine so that any requests for <code>*.local</code> are redirected to <code>localhost</code>. The idea is that as I develop multiple sites, I can just add vhosts to Apache called <code>site1.local</code>, <code>site2.local</code> etc, and have them all resolve to <code>localhost</code>, while Apache serves a different site accordingly.</p>
<p>I am on Windows XP.</p>
<p>I tried adding </p>
<pre><code>127.0.0.1 *.local
</code></pre>
<p>to my <code>c:\windows\system32\drivers\etc\hosts</code> file, also tried:</p>
<pre><code>127.0.0.1 .local
</code></pre>
<p>Neither of which seem to work.</p>
<p>I know I can set them up on different port numbers, but that is a pain since it is hard to remember which port is which.</p>
<p>I don't want to have to setup a local DNS server or anything hard, any suggestions?</p>
| [
{
"answer_id": 138181,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 5,
"selected": false,
"text": "<p>I don't think that it is possible.</p>\n\n<p>You anyway have to modify the apache virtualroot entries every time you add a new... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20851/"
] | I want to setup my local development machine so that any requests for `*.local` are redirected to `localhost`. The idea is that as I develop multiple sites, I can just add vhosts to Apache called `site1.local`, `site2.local` etc, and have them all resolve to `localhost`, while Apache serves a different site accordingly.
I am on Windows XP.
I tried adding
```
127.0.0.1 *.local
```
to my `c:\windows\system32\drivers\etc\hosts` file, also tried:
```
127.0.0.1 .local
```
Neither of which seem to work.
I know I can set them up on different port numbers, but that is a pain since it is hard to remember which port is which.
I don't want to have to setup a local DNS server or anything hard, any suggestions? | Acrylic DNS Proxy (free, open source) does the job. It creates a proxy DNS server (on your own computer) with its own hosts file. The hosts file accepts wildcards.
**Download from the offical website**
<http://mayakron.altervista.org/support/browse.php?path=Acrylic&name=Home>
Configuring Acrylic DNS Proxy
-----------------------------
**To configure Acrylic DNS Proxy, install it from the above link then go to:**
1. Start
2. Programs
3. Acrylic DNS Proxy
4. Config
5. Edit Custom Hosts File (AcrylicHosts.txt)
**Add the folowing lines on the end of the file:**
```
127.0.0.1 *.localhost
127.0.0.1 *.local
127.0.0.1 *.lc
```
**Restart the Acrylic DNS Proxy service:**
1. Start
2. Programs
3. Acrilic DNS Proxy
4. Config
5. Restart Acrylic Service
**You will also need to adjust your DNS setting in you network interface settings:**
1. Start
2. Control Panel
3. Network and Internet
4. Network Connections
5. Local Area Connection Properties
6. TCP/IPv4
**Set "Use the following DNS server address":**
```
Preferred DNS Server: 127.0.0.1
```
*If you then combine this answer with jeremyasnyder's answer (using `VirtualDocumentRoot`) you can then automatically setup domains/virtual hosts by simply creating a directory.* |
138,194 | <p>In the Flex framework a custom preloader can be used while the site is loading.</p>
<p>In the <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=app_container_4.html" rel="nofollow noreferrer">Adobe docs</a> it specifies that '<strong>the progress bar [preloader] is displayed if less than half of the application is downloaded after 700 milliseconds of downloading.</strong>'</p>
<p>However I ALWAYS want the preloader to appear instantly since I know that 95% of our users are first time visitors and the site is over 500kb. I dont want people to have to wait .7 seconds for the preloader animation to appear.</p>
<p>I would think in theory that it is possible to 'monkey patch' the framework to remove this .7 second limitation. I dont have time to figure out how, and I've never done it before.</p>
<p>Anybody help?</p>
| [
{
"answer_id": 138247,
"author": "Simon Buchan",
"author_id": 20135,
"author_profile": "https://Stackoverflow.com/users/20135",
"pm_score": 1,
"selected": false,
"text": "<p>This is in mx.preloaders::DownloadProgressBar.as, line 1205 in the <code>showDisplayForDownloading</code> function... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
] | In the Flex framework a custom preloader can be used while the site is loading.
In the [Adobe docs](http://livedocs.adobe.com/flex/3/html/help.html?content=app_container_4.html) it specifies that '**the progress bar [preloader] is displayed if less than half of the application is downloaded after 700 milliseconds of downloading.**'
However I ALWAYS want the preloader to appear instantly since I know that 95% of our users are first time visitors and the site is over 500kb. I dont want people to have to wait .7 seconds for the preloader animation to appear.
I would think in theory that it is possible to 'monkey patch' the framework to remove this .7 second limitation. I dont have time to figure out how, and I've never done it before.
Anybody help? | You should just extend the DownloadProgressBar, try the following code. i've used this before and I've found jesse warden site [click here](http://jessewarden.com/2007/07/making-a-cooler-preloader-in-flex-part-1-of-3.html) usful for info on this (where I found out about it and this is a cut down version of his code)
```
package{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.ProgressEvent;
import mx.events.FlexEvent;
import mx.preloaders.DownloadProgressBar;
public class Preloader extends DownloadProgressBar
{
/**
* The Flash 8 MovieClip embedded as a Class.
*/
[Embed(source="yourPreloaderFile.swf")]
private var FlashPreloaderSymbol:Class;
private var clip:MovieClip;
public function Preloader()
{
super();
clip = new FlashPreloaderSymbol();
addChild(clip);
}
public override function set preloader(preloader:Sprite):void
{
preloader.addEventListener( FlexEvent.INIT_COMPLETE , onFlexInitComplete );
centerPreloader();
}
private function centerPreloader():void
{
x = (stageWidth / 2) - (clip.width / 2);
y = (stageHeight / 2) - (clip.height / 2);
}
private function onFlexInitComplete( event:FlexEvent ):void
{
dispatchEvent( new Event( Event.COMPLETE ) );
}
protected override function showDisplayForDownloading(time : int, event : ProgressEvent) : Boolean {
return true;
}
}
```
}
after that just change the preloader property in the main application tag to the Preloader class. |
138,203 | <p>Is it possible for a stand alone executable to generate a report and output it as PDF (or one of the other export options available from the report viewer) without displaying the ReportViewer control? </p>
<p>The report definition should be embedded in the executable and should not use the Reporting Services web service.</p>
| [
{
"answer_id": 138222,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 2,
"selected": false,
"text": "<p>You don't have to show the control itself.</p>\n\n<pre><code>ReportViewer rv = new ReportViewer();\nrv.LocalReport.ReportPath ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/966/"
] | Is it possible for a stand alone executable to generate a report and output it as PDF (or one of the other export options available from the report viewer) without displaying the ReportViewer control?
The report definition should be embedded in the executable and should not use the Reporting Services web service. | Actually you don't need a ReportViewer at all, you can directly instantiate and use a LocalReport:
```
LocalReport report = new LocalReport();
report.ReportPath = "templatepath";
// or use file from resource with report.ReportEmbeddedResource
// add parameters, datasource, etc.
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
byte[] bytes;
bytes =report.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
// save byte[] to file with FileStream or something else
``` |
138,245 | <p>currently I'm dealing with a video processing software in which the picture data (8bit signed and unsigned) is stored in arrays of 16-aligned integers allocated as</p>
<pre><code>__declspec(align(16)) int *pData = (__declspec(align(16)) int *)_mm_malloc(width*height*sizeof(int),16);
</code></pre>
<p>Generally, wouldn't it enable faster reading and writing if one used signed/unsigned char arrays like this?:</p>
<pre><code>__declspec(align(16)) int *pData = (__declspec(align(16)) unsigned char *)_mm_malloc(width*height*sizeof(unsigned char),16);
</code></pre>
<p>I know little about cache line size and data transfer optimization, but at least I know that it is an issue. Beyond that, SSE will be used in future, and in that case char-arrays - unlike int arrays - are already in a <em>packed</em> format. So which version would be faster?</p>
| [
{
"answer_id": 138297,
"author": "akiva",
"author_id": 65724,
"author_profile": "https://Stackoverflow.com/users/65724",
"pm_score": -1,
"selected": false,
"text": "<p>on the contrary, packing and unpacking is CPU commands expensive.</p>\n\n<p>if you want to make a lot of a random pixel ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | currently I'm dealing with a video processing software in which the picture data (8bit signed and unsigned) is stored in arrays of 16-aligned integers allocated as
```
__declspec(align(16)) int *pData = (__declspec(align(16)) int *)_mm_malloc(width*height*sizeof(int),16);
```
Generally, wouldn't it enable faster reading and writing if one used signed/unsigned char arrays like this?:
```
__declspec(align(16)) int *pData = (__declspec(align(16)) unsigned char *)_mm_malloc(width*height*sizeof(unsigned char),16);
```
I know little about cache line size and data transfer optimization, but at least I know that it is an issue. Beyond that, SSE will be used in future, and in that case char-arrays - unlike int arrays - are already in a *packed* format. So which version would be faster? | If you're planning to use SSE, storing the data in its native size (8-bit) is almost certainly a better choice, since loads of operations can be done without unpacking, and even if you need to unpack for pmaddwd or other similar instructions, its still faster because you have to load less data.
Even in scalar code, loading 8-bit or 16-bit values is no slower than loading 32-bit, since movzx/movsx is no different in speed from mov. So you just save memory, which surely can't hurt. |
138,250 | <p>If I open an image with <code>open("image.jpg")</code>, how can I get the RGB values of a pixel assuming I have the coordinates of the pixel?</p>
<p>Then, how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?</p>
<p>I would prefer if I didn't have to download any additional libraries.</p>
| [
{
"answer_id": 138254,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>Image manipulation is a complex topic, and it's best if you <em>do</em> use a library. I can recommend <a href=\"http:... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] | If I open an image with `open("image.jpg")`, how can I get the RGB values of a pixel assuming I have the coordinates of the pixel?
Then, how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?
I would prefer if I didn't have to download any additional libraries. | It's probably best to use the [Python Image Library](http://www.pythonware.com/products/pil/) to do this which I'm afraid is a separate download.
The easiest way to do what you want is via the [load() method on the Image object](http://effbot.org/imagingbook/image.htm) which returns a pixel access object which you can manipulate like an array:
```
from PIL import Image
im = Image.open('dead_parrot.jpg') # Can be many different formats.
pix = im.load()
print im.size # Get the width and hight of the image for iterating over
print pix[x,y] # Get the RGBA Value of the a pixel of an image
pix[x,y] = value # Set the RGBA Value of the image (tuple)
im.save('alive_parrot.png') # Save the modified pixels as .png
```
Alternatively, look at [ImageDraw](http://effbot.org/imagingbook/imagedraw.htm) which gives a much richer API for creating images. |
138,251 | <p>I am trying to access a Windows Media Player library from ASP.NET.</p>
<p>The following code:</p>
<p>WMPLib.WindowsMediaPlayer mplayer = new WMPLib.WindowsMediaPlayer();</p>
<p>WMPLib.IWMPStringCollection list = mplayer.mediaCollection.getAttributeStringCollection("artist", "audio");</p>
<p>Returns an non-empty list when run using the VS2005 development web server but an empty list when using IIS.</p>
<p>Setting impersonation with:</p>
<p>System.Security.Principal.WindowsImpersonationContext impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();</p>
<p>Doesn't help. It seems that WMPLib still doesn't thinks its running as a user who has a library. </p>
<p>Is there a way to get around this?</p>
| [
{
"answer_id": 140939,
"author": "Dylan Beattie",
"author_id": 5017,
"author_profile": "https://Stackoverflow.com/users/5017",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried configuration via web.config in ASP.NET? When you're running in the VS2005 debugger, you're (probabl... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22590/"
] | I am trying to access a Windows Media Player library from ASP.NET.
The following code:
WMPLib.WindowsMediaPlayer mplayer = new WMPLib.WindowsMediaPlayer();
WMPLib.IWMPStringCollection list = mplayer.mediaCollection.getAttributeStringCollection("artist", "audio");
Returns an non-empty list when run using the VS2005 development web server but an empty list when using IIS.
Setting impersonation with:
System.Security.Principal.WindowsImpersonationContext impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
Doesn't help. It seems that WMPLib still doesn't thinks its running as a user who has a library.
Is there a way to get around this? | Have you tried configuration via web.config in ASP.NET? When you're running in the VS2005 debugger, you're (probably) running code as yourself, but when under IIS you'll be running it as IUSR\_*machinename* or another low-permission system account.
Try adding something like this to your web.config file:
```
<system.web>
<identity impersonate="true" userName="MYDOMAIN\myuser" password="p@ssw0rd" />
</system.web>
```
No idea whether this works with Media Player specifically, but it works for other identity/security related problems like this. |
138,261 | <p>I am having a table Table1 with columns id1, id2, id3 all the columns are nullable</p>
<p>I may enter null or value to all columns in rows.</p>
<p>My question is I need to select the rows whose all the column values should not be null.</p>
<p>Thanks</p>
<hr>
<p>There are totally around 300 columns in the table. I can't do the <code>is null</code> property for all the columns in <code>where</code> condition.</p>
| [
{
"answer_id": 138274,
"author": "Georgi",
"author_id": 13209,
"author_profile": "https://Stackoverflow.com/users/13209",
"pm_score": 2,
"selected": false,
"text": "<p>The answer to use a \"function\" to test the null-values is correct. The syntax depends on the database. If ISNULL() doe... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] | I am having a table Table1 with columns id1, id2, id3 all the columns are nullable
I may enter null or value to all columns in rows.
My question is I need to select the rows whose all the column values should not be null.
Thanks
---
There are totally around 300 columns in the table. I can't do the `is null` property for all the columns in `where` condition. | You need to do this:
```
SELECT *
FROM yourtable
WHERE
column1 IS NOT NULL
AND column2 IS NOT NULL
AND column3 IS NOT NULL
AND ....
``` |
138,302 | <p>When using SQLBulkCopy on a table with a GUID primary key and default newsequentialid()</p>
<p>e.g</p>
<pre><code>CREATE TABLE [dbo].[MyTable](
[MyPrimaryKey] [uniqueidentifier] NOT NULL CONSTRAINT [MyConstraint] DEFAULT (newsequentialid()),
[Status] [int] NULL,
[Priority] [int] NULL,
CONSTRAINT [PK_MyTable] PRIMARY KEY NONCLUSTERED
(
[MyPrimaryKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
</code></pre>
<p>wIth the C# code</p>
<pre><code> tran = connection.BeginTransaction();
SqlBulkCopy sqlCopy = new SqlBulkCopy(connection,SqlBulkCopyOptions.Default, tran);
sqlCopy.DestinationTableName = "MyTable";
sqlCopy.WriteToServer(dataTable);
</code></pre>
<p>Gives you an error...</p>
<p>Column 'MyPrimaryKey' does not allow DBNull.Value</p>
<p>I've tried fiddling the the SqlBulkCopyOptions. The only thing that works is setting the MyPrimaryKey field to allow nulls and removing the primary key.</p>
<p>Anyone know if there is a workaround for this issue?
Or can you verify that there is no workaround (other than changing the table structure)?</p>
| [
{
"answer_id": 139804,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 0,
"selected": false,
"text": "<p>You're only options are to remove the MyPrimaryKey field from the data that is being loaded or to modify the table structur... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | When using SQLBulkCopy on a table with a GUID primary key and default newsequentialid()
e.g
```
CREATE TABLE [dbo].[MyTable](
[MyPrimaryKey] [uniqueidentifier] NOT NULL CONSTRAINT [MyConstraint] DEFAULT (newsequentialid()),
[Status] [int] NULL,
[Priority] [int] NULL,
CONSTRAINT [PK_MyTable] PRIMARY KEY NONCLUSTERED
(
[MyPrimaryKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
```
wIth the C# code
```
tran = connection.BeginTransaction();
SqlBulkCopy sqlCopy = new SqlBulkCopy(connection,SqlBulkCopyOptions.Default, tran);
sqlCopy.DestinationTableName = "MyTable";
sqlCopy.WriteToServer(dataTable);
```
Gives you an error...
Column 'MyPrimaryKey' does not allow DBNull.Value
I've tried fiddling the the SqlBulkCopyOptions. The only thing that works is setting the MyPrimaryKey field to allow nulls and removing the primary key.
Anyone know if there is a workaround for this issue?
Or can you verify that there is no workaround (other than changing the table structure)? | You need to set up the column mappings. First call
```
sqlCopy.ColumnMappings.Clear();
```
Then call
```
sqlBulkCopy.ColumnMappings.Add("Status", "Status");
sqlBulkCopy.ColumnMappings.Add("Priority", "Priority");
```
This means the bulk copy will stop trying to insert into MyPrimaryKey column and will only insert into the status and Priority columns. |
138,309 | <p>I have made a SVG image, or more like mini application, for viewing graphs of data. I want to include this in a HTML page, and call methods on the SVG image.</p>
<p>Example:</p>
<pre><code><object id="img" data="image.svg" width="500" height="300"/>
<script>document.getElementById("img").addData([1,23,4]);</script>
</code></pre>
<p>Is it at all possible to call methods on the SVG document? If so, how do I declare the methods to expose in the SVG file, and how do I call them from the HTML document?</p>
| [
{
"answer_id": 138358,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 5,
"selected": true,
"text": "<p>Solution:</p>\n\n<p>in svg:</p>\n\n<pre><code><script>document.method = function() {}</script>\n</code></pre>\n... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355/"
] | I have made a SVG image, or more like mini application, for viewing graphs of data. I want to include this in a HTML page, and call methods on the SVG image.
Example:
```
<object id="img" data="image.svg" width="500" height="300"/>
<script>document.getElementById("img").addData([1,23,4]);</script>
```
Is it at all possible to call methods on the SVG document? If so, how do I declare the methods to expose in the SVG file, and how do I call them from the HTML document? | Solution:
in svg:
```
<script>document.method = function() {}</script>
```
in html (using prototype to add event listeners):
```
<script>$("img").observe("load", function() {$("img").contentDocument.method()});
```
You need to listen to the load event on the image. Once the image is loaded, you can use the `element.contentDocument` to access the document variable on the svg document. Any methods added to that, will be available. |
138,311 | <p>The CSRF prevention built in to Rails is causing some problems for some automated load testing we are doing, and I want to turn it off for the duration of the process. How do I do this?</p>
| [
{
"answer_id": 138372,
"author": "Patrick McKenzie",
"author_id": 15046,
"author_profile": "https://Stackoverflow.com/users/15046",
"pm_score": 6,
"selected": true,
"text": "<p>I love simple questions with clear answers.</p>\n\n<pre><code>#I go in application.rb\nself.allow_forgery_prote... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7473/"
] | The CSRF prevention built in to Rails is causing some problems for some automated load testing we are doing, and I want to turn it off for the duration of the process. How do I do this? | I love simple questions with clear answers.
```
#I go in application.rb
self.allow_forgery_protection = false
```
If you want to do this for testing only you can move that into one of the environment files (obviously, you'll be touching `Application` then rather than `self`). You could also write something like:
```
#I still go in application.rb
self.allow_forgery_protection = false unless ENV["RAILS_ENV"] == "production"
```
See [here](http://ryandaigle.com/articles/2007/9/24/what-s-new-in-edge-rails-better-cross-site-request-forging-prevention) for details. (Continuing Rails' wonderful tradition of having documentation of core features in 2 year old blog posts, which were distilled from commit logs.) |
138,313 | <p>I would like to create a page where all images which reside on my website are listed with title and alternative representation.</p>
<p>I already wrote me a little program to find and load all HTML files, but now I am stuck at how to extract <code>src</code>, <code>title</code> and <code>alt</code> from this HTML:</p>
<pre><code><img <b>src</b>="/image/fluffybunny.jpg" <b>title</b>="Harvey the bunny" <b>alt</b>="a cute little fluffy bunny" /></code></pre>
<p>I guess this should be done with some regex, but since the order of the tags may vary, and I need all of them, I don't really know how to parse this in an elegant way (I could do it the hard char by char way, but that's painful).</p>
| [
{
"answer_id": 138614,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 6,
"selected": false,
"text": "<p>Just to give a small example of using PHP's XML functionality for the task:</p>\n\n<pre><code>$doc=new DOMDocumen... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7021/"
] | I would like to create a page where all images which reside on my website are listed with title and alternative representation.
I already wrote me a little program to find and load all HTML files, but now I am stuck at how to extract `src`, `title` and `alt` from this HTML:
```
<img **src**="/image/fluffybunny.jpg" **title**="Harvey the bunny" **alt**="a cute little fluffy bunny" />
```
I guess this should be done with some regex, but since the order of the tags may vary, and I need all of them, I don't really know how to parse this in an elegant way (I could do it the hard char by char way, but that's painful). | EDIT : now that I know better
-----------------------------
Using regexp to solve this kind of problem is [a bad idea](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) and will likely lead in unmaintainable and unreliable code. Better use an [HTML parser](http://simplehtmldom.sourceforge.net/).
Solution With regexp
--------------------
In that case it's better to split the process into two parts :
* get all the img tag
* extract their metadata
I will assume your doc is not xHTML strict so you can't use an XML parser. E.G. with this web page source code :
```
/* preg_match_all match the regexp in all the $html string and output everything as
an array in $result. "i" option is used to make it case insensitive */
preg_match_all('/<img[^>]+>/i',$html, $result);
print_r($result);
Array
(
[0] => Array
(
[0] => <img src="/Content/Img/stackoverflow-logo-250.png" width="250" height="70" alt="logo link to homepage" />
[1] => <img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />
[2] => <img class="vote-down" src="/content/img/vote-arrow-down.png" alt="vote down" title="This was not helpful (click again to undo)" />
[3] => <img src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" height=32 width=32 alt="gravatar image" />
[4] => <img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />
[...]
)
)
```
Then we get all the img tag attributes with a loop :
```
$img = array();
foreach( $result as $img_tag)
{
preg_match_all('/(alt|title|src)=("[^"]*")/i',$img_tag, $img[$img_tag]);
}
print_r($img);
Array
(
[<img src="/Content/Img/stackoverflow-logo-250.png" width="250" height="70" alt="logo link to homepage" />] => Array
(
[0] => Array
(
[0] => src="/Content/Img/stackoverflow-logo-250.png"
[1] => alt="logo link to homepage"
)
[1] => Array
(
[0] => src
[1] => alt
)
[2] => Array
(
[0] => "/Content/Img/stackoverflow-logo-250.png"
[1] => "logo link to homepage"
)
)
[<img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />] => Array
(
[0] => Array
(
[0] => src="/content/img/vote-arrow-up.png"
[1] => alt="vote up"
[2] => title="This was helpful (click again to undo)"
)
[1] => Array
(
[0] => src
[1] => alt
[2] => title
)
[2] => Array
(
[0] => "/content/img/vote-arrow-up.png"
[1] => "vote up"
[2] => "This was helpful (click again to undo)"
)
)
[<img class="vote-down" src="/content/img/vote-arrow-down.png" alt="vote down" title="This was not helpful (click again to undo)" />] => Array
(
[0] => Array
(
[0] => src="/content/img/vote-arrow-down.png"
[1] => alt="vote down"
[2] => title="This was not helpful (click again to undo)"
)
[1] => Array
(
[0] => src
[1] => alt
[2] => title
)
[2] => Array
(
[0] => "/content/img/vote-arrow-down.png"
[1] => "vote down"
[2] => "This was not helpful (click again to undo)"
)
)
[<img src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" height=32 width=32 alt="gravatar image" />] => Array
(
[0] => Array
(
[0] => src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG"
[1] => alt="gravatar image"
)
[1] => Array
(
[0] => src
[1] => alt
)
[2] => Array
(
[0] => "http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG"
[1] => "gravatar image"
)
)
[..]
)
)
```
Regexps are CPU intensive so you may want to cache this page. If you have no cache system, you can tweak your own by using [ob\_start](http://fr2.php.net/manual/fr/function.ob-start.php) and loading / saving from a text file.
How does this stuff work ?
--------------------------
First, we use [preg\_ match\_ all](http://fr2.php.net/manual/fr/function.preg-match-all.php), a function that gets every string matching the pattern and ouput it in it's third parameter.
The regexps :
```
<img[^>]+>
```
We apply it on all html web pages. It can be read as *every string that starts with "`<img`", contains non ">" char and ends with a >*.
```
(alt|title|src)=("[^"]*")
```
We apply it successively on each img tag. It can be read as *every string starting with "alt", "title" or "src", then a "=", then a ' " ', a bunch of stuff that are not ' " ' and ends with a ' " '. Isolate the sub-strings between ()*.
Finally, every time you want to deal with regexps, it handy to have good tools to quickly test them. Check this [online regexp tester](http://regex.larsolavtorvik.com/).
EDIT : answer to the first comment.
It's true that I did not think about the (hopefully few) people using single quotes.
Well, if you use only ', just replace all the " by '.
If you mix both. First you should slap yourself :-), then try to use ("|') instead or " and [^ø] to replace [^"]. |
138,318 | <p>here is my directory structure.</p>
<p>/user/a
/user/b
/user/b</p>
<p>inside folder a,b,c there is a file person.java (it is the Same file, just a one line modification.</p>
<p>now, on my shell, im on my /user/ directory and i try to do </p>
<pre><code> javac */person.java
</code></pre>
<p>the shell returns the following error,</p>
<p>person.java:14: duplicate class: person</p>
<p>Is there anything to resolve this?</p>
| [
{
"answer_id": 138329,
"author": "Horst Gutmann",
"author_id": 22312,
"author_profile": "https://Stackoverflow.com/users/22312",
"pm_score": 4,
"selected": true,
"text": "<p>I think the problem here might be, that javac tries to compile everything in one go, which naturally results in du... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17085/"
] | here is my directory structure.
/user/a
/user/b
/user/b
inside folder a,b,c there is a file person.java (it is the Same file, just a one line modification.
now, on my shell, im on my /user/ directory and i try to do
```
javac */person.java
```
the shell returns the following error,
person.java:14: duplicate class: person
Is there anything to resolve this? | I think the problem here might be, that javac tries to compile everything in one go, which naturally results in duplicated class definitions.
A simple way to resolve this would be
`find . -name '*.java' -exec javac {} \;`
**Edit:**
Or to be more precise `find . -name 'person.java' -maxdepth 2 -exec javac {} \;` |
138,321 | <p>I unpacked a zip-file delivery into a clearcase view. Now I want to add the complete file tree to the repository. The GUI only provides an "Add to source control ..." for individual files/directories. Do you know how to recursively add the whole tree?</p>
<p>(I'm on a Windows system, but have Cygwin installed.)</p>
| [
{
"answer_id": 138325,
"author": "prakash",
"author_id": 123,
"author_profile": "https://Stackoverflow.com/users/123",
"pm_score": 2,
"selected": false,
"text": "<p>You have to use the commandline. The Context menu in Explorer doesnt do this recursively!</p>\n\n<pre><code>clearfsimport –... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20668/"
] | I unpacked a zip-file delivery into a clearcase view. Now I want to add the complete file tree to the repository. The GUI only provides an "Add to source control ..." for individual files/directories. Do you know how to recursively add the whole tree?
(I'm on a Windows system, but have Cygwin installed.) | I would rather go with the clearfsimport script, better equipped to import multiple times the same set of files, and automatically:
* add new files,
* make new version of existing files previously imported (but modified in the source set of files re-imported)
* remove files already imported but no longer present in the source set of files.
* make a clear log of all operations made during the import process.
So if your 'zip-file delivery needs to be updated on a regularly basis, clearfsimport is the way to go, but with the following options:
```
clearfsimport -preview -rec -nset c:\sourceDir\* m:\MyView\MyVob\MyDestinationDirectory
```
Note the :
* -preview option: it will allow to check *what would happen* without actually doing anything.
* '\*' used only in Windows environment, in order to import the content of a directory
* -nset option.
From [CMWiki](http://www.cmcrossroads.com/cgi-bin/cmwiki/view/CM/ClearFsImport), about that 'nset' option:
>
> By default, clearfsimport is meant to be used by the vob owner or a privileged user, but users often overlook the -nsetevent option, with which it may be used by any user.
>
> This option drives clearfsimport not to set the time stamps of elements to this of the source file object outside the vob (which requires privileged access).
>
> There is a minor non-obvious side-effect with this: once a version will have been created with a current time stamp, even the vob owner will not be able to import on top of it a version with an older (as it would be) time stamp, without this -nsetevent option. I.e. once you use this option, normal or privileged user, you are more or less bound to use it in the continuation.
>
>
> |
138,353 | <p>In wxPython, if I create a list of radio buttons and place the list initially, is it possible to change the contents in that list later?</p>
<p>For example, I have a panel that uses a boxSizer to place the widgets initially. One of those widgets is a list of radio buttons (I have also tried a normal radiobox). I would like to dynamically change the list based on variables from another class.</p>
<p>However, once the list is placed in the sizer, it's effectively "locked"; I can't just modify the list and have the changes appear. If I try re-adding the list to the sizer, it just gets put in the top left corner of the panel.</p>
<p>I'm sure I could hide the original list and manually place the new list in the same position but that feels like a kludge. I'm sure I'm making this harder than it is. I'm probably using the wrong widgets for this, much less the wrong approach, but I'm building this as a learning experience.</p>
<pre><code> class Job(wiz.WizardPageSimple):
"""Character's job class."""
def __init__(self, parent, title, attribs):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
self.charAttribs = attribs
#---Create widgets
self.Job_list = ["Aircraft Mechanic", "Vehicle Mechanic", "Electronics Specialist"]
box1_title = wx.StaticBox( self, -1, "" )
box1 = wx.StaticBoxSizer( box1_title, wx.VERTICAL )
grid1 = wx.BoxSizer(wx.VERTICAL)
for item in self.Job_list:
radio = wx.RadioButton(self, -1, item)
grid1.Add(radio)
##Debugging
self.btn = wx.Button(self, -1, "click")
self.Bind(wx.EVT_BUTTON, self.eligibleJob, self.btn)
#---Place widgets
self.sizer.Add(self.Job_intro)
self.sizer.Add(self.btn)
box1.Add(grid1)
self.sizer.Add(box1)
def eligibleJob(self, event):
"""Determine which Jobs a character is eligible for."""
if self.charAttribs.intelligence >= 12:
skillList = ["Analyst", "Interrogator", "Fire Specialist", "Aircraft Pilot"]
for skill in skillList:
self.Job_list.append(skill)
print self.Job_list ##Debugging
#return self.Job_list
</code></pre>
| [
{
"answer_id": 138479,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 0,
"selected": false,
"text": "<p>Two possible solutions</p>\n\n<ol>\n<li>Rebuild the sizer with the radio widgets each time you have to make a chang... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18676/"
] | In wxPython, if I create a list of radio buttons and place the list initially, is it possible to change the contents in that list later?
For example, I have a panel that uses a boxSizer to place the widgets initially. One of those widgets is a list of radio buttons (I have also tried a normal radiobox). I would like to dynamically change the list based on variables from another class.
However, once the list is placed in the sizer, it's effectively "locked"; I can't just modify the list and have the changes appear. If I try re-adding the list to the sizer, it just gets put in the top left corner of the panel.
I'm sure I could hide the original list and manually place the new list in the same position but that feels like a kludge. I'm sure I'm making this harder than it is. I'm probably using the wrong widgets for this, much less the wrong approach, but I'm building this as a learning experience.
```
class Job(wiz.WizardPageSimple):
"""Character's job class."""
def __init__(self, parent, title, attribs):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
self.charAttribs = attribs
#---Create widgets
self.Job_list = ["Aircraft Mechanic", "Vehicle Mechanic", "Electronics Specialist"]
box1_title = wx.StaticBox( self, -1, "" )
box1 = wx.StaticBoxSizer( box1_title, wx.VERTICAL )
grid1 = wx.BoxSizer(wx.VERTICAL)
for item in self.Job_list:
radio = wx.RadioButton(self, -1, item)
grid1.Add(radio)
##Debugging
self.btn = wx.Button(self, -1, "click")
self.Bind(wx.EVT_BUTTON, self.eligibleJob, self.btn)
#---Place widgets
self.sizer.Add(self.Job_intro)
self.sizer.Add(self.btn)
box1.Add(grid1)
self.sizer.Add(box1)
def eligibleJob(self, event):
"""Determine which Jobs a character is eligible for."""
if self.charAttribs.intelligence >= 12:
skillList = ["Analyst", "Interrogator", "Fire Specialist", "Aircraft Pilot"]
for skill in skillList:
self.Job_list.append(skill)
print self.Job_list ##Debugging
#return self.Job_list
``` | To make new list elements appear in correct places, you have to re-layout the grid after adding new elements to it. For example, to add a few new items, you could call:
```
def addNewSkills(self, newSkillList):
'''newSkillList is a list of skill names you want to add'''
for skillName in newSkillList:
newRadioButton = wx.RadioButton(self, -1, skillName)
self.grid1.Add(newRadioButton) # appears in top-left corner of the panel
self.Layout() # all newly added radio buttons appear where they should be
self.Fit() # if you need to resize the panel to fit new items, this will help
```
where `self.grid1` is the sizer you keep all your radio buttons on. |
138,355 | <p>I have a third party .NET Assembly and a large Java application. I need to call mothods provided by the .NET class library from the Java application. The assembly is not COM-enabled.
I have searched the net and so far i have the following:</p>
<p>C# code (cslib.cs):</p>
<pre><code>using System;
namespace CSLib
{
public class CSClass
{
public static void SayHi()
{
System.Console.WriteLine("Hi");
}
}
}
</code></pre>
<p>compiled with (using .net 3.5, but the same happens when 2.0 is used):</p>
<pre><code>csc /target:library cslib.cs
</code></pre>
<p>C++ code (clib.cpp):</p>
<pre><code>#include <jni.h>
#using <CSLib.dll>
using namespace CSLib;
extern "C" _declspec(dllexport) void Java_CallCS_callCS(JNIEnv* env, jclass cls) {
CSLib::CSClass::SayHi();
}
</code></pre>
<p>compiled with (using VC 2008 tools, but the same happens when 2003 tools are used):</p>
<pre><code>cl /clr /LD clib.cpp
mt -manifest clib.dll.manifest -outputresource:clib.dll;2
</code></pre>
<p>Java code (CallCS.java):</p>
<pre><code>class CallCS {
static {
System.loadLibrary("clib");
}
private static native void callCS();
public static void main(String[] args) {
callCS();
}
}
</code></pre>
<p>When I try to run the java class, the Java VM crashes while invoking the method (it is able to load the library):</p>
<pre>
#
# An unexpected error has been detected by Java Runtime Environment:
#
# Internal Error (0xe0434f4d), pid=3144, tid=3484
#
# Java VM: Java HotSpot(TM) Client VM (10.0-b19 mixed mode, sharing windows-x86)
# Problematic frame:
# C [kernel32.dll+0x22366]
#
...
Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j CallCS.callCS()V+0
j CallCS.main([Ljava/lang/String;)V+0
v ~StubRoutines::call_stub
</pre>
<p>However, if I create a plain cpp application that loads clib.dll and calls the exported function Java_CallCS_callCS, everything is OK.
I have tried this on both x86 and x64 environments and the result is the same. I have not tried other versions of Java, but I need the code to run on 1.5.0.</p>
<p>Moreover, if I modify clib.cpp to call only System methods everything works fine even from Java:</p>
<pre><code>#include <jni.h>
#using <mscorlib.dll>
using namespace System;
extern "C" _declspec(dllexport) void Java_CallCS_callCS(JNIEnv* env, jclass cls) {
System::Console::WriteLine("It works");
}
</code></pre>
<p>To wrap up:</p>
<ol>
<li>I am ABLE to call System methods from Java -> clib.dll -> mscorlib.dll</li>
<li>I am ABLE to call any methods from CPPApp -> clib.dll -> cslib.dll</li>
<li>I am UNABLE to call any methods from Java -> clib.dll -> cslib.dll</li>
</ol>
<p>I am aware of a workaround that uses 1. above - I can use reflection to load the assmebly and invoke desired methods using only System calls, but the code gets messy and I am hoping for a better solution. </p>
<p>I know about dotnetfromjava project, which uses the reflection method, but prefer not to add more complexity than needed. I'll use something like this if there is no other way, however.</p>
<p>I have looked at ikvm.net also, but my understanding is that it uses its own JVM (written in C#) to do the magic. However, running the entire Java application under its VM is no option for me.</p>
<p>Thanks.</p>
| [
{
"answer_id": 138359,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 2,
"selected": false,
"text": "<p>Have you looked at ikvm.NET, which allows calls between .NET and Java code?</p>\n"
},
{
"answer_id": 138763,
... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22602/"
] | I have a third party .NET Assembly and a large Java application. I need to call mothods provided by the .NET class library from the Java application. The assembly is not COM-enabled.
I have searched the net and so far i have the following:
C# code (cslib.cs):
```
using System;
namespace CSLib
{
public class CSClass
{
public static void SayHi()
{
System.Console.WriteLine("Hi");
}
}
}
```
compiled with (using .net 3.5, but the same happens when 2.0 is used):
```
csc /target:library cslib.cs
```
C++ code (clib.cpp):
```
#include <jni.h>
#using <CSLib.dll>
using namespace CSLib;
extern "C" _declspec(dllexport) void Java_CallCS_callCS(JNIEnv* env, jclass cls) {
CSLib::CSClass::SayHi();
}
```
compiled with (using VC 2008 tools, but the same happens when 2003 tools are used):
```
cl /clr /LD clib.cpp
mt -manifest clib.dll.manifest -outputresource:clib.dll;2
```
Java code (CallCS.java):
```
class CallCS {
static {
System.loadLibrary("clib");
}
private static native void callCS();
public static void main(String[] args) {
callCS();
}
}
```
When I try to run the java class, the Java VM crashes while invoking the method (it is able to load the library):
```
#
# An unexpected error has been detected by Java Runtime Environment:
#
# Internal Error (0xe0434f4d), pid=3144, tid=3484
#
# Java VM: Java HotSpot(TM) Client VM (10.0-b19 mixed mode, sharing windows-x86)
# Problematic frame:
# C [kernel32.dll+0x22366]
#
...
Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j CallCS.callCS()V+0
j CallCS.main([Ljava/lang/String;)V+0
v ~StubRoutines::call_stub
```
However, if I create a plain cpp application that loads clib.dll and calls the exported function Java\_CallCS\_callCS, everything is OK.
I have tried this on both x86 and x64 environments and the result is the same. I have not tried other versions of Java, but I need the code to run on 1.5.0.
Moreover, if I modify clib.cpp to call only System methods everything works fine even from Java:
```
#include <jni.h>
#using <mscorlib.dll>
using namespace System;
extern "C" _declspec(dllexport) void Java_CallCS_callCS(JNIEnv* env, jclass cls) {
System::Console::WriteLine("It works");
}
```
To wrap up:
1. I am ABLE to call System methods from Java -> clib.dll -> mscorlib.dll
2. I am ABLE to call any methods from CPPApp -> clib.dll -> cslib.dll
3. I am UNABLE to call any methods from Java -> clib.dll -> cslib.dll
I am aware of a workaround that uses 1. above - I can use reflection to load the assmebly and invoke desired methods using only System calls, but the code gets messy and I am hoping for a better solution.
I know about dotnetfromjava project, which uses the reflection method, but prefer not to add more complexity than needed. I'll use something like this if there is no other way, however.
I have looked at ikvm.net also, but my understanding is that it uses its own JVM (written in C#) to do the magic. However, running the entire Java application under its VM is no option for me.
Thanks. | OK, the mystery is solved.
The JVM crash is caused by unhandled System.IO.FileNotFoundException. The exception is thrown because the .NET assembly is searched in the folder where the calling exe file resides.
1. The mscorlib.dll is in the Global Assembly Cache, so it works.
2. The CPP application exe is in the same folder as the assembly, so it works also.
3. The cslib.dll assembly is NEITHER in the folder of java.exe, NOR in the GAC, so it doesn't work.
It seems my only option is to install the .NET assembly in GAC (the third-party dll does have a strong name). |
138,371 | <p>What are (if any)the implied assumptions or restrictions and the differences of designing like:</p>
<p>A) this:</p>
<pre><code>class SampleClass1
{
IWorker workerA;
IWorker workerB;
void setWorkerA(IWorker w);
void setWorkerB(IWorker w);
WorkResult doWork();
}
</code></pre>
<p>B) versus this:</p>
<pre><code>class SampleClass2
{
WorkResult doWork(IWorker workerA, IWorker workerB);
}
</code></pre>
<p>I know it depends on the specific project but what if the above class is a part of a small framework? The first Class is able to maintain state and separate the steps more naturaly but Second class ensures "real time communication" with the external caller more naturaly since Worker are passed each time doWork() is called.</p>
<p>Are there any recommended usages or generic practices that guide the choice between the two above ways? Thanks.</p>
| [
{
"answer_id": 138376,
"author": "Richard Walton",
"author_id": 15075,
"author_profile": "https://Stackoverflow.com/users/15075",
"pm_score": 0,
"selected": false,
"text": "<p>Another Option:</p>\n\n<p>IWorker class:</p>\n\n<p>static WorkResult doWork(Iworker a, Iworker b);</p>\n"
},
... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11906/"
] | What are (if any)the implied assumptions or restrictions and the differences of designing like:
A) this:
```
class SampleClass1
{
IWorker workerA;
IWorker workerB;
void setWorkerA(IWorker w);
void setWorkerB(IWorker w);
WorkResult doWork();
}
```
B) versus this:
```
class SampleClass2
{
WorkResult doWork(IWorker workerA, IWorker workerB);
}
```
I know it depends on the specific project but what if the above class is a part of a small framework? The first Class is able to maintain state and separate the steps more naturaly but Second class ensures "real time communication" with the external caller more naturaly since Worker are passed each time doWork() is called.
Are there any recommended usages or generic practices that guide the choice between the two above ways? Thanks. | In option (A) you are creating what is known as a Function Object or Functor, this is a design pattern that is [well documented](http://en.wikipedia.org/wiki/Function_object).
The two main advantages are:
* The workers can be set by in one place and then the object used elsewhere
* The object can retain state between calls
Also if you are using a dependency injection framework (Spring, Guice etc...) the functor can be automatically initialized and injected wherever required.
Function objects are extensively used in libraries e.g. the C++ Standard Template Library |
138,374 | <p>I'm attempting to do an AJAX call (via JQuery) that will initiate a fairly long process. I'd like the script to simply send a response indicating that the process has started, but JQuery won't return the response until the PHP script is done running.</p>
<p>I've tried this with a "close" header (below), and also with output buffering; neither seems to work. Any guesses? or is this something I need to do in JQuery?</p>
<pre><code><?php
echo( "We'll email you as soon as this is done." );
header( "Connection: Close" );
// do some stuff that will take a while
mail( 'dude@thatplace.com', "okay I'm done", 'Yup, all done.' );
?>
</code></pre>
| [
{
"answer_id": 138409,
"author": "paan",
"author_id": 2976,
"author_profile": "https://Stackoverflow.com/users/2976",
"pm_score": 1,
"selected": false,
"text": "<p>You could try to do multithreading.</p>\n\n<p>you could whip up a script that makes a system call ( using <a href=\"http://m... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/82944/"
] | I'm attempting to do an AJAX call (via JQuery) that will initiate a fairly long process. I'd like the script to simply send a response indicating that the process has started, but JQuery won't return the response until the PHP script is done running.
I've tried this with a "close" header (below), and also with output buffering; neither seems to work. Any guesses? or is this something I need to do in JQuery?
```
<?php
echo( "We'll email you as soon as this is done." );
header( "Connection: Close" );
// do some stuff that will take a while
mail( 'dude@thatplace.com', "okay I'm done", 'Yup, all done.' );
?>
``` | The following PHP manual page (incl. user-notes) suggests multiple instructions on how to close the TCP connection to the browser without ending the PHP script:
* [Connection handling *Docs*](http://php.net/features.connection-handling)
Supposedly it requires a bit more than sending a close header.
---
OP then confirms: *yup, this did the trick:* [pointing to user-note #71172 (Nov 2006)](http://php.net/manual/en/features.connection-handling.php#71172) copied here:
>
> Closing the users browser connection whilst keeping your php script running has been an issue since [PHP] 4.1, when the behaviour of `register_shutdown_function()` was modified so that it would not automatically close the users connection.
>
>
> sts at mail dot xubion dot hu Posted the original solution:
>
>
>
> ```
> <?php
> header("Connection: close");
> ob_start();
> phpinfo();
> $size = ob_get_length();
> header("Content-Length: $size");
> ob_end_flush();
> flush();
> sleep(13);
> error_log("do something in the background");
> ?>
>
> ```
>
> Which works fine until you substitute `phpinfo()` for `echo('text I want user to see');` in which case the headers are never sent!
>
>
> The solution is to explicitly turn off output buffering and clear the buffer prior to sending your header information. Example:
>
>
>
> ```
> <?php
> ob_end_clean();
> header("Connection: close");
> ignore_user_abort(true); // just to be safe
> ob_start();
> echo('Text the user will see');
> $size = ob_get_length();
> header("Content-Length: $size");
> ob_end_flush(); // Strange behaviour, will not work
> flush(); // Unless both are called !
> // Do processing here
> sleep(30);
> echo('Text user will never see');
> ?>
>
> ```
>
> Just spent 3 hours trying to figure this one out, hope it helps someone :)
>
>
> Tested in:
>
>
> * IE 7.5730.11
> * Mozilla Firefox 1.81
>
>
>
---
Later on in July 2010 in a [related answer](https://stackoverflow.com/a/3270882/367456) [*Arctic Fire*](https://stackoverflow.com/users/347655/arctic-fire) then linked two further user-notes that were-follow-ups to the one above:
* [Connection Handling user-note #89177 (Feb 2009)](http://www.php.net/manual/en/features.connection-handling.php#89177)
* [Connection Handling user-note #93441 (Sep 2009)](http://www.php.net/manual/en/features.connection-handling.php#93441) |
138,379 | <p>What happens if I use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb762181%28v=vs.85%29.aspx" rel="nofollow noreferrer">SHGetFolderPath</a> api call in a 32 bit system with CSIDL_PROGRAM_FILESx86 folder id instead of the CSIDL_PROGRAM_FILES id?</p>
<p>Theoretically CSIDL_PROGRAM_FILESx86 should map to <code>C:\program files (x86)</code> in a 64 bit system but what does it map to in a 32 bit system where this path doesn't exist?</p>
| [
{
"answer_id": 138473,
"author": "Magnus Johansson",
"author_id": 3584,
"author_profile": "https://Stackoverflow.com/users/3584",
"pm_score": 4,
"selected": true,
"text": "<p>The different scenarios are described in <a href=\"http://msdn.microsoft.com/en-us/library/bb762584(VS.85).aspx\"... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14587/"
] | What happens if I use [SHGetFolderPath](http://msdn.microsoft.com/en-us/library/windows/desktop/bb762181%28v=vs.85%29.aspx) api call in a 32 bit system with CSIDL\_PROGRAM\_FILESx86 folder id instead of the CSIDL\_PROGRAM\_FILES id?
Theoretically CSIDL\_PROGRAM\_FILESx86 should map to `C:\program files (x86)` in a 64 bit system but what does it map to in a 32 bit system where this path doesn't exist? | The different scenarios are described in [this article on MSDN](http://msdn.microsoft.com/en-us/library/bb762584(VS.85).aspx).
Scroll down to remarks, "FOLDERID\_ProgramFiles"
```
The interpretation of certain KNOWNFOLDERID values depends on whether the folder is part of a 32-bit or 64-bit application and whether that application is running on a 32-bit or 64-bit operating system. If your application needs to distinguish between, for example, Program Files and Program Files (x86), you must use the right KNOWNFOLDERID for the situation.
The following tables summarize the KNOWNFOLDERID use in those cases.
FOLDERID_ProgramFiles
OS Application KNOWNFOLDERID Default Path CSIDL Equivalent
32 bit 32 bit FOLDERID_ProgramFiles %SystemDrive%\Program Files CSIDL_PROGRAM_FILES
32 bit 32 bit FOLDERID_ProgramFilesX86 %SystemDrive%\Program Files CSIDL_PROGRAM_FILESX86
32 bit 32 bit FOLDERID_ProgramFilesX64 (undefined) Not applicable Not applicable
64 bit 64 bit FOLDERID_ProgramFiles %SystemDrive%\Program Files CSIDL_PROGRAM_FILES
64 bit 64 bit FOLDERID_ProgramFilesX86 %SystemDrive%\Program Files (x86) CSIDL_PROGRAM_FILESX86
64 bit 64 bit FOLDERID_ProgramFilesX64 %SystemDrive%\Program Files None
64 bit 32 bit FOLDERID_ProgramFiles %SystemDrive%\Program Files (x86) CSIDL_PROGRAM_FILES
64 bit 32 bit FOLDERID_ProgramFilesX86 %SystemDrive%\Program Files (x86) CSIDL_PROGRAM_FILESX86
64 bit 32 bit FOLDERID_ProgramFilesX64 %SystemDrive%\Program Files None
```
Summary: It will point to %SystemDrive%\Program Files |
138,383 | <p>Sometimes coloring a logfile or other gives a good overview when looking for <em>stuff</em> and <em>behaviors</em></p>
<p>I just saw that grep have a coloring feature</p>
<pre><code>grep -C 99999 --color <regexp> <filename>
</code></pre>
<p>What other methods are there?</p>
| [
{
"answer_id": 138390,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": true,
"text": "<p>For searching source code, I use <a href=\"http://petdance.com/ack/\" rel=\"noreferrer\">ack</a>. It's got a lot of opt... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/842/"
] | Sometimes coloring a logfile or other gives a good overview when looking for *stuff* and *behaviors*
I just saw that grep have a coloring feature
```
grep -C 99999 --color <regexp> <filename>
```
What other methods are there? | For searching source code, I use [ack](http://petdance.com/ack/). It's got a lot of options that make sense for searching code (such as automatically ignoring SCM directories). |
138,412 | <p>I can't get my GridView to enable a user to sort a column of data when I'm using a custom SqlDataSource.</p>
<p>I have a GridView in which the code in the ASP reference to it in the HTML is minimal:</p>
<pre><code><asp:GridView id="grid" runat="server" AutoGenerateColumns="False" AllowSorting="True">
</asp:GridView>
</code></pre>
<p>In the code-behind I attach a dynamically-created SqlDataSource (the columns it contains are not always the same so the SQL used to create it is constructed at runtime). For example:</p>
<p>I set up the columns...</p>
<pre><code>BoundField column = new BoundField();
column.DataField = columnName;
column.HeaderText = "Heading";
column.SortExpression = columnName;
grid.Columns.Add(column);
</code></pre>
<p>the data source...</p>
<pre><code>SqlDataSource dataSource = new SqlDataSource(
"System.Data.SqlClient",
connectionString,
generatedSelectCommand);
</code></pre>
<p>then the gridview...</p>
<pre><code>grid.DataSource = dataSource;
grid.DataKeyNames = mylistOfKeys;
grid.DataBind();
</code></pre>
<p>At the moment nothing happens when a user clicks on a column heading when I'd expect it to sort the column data. Anyone any ideas what I'm missing?</p>
<p>If there's a nicer way of doing this that would be helpful too as this looks messy to me!</p>
| [
{
"answer_id": 138467,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure about this one, but if you use a standard SqlDataSource and you click on a field to sort according to that field,... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22185/"
] | I can't get my GridView to enable a user to sort a column of data when I'm using a custom SqlDataSource.
I have a GridView in which the code in the ASP reference to it in the HTML is minimal:
```
<asp:GridView id="grid" runat="server" AutoGenerateColumns="False" AllowSorting="True">
</asp:GridView>
```
In the code-behind I attach a dynamically-created SqlDataSource (the columns it contains are not always the same so the SQL used to create it is constructed at runtime). For example:
I set up the columns...
```
BoundField column = new BoundField();
column.DataField = columnName;
column.HeaderText = "Heading";
column.SortExpression = columnName;
grid.Columns.Add(column);
```
the data source...
```
SqlDataSource dataSource = new SqlDataSource(
"System.Data.SqlClient",
connectionString,
generatedSelectCommand);
```
then the gridview...
```
grid.DataSource = dataSource;
grid.DataKeyNames = mylistOfKeys;
grid.DataBind();
```
At the moment nothing happens when a user clicks on a column heading when I'd expect it to sort the column data. Anyone any ideas what I'm missing?
If there's a nicer way of doing this that would be helpful too as this looks messy to me! | First you need to add an event:
```
<asp:GridView AllowSorting="True" OnSorting="gvName_Sorting" ...
```
Then that event looks like:
```
protected void gvName_Sorting( object sender, GridViewSortEventArgs e )
{
...
//rebind gridview
}
```
You basically have to get your data again.
You're right that it looks messy and there is a better way: ASP.Net MVC
Unfortunately that's a drastically different page model. |
138,419 | <p>While porting an application from SQL 2005 to SQL Server Compact Edition, I found that I need to port this command:</p>
<pre><code>SELECT TOP 1 Id FROM tblJob WHERE Holder_Id IS NULL
</code></pre>
<p>But SQL Server Compact Edition doesn't support the <code>TOP</code> keyword. How can I port this command?</p>
| [
{
"answer_id": 138436,
"author": "Jesper Blad Jensen",
"author_id": 11559,
"author_profile": "https://Stackoverflow.com/users/11559",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like it can't be done in compact. You have to read all the jobs, or make a SqlReader, and just read th... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15136/"
] | While porting an application from SQL 2005 to SQL Server Compact Edition, I found that I need to port this command:
```
SELECT TOP 1 Id FROM tblJob WHERE Holder_Id IS NULL
```
But SQL Server Compact Edition doesn't support the `TOP` keyword. How can I port this command? | ```
SELECT TOP(1) Id
FROM tblJob
WHERE Holder_Id IS NULL
```
Need the brackets as far as I know.
reference: <http://technet.microsoft.com/en-us/library/bb686896.aspx>
addition: likewise, only for version 3.5 onwards |
138,422 | <p>I have a HTML report, which needs to be printed landscape because of the many columns. It there a way to do this, without the user having to change the document settings?</p>
<p>And what are the options amongst browsers.</p>
| [
{
"answer_id": 138456,
"author": "yann.kmm",
"author_id": 15780,
"author_profile": "https://Stackoverflow.com/users/15780",
"pm_score": 3,
"selected": false,
"text": "<p>You can also use the non-standard IE-only css attribute <a href=\"http://www.eskimo.com/~bloo/indexdot/css/properties/... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56/"
] | I have a HTML report, which needs to be printed landscape because of the many columns. It there a way to do this, without the user having to change the document settings?
And what are the options amongst browsers. | In your CSS you can set the @page property as shown below.
```
@media print{@page {size: landscape}}
```
The @page is part of [CSS 2.1 specification](http://www.w3.org/TR/CSS21/page.html#page-box) however this `size` is not as highlighted by the answer to the question [Is @Page { size:landscape} obsolete?](https://stackoverflow.com/questions/4249532/is-page-sizelandscape-obsolete):
>
> CSS 2.1 no longer specifies the size attribute. The current working
> draft for CSS3 Paged Media module does specify it (but this is not
> standard or accepted).
>
>
>
As stated the size option comes from the [CSS 3 Draft Specification](http://www.w3.org/TR/css3-page/#page-size). In theory it can be set to both a page size and orientation although in my sample the size is omitted.
The support is very mixed with a [bug report begin filed in firefox](https://developer.mozilla.org/en/Mozilla_CSS_support_chart#section_3), most browsers do not support it.
It may seem to work in IE7 but this is because IE7 will remember the users last selection of landscape or portrait in print preview (only the browser is re-started).
[This article](https://web.archive.org/web/20090228163159/http://edacio.us:80/forum/comments.php?DiscussionID=39) does have some suggested work arounds using JavaScript or ActiveX that send keys to the users browser although it they are not ideal and rely on changing the browsers security settings.
Alternately you could rotate the content rather than the page orientation. This can be done by creating a style and applying it to the body that includes these two lines but this also has draw backs creating many alignment and layout issues.
```
<style type="text/css" media="print">
.page
{
-webkit-transform: rotate(-90deg);
-moz-transform:rotate(-90deg);
filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}
</style>
```
The final alternative I have found is to create a landscape version in a PDF. You can point to so when the user selects print it prints the PDF. However I could not get this to auto print work in IE7.
```
<link media="print" rel="Alternate" href="print.pdf">
```
In conclusion in some browsers it is relativity easy using the @page size option however in many browsers there is no sure way and it would depend on your content and environment.
This maybe why Google Documents creates a PDF when print is selected and then allows the user to open and print that. |
138,449 | <p>Here's the problem:</p>
<p>In C# I'm getting information from a legacy ACCESS database. .NET converts the content of the database (in the case of this problem a string) to Unicode before handing the content to me.</p>
<p>How do I convert this Unicode string back to it's ASCII equivalent?</p>
<p><hr>
<strong>Edit</strong><br>
Unicode char 710 is indeed MODIFIER LETTER CIRCUMFLEX ACCENT. Here's the problem a bit more precise: </p>
<pre> -> (Extended) ASCII character ê (Extended ASCII 136) was inserted in the database.
-> Either Access or the reading component in .NET converted this to U+02C6 U+0065
(MODIFIER LETTER CIRCUMFLEX ACCENT + LATIN SMALL LETTER E)
-> I need the (Extended) ASCII character 136 back.
</pre>
<p><hr>
Here's what I've tried (I see now why this did not work...):</p>
<pre><code>string myInput = Convert.ToString(Convert.ToChar(710));
byte[] asBytes = Encoding.ASCII.GetBytes(myInput);
</code></pre>
<p>But this does not result in 94 but a byte with value 63...<br>
Here's a new try but it still does not work:</p>
<pre><code>byte[] bytes = Encoding.ASCII.GetBytes("ê");
</code></pre>
<p><hr>
<strong>Soltution</strong><br>
Thanks to both <a href="https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138579">csgero</a> and <a href="https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138583">bzlm</a> for pointing in the right direction I solved the problem <a href="https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-ascii-equivalent#141816">here</a>.</p>
| [
{
"answer_id": 138462,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>Hmm … I'm not sure which character you mean. The caret (“^”, CIRCUMFLEX ACCENT) has the same code in ASCII and Uni... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1830/"
] | Here's the problem:
In C# I'm getting information from a legacy ACCESS database. .NET converts the content of the database (in the case of this problem a string) to Unicode before handing the content to me.
How do I convert this Unicode string back to it's ASCII equivalent?
---
**Edit**
Unicode char 710 is indeed MODIFIER LETTER CIRCUMFLEX ACCENT. Here's the problem a bit more precise:
```
-> (Extended) ASCII character ê (Extended ASCII 136) was inserted in the database.
-> Either Access or the reading component in .NET converted this to U+02C6 U+0065
(MODIFIER LETTER CIRCUMFLEX ACCENT + LATIN SMALL LETTER E)
-> I need the (Extended) ASCII character 136 back.
```
---
Here's what I've tried (I see now why this did not work...):
```
string myInput = Convert.ToString(Convert.ToChar(710));
byte[] asBytes = Encoding.ASCII.GetBytes(myInput);
```
But this does not result in 94 but a byte with value 63...
Here's a new try but it still does not work:
```
byte[] bytes = Encoding.ASCII.GetBytes("ê");
```
---
**Soltution**
Thanks to both [csgero](https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138579) and [bzlm](https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138583) for pointing in the right direction I solved the problem [here](https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-ascii-equivalent#141816). | Okay, let's elaborate. Both [csgero](https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138579) and [bzlm](https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138583) pointed in the right direction.
Because of blzm's reply I looked up the Windows-1252 page on wiki and found that it's called a codepage. The wikipedia article for [Code page](http://en.wikipedia.org/wiki/Codepage) which stated the following:
>
> No formal standard existed for these ‘[extended character sets](http://en.wikipedia.org/wiki/Extended_ASCII)’; IBM merely referred to the variants as code pages, as it had always done for variants of EBCDIC encodings.
>
>
>
This led me to codepage 437:
>
> n ASCII-compatible code pages, the lower 128 characters maintained their standard US-ASCII values, and different pages (or sets of characters) could be made available in the upper 128 characters. DOS computers built for the North American market, for example, used [code page 437](http://en.wikipedia.org/wiki/Code_page_437), which included accented characters needed for French, German, and a few other European languages, as well as some graphical line-drawing characters.
>
>
>
So, codepage 437 was the codepage I was calling 'extended ASCII', it had the ê as character 136 so I looked up some other chars as well and they seem right.
csgero came with the Encoding.GetEncoding() hint, I used it to create the following statement which solves my problem:
```
byte[] bytes = Encoding.GetEncoding(437).GetBytes("ê");
``` |
138,477 | <p>Is it possible to send my own developed exceptions over Soap to a client using http.sys??</p>
| [
{
"answer_id": 303158,
"author": "Zach",
"author_id": 8720,
"author_profile": "https://Stackoverflow.com/users/8720",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, you can throw your own exceptions. Any uncaught exception that does not derive from SoapException will be bottled up by... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Is it possible to send my own developed exceptions over Soap to a client using http.sys?? | To the best of my knowledge unfortunately the answer is no. You cannot build your own custom exceptions on the server side and expect to use them on the client side through WSE. I can't give much technical background as to why (as in why this is not allowed by WSE), but I am sure about my answer because I tested this out.
You can use the approach described in the provided link to return a custom exception that inherits from a System.Web.Services.Protocols.SoapException, however you must capture the exception on the client side as a SoapException since you will not be able to capture it as the custom exception type: <http://msdn.microsoft.com/en-us/library/ms229064.aspx>
To recreate the test for your own confirmation do the following:
1. Create a test exception class, call it whatever you'd like and make sure it follows the pattern described in the link I provided above (there are code samples provided).
2. Create a web method that explicitly returns the test exception like so:
```
'This is in VB.Net
<WebMethod()> _
Public Function ThrowTestSoapException() As TestSoapException
Return New TestSoapException()
End Function
```
3. Try to regenerate your client's WSE Library (using WseWsdl3.exe) and you should receive an error message like this one: "*Error: Server unavailable, please try later*"
That is as far as I could get when trying to create my own transferable Custom Exceptions. Again the only thing I was able to do was return a Custom Exception that inherited from the SoapException class, and caught it on the client side as a SoapException. That is the same method described in the link that "CheGueVerra" pointed out [above](http://msdn.microsoft.com/en-us/library/aa480592.aspx).
In response to John Saunders's comment above: Yes, if *possible* move over to WCF, WSE is indeed obsolete. Since this is work related for me and for others asking these questions, making a shift from WSE to WCF would require managerial approval - so some of us cannot make those changes easily - even if we desperately want to. |
138,493 | <p>How does one handle a <code>DateTime</code> with a <code>NOT NULL</code>?</p>
<p>I want to do something like this:</p>
<pre><code>SELECT * FROM someTable WHERE thisDateTime IS NOT NULL
</code></pre>
<p>But how?</p>
| [
{
"answer_id": 138495,
"author": "Johnno Nolan",
"author_id": 1116,
"author_profile": "https://Stackoverflow.com/users/1116",
"pm_score": 6,
"selected": true,
"text": "<p>erm it does work? I've just tested it?</p>\n\n<pre><code>/****** Object: Table [dbo].[DateTest] Script Date: 09/2... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14777/"
] | How does one handle a `DateTime` with a `NOT NULL`?
I want to do something like this:
```
SELECT * FROM someTable WHERE thisDateTime IS NOT NULL
```
But how? | erm it does work? I've just tested it?
```
/****** Object: Table [dbo].[DateTest] Script Date: 09/26/2008 10:44:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DateTest](
[Date1] [datetime] NULL,
[Date2] [datetime] NOT NULL
) ON [PRIMARY]
GO
Insert into DateTest (Date1,Date2) VALUES (NULL,'1-Jan-2008')
Insert into DateTest (Date1,Date2) VALUES ('1-Jan-2008','1-Jan-2008')
Go
SELECT * FROM DateTest WHERE Date1 is not NULL
GO
SELECT * FROM DateTest WHERE Date2 is not NULL
``` |
138,496 | <p>How would you go about producing reports by user selected date ranges in a rails app? What are the best date range pickers? </p>
<p>edit in response to patrick : I am looking for a bit of both widget and active record advice but what I am really curious about is how to restfully display a date ranged list based on user selected dates. </p>
| [
{
"answer_id": 138810,
"author": "Patrick McKenzie",
"author_id": 15046,
"author_profile": "https://Stackoverflow.com/users/15046",
"pm_score": 6,
"selected": true,
"text": "<p>Are we asking an interface question here (i.e. you want a widget) or an ActiveRecord question?</p>\n\n<h1>Date ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6805/"
] | How would you go about producing reports by user selected date ranges in a rails app? What are the best date range pickers?
edit in response to patrick : I am looking for a bit of both widget and active record advice but what I am really curious about is how to restfully display a date ranged list based on user selected dates. | Are we asking an interface question here (i.e. you want a widget) or an ActiveRecord question?
Date Picking Widgets
====================
1) **Default Rails Solution**: See `date_select` documentation [here](http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html).
2) **Use a plugin** : Why write code? I personally like the [CalendarDateSelect](http://code.google.com/p/calendardateselect/) plugin, using a pair of the suckers when I need a range.
3) **Adapt a Javascript widget to Rails**: It is almost trivial to integrate something like the Yahoo UI library (YUI) [Calendar](http://developer.yahoo.com/yui/calendar/), which is all Javascript, to Rails. From the perspective of Rails its just another way to populate the `params[:start_date]` and `params[:end_date]`. YUI Calendar has native support for ranges.
Getting the data from the Widgets
=================================
1) **Default Rails Solution** See `date_select` documentation [here](http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html).
```
#an application helper method you'll find helpful
#credit to http://blog.zerosum.org/2007/5/9/deconstructing-date_select
# Reconstruct a date object from date_select helper form params
def build_date_from_params(field_name, params)
Date.new(params["#{field_name.to_s}(1i)"].to_i,
params["#{field_name.to_s}(2i)"].to_i,
params["#{field_name.to_s}(3i)"].to_i)
end
#goes into view
<%= date_select "report", "start_date", ... %>
<%= date_select "report", "end_date", ... %>
#goes into controller -- add your own error handling/defaults, please!
report_start_date = build_date_from_params("start_date", params[:report])
report_end_date = build_date_from_params("end_date", params[:report])
```
2) **CalendarDateSelect**: Rather similar to the above, just with sexier visible UI.
3) **Adapt a Javascript widget**: Typically this means that some form element will have the date input as a string. Great news for you, since Date.parse is some serious magic. The params[:some\_form\_element\_name] will be initialized by Rails for you.
```
#goes in controller. Please handle errors yourself -- Javascript != trusted input.
report_start_date = Date.parse(params[:report_start_date])
```
Writing the call to ActiveRecord
================================
Easy as pie.
```
#initialize start_date and end_date up here, by pulling from params probably
@models = SomeModel.find(:all, :conditions => ['date >= ? and date <= ?',
start_date, end_date])
#do something with models
``` |
138,497 | <p>How can I iterate over each file in a directory using a <code>for</code> loop?</p>
<p>And how could I tell if a certain entry is a directory or if it's just a file?</p>
| [
{
"answer_id": 138513,
"author": "Axeman",
"author_id": 22108,
"author_profile": "https://Stackoverflow.com/users/22108",
"pm_score": 3,
"selected": false,
"text": "<pre><code>for %1 in (*.*) do echo %1\n</code></pre>\n\n<p>Try \"HELP FOR\" in cmd for a full guide</p>\n\n<p>This is the g... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11234/"
] | How can I iterate over each file in a directory using a `for` loop?
And how could I tell if a certain entry is a directory or if it's just a file? | This lists all the files (and only the files) in the current directory and its subdirectories recursively:
```
for /r %i in (*) do echo %i
```
Also if you run that command in a batch file you need to double the % signs.
```
for /r %%i in (*) do echo %%i
```
(thanks @agnul) |
138,501 | <p>I have mixed data i nvarchar column (words and numbers).
Which is fastest way to sort data in this column in Numeric Order.</p>
<p>Result example:</p>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>...</li>
<li>10</li>
<li>11</li>
<li>...</li>
<li>aaaa</li>
<li>aaab</li>
<li>b</li>
<li>ba</li>
<li>ba</li>
<li>...</li>
</ul>
| [
{
"answer_id": 138507,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": -1,
"selected": false,
"text": "<p>Cast it. </p>\n\n<pre><code>SELECT * FROM foo ORDER BY CAST(somecolumn AS int);\n</code></pre>\n\n<p>Been a while since I'... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17465/"
] | I have mixed data i nvarchar column (words and numbers).
Which is fastest way to sort data in this column in Numeric Order.
Result example:
* 1
* 2
* 3
* ...
* 10
* 11
* ...
* aaaa
* aaab
* b
* ba
* ba
* ... | Use this:
```
ORDER BY
CASE WHEN ISNUMERIC(column) = 1 THEN 0 ELSE 1 END,
CASE WHEN ISNUMERIC(column) = 1 THEN CAST(column AS INT) ELSE 0 END,
column
```
This works as expected.
---
**Note**: You say *fastest way*. This sql was fast for me to produce, but the execution plan shows a table-scan, followed by a scalar computation. This could possibly produce a temporary result containing all the values of that column with some extra temporary columns for the ISNUMERIC results. It might not be fast to execute. |
138,508 | <p>My understanding of the MVC is as follows (incase it's horribly wrong, I am afterall new to it)</p>
<ol>
<li>Models are the things that interface with the database</li>
<li>Views are the design/layout of the page</li>
<li>Controllers are where everything starts and are essentially the page logic</li>
</ol>
<p>I'm using <a href="http://codeigniter.com/" rel="noreferrer">CodeIgniter</a> but I would hazard a guess it's not just limited to that or possibly even just to PHP frameworks.</p>
<p>Where do I put global classes?</p>
<p>I may have a model for Products and I then run a query that collects 20 products from the database. Do I now make 20 models or should I have a separate class for it, if the latter, where do I put this class (other controllers will need to use it too)</p>
| [
{
"answer_id": 138527,
"author": "Alexander Morland",
"author_id": 4013,
"author_profile": "https://Stackoverflow.com/users/4013",
"pm_score": 1,
"selected": false,
"text": "<p>In <a href=\"http://cakephp.org\" rel=\"nofollow noreferrer\">CakePHP</a> there are 3 more \"parts\" : </p>\n\n... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | My understanding of the MVC is as follows (incase it's horribly wrong, I am afterall new to it)
1. Models are the things that interface with the database
2. Views are the design/layout of the page
3. Controllers are where everything starts and are essentially the page logic
I'm using [CodeIgniter](http://codeigniter.com/) but I would hazard a guess it's not just limited to that or possibly even just to PHP frameworks.
Where do I put global classes?
I may have a model for Products and I then run a query that collects 20 products from the database. Do I now make 20 models or should I have a separate class for it, if the latter, where do I put this class (other controllers will need to use it too) | Model is the wrong word to use when discussing what to do with products: each product is a **value object (VO)** (or data transfer objet/DTO, whatever fits in your mouth better). Value objects generally have the same fields that a table contains. In your case ProductVO should have the fields that are in Products table.
Model is a **Data Access Object (DAO)** that has methods like
```
findByPk --> returns a single value object
findAll --> returns a collection of value objects (0-n)
etc.
```
In your case you would have a ProductDAO that has something like the above methods. This ProductDAO would then return ProductVO's and collections of them.
Data Access Objects can also return **Business Objects (BO)** which may contain multiple VO's and additional methods that are business case specific.
Addendum:
In your controller you call a ProductDAO to find the products you want.
The returned ProductVO(s) are then passed to the view (as request attributes in Java). The view then loops through/displays the data from the productVO's. |
138,511 | <p>I know there's some <code>JAVA_OPTS</code> to set to remotely debug a Java program.</p>
<p>What are they and what do they mean ?</p>
| [
{
"answer_id": 138518,
"author": "Hans Sjunnesson",
"author_id": 8683,
"author_profile": "https://Stackoverflow.com/users/8683",
"pm_score": 10,
"selected": true,
"text": "<p>I have <a href=\"http://www.eclipsezone.com/eclipse/forums/t53459.html\" rel=\"noreferrer\">this article</a> book... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3122/"
] | I know there's some `JAVA_OPTS` to set to remotely debug a Java program.
What are they and what do they mean ? | I have [this article](http://www.eclipsezone.com/eclipse/forums/t53459.html) bookmarked on setting this up for Java 5 and below.
Basically [run it with](http://download.oracle.com/otn_hosted_doc/jdeveloper/904preview/jdk14doc/docs/tooldocs/windows/jdb.html):
```
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044
```
For [Java 5 and above](http://javahowto.blogspot.ru/2010/09/java-agentlibjdwp-for-attaching.html), run it with:
```
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=1044
```
If you want Java to **wait for you to connect** before executing the application, replace `suspend=n` with `suspend=y`. |
138,514 | <p>I have a ASP.NET 2.0 webpage with 2 UserControls (.ascx). Each UserControl contains a bunch of validators. Placing a ValidationSummary on the page will display all validation errors, of both UserControl's. Placing a ValidationSummary in each UserControl will display all the errors of both controls twice. </p>
<p>What I want is a ValidationSummary for each UserControl, displaying only the errors on that UserControl. </p>
<p>I've tried to solve this by setting the ValidationGroup property of the validators on each usercontrol dynamicaly. That way each validationsummary should display only the errors of its UserControl. I've used this code:</p>
<pre><code>foreach (Control ctrl in this.Controls)
{
if (ctrl is BaseValidator)
{
(ctrl as BaseValidator).ValidationGroup = this.ClientID;
}
}
ValidationSummary1.ValidationGroup = this.ClientID;
</code></pre>
<p>This however seems to disable both clientside and server side validation, because no validation occurs when submitting the form.</p>
<p>Help?</p>
| [
{
"answer_id": 138557,
"author": "Jonathan Carter",
"author_id": 6412,
"author_profile": "https://Stackoverflow.com/users/6412",
"pm_score": 2,
"selected": false,
"text": "<p>The control that is causing your form submission (i.e. a Button control) has to be a part of the same validation ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6399/"
] | I have a ASP.NET 2.0 webpage with 2 UserControls (.ascx). Each UserControl contains a bunch of validators. Placing a ValidationSummary on the page will display all validation errors, of both UserControl's. Placing a ValidationSummary in each UserControl will display all the errors of both controls twice.
What I want is a ValidationSummary for each UserControl, displaying only the errors on that UserControl.
I've tried to solve this by setting the ValidationGroup property of the validators on each usercontrol dynamicaly. That way each validationsummary should display only the errors of its UserControl. I've used this code:
```
foreach (Control ctrl in this.Controls)
{
if (ctrl is BaseValidator)
{
(ctrl as BaseValidator).ValidationGroup = this.ClientID;
}
}
ValidationSummary1.ValidationGroup = this.ClientID;
```
This however seems to disable both clientside and server side validation, because no validation occurs when submitting the form.
Help? | If you use ValidationGroups, the validation only occurs if the control causing the postback is assign to the same ValidationGroup.
If you want to use a single control to postback you can still do this but you would need to explicitly call the Page.Validate method.
```
Page.Validate(MyValidationGroup1);
Page.Validate(MyValidationGroup2);
if(Page.IsValid)
{
//do stuff
}
```
Suggestion:
Why don't you expose a public property on your user controls called ValidationGroup?
In the setter you could explicitly set the validation group for each validator. You could also use your loop, but it would be more efficient to set each validator explicitly. This might improve the readability of the code using the user controls. |
138,533 | <p>I have a swing gui with a tabbed pane in the north. Several key events are added to its input map:</p>
<pre><code>InputMap paneInputMap = pane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
paneInputMap.put( KeyStroke.getKeyStroke( KeyEvent.VK_E, KeyEvent.CTRL_MASK ), "finish");
paneInputMap.put( KeyStroke.getKeyStroke( KeyEvent.VK_F1, KeyEvent.CTRL_MASK ), "toggletoolbar");
</code></pre>
<p>If the tabbed pane or another button in a toolbar has the focus, <kbd>Ctrl</kbd>+<kbd>F1</kbd> has no function. If another component is focused (e.g. JTree), <kbd>Ctrl</kbd>+<kbd>F1</kbd> executes the action.</p>
<p>The problem is, that it workes everywhere if I change the Keycode to e.g. <code>VK_F2</code>.</p>
<p>The key <kbd>F1</kbd> is'nt used anywhere else in the program.</p>
<p>Any idea?</p>
<p>Thanks,
André</p>
<p><strong>Edit:</strong> A full text search in the java source code gave the answer: The <code>ToolTipManager</code> registeres the Key <kbd>Ctrl</kbd>+<kbd>F1</kbd> to display the tooltip text if the key combination is pressed. So if a button with a tooltip is focused, <kbd>Ctrl</kbd>+<kbd>F1</kbd> is handled by the <code>ToolTipManager</code>. Otherwise my action is called.</p>
| [
{
"answer_id": 138668,
"author": "Daniel Hiller",
"author_id": 16193,
"author_profile": "https://Stackoverflow.com/users/16193",
"pm_score": 0,
"selected": false,
"text": "<p>May be the OS retargets the <kbd>F1</kbd> key? Install a key listener and see what events are handled.</p>\n\n<p>... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18633/"
] | I have a swing gui with a tabbed pane in the north. Several key events are added to its input map:
```
InputMap paneInputMap = pane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
paneInputMap.put( KeyStroke.getKeyStroke( KeyEvent.VK_E, KeyEvent.CTRL_MASK ), "finish");
paneInputMap.put( KeyStroke.getKeyStroke( KeyEvent.VK_F1, KeyEvent.CTRL_MASK ), "toggletoolbar");
```
If the tabbed pane or another button in a toolbar has the focus, `Ctrl`+`F1` has no function. If another component is focused (e.g. JTree), `Ctrl`+`F1` executes the action.
The problem is, that it workes everywhere if I change the Keycode to e.g. `VK_F2`.
The key `F1` is'nt used anywhere else in the program.
Any idea?
Thanks,
André
**Edit:** A full text search in the java source code gave the answer: The `ToolTipManager` registeres the Key `Ctrl`+`F1` to display the tooltip text if the key combination is pressed. So if a button with a tooltip is focused, `Ctrl`+`F1` is handled by the `ToolTipManager`. Otherwise my action is called. | So that this gets an answer, here's the solution copied from your edit in the question. ;-)
>
> The ToolTipManager registeres the Key
> `Ctrl`+`F1` to display the tooltip text if
> the key combination is pressed. So if
> a button with a tooltip is focused,
> `Ctrl`+`F1` is handled by the
> ToolTipManager. Otherwise my action is
> called.
>
>
> |
138,550 | <p>I didn't find an explicit answer to this question in the WiX Documentation (or Google, for that matter). Of course I could just write the appropriate registry keys in HKCR, but it makes me feel dirty and I'd expect this to be a standard task which should have a nice default solution.</p>
<p>For bonus points, I'd like to know how to make it "safe", i.e. don't overwrite existing registrations for the file type and remove the registration on uninstall only if it has been registered during installation and is unchanged.</p>
| [
{
"answer_id": 139151,
"author": "Edward Wilde",
"author_id": 5182,
"author_profile": "https://Stackoverflow.com/users/5182",
"pm_score": 3,
"selected": false,
"text": "<p>\"If your application handles its own file data type, you will need to register a file association for it. Put a Pro... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20363/"
] | I didn't find an explicit answer to this question in the WiX Documentation (or Google, for that matter). Of course I could just write the appropriate registry keys in HKCR, but it makes me feel dirty and I'd expect this to be a standard task which should have a nice default solution.
For bonus points, I'd like to know how to make it "safe", i.e. don't overwrite existing registrations for the file type and remove the registration on uninstall only if it has been registered during installation and is unchanged. | After some additional research, I found a partial answer to this question in the [WiX Tutorial](http://www.tramontana.co.hu/wix/lesson1.php#1.7). It shows an advertised solution and does not work with WiX 3.0, but given that information, I figured it out. Add a ProgId element to the component containing your executable, like the following:
```
<ProgId Id="MyApplication.MyFile" Description="My file type">
<Extension Id="myext" ContentType="application/whatever">
<Verb Id="open" Command="open" TargetFile="MyApplication.exe" Argument=""%1""/>
</Extension>
</ProgId>
```
myext is the file extension without the dot, and MyApplication.exe is the file id (not name) of the executable file (i.e. the Id attribute of the File element).
This will register the file type with your executable and will supply a default icon (a white page with the application icon on it), which is sufficient for my needs. If you want to specify a dedicated icon, it seems you still have to do this yourself, like the following (code from the linked tutorial):
```
<Registry Id='FooIcon1' Root='HKCR' Key='.xyz' Action='write' Type='string' Value='AcmeFoobar.xyzfile' />
<Registry Id='FooIcon2' Root='HKCR' Key='AcmeFoobar.xyzfile' Action='write' Type='string' Value='Acme Foobar data file' />
<Registry Id='FooIcon3' Root='HKCR' Key='AcmeFoobar.xyzfile\DefaultIcon' Action='write' Type='string' Value='[INSTALLDIR]Foobar.exe,1' />
```
I didn't find a good solution for my bonus question though.
Edit: I started writing this before the previous answer came. However, my solution actually works, in contrast to the previous answer. |
138,552 | <p>I need to replace character (say) <strong>x</strong> with character (say) <strong>P</strong> in a string, but only if it is contained in a quoted substring.
An example makes it clearer:</p>
<pre><code>axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k
</code></pre>
<p>Let's assume, for the sake of simplicity, that quotes always come in pairs. </p>
<p>The obvious way is to just process the string one character at a time (a simple state machine approach);<br>
however, I'm wondering if regular expressions can be used to do all the processing in one go.</p>
<p>My target language is C#, but I guess my question pertains to any language having builtin or library support for regular expressions.</p>
| [
{
"answer_id": 138594,
"author": "Remo.D",
"author_id": 16827,
"author_profile": "https://Stackoverflow.com/users/16827",
"pm_score": 1,
"selected": false,
"text": "<p>Not with plain regexp. Regular expressions have no \"memory\" so they cannot distinguish between being \"inside\" or \"o... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11545/"
] | I need to replace character (say) **x** with character (say) **P** in a string, but only if it is contained in a quoted substring.
An example makes it clearer:
```
axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k
```
Let's assume, for the sake of simplicity, that quotes always come in pairs.
The obvious way is to just process the string one character at a time (a simple state machine approach);
however, I'm wondering if regular expressions can be used to do all the processing in one go.
My target language is C#, but I guess my question pertains to any language having builtin or library support for regular expressions. | I was able to do this with Python:
```
>>> import re
>>> re.sub(r"x(?=[^']*'([^']|'[^']*')*$)", "P", "axbx'cxdxe'fxgh'ixj'k")
"axbx'cPdPe'fxgh'iPj'k"
```
What this does is use the non-capturing match (?=...) to check that the character x is within a quoted string. It looks for some nonquote characters up to the next quote, then looks for a sequence of either single characters or quoted groups of characters, until the end of the string.
This relies on your assumption that the quotes are always balanced. This is also not very efficient. |
138,555 | <p>I need to convert HTML documents into valid XML, preferably XHTML. What's the best way to do this? Does anybody know a toolkit/library/sample/...whatever that helps me to get that task done?</p>
<p>To be a bit more clear here, my application has to do the conversion automatically at runtime. I don't look for a tool that helps me to move some pages to XHTML manually.</p>
| [
{
"answer_id": 138561,
"author": "prakash",
"author_id": 123,
"author_profile": "https://Stackoverflow.com/users/123",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://www.ibm.com/developerworks/library/tiptidy.html\" rel=\"nofollow noreferrer\"><strong>Convert from HTML to ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6777/"
] | I need to convert HTML documents into valid XML, preferably XHTML. What's the best way to do this? Does anybody know a toolkit/library/sample/...whatever that helps me to get that task done?
To be a bit more clear here, my application has to do the conversion automatically at runtime. I don't look for a tool that helps me to move some pages to XHTML manually. | [**Convert from HTML to XML with HTML Tidy**](http://www.ibm.com/developerworks/library/tiptidy.html)
[**Downloadable Binaries**](http://tidy.sourceforge.net/#binaries)
JRoppert, For your need, i guess you might want to look at the [Sources](http://sourceforge.net/cvs/?group_id=27659)
```
c:\temp>tidy -help
tidy [option...] [file...] [option...] [file...]
Utility to clean up and pretty print HTML/XHTML/XML
see http://tidy.sourceforge.net/
Options for HTML Tidy for Windows released on 14 February 2006:
File manipulation
-----------------
-output <file>, -o write output to the specified <file>
<file>
-config <file> set configuration options from the specified <file>
-file <file>, -f write errors to the specified <file>
<file>
-modify, -m modify the original input files
Processing directives
---------------------
-indent, -i indent element content
-wrap <column>, -w wrap text at the specified <column>. 0 is assumed if
<column> <column> is missing. When this option is omitted, the
default of the configuration option "wrap" applies.
-upper, -u force tags to upper case
-clean, -c replace FONT, NOBR and CENTER tags by CSS
-bare, -b strip out smart quotes and em dashes, etc.
-numeric, -n output numeric rather than named entities
-errors, -e only show errors
-quiet, -q suppress nonessential output
-omit omit optional end tags
-xml specify the input is well formed XML
-asxml, -asxhtml convert HTML to well formed XHTML
-ashtml force XHTML to well formed HTML
-access <level> do additional accessibility checks (<level> = 0, 1, 2, 3).
0 is assumed if <level> is missing.
Character encodings
-------------------
-raw output values above 127 without conversion to entities
-ascii use ISO-8859-1 for input, US-ASCII for output
-latin0 use ISO-8859-15 for input, US-ASCII for output
-latin1 use ISO-8859-1 for both input and output
-iso2022 use ISO-2022 for both input and output
-utf8 use UTF-8 for both input and output
-mac use MacRoman for input, US-ASCII for output
-win1252 use Windows-1252 for input, US-ASCII for output
-ibm858 use IBM-858 (CP850+Euro) for input, US-ASCII for output
-utf16le use UTF-16LE for both input and output
-utf16be use UTF-16BE for both input and output
-utf16 use UTF-16 for both input and output
-big5 use Big5 for both input and output
-shiftjis use Shift_JIS for both input and output
-language <lang> set the two-letter language code <lang> (for future use)
Miscellaneous
-------------
-version, -v show the version of Tidy
-help, -h, -? list the command line options
-xml-help list the command line options in XML format
-help-config list all configuration options
-xml-config list all configuration options in XML format
-show-config list the current configuration settings
Use --blah blarg for any configuration option "blah" with argument "blarg"
Input/Output default to stdin/stdout respectively
Single letter options apart from -f may be combined
as in: tidy -f errs.txt -imu foo.html
For further info on HTML see http://www.w3.org/MarkUp
``` |
138,565 | <p>For a new project that I'm doing in PHP I've created an SQLMethods class to connect to the database and perform queries. Tonight was the first night that I actually got to test it (I wrote it a week or so ago and forgot about it) and an unexpected error occured: When it was calling my ExecuteQuery() function, it wouldn't use the database I selected in the constructor.</p>
<p>The constructor:</p>
<pre><code> public function SQLMethods() {
$SQLConnection = mysql_connect($SQLDBAddress, $SQLUserName, $SQLPassword);
if (!$SQLConnection) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($SQLDB, $SQLConnection);
}
</code></pre>
<p>The function in question:</p>
<pre><code> public function ExecuteQuery($Query) {
mysql_query($Query, $SQLConnection) or die('Could not perform query: ' . mysql_error());
}
</code></pre>
<p>Does anyone see what the issue might be? Does the connection close after the constructor completes?</p>
| [
{
"answer_id": 138590,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 4,
"selected": true,
"text": "<p>you should declare $SQLConnection in your class, and you should refer to it as </p>\n\n<pre><code> $this->SQLConnection... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14877/"
] | For a new project that I'm doing in PHP I've created an SQLMethods class to connect to the database and perform queries. Tonight was the first night that I actually got to test it (I wrote it a week or so ago and forgot about it) and an unexpected error occured: When it was calling my ExecuteQuery() function, it wouldn't use the database I selected in the constructor.
The constructor:
```
public function SQLMethods() {
$SQLConnection = mysql_connect($SQLDBAddress, $SQLUserName, $SQLPassword);
if (!$SQLConnection) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($SQLDB, $SQLConnection);
}
```
The function in question:
```
public function ExecuteQuery($Query) {
mysql_query($Query, $SQLConnection) or die('Could not perform query: ' . mysql_error());
}
```
Does anyone see what the issue might be? Does the connection close after the constructor completes? | you should declare $SQLConnection in your class, and you should refer to it as
```
$this->SQLConnection
```
and not simply $SQLConnection. |
138,576 | <p>I'm trying to use the tree command in a windows commandline to generate a text file listing the contents of a directory but when I pipe the output the unicode characters get stuffed up.</p>
<p>Here is the command I am using:</p>
<pre><code>tree /f /a > output.txt
</code></pre>
<p>The results in the console window are fine:</p>
<pre>
\---Erika szobája
cover.jpg
Erika szobája.m3u
Kátai Tamás - 01 Télvíz.ogg
Kátai Tamás - 02 Zölderdõ.ogg
Kátai Tamás - 03 Renoir kertje.ogg
Kátai Tamás - 04 Esõben szaladtál.ogg
Kátai Tamás - 05 Ázik az út.ogg
Kátai Tamás - 06 Sûrû völgyek takaród.ogg
Kátai Tamás - 07 Õszhozó.ogg
Kátai Tamás - 08 Mécsvilág.ogg
Kátai Tamás - 09 Zúzmara.ogg
</pre>
<p>But the text file is no good:</p>
<pre>
\---Erika szob ja
cover.jpg
Erika szob ja.m3u
K tai Tam s - 01 T‚lv¡z.ogg
K tai Tam s - 02 Z”lderdä.ogg
K tai Tam s - 03 Renoir kertje.ogg
K tai Tam s - 04 Esäben szaladt l.ogg
K tai Tam s - 05 µzik az £t.ogg
K tai Tam s - 06 S–r– v”lgyek takar¢d.ogg
K tai Tam s - 07 åszhoz¢.ogg
K tai Tam s - 08 M‚csvil g.ogg
K tai Tam s - 09 Z£zmara.ogg
</pre>
<p>How can I fix this? Ideally the text file would be exactly the same as the output in the console window.</p>
<p>I tried Chris Jester-Young's suggestion (what happened, did you delete it Chris?) of running the command line with the /U switch, it looked like exactly what I needed but it does not appear to work. I have tried opening the file in both VS2008 and notepad and both show the same incorrect characters.</p>
| [
{
"answer_id": 138736,
"author": "bzlm",
"author_id": 7724,
"author_profile": "https://Stackoverflow.com/users/7724",
"pm_score": 4,
"selected": false,
"text": "<p>If you output as non-Unicode (which you apparently do), you have to view the text file you create using the same encoding th... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/48281/"
] | I'm trying to use the tree command in a windows commandline to generate a text file listing the contents of a directory but when I pipe the output the unicode characters get stuffed up.
Here is the command I am using:
```
tree /f /a > output.txt
```
The results in the console window are fine:
```
\---Erika szobája
cover.jpg
Erika szobája.m3u
Kátai Tamás - 01 Télvíz.ogg
Kátai Tamás - 02 Zölderdõ.ogg
Kátai Tamás - 03 Renoir kertje.ogg
Kátai Tamás - 04 Esõben szaladtál.ogg
Kátai Tamás - 05 Ázik az út.ogg
Kátai Tamás - 06 Sûrû völgyek takaród.ogg
Kátai Tamás - 07 Õszhozó.ogg
Kátai Tamás - 08 Mécsvilág.ogg
Kátai Tamás - 09 Zúzmara.ogg
```
But the text file is no good:
```
\---Erika szob ja
cover.jpg
Erika szob ja.m3u
K tai Tam s - 01 T‚lv¡z.ogg
K tai Tam s - 02 Z”lderdä.ogg
K tai Tam s - 03 Renoir kertje.ogg
K tai Tam s - 04 Esäben szaladt l.ogg
K tai Tam s - 05 µzik az £t.ogg
K tai Tam s - 06 S–r– v”lgyek takar¢d.ogg
K tai Tam s - 07 åszhoz¢.ogg
K tai Tam s - 08 M‚csvil g.ogg
K tai Tam s - 09 Z£zmara.ogg
```
How can I fix this? Ideally the text file would be exactly the same as the output in the console window.
I tried Chris Jester-Young's suggestion (what happened, did you delete it Chris?) of running the command line with the /U switch, it looked like exactly what I needed but it does not appear to work. I have tried opening the file in both VS2008 and notepad and both show the same incorrect characters. | Have someone already tried this:
```
tree /f /a |clip
```
Open notepad, ctrl + V, save in notepad as output.txt with unicode support? |
138,600 | <p>What is the right way of initializing a static map? Do we need a static function that will initialize it? </p>
| [
{
"answer_id": 138612,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 9,
"selected": false,
"text": "<p>Using C++11:</p>\n\n<pre><code>#include <map>\nusing namespace std;\n\nmap<int, char> m = {{1, 'a'}, {3, 'b... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15163/"
] | What is the right way of initializing a static map? Do we need a static function that will initialize it? | Using C++11:
```
#include <map>
using namespace std;
map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};
```
Using [Boost.Assign](http://www.boost.org/doc/libs/1_36_0/libs/assign/doc/index.html):
```
#include <map>
#include "boost/assign.hpp"
using namespace std;
using namespace boost::assign;
map<int, char> m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');
``` |
138,607 | <p>I have a very simple bit of script that changes the status of an item in a MySql database - it works fine in IE7, but if I try it in Firefox, it looks like it's worked, but hasn't... Which is extremely odd.</p>
<p>The code is very simple - first I get the details of the record I'm looking for:</p>
<pre><code><cfscript>
// Get the Product Attribute details
Arguments.qGetProductAttribute = Application.cfcProducts.getProductAttributes(Arguments.iProductAttributeID);
</cfscript>
</code></pre>
<p>This is working fine, if I dump the results, it's just the content of the record as expected. So then I use an if statement to change the 'active' field from one to zero or vice versa.</p>
<pre><code><!--- If Product Attribute is active, mark as inactive --->
<cfif Arguments.qGetProductAttribute.bActive EQ 0>
<cfquery name="qChangeStatus" datasource="#Request.sDSN#">
UPDATE tblProductAttributes
SET bActive = <cfqueryparam value="1" cfsqltype="CF_SQL_INTEGER" maxlength="1" />
WHERE iProductAttributeID = <cfqueryparam value="#Arguments.iProductAttributeID#" cfsqltype="CF_SQL_INTEGER" />;
</cfquery>
<!--- Else if Product Attribute is inactive, mark as active --->
<cfelseif Arguments.qGetProductAttribute.bActive EQ 1>
<cfquery name="qChangeStatus" datasource="#Request.sDSN#">
UPDATE tblProductAttributes
SET bActive = <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER" maxlength="1" />
WHERE iProductAttributeID = <cfqueryparam value="#Arguments.iProductAttributeID#" cfsqltype="CF_SQL_INTEGER" />;
</cfquery>
</cfif>
</code></pre>
<p>I can't see any reason whatsoever for this not to work... and indeed, in IE7 it works perfectly...</p>
<p>What happens is after this script is run, the browser goes back to the page that displays all of these records. For each record if the 'bActive' field is set to '1', it will display the word 'Active' and if it's set to 'zero', it will display 'Disabled'.
Simple enough.</p>
<p>If I run the script to disable a record, Firefox actually displays the word 'disabled' as expected, but the database record doesn't change!</p>
<p>I'm at a loss... how can server-side code work fine in one browser and not in another?!</p>
| [
{
"answer_id": 138659,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 2,
"selected": false,
"text": "<p>Are you 100% certain that the database record does not change? You could get this affect if firefox calls you script twi... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22113/"
] | I have a very simple bit of script that changes the status of an item in a MySql database - it works fine in IE7, but if I try it in Firefox, it looks like it's worked, but hasn't... Which is extremely odd.
The code is very simple - first I get the details of the record I'm looking for:
```
<cfscript>
// Get the Product Attribute details
Arguments.qGetProductAttribute = Application.cfcProducts.getProductAttributes(Arguments.iProductAttributeID);
</cfscript>
```
This is working fine, if I dump the results, it's just the content of the record as expected. So then I use an if statement to change the 'active' field from one to zero or vice versa.
```
<!--- If Product Attribute is active, mark as inactive --->
<cfif Arguments.qGetProductAttribute.bActive EQ 0>
<cfquery name="qChangeStatus" datasource="#Request.sDSN#">
UPDATE tblProductAttributes
SET bActive = <cfqueryparam value="1" cfsqltype="CF_SQL_INTEGER" maxlength="1" />
WHERE iProductAttributeID = <cfqueryparam value="#Arguments.iProductAttributeID#" cfsqltype="CF_SQL_INTEGER" />;
</cfquery>
<!--- Else if Product Attribute is inactive, mark as active --->
<cfelseif Arguments.qGetProductAttribute.bActive EQ 1>
<cfquery name="qChangeStatus" datasource="#Request.sDSN#">
UPDATE tblProductAttributes
SET bActive = <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER" maxlength="1" />
WHERE iProductAttributeID = <cfqueryparam value="#Arguments.iProductAttributeID#" cfsqltype="CF_SQL_INTEGER" />;
</cfquery>
</cfif>
```
I can't see any reason whatsoever for this not to work... and indeed, in IE7 it works perfectly...
What happens is after this script is run, the browser goes back to the page that displays all of these records. For each record if the 'bActive' field is set to '1', it will display the word 'Active' and if it's set to 'zero', it will display 'Disabled'.
Simple enough.
If I run the script to disable a record, Firefox actually displays the word 'disabled' as expected, but the database record doesn't change!
I'm at a loss... how can server-side code work fine in one browser and not in another?! | I found the cause of the problem... Firebug.
I haven't the slightest idea what Firebug thinks it's doing, if I remove the 'cflocation' tag from the script (the one that takes the user back to the summary page), then it works fine. But if I keep it in, Firebug seems to run the function again before forwarding the browser to the summary page.
There's no reason for it to be doing this.
Un-bloody-belivable.
At least it won't be happening on the clients' machines. |
138,616 | <p>I need to enumerate all running applications. In particular, all top windows. And for every window I need to add my custom item to the system menu of that window.</p>
<p>How can I accomplish that in C++?</p>
<p><strong>Update.</strong></p>
<p>I would be more than happy to have a solution for Windows, MacOS, and Ubuntu (though, I'm not sure if MacOS and Ubuntu have such thing as 'system menu').</p>
| [
{
"answer_id": 138657,
"author": "Chris",
"author_id": 2134,
"author_profile": "https://Stackoverflow.com/users/2134",
"pm_score": 1,
"selected": false,
"text": "<p>Once you have another window's top level handle, you may be able to call <a href=\"http://msdn.microsoft.com/en-us/library/... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22623/"
] | I need to enumerate all running applications. In particular, all top windows. And for every window I need to add my custom item to the system menu of that window.
How can I accomplish that in C++?
**Update.**
I would be more than happy to have a solution for Windows, MacOS, and Ubuntu (though, I'm not sure if MacOS and Ubuntu have such thing as 'system menu'). | For Windows, another way to get the top-level windows (besides EnumWindows, which uses a callback) is to get the first child of the desktop and then retrieve all its siblings:
```
HWND wnd = GetWindow(GetDesktopWindow(), GW_CHILD);
while (wnd) {
// handle 'wnd' here
// ...
wnd = GetNextWindow(wnd, GW_HWNDNEXT);
}
```
As for getting the *system* menu, use the [`GetSystemMenu`](http://msdn.microsoft.com/en-us/library/ms647985(VS.85).aspx) function, with FALSE as the second argument. The [`GetMenu`](http://msdn.microsoft.com/en-us/library/ms647640(VS.85).aspx) mentioned in the other answers returns the *normal* window menu.
Note, however, that while adding a custom menu item to a foreign process's window is easy, responding to the selection of that item is a bit tricky. You'll either have to inject some code to the process in order to be able to subclass the window, or install a global hook (probably a `WH_GETMESSAGE` or `WH_CBT` type) to monitor `WM_SYSCOMMAND` messages. |
138,617 | <p>Is there a way to create an html link using h:outputLink, other JSF tag or code to create a non faces request (HTTP GET) with request parameters?</p>
<p>For example I have the following navigation-rule</p>
<pre><code><navigation-rule>
<navigation-case>
<from-outcome>showMessage</from-outcome>
<to-view-id>/showMessage.jsf</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>
</code></pre>
<p>In my page I would like to output the following html code:</p>
<pre><code><a href="/showMessage.jsf?msg=23">click to see the message</a>
</code></pre>
<p>I could just write the html code in the page, but I want to use the navigation rule in order to have all the urls defined in a single configurable file.</p>
| [
{
"answer_id": 139620,
"author": "hubbardr",
"author_id": 22457,
"author_profile": "https://Stackoverflow.com/users/22457",
"pm_score": 0,
"selected": false,
"text": "<p>Have you considered a form?</p>\n\n<pre><code><h:form>\n <h:commandLink value=\"Click to see the message\"... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19331/"
] | Is there a way to create an html link using h:outputLink, other JSF tag or code to create a non faces request (HTTP GET) with request parameters?
For example I have the following navigation-rule
```
<navigation-rule>
<navigation-case>
<from-outcome>showMessage</from-outcome>
<to-view-id>/showMessage.jsf</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>
```
In my page I would like to output the following html code:
```
<a href="/showMessage.jsf?msg=23">click to see the message</a>
```
I could just write the html code in the page, but I want to use the navigation rule in order to have all the urls defined in a single configurable file. | This is an interesting idea. I'd be curious to know how it pans out in practice.
**Getting the navigation rules**
Navigation is handled by the [NavigationHandler](http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/application/NavigationHandler.html). Getting hold of the NavigationHandler isn't difficult, but the API does not expose the rules it uses.
As I see it, you can:
1. parse faces-config.xml on initialization and store the rules in the application context (*easy*)
2. implement your own NavigationHandler that ignores the rules in faces-config.xml or supplements them with your own rules file and exposes its ruleset somehow (*workable, but takes a bit of work*)
3. mock your own [FacesContext](http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/context/FacesContext.html) and pass it to the existing navigation handler (*really difficult to make two FacesContext object coexist in same thread and extremely inefficient*)
Now, you have another problem too. Where are you going to keep the mappings to look up the views? Hard-code them in the beans?
**Using the navigation rules**
Off hand, I can think of two ways you could construct parameter-containing URLs from the back-end. Both involve defining a bean of some kind.
```
<managed-bean>
<managed-bean-name>navBean</managed-bean-name>
<managed-bean-class>foo.NavBean</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
</managed-bean>
```
Source:
```
package foo;
import java.io.IOException;
import java.io.Serializable;
import java.net.URLEncoder;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
public class NavBean implements Serializable {
private String getView() {
String viewId = "/showMessage.faces"; // or look this up somewhere
return viewId;
}
/**
* Regular link to page
*/
public String getUrlLink() {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext extContext = context.getExternalContext();
String viewId = getView();
String navUrl = context.getExternalContext().encodeActionURL(
extContext.getRequestContextPath() + viewId);
return navUrl;
}
/**
* Just some value
*/
public String getValue() {
return "" + System.currentTimeMillis();
}
/**
* Invoked by action
*/
public String invokeRedirect() {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext extContext = context.getExternalContext();
String viewId = getView();
try {
String charEncoding = extContext.getRequestCharacterEncoding();
String name = URLEncoder.encode("foo", charEncoding);
String value = URLEncoder.encode(getValue(), charEncoding);
viewId = extContext.getRequestContextPath() + viewId + '?' + name
+ "=" + value;
String urlLink = context.getExternalContext().encodeActionURL(
viewId);
extContext.redirect(urlLink);
} catch (IOException e) {
extContext.log(getClass().getName() + ".invokeRedirect", e);
}
return null;
}
}
```
**GET**
For a GET request, you can use the UIParameters to set the values and let the renderer build the parameter list.
```
<h:outputLink value="#{navBean.urlLink}">
<f:param name="foo" value="#{navBean.value}" />
<h:outputText value="get" />
</h:outputLink>
```
**POST**
If you want to set the URL to a view during a POST action, you can do it using a redirect in an action (invoked by a button or commandLink).
```
<h:commandLink id="myCommandLink" action="#{navBean.invokeRedirect}">
<h:outputText value="post" />
</h:commandLink>
```
**Notes**
Note that [ExternalContext.encodeActionURL](http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/context/ExternalContext.html#encodeActionURL(java.lang.String)) is used to encode the string. This is good practice for producing code that is portable across contexts (portlets, etcetera). You would use *encodeResourceURL* if you were encoding a link to an image or download file. |
138,638 | <p>Can I expose a class from another .net namespace as a class in my namespace? I use a class - antlr.collections.AST - as the return type for a function belonging to a class in my namespace; as a result, the user has to have</p>
<pre><code>using antlr.collections;
using myNamespace;
</code></pre>
<p>at the top of their files in order to use my function. Can I make myNamespace.AST an alias for antlr.collections.AST, such that the user only has to have</p>
<pre><code>using myNamespace;
</code></pre>
<p>at the top of their files?</p>
| [
{
"answer_id": 138642,
"author": "Agnel Kurian",
"author_id": 45603,
"author_profile": "https://Stackoverflow.com/users/45603",
"pm_score": 2,
"selected": false,
"text": "<p>How about deriving a class using the same name in the new namespace? I meant:</p>\n\n<pre><code>namespace MyForms ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
] | Can I expose a class from another .net namespace as a class in my namespace? I use a class - antlr.collections.AST - as the return type for a function belonging to a class in my namespace; as a result, the user has to have
```
using antlr.collections;
using myNamespace;
```
at the top of their files in order to use my function. Can I make myNamespace.AST an alias for antlr.collections.AST, such that the user only has to have
```
using myNamespace;
```
at the top of their files? | Bear in mind that the consumers of your code won't actually *need* to have using statements. Those are there to make their lives easier, so they don't have to type antlr.collections.Foo and antlr.collections.Bar all over their source.
The bigger "impact" (if indeed there really is a severe one) is that the consumer of your code will need a hard reference to the assembly where antlr.collections is defined.
However, if that's documented up front, I honestly don't see it being that big of a problem. It's no different than the consumer of a SubSonic-generated DAL needing references both to the generated DAL assembly and the original SubSonic assembly. (And, quite possibly, using statements as well.)
Dependencies are what they are. There's a reason classes are broken into namespaces -- primarily for organization and to reduce naming conflicts. Not knowing what classes are in the namespace you mention, I don't know how likely such a conflict actually is in your scenario ... But attempting to move the class from one namespace to another, or to hide the fact that such is needed by deriving a blank class from it, is probably not the best idea. It won't kill the consumers of your class to have another reference and using statement. |
138,680 | <p>is it possible to extend vim functionality via custom extension (preferably, written in Python)?</p>
<p>What I need ideally is custom command when in command mode. E.g.</p>
<p>ESC</p>
<p>:do_this</p>
<p>:do_that</p>
| [
{
"answer_id": 138709,
"author": "Paolo Tedesco",
"author_id": 15622,
"author_profile": "https://Stackoverflow.com/users/15622",
"pm_score": 5,
"selected": true,
"text": "<p>vim supports scripting in python (and in perl as well, I think).</p>\n\n<p>You just have to make sure that the vim... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22623/"
] | is it possible to extend vim functionality via custom extension (preferably, written in Python)?
What I need ideally is custom command when in command mode. E.g.
ESC
:do\_this
:do\_that | vim supports scripting in python (and in perl as well, I think).
You just have to make sure that the vim distribution you are using has been compiled with python support.
If you are using a Linux system, you can download the source and then compile it with
```
./configure --enable-pythoninterp
make
sudo make install
```
Inside vim, you can type
```
:version
```
to list the available features; if it has python support, you should see a '+python' somewhere (a '-python' otherwise).
Then, to check the usage of the python module, you can type
```
:help python
```
P.S: if you're going to compile the vim sources, make sure to check the available configure options, you might need to specify --with-python-config-dir as well.
P.P.S: to create a "custom command in command mode" (if I understand correctly what you mean), you can create a function "MyFunction" in a vim script (using python or the vim scripting language) and then invoke it with
```
:Call MyFunction()
```
Check
```
:help user-functions
```
for details |
138,747 | <p>A client of mine uses Oracle 9i's utl_smtp to send mails out notifications to managers when their employees have made travel requests and they woul like quite a few changes made to the mailouts done. </p>
<p>We're having a lot of problems getting utl_smtp to talk to any smtp server on our network. We've even tried installing free smtp server on the oracle box but it will not spot the mail server running on port 25. The error code is ORA-29278.</p>
<p>So two questions really.</p>
<ol>
<li><p>Does anyone have any experience setting up email using Oracle's utl_smtp utility and have any suggestions as to where we might be going wrong.</p></li>
<li><p>Does anyone know if it is possible to get utl_smtp to dump text emails to a directory much as you can do if you're using system.net.mail's specifiedpickupdirectory config setting. This would be by far the preferable option.</p></li>
</ol>
<p>Thanks, Dan</p>
| [
{
"answer_id": 139021,
"author": "Dan Maharry",
"author_id": 2756,
"author_profile": "https://Stackoverflow.com/users/2756",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, we can telnet to the server.</p>\n\n<pre><code>-- ****** Object: Stored Procedure TRAVELADMIN_DEV.HTML_EMAIL Scr... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2756/"
] | A client of mine uses Oracle 9i's utl\_smtp to send mails out notifications to managers when their employees have made travel requests and they woul like quite a few changes made to the mailouts done.
We're having a lot of problems getting utl\_smtp to talk to any smtp server on our network. We've even tried installing free smtp server on the oracle box but it will not spot the mail server running on port 25. The error code is ORA-29278.
So two questions really.
1. Does anyone have any experience setting up email using Oracle's utl\_smtp utility and have any suggestions as to where we might be going wrong.
2. Does anyone know if it is possible to get utl\_smtp to dump text emails to a directory much as you can do if you're using system.net.mail's specifiedpickupdirectory config setting. This would be by far the preferable option.
Thanks, Dan | Looks like the HELO is the problem. Please can we check with a simple testcase...
```
set serveroutput on
declare
lConnection UTL_SMTP.CONNECTION;
begin
lConnection := UTL_SMTP.OPEN_CONNECTION(your_smtp_server);
DBMS_OUTPUT.PUT_LINE('Opened ok');
UTL_SMTP.HELO(lConnection, your_client_machine_name);
DBMS_OUTPUT.PUT_LINE('HELO ok');
UTL_SMTP.MAIL(lConnection, your_email_address);
UTL_SMTP.RCPT(lConnection, your_email_address);
DBMS_OUTPUT.PUT_LINE('Addressing ok');
end;
/
``` |
138,785 | <p>I'm trying to learn RegEx in Ruby, based on what I'm reading in "<em>The Rails Way</em>". But, even this simple example has me stumped. I can't tell if it is a typo or not:</p>
<pre><code>text.gsub(/\s/, "-").gsub([^\W-], '').downcase
</code></pre>
<p>It seems to me that this would replace all spaces with <code>-</code>, then anywhere a string starts with a non letter or number followed by a dash, replace that with ''. But, using irb, it fails first on <code>^</code>:</p>
<blockquote>
<p>syntax error, unexpected '^', expecting ']'</p>
</blockquote>
<p>If I take out the <code>^</code>, it fails again on the W.</p>
| [
{
"answer_id": 138800,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 2,
"selected": false,
"text": "<p>You forgot the slashes. It should be <code>/[^\\W-]/</code></p>\n"
},
{
"answer_id": 138809,
"author": "Vinko... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9450/"
] | I'm trying to learn RegEx in Ruby, based on what I'm reading in "*The Rails Way*". But, even this simple example has me stumped. I can't tell if it is a typo or not:
```
text.gsub(/\s/, "-").gsub([^\W-], '').downcase
```
It seems to me that this would replace all spaces with `-`, then anywhere a string starts with a non letter or number followed by a dash, replace that with ''. But, using irb, it fails first on `^`:
>
> syntax error, unexpected '^', expecting ']'
>
>
>
If I take out the `^`, it fails again on the W. | ```
>> text = "I love spaces"
=> "I love spaces"
>> text.gsub(/\s/, "-").gsub(/[^\W-]/, '').downcase
=> "--"
```
Missing //
Although this makes a little more sense :-)
```
>> text.gsub(/\s/, "-").gsub(/([^\W-])/, '\1').downcase
=> "i-love-spaces"
```
And this is probably what is meant
```
>> text.gsub(/\s/, "-").gsub(/[^\w-]/, '').downcase
=> "i-love-spaces"
```
\W means "not a word"
\w means "a word"
The // generate a regexp object
>
>
> >
> > /[^\W-]/.class
> > => Regexp
> >
> >
> >
>
>
> |
138,819 | <p>If I am iterating over each file using :</p>
<pre><code>@echo off
FOR %%f IN (*\*.\**) DO (
echo %%f
)
</code></pre>
<p>how could I print the extension of each file? I tried assigning %%f to a temporary variable, and then using the code : <code>echo "%t:~-3%"</code> to print but with no success.</p>
| [
{
"answer_id": 138847,
"author": "Sam Holloway",
"author_id": 1377325,
"author_profile": "https://Stackoverflow.com/users/1377325",
"pm_score": 6,
"selected": true,
"text": "<p>The FOR command has several built-in switches that allow you to modify file names. Try the following:</p>\n\n<p... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11234/"
] | If I am iterating over each file using :
```
@echo off
FOR %%f IN (*\*.\**) DO (
echo %%f
)
```
how could I print the extension of each file? I tried assigning %%f to a temporary variable, and then using the code : `echo "%t:~-3%"` to print but with no success. | The FOR command has several built-in switches that allow you to modify file names. Try the following:
```
@echo off
for %%i in (*.*) do echo "%%~xi"
```
For further details, use `help for` to get a complete list of the modifiers - there are quite a few! |
138,839 | <p>Currently I use .Net <code>WebBrowser.Document.Images()</code> to do this. It requires the <code>Webrowser</code> to load the document. It's messy and takes up resources. </p>
<p>According to <a href="https://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php">this question</a> XPath is better than a regex at this. </p>
<p>Anyone know how to do this in C#?</p>
| [
{
"answer_id": 138863,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": -1,
"selected": false,
"text": "<p>If it's valid xhtml, you could do this:</p>\n\n<pre><code>XmlDocument doc = new XmlDocument();\ndoc.LoadXml(html);\nXmlN... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5648/"
] | Currently I use .Net `WebBrowser.Document.Images()` to do this. It requires the `Webrowser` to load the document. It's messy and takes up resources.
According to [this question](https://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php) XPath is better than a regex at this.
Anyone know how to do this in C#? | If your input string is valid XHTML you can treat is as xml, load it into an xmldocument, and do XPath magic :) But it's not always the case.
Otherwise you can try this function, that will return all image links from HtmlSource :
```
public List<Uri> FetchLinksFromSource(string htmlSource)
{
List<Uri> links = new List<Uri>();
string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match m in matchesImgSrc)
{
string href = m.Groups[1].Value;
links.Add(new Uri(href));
}
return links;
}
```
And you can use it like this :
```
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
using(StreamReader sr = new StreamReader(response.GetResponseStream()))
{
List<Uri> links = FetchLinksFromSource(sr.ReadToEnd());
}
}
``` |
138,880 | <p>Our web site (running Rails) freezes IE6 nearly every time. The same code, deployed on a different server, does not freeze IE6. Where and how should we start tracking this down?</p>
| [
{
"answer_id": 138891,
"author": "Liam",
"author_id": 18333,
"author_profile": "https://Stackoverflow.com/users/18333",
"pm_score": 0,
"selected": false,
"text": "<p>Use Firefox with Firebug to compare the HTTP Headers in the Request and Response from both servers.</p>\n"
},
{
"a... | 2008/09/26 | [
"https://Stackoverflow.com/questions/138880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18666/"
] | Our web site (running Rails) freezes IE6 nearly every time. The same code, deployed on a different server, does not freeze IE6. Where and how should we start tracking this down? | You need to determine the difference between them, so I'd start out with the following:
```
curl -D first.headers -o first.body http://first.example.com
curl -D second.headers -o second.body http://second.example.com
diff -u first.headers second.headers
diff -u first.body second.body
``` |