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 |
|---|---|---|---|---|---|---|
1,329 | <p>I need to copy hundreds of gigs of random files around on my computer and am pretty leery of using the vanilla file copy built into Windows.</p>
<p>I don't want it to hang on a "Are you sure?", "Are you really sure?", "Even zip files?", "Surely not read-only files too!" loop as soon as I step away.</p>
<p>I don't want it to work for hours and then stop unexpectedly: "Someone once opened this file and so I won't copy it!" and then cancel the whole copy or just quit with no indication of what was done and what work remains.</p>
<p>What file management programs do you have experience with? Which do you recommend?</p>
<p>This question is related to my other question: <a href="https://stackoverflow.com/questions/225/how-can-i-use-an-old-pata-hard-disk-drive-on-my-newer-sata-only-computer">How can I use an old PATA hard disk drive on my newer SATA-only computer?</a></p>
| [
{
"answer_id": 1331,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 6,
"selected": false,
"text": "<p>Use <a href=\"http://en.wikipedia.org/wiki/Robocopy\" rel=\"noreferrer\">Robocopy (Robust File Copy)</a>.</p>\n\n<p>NOTE:</p>\... | 2008/08/04 | [
"https://Stackoverflow.com/questions/1329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | I need to copy hundreds of gigs of random files around on my computer and am pretty leery of using the vanilla file copy built into Windows.
I don't want it to hang on a "Are you sure?", "Are you really sure?", "Even zip files?", "Surely not read-only files too!" loop as soon as I step away.
I don't want it to work for hours and then stop unexpectedly: "Someone once opened this file and so I won't copy it!" and then cancel the whole copy or just quit with no indication of what was done and what work remains.
What file management programs do you have experience with? Which do you recommend?
This question is related to my other question: [How can I use an old PATA hard disk drive on my newer SATA-only computer?](https://stackoverflow.com/questions/225/how-can-i-use-an-old-pata-hard-disk-drive-on-my-newer-sata-only-computer) | How about good old Command-Line Xcopy? With S: being the source and T: the target:
```
xcopy /K /R /E /I /S /C /H /G /X /Y s:\*.* t:\
```
>
> /K Copies attributes. Normal Xcopy will reset read-only attributes.
>
>
> /R Overwrites read-only files.
>
>
> /E Copies directories and subdirectories, including empty ones.
>
>
> /I If destination does not exist and copying more than one file, assumes that destination must be a directory.
>
>
> /S Copies directories and subdirectories except empty ones.
>
>
> /C Continues copying even if errors occur.
>
>
> /H Copies hidden and system files also.
>
>
> /Y Suppresses prompting to confirm you want to overwrite an existing destination file.
>
>
> /G Allows the copying of encrypted files to destination that does not support encryption.
>
>
> /X Copies file audit settings (implies /O).
>
>
>
(Edit: Added /G and /X which are new since a few years) |
1,376 | <p>I need the name of the current logged in user in my <strong>Air/Flex</strong> application. The application will only be deployed on Windows machines. I think I could attain this by regexing the User directory, but am open to other ways.</p>
| [
{
"answer_id": 1380,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a solution that works in XP / Vista, but is definitely expandable to OSX, linux, I'd still be interested in another way.<... | 2008/08/04 | [
"https://Stackoverflow.com/questions/1376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] | I need the name of the current logged in user in my **Air/Flex** application. The application will only be deployed on Windows machines. I think I could attain this by regexing the User directory, but am open to other ways. | Also I would try:
```
File.userDirectory.name
```
But I don't have Air installed so I can't really test this... |
1,401 | <p>I have a custom validation function in JavaScript in a user control on a .Net 2.0 web site which checks to see that the fee paid is not in excess of the fee amount due. </p>
<p>I've placed the validator code in the <code>ascx</code> file, and I have also tried using <code>Page.ClientScript.RegisterClientScriptBlock()</code> and in both cases the validation fires, but cannot find the JavaScript function.</p>
<p>The output in Firefox's error console is <code>"feeAmountCheck is not defined"</code>. Here is the function (this was taken directly from firefox->view source)</p>
<pre><code><script type="text/javascript">
function feeAmountCheck(source, arguments)
{
var amountDue = document.getElementById('ctl00_footerContentHolder_Fees1_FeeDue');
var amountPaid = document.getElementById('ctl00_footerContentHolder_Fees1_FeePaid');
if (amountDue.value > 0 && amountDue >= amountPaid)
{
arguments.IsValid = true;
}
else
{
arguments.IsValid = false;
}
return arguments;
}
</script>
</code></pre>
<p>Any ideas as to why the function isn't being found? How can I remedy this without having to add the function to my master page or consuming page?</p>
| [
{
"answer_id": 1405,
"author": "brendan",
"author_id": 225,
"author_profile": "https://Stackoverflow.com/users/225",
"pm_score": 3,
"selected": false,
"text": "<p>When you're using .Net 2.0 and Ajax - you should use:</p>\n\n<pre><code>ScriptManager.RegisterClientScriptBlock\n</code></pre... | 2008/08/04 | [
"https://Stackoverflow.com/questions/1401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149/"
] | I have a custom validation function in JavaScript in a user control on a .Net 2.0 web site which checks to see that the fee paid is not in excess of the fee amount due.
I've placed the validator code in the `ascx` file, and I have also tried using `Page.ClientScript.RegisterClientScriptBlock()` and in both cases the validation fires, but cannot find the JavaScript function.
The output in Firefox's error console is `"feeAmountCheck is not defined"`. Here is the function (this was taken directly from firefox->view source)
```
<script type="text/javascript">
function feeAmountCheck(source, arguments)
{
var amountDue = document.getElementById('ctl00_footerContentHolder_Fees1_FeeDue');
var amountPaid = document.getElementById('ctl00_footerContentHolder_Fees1_FeePaid');
if (amountDue.value > 0 && amountDue >= amountPaid)
{
arguments.IsValid = true;
}
else
{
arguments.IsValid = false;
}
return arguments;
}
</script>
```
Any ideas as to why the function isn't being found? How can I remedy this without having to add the function to my master page or consuming page? | Try changing the argument names to `sender` and `args`. And, after you have it working, switch the call over to `ScriptManager.RegisterClientScriptBlock`, regardless of AJAX use. |
1,408 | <p>Is it possible to configure <a href="http://www.apachefriends.org/en/xampp.html" rel="noreferrer">xampp</a> to serve up a file outside of the <code>htdocs</code> directory?</p>
<p>For instance, say I have a file located as follows:</p>
<p><code>C:\projects\transitCalculator\trunk\TransitCalculator.php</code></p>
<p>and my <a href="http://www.apachefriends.org/en/xampp.html" rel="noreferrer">xampp</a> files are normally served out from:</p>
<p><code>C:\xampp\htdocs\</code></p>
<p>(because that's the default configuration) Is there some way to make Apache recognize and serve up my <code>TransitCalculator.php</code> file without moving it under <code>htdocs</code>? Preferably I'd like Apache to serve up/have access to the entire contents of the projects directory, and I don't want to move the projects directory under <code>htdocs</code>.</p>
<p>edit: edited to add Apache to the question title to make Q/A more "searchable"</p>
| [
{
"answer_id": 1413,
"author": "sparkes",
"author_id": 269,
"author_profile": "https://Stackoverflow.com/users/269",
"pm_score": 4,
"selected": false,
"text": "<p>You can set Apache to serve pages from anywhere with any restrictions but it's normally distributed in a more secure form.</p... | 2008/08/04 | [
"https://Stackoverflow.com/questions/1408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58/"
] | Is it possible to configure [xampp](http://www.apachefriends.org/en/xampp.html) to serve up a file outside of the `htdocs` directory?
For instance, say I have a file located as follows:
`C:\projects\transitCalculator\trunk\TransitCalculator.php`
and my [xampp](http://www.apachefriends.org/en/xampp.html) files are normally served out from:
`C:\xampp\htdocs\`
(because that's the default configuration) Is there some way to make Apache recognize and serve up my `TransitCalculator.php` file without moving it under `htdocs`? Preferably I'd like Apache to serve up/have access to the entire contents of the projects directory, and I don't want to move the projects directory under `htdocs`.
edit: edited to add Apache to the question title to make Q/A more "searchable" | Ok, per [pix0r](https://stackoverflow.com/questions/1408/#2471)'s, [Sparks](https://stackoverflow.com/questions/1408/#1413)' and [Dave](https://stackoverflow.com/questions/1408/#1414)'s answers it looks like there are three ways to do this:
---
[Virtual Hosts](https://stackoverflow.com/questions/1408/#2471)
---------------------------------------------------------------
1. Open C:\xampp\apache\conf\extra\httpd-vhosts.conf.
2. Un-comment ~line 19 (`NameVirtualHost *:80`).
3. Add your virtual host (~line 36):
```
<VirtualHost *:80>
DocumentRoot C:\Projects\transitCalculator\trunk
ServerName transitcalculator.localhost
<Directory C:\Projects\transitCalculator\trunk>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
```
4. Open your hosts file (C:\Windows\System32\drivers\etc\hosts).
5. Add
```
127.0.0.1 transitcalculator.localhost #transitCalculator
```
to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed).
6. Save (You might have to save it to the desktop, change the permissions on the old hosts file (right click > properties), and copy the new one into the directory over the old one (or rename the old one) if you are using Vista and have trouble).
7. Restart Apache.
Now you can access that directory by browsing to <http://transitcalculator.localhost/>.
---
[Make an Alias](https://stackoverflow.com/questions/1408/#1413)
---------------------------------------------------------------
1. Starting ~line 200 of your `http.conf` file, copy everything between `<Directory "C:/xampp/htdocs">` and `</Directory>` (~line 232) and paste it immediately below with `C:/xampp/htdocs` replaced with your desired directory (in this case `C:/Projects`) to give your server the correct permissions for the new directory.
2. Find the `<IfModule alias_module></IfModule>` section (~line 300) and add
```
Alias /transitCalculator "C:/Projects/transitCalculator/trunk"
```
(or whatever is relevant to your desires) below the `Alias` comment block, inside the module tags.
---
[Change your document root](https://stackoverflow.com/questions/1408/#1414)
---------------------------------------------------------------------------
1. Edit ~line 176 in C:\xampp\apache\conf\httpd.conf; change `DocumentRoot "C:/xampp/htdocs"` to `#DocumentRoot "C:/Projects"` (or whatever you want).
2. Edit ~line 203 to match your new location (in this case `C:/Projects`).
---
**Notes:**
* You have to use forward slashes "/" instead of back slashes "\".
* Don't include the trailing "/" at the end.
* *restart your server*. |
1,451 | <p>I often encounter the following scenario where I need to offer many different types of permissions. I primarily use ASP.NET / VB.NET with SQL Server 2000.</p>
<p><strong>Scenario</strong></p>
<p>I want to offer a dynamic permission system that can work on different parameters. Let's say that I want to give either a department or just a specific person access to an application. And pretend that we have a number of applications that keeps growing.</p>
<p>In the past, I have chosen one of the following two ways that I know to do this.</p>
<ol>
<li><p>Use a single permission table with special columns that are used for
determining a how to apply the parameters. The special columns in
this example are <code>TypeID</code> and <code>TypeAuxID</code>. The SQL would look something
like this.</p>
<pre><code>SELECT COUNT(PermissionID)
FROM application_permissions
WHERE
(TypeID = 1 AND TypeAuxID = @UserID) OR
(TypeID = 2 AND TypeAuxID = @DepartmentID)
AND ApplicationID = 1
</code></pre>
</li>
<li><p>Use a mapping table for each type of permission, then joining them
all together.</p>
<pre><code>SELECT COUNT(perm.PermissionID)
FROM application_permissions perm
LEFT JOIN application_UserPermissions emp
ON perm.ApplicationID = emp.ApplicationID
LEFT JOIN application_DepartmentPermissions dept
ON perm.ApplicationID = dept.ApplicationID
WHERE q.SectionID=@SectionID
AND (emp.UserID=@UserID OR dept.DeptID=@DeptID OR
(emp.UserID IS NULL AND dept.DeptID IS NULL)) AND ApplicationID = 1
ORDER BY q.QID ASC
</code></pre>
</li>
</ol>
<p><strong>My Thoughts</strong></p>
<p>I hope that the examples make sense. I cobbled them together.</p>
<p>The first example requires less work, but neither of them feel like the best answer. Is there a better way to handle this?</p>
| [
{
"answer_id": 1459,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 4,
"selected": false,
"text": "<p>The way I typically go about coding permission systems is having 6 tables.</p>\n\n<ul>\n<li>Users - this is pretty straig... | 2008/08/04 | [
"https://Stackoverflow.com/questions/1451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/106/"
] | I often encounter the following scenario where I need to offer many different types of permissions. I primarily use ASP.NET / VB.NET with SQL Server 2000.
**Scenario**
I want to offer a dynamic permission system that can work on different parameters. Let's say that I want to give either a department or just a specific person access to an application. And pretend that we have a number of applications that keeps growing.
In the past, I have chosen one of the following two ways that I know to do this.
1. Use a single permission table with special columns that are used for
determining a how to apply the parameters. The special columns in
this example are `TypeID` and `TypeAuxID`. The SQL would look something
like this.
```
SELECT COUNT(PermissionID)
FROM application_permissions
WHERE
(TypeID = 1 AND TypeAuxID = @UserID) OR
(TypeID = 2 AND TypeAuxID = @DepartmentID)
AND ApplicationID = 1
```
2. Use a mapping table for each type of permission, then joining them
all together.
```
SELECT COUNT(perm.PermissionID)
FROM application_permissions perm
LEFT JOIN application_UserPermissions emp
ON perm.ApplicationID = emp.ApplicationID
LEFT JOIN application_DepartmentPermissions dept
ON perm.ApplicationID = dept.ApplicationID
WHERE q.SectionID=@SectionID
AND (emp.UserID=@UserID OR dept.DeptID=@DeptID OR
(emp.UserID IS NULL AND dept.DeptID IS NULL)) AND ApplicationID = 1
ORDER BY q.QID ASC
```
**My Thoughts**
I hope that the examples make sense. I cobbled them together.
The first example requires less work, but neither of them feel like the best answer. Is there a better way to handle this? | I agree with John Downey.
Personally, I sometimes use a flagged enumeration of permissions. This way you can use AND, OR, NOT and XOR bitwise operations on the enumeration's items.
```
"[Flags]
public enum Permission
{
VIEWUSERS = 1, // 2^0 // 0000 0001
EDITUSERS = 2, // 2^1 // 0000 0010
VIEWPRODUCTS = 4, // 2^2 // 0000 0100
EDITPRODUCTS = 8, // 2^3 // 0000 1000
VIEWCLIENTS = 16, // 2^4 // 0001 0000
EDITCLIENTS = 32, // 2^5 // 0010 0000
DELETECLIENTS = 64, // 2^6 // 0100 0000
}"
```
Then, you can combine several permissions using the AND bitwise operator.
For example, if a user can view & edit users, the binary result of the operation is 0000 0011 which converted to decimal is 3.
You can then store the permission of one user into a single column of your Database (in our case it would be 3).
Inside your application, you just need another bitwise operation (OR) to verify if a user has a particular permission or not. |
1,453 | <p>I'm trying to do this (which produces an unexpected T_VARIABLE error):</p>
<pre><code>public function createShipment($startZip, $endZip, $weight =
$this->getDefaultWeight()){}
</code></pre>
<p>I don't want to put a magic number in there for weight since the object I am using has a <code>"defaultWeight"</code> parameter that all new shipments get if you don't specify a weight. I can't put the <code>defaultWeight</code> in the shipment itself, because it changes from shipment group to shipment group. Is there a better way to do it than the following?</p>
<pre><code>public function createShipment($startZip, $endZip, weight = 0){
if($weight <= 0){
$weight = $this->getDefaultWeight();
}
}
</code></pre>
| [
{
"answer_id": 1456,
"author": "Kevin",
"author_id": 40,
"author_profile": "https://Stackoverflow.com/users/40",
"pm_score": 5,
"selected": true,
"text": "<p>This isn't much better:</p>\n\n<pre><code>public function createShipment($startZip, $endZip, $weight=null){\n $weight = !$weigh... | 2008/08/04 | [
"https://Stackoverflow.com/questions/1453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58/"
] | I'm trying to do this (which produces an unexpected T\_VARIABLE error):
```
public function createShipment($startZip, $endZip, $weight =
$this->getDefaultWeight()){}
```
I don't want to put a magic number in there for weight since the object I am using has a `"defaultWeight"` parameter that all new shipments get if you don't specify a weight. I can't put the `defaultWeight` in the shipment itself, because it changes from shipment group to shipment group. Is there a better way to do it than the following?
```
public function createShipment($startZip, $endZip, weight = 0){
if($weight <= 0){
$weight = $this->getDefaultWeight();
}
}
``` | This isn't much better:
```
public function createShipment($startZip, $endZip, $weight=null){
$weight = !$weight ? $this->getDefaultWeight() : $weight;
}
// or...
public function createShipment($startZip, $endZip, $weight=null){
if ( !$weight )
$weight = $this->getDefaultWeight();
}
``` |
1,457 | <p>I'm writing an AJAX app, but as the user moves through the app, I'd like the URL in the address bar to update despite the lack of page reloads. Basically, I'd like for them to be able to bookmark at any point and thereby return to the current state. </p>
<p>How are people handling maintaining RESTfulness in AJAX apps? </p>
| [
{
"answer_id": 1465,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>This is similar to what Kevin said. You can have your client state as some javascript object, and when you want to save the ... | 2008/08/04 | [
"https://Stackoverflow.com/questions/1457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/331/"
] | I'm writing an AJAX app, but as the user moves through the app, I'd like the URL in the address bar to update despite the lack of page reloads. Basically, I'd like for them to be able to bookmark at any point and thereby return to the current state.
How are people handling maintaining RESTfulness in AJAX apps? | The way to do this is to manipulate `location.hash` when AJAX updates result in a state change that you'd like to have a discrete URL. For example, if your page's url is:
>
> <http://example.com/>
>
>
>
If a client side function executed this code:
```
// AJAX code to display the "foo" state goes here.
location.hash = 'foo';
```
Then, the URL displayed in the browser would be updated to:
>
> <http://example.com/#foo>
>
>
>
This allows users to bookmark the "foo" state of the page, and use the browser history to navigate between states.
With this mechanism in place, you'll then need to parse out the hash portion of the URL on the client side using JavaScript to create and display the appropriate initial state, as fragment identifiers (the part after the #) are not sent to the server.
[Ben Alman's hashchange plugin](http://benalman.com/projects/jquery-hashchange-plugin/) makes the latter a breeze if you're using jQuery. |
1,476 | <p>How do you express an integer as a binary number with Python literals?</p>
<p>I was easily able to find the answer for hex:</p>
<pre><code>>>> 0x12AF
4783
>>> 0x100
256
</code></pre>
<p>and octal:</p>
<pre><code>>>> 01267
695
>>> 0100
64
</code></pre>
<p><strong>How do you use literals to express binary in Python?</strong></p>
<hr>
<p><strong><em>Summary of Answers</em></strong></p>
<ul>
<li>Python 2.5 and earlier: can express binary using <code>int('01010101111',2)</code> but not with a literal.</li>
<li>Python 2.5 and earlier: there is <em>no way</em> to express binary literals.</li>
<li>Python 2.6 beta: You can do like so: <code>0b1100111</code> or <code>0B1100111</code>.</li>
<li>Python 2.6 beta: will also allow <code>0o27</code> or <code>0O27</code> (second character is the letter O) to represent an octal.</li>
<li>Python 3.0 beta: Same as 2.6, but will no longer allow the older <code>027</code> syntax for octals.</li>
</ul>
| [
{
"answer_id": 1478,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": -1,
"selected": false,
"text": "<p>As far as I can tell Python, up through 2.5, only supports hexadecimal & octal literals. I did find some discussions ... | 2008/08/04 | [
"https://Stackoverflow.com/questions/1476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92/"
] | How do you express an integer as a binary number with Python literals?
I was easily able to find the answer for hex:
```
>>> 0x12AF
4783
>>> 0x100
256
```
and octal:
```
>>> 01267
695
>>> 0100
64
```
**How do you use literals to express binary in Python?**
---
***Summary of Answers***
* Python 2.5 and earlier: can express binary using `int('01010101111',2)` but not with a literal.
* Python 2.5 and earlier: there is *no way* to express binary literals.
* Python 2.6 beta: You can do like so: `0b1100111` or `0B1100111`.
* Python 2.6 beta: will also allow `0o27` or `0O27` (second character is the letter O) to represent an octal.
* Python 3.0 beta: Same as 2.6, but will no longer allow the older `027` syntax for octals. | For reference—*future* Python possibilities:
Starting with Python 2.6 you can express binary literals using the prefix **0b** or **0B**:
```
>>> 0b101111
47
```
You can also use the new **bin** function to get the binary representation of a number:
```
>>> bin(173)
'0b10101101'
```
Development version of the documentation: [What's New in Python 2.6](http://docs.python.org/dev/whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax) |
1,528 | <p>I'm looking for some way to effectively hide inherited members. I have a library of classes which inherit from common base classes. Some of the more recent descendant classes inherit dependency properties which have become vestigial and can be a little confusing when using <em>IntelliSense</em> or using the classes in a visual designer.</p>
<p>These classes are all controls that are written to be compiled for either WPF or Silverlight 2.0. I know about <code>ICustomTypeDescriptor</code> and <code>ICustomPropertyProvider</code>, but I'm pretty certain those can't be used in Silverlight. </p>
<p>It's not as much a functional issue as a usability issue. What should I do?</p>
<p><strong>Update</strong></p>
<p>Some of the properties that I would really like to hide come from ancestors that are not my own and because of a specific tool I'm designing for, I can't do member hiding with the <code>new</code> operator. (I know, it's ridiculous)</p>
| [
{
"answer_id": 1533,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 4,
"selected": false,
"text": "<p>While you cannot prevent usage of those inherited members to my knowledge, you should be able to hide them from IntelliSen... | 2008/08/04 | [
"https://Stackoverflow.com/questions/1528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93/"
] | I'm looking for some way to effectively hide inherited members. I have a library of classes which inherit from common base classes. Some of the more recent descendant classes inherit dependency properties which have become vestigial and can be a little confusing when using *IntelliSense* or using the classes in a visual designer.
These classes are all controls that are written to be compiled for either WPF or Silverlight 2.0. I know about `ICustomTypeDescriptor` and `ICustomPropertyProvider`, but I'm pretty certain those can't be used in Silverlight.
It's not as much a functional issue as a usability issue. What should I do?
**Update**
Some of the properties that I would really like to hide come from ancestors that are not my own and because of a specific tool I'm designing for, I can't do member hiding with the `new` operator. (I know, it's ridiculous) | Override them like Michael Suggests [above](https://stackoverflow.com/questions/1528/#1533) and to prevent folks from using the overridden (sp?) methods, mark them as obsolete:
```
[Obsolete("These are not supported in this class.", true)]
public override void dontcallmeanymore()
{
}
```
If the second parm is set to true, a compiler error will be generated if anyone tries to call that method and the string in the first parm is the message. If parm2 is false only a compiler warning will be generated. |
1,535 | <p>I've never been completely happy with the way exception handling works, there's a lot exceptions and try/catch brings to the table (stack unwinding, etc.), but it seems to break a lot of the OO model in the process.</p>
<p>Anyway, here's the problem:</p>
<p>Let's say you have some class which wraps or includes networked file IO operations (e.g. reading and writing to some file at some particular UNC path somewhere). For various reasons you don't want those IO operations to fail, so if you detect that they fail you retry them and you keep retrying them until they succeed or you reach a timeout. I already have a convenient RetryTimer class which I can instantiate and use to sleep the current thread between retries and determine when the timeout period has elapsed, etc.</p>
<p>The problem is that you have a bunch of IO operations in several methods of this class, and you need to wrap each of them in try-catch / retry logic.</p>
<p>Here's an example code snippet:</p>
<pre><code>RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10));
bool success = false;
while (!success)
{
try
{
// do some file IO which may succeed or fail
success = true;
}
catch (IOException e)
{
if (fileIORetryTimer.HasExceededRetryTimeout)
{
throw e;
}
fileIORetryTimer.SleepUntilNextRetry();
}
}
</code></pre>
<p>So, how do you avoid duplicating most of this code for every file IO operation throughout the class? My solution was to use anonymous delegate blocks and a single method in the class which executed the delegate block passed to it. This allowed me to do things like this in other methods:</p>
<pre><code>this.RetryFileIO( delegate()
{
// some code block
} );
</code></pre>
<p>I like this somewhat, but it leaves a lot to be desired. I'd like to hear how other people would solve this sort of problem.</p>
| [
{
"answer_id": 1554,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 2,
"selected": false,
"text": "<p>Just wondering, what do you feel your method leaves to be desired? You could replace the anonymous delegate with a... | 2008/08/04 | [
"https://Stackoverflow.com/questions/1535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332/"
] | I've never been completely happy with the way exception handling works, there's a lot exceptions and try/catch brings to the table (stack unwinding, etc.), but it seems to break a lot of the OO model in the process.
Anyway, here's the problem:
Let's say you have some class which wraps or includes networked file IO operations (e.g. reading and writing to some file at some particular UNC path somewhere). For various reasons you don't want those IO operations to fail, so if you detect that they fail you retry them and you keep retrying them until they succeed or you reach a timeout. I already have a convenient RetryTimer class which I can instantiate and use to sleep the current thread between retries and determine when the timeout period has elapsed, etc.
The problem is that you have a bunch of IO operations in several methods of this class, and you need to wrap each of them in try-catch / retry logic.
Here's an example code snippet:
```
RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10));
bool success = false;
while (!success)
{
try
{
// do some file IO which may succeed or fail
success = true;
}
catch (IOException e)
{
if (fileIORetryTimer.HasExceededRetryTimeout)
{
throw e;
}
fileIORetryTimer.SleepUntilNextRetry();
}
}
```
So, how do you avoid duplicating most of this code for every file IO operation throughout the class? My solution was to use anonymous delegate blocks and a single method in the class which executed the delegate block passed to it. This allowed me to do things like this in other methods:
```
this.RetryFileIO( delegate()
{
// some code block
} );
```
I like this somewhat, but it leaves a lot to be desired. I'd like to hear how other people would solve this sort of problem. | This looks like an excellent opportunity to have a look at Aspect Oriented Programming. Here is a good article on [AOP in .NET](https://learn.microsoft.com/en-us/archive/blogs/simonince/aspect-oriented-interception). The general idea is that you'd extract the cross-functional concern (i.e. Retry for x hours) into a separate class and then you'd annotate any methods that need to modify their behaviour in that way. Here's how it might look (with a nice extension method on Int32)
```
[RetryFor( 10.Hours() )]
public void DeleteArchive()
{
//.. code to just delete the archive
}
``` |
1,615 | <p>The <code>.XFDL</code> file extension identifies <code>XFDL</code> Formatted Document files. These belong to the XML-based document and template formatting standard. This format is exactly like the XML file format however, contains a level of encryption for use in secure communications.</p>
<p>I know how to view XFDL files using a file viewer I found <a href="http://web.archive.org/web/20170903022252/http://www.e-publishing.af.mil:80/viewerdownload.asp" rel="nofollow noreferrer">here</a>. I can also modify and save these files by doing File:Save/Save As. I'd like, however, to modify these files on the fly. Any suggestions? Is this even possible?</p>
<p>Update #1: I have now successfully decoded and unziped a <code>.xfdl</code> into an XML file which I can then edit. Now, I am looking for a way to re-encode the modified XML file back into base64-gzip (using Ruby or the command line)</p>
| [
{
"answer_id": 1628,
"author": "saniul",
"author_id": 52,
"author_profile": "https://Stackoverflow.com/users/52",
"pm_score": 4,
"selected": true,
"text": "<p>If the encoding is <strong>base64</strong> then this is the solution I've stumbled upon on the web:</p>\n\n<p>\"Decoding XDFL fil... | 2008/08/04 | [
"https://Stackoverflow.com/questions/1615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25/"
] | The `.XFDL` file extension identifies `XFDL` Formatted Document files. These belong to the XML-based document and template formatting standard. This format is exactly like the XML file format however, contains a level of encryption for use in secure communications.
I know how to view XFDL files using a file viewer I found [here](http://web.archive.org/web/20170903022252/http://www.e-publishing.af.mil:80/viewerdownload.asp). I can also modify and save these files by doing File:Save/Save As. I'd like, however, to modify these files on the fly. Any suggestions? Is this even possible?
Update #1: I have now successfully decoded and unziped a `.xfdl` into an XML file which I can then edit. Now, I am looking for a way to re-encode the modified XML file back into base64-gzip (using Ruby or the command line) | If the encoding is **base64** then this is the solution I've stumbled upon on the web:
"Decoding XDFL files saved with 'encoding=base64'.
Files saved with:
```
application/vnd.xfdl;content-encoding="base64-gzip"
```
are simple base64-encoded gzip files. They can be easily restored to XML by first decoding and then unzipping them. This can be done as follows on Ubuntu:
```
sudo apt-get install uudeview
uudeview -i yourform.xfdl
gunzip -S "" < UNKNOWN.001 > yourform-unpacked.xfdl
```
The first command will install uudeview, a package that can decode base64, among others. You can skip this step once it is installed.
Assuming your form is saved as 'yourform.xfdl', the uudeview command will decode the contents as 'UNKNOWN.001', since the xfdl file doesn't contain a file name. The '-i' option makes uudeview uninteractive, remove that option for more control.
The last command gunzips the decoded file into a file named 'yourform-unpacked.xfdl'.
**Another** possible solution - [here](http://www.chilkatsoft.com/p/p_531.asp)
*Side Note: Block quoted < code > doesn't work for long strings of code* |
1,711 | <p>If you could go back in time and tell yourself to read a specific book at the beginning of your career as a developer, which book would it be?</p>
<p>I expect this list to be varied and to cover a wide range of things.</p>
<p><strong>To search:</strong> Use the search box in the upper-right corner. To search the answers of the current question, use <code>inquestion:this</code>. For example:</p>
<pre><code>inquestion:this "Code Complete"
</code></pre>
| [
{
"answer_id": 1713,
"author": "Justin Standard",
"author_id": 92,
"author_profile": "https://Stackoverflow.com/users/92",
"pm_score": 11,
"selected": false,
"text": "<ul>\n<li><em>Code Complete</em> (2nd edition) by Steve McConnell</li>\n<li><em>The Pragmatic Programmer</em></li>\n<li><... | 2008/08/04 | [
"https://Stackoverflow.com/questions/1711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/303/"
] | If you could go back in time and tell yourself to read a specific book at the beginning of your career as a developer, which book would it be?
I expect this list to be varied and to cover a wide range of things.
**To search:** Use the search box in the upper-right corner. To search the answers of the current question, use `inquestion:this`. For example:
```
inquestion:this "Code Complete"
``` | * *Code Complete* (2nd edition) by Steve McConnell
* *The Pragmatic Programmer*
* *Structure and Interpretation of Computer Programs*
* *The C Programming Language* by Kernighan and Ritchie
* *Introduction to Algorithms* by Cormen, Leiserson, Rivest & Stein
* *Design Patterns* by the Gang of Four
* *Refactoring: Improving the Design of Existing Code*
* *The Mythical Man Month*
* *The Art of Computer Programming* by Donald Knuth
* *Compilers: Principles, Techniques and Tools* by Alfred V. Aho, Ravi Sethi and Jeffrey D. Ullman
* *Gödel, Escher, Bach* by Douglas Hofstadter
* *Clean Code: A Handbook of Agile Software Craftsmanship* by Robert C. Martin
* *Effective C++*
* *More Effective C++*
* *CODE* by Charles Petzold
* *Programming Pearls* by Jon Bentley
* *Working Effectively with Legacy Code* by Michael C. Feathers
* *Peopleware* by Demarco and Lister
* *Coders at Work* by Peter Seibel
* *Surely You're Joking, Mr. Feynman!*
* *Effective Java* 2nd edition
* *Patterns of Enterprise Application Architecture* by Martin Fowler
* *The Little Schemer*
* *The Seasoned Schemer*
* *Why's (Poignant) Guide to Ruby*
* *The Inmates Are Running The Asylum: Why High Tech Products Drive Us Crazy and How to Restore the Sanity*
* *The Art of Unix Programming*
* *Test-Driven Development: By Example* by Kent Beck
* *Practices of an Agile Developer*
* *Don't Make Me Think*
* *Agile Software Development, Principles, Patterns, and Practices* by Robert C. Martin
* *Domain Driven Designs* by Eric Evans
* *The Design of Everyday Things* by Donald Norman
* *Modern C++ Design* by Andrei Alexandrescu
* *Best Software Writing I* by Joel Spolsky
* *The Practice of Programming* by Kernighan and Pike
* *Pragmatic Thinking and Learning: Refactor Your Wetware* by Andy Hunt
* *Software Estimation: Demystifying the Black Art* by Steve McConnel
* *The Passionate Programmer (My Job Went To India)* by Chad Fowler
* *Hackers: Heroes of the Computer Revolution*
* *Algorithms + Data Structures = Programs*
* *Writing Solid Code*
* *JavaScript - The Good Parts*
* *Getting Real* by 37 Signals
* *Foundations of Programming* by Karl Seguin
* *Computer Graphics: Principles and Practice in C* (2nd Edition)
* *Thinking in Java* by Bruce Eckel
* *The Elements of Computing Systems*
* *Refactoring to Patterns* by Joshua Kerievsky
* *Modern Operating Systems* by Andrew S. Tanenbaum
* *The Annotated Turing*
* *Things That Make Us Smart* by Donald Norman
* *The Timeless Way of Building* by Christopher Alexander
* *The Deadline: A Novel About Project Management* by Tom DeMarco
* *The C++ Programming Language (3rd edition)* by Stroustrup
* *Patterns of Enterprise Application Architecture*
* *Computer Systems - A Programmer's Perspective*
* *Agile Principles, Patterns, and Practices in C#* by Robert C. Martin
* *Growing Object-Oriented Software, Guided* by Tests
* *Framework Design Guidelines* by Brad Abrams
* *Object Thinking* by Dr. David West
* *Advanced Programming in the UNIX Environment* by W. Richard Stevens
* *Hackers and Painters: Big Ideas from the Computer Age*
* *The Soul of a New Machine* by Tracy Kidder
* *CLR via C#* by Jeffrey Richter
* *The Timeless Way of Building* by Christopher Alexander
* *Design Patterns in C#* by Steve Metsker
* *Alice in Wonderland* by Lewis Carol
* *Zen and the Art of Motorcycle Maintenance* by Robert M. Pirsig
* *About Face - The Essentials of Interaction Design*
* *Here Comes Everybody: The Power of Organizing Without Organizations* by Clay Shirky
* *The Tao of Programming*
* *Computational Beauty of Nature*
* *Writing Solid Code* by Steve Maguire
* *Philip and Alex's Guide to Web Publishing*
* *Object-Oriented Analysis and Design with Applications* by Grady Booch
* *Effective Java* by Joshua Bloch
* *Computability* by N. J. Cutland
* *Masterminds of Programming*
* *The Tao Te Ching*
* *The Productive Programmer*
* *The Art of Deception* by Kevin Mitnick
* *The Career Programmer: Guerilla Tactics for an Imperfect World* by Christopher Duncan
* *Paradigms of Artificial Intelligence Programming: Case studies in Common Lisp*
* *Masters of Doom*
* *Pragmatic Unit Testing in C# with NUnit* by Andy Hunt and Dave Thomas with Matt Hargett
* *How To Solve It* by George Polya
* *The Alchemist* by Paulo Coelho
* *Smalltalk-80: The Language and its Implementation*
* *Writing Secure Code* (2nd Edition) by Michael Howard
* *Introduction to Functional Programming* by Philip Wadler and Richard Bird
* *No Bugs!* by David Thielen
* *Rework* by Jason Freid and DHH
* *JUnit in Action* |
1,746 | <p>I am trying to grab the capital letters of a couple of words and wrap them in span tags. I am using <a href="http://php.net/manual/en/function.preg-replace.php" rel="noreferrer">preg_replace</a> for extract and wrapping purposes, but it's not outputting anything.</p>
<pre><code>preg_replace("/[A-Z]/", "<span class=\"initial\">$1</span>", $str)
</code></pre>
| [
{
"answer_id": 1749,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 7,
"selected": true,
"text": "<p>You need to put the pattern in parentheses <code>/([A-Z])/</code>, like this:</p>\n\n<pre><code>preg_replace(\"/([A-Z])/\", \... | 2008/08/05 | [
"https://Stackoverflow.com/questions/1746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137/"
] | I am trying to grab the capital letters of a couple of words and wrap them in span tags. I am using [preg\_replace](http://php.net/manual/en/function.preg-replace.php) for extract and wrapping purposes, but it's not outputting anything.
```
preg_replace("/[A-Z]/", "<span class=\"initial\">$1</span>", $str)
``` | You need to put the pattern in parentheses `/([A-Z])/`, like this:
```
preg_replace("/([A-Z])/", "<span class=\"initial\">$1</span>", $str)
``` |
1,762 | <p>I am trying to set a flag to show or hide a page element, but it always displays even when the expression is false. </p>
<pre><code>$canMerge = ($condition1 && $condition2) ? 'true' : 'false';
...
<?php if ($canMerge) { ?>Stuff<?php } ?>
</code></pre>
<p>What's up?</p>
| [
{
"answer_id": 1764,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 1,
"selected": false,
"text": "<p>The value of 'false' is true. You need to remove the quotes:</p>\n\n<pre><code>$canMerge = ($condition1 && $conditio... | 2008/08/05 | [
"https://Stackoverflow.com/questions/1762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137/"
] | I am trying to set a flag to show or hide a page element, but it always displays even when the expression is false.
```
$canMerge = ($condition1 && $condition2) ? 'true' : 'false';
...
<?php if ($canMerge) { ?>Stuff<?php } ?>
```
What's up? | This is broken because 'false' as a string will evaluate to true as a boolean.
However, this is an unneeded ternary expression, because the resulting values are simple true and false. This would be equivalent:
```
$canMerge = ($condition1 && $condition2);
``` |
1,829 | <p>I've got a menu in Python. That part was easy. I'm using <code>raw_input()</code> to get the selection from the user. </p>
<p>The problem is that <code>raw_input</code> (and input) require the user to press <kbd>Enter</kbd> after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far:</p>
<pre><code>import sys
print """Menu
1) Say Foo
2) Say Bar"""
answer = raw_input("Make a selection> ")
if "1" in answer: print "foo"
elif "2" in answer: print "bar"
</code></pre>
<p>It would be great to have something like</p>
<pre><code>print menu
while lastKey = "":
lastKey = check_for_recent_keystrokes()
if "1" in lastKey: #do stuff...
</code></pre>
| [
{
"answer_id": 1840,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 3,
"selected": false,
"text": "<p><strong>On Linux:</strong></p>\n\n<ul>\n<li>set raw mode</li>\n<li>select and read the keystroke</li>\n<li>restore norm... | 2008/08/05 | [
"https://Stackoverflow.com/questions/1829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30/"
] | I've got a menu in Python. That part was easy. I'm using `raw_input()` to get the selection from the user.
The problem is that `raw_input` (and input) require the user to press `Enter` after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far:
```
import sys
print """Menu
1) Say Foo
2) Say Bar"""
answer = raw_input("Make a selection> ")
if "1" in answer: print "foo"
elif "2" in answer: print "bar"
```
It would be great to have something like
```
print menu
while lastKey = "":
lastKey = check_for_recent_keystrokes()
if "1" in lastKey: #do stuff...
``` | **On Windows:**
```
import msvcrt
answer=msvcrt.getch()
``` |
1,836 | <p>OK. This is a bit of a vanity app, but I had a situation today at work where I was in a training class and the machine was set to lock every 10 minutes. Well, if the trainers got excited about talking - as opposed to changing slides - the machine would lock up.</p>
<p>I'd like to write a teeny app that has nothing but a taskbar icon that does nothing but move the mouse by 1 pixel every 4 minutes. </p>
<p>I can do that in 3 ways with Delphi (my strong language) but I'm moving to C# for work and I'd like to know the path of least resistance there.</p>
| [
{
"answer_id": 1843,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 6,
"selected": true,
"text": "<p><strong>for C# 3.5</strong></p>\n\n<p>without notifyicon therefore you will need to terminate this application in task man... | 2008/08/05 | [
"https://Stackoverflow.com/questions/1836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172/"
] | OK. This is a bit of a vanity app, but I had a situation today at work where I was in a training class and the machine was set to lock every 10 minutes. Well, if the trainers got excited about talking - as opposed to changing slides - the machine would lock up.
I'd like to write a teeny app that has nothing but a taskbar icon that does nothing but move the mouse by 1 pixel every 4 minutes.
I can do that in 3 ways with Delphi (my strong language) but I'm moving to C# for work and I'd like to know the path of least resistance there. | **for C# 3.5**
without notifyicon therefore you will need to terminate this application in task manager manually
```
using System;
using System.Drawing;
using System.Windows.Forms;
static class Program
{
static void Main()
{
Timer timer = new Timer();
// timer.Interval = 4 minutes
timer.Interval = (int)(TimeSpan.TicksPerMinute * 4 / TimeSpan.TicksPerMillisecond);
timer.Tick += (sender, args) => { Cursor.Position = new Point(Cursor.Position.X + 1, Cursor.Position.Y + 1); };
timer.Start();
Application.Run();
}
}
``` |
1,854 | <p>What do I need to look at to see whether I'm on Windows or Unix, etc?</p>
| [
{
"answer_id": 1857,
"author": "Louis Brandy",
"author_id": 2089740,
"author_profile": "https://Stackoverflow.com/users/2089740",
"pm_score": 11,
"selected": true,
"text": "<pre><code>>>> import os\n>>> os.name\n'posix'\n>>> import platform\n>>> platfo... | 2008/08/05 | [
"https://Stackoverflow.com/questions/1854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | What do I need to look at to see whether I'm on Windows or Unix, etc? | ```
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'
```
The output of [`platform.system()`](https://docs.python.org/library/platform.html#platform.system) is as follows:
* Linux: `Linux`
* Mac: `Darwin`
* Windows: `Windows`
See: [`platform` — Access to underlying platform’s identifying data](https://docs.python.org/library/platform.html) |
1,873 | <p>How do I delimit a Javascript data-bound string parameter in an anchor <code>OnClick</code> event?</p>
<ul>
<li>I have an anchor tag in an ASP.NET Repeater control.</li>
<li>The <code>OnClick</code> event of the anchor contains a call to a Javascript function.</li>
<li>The Javascript function takes a string for its input parameter.</li>
<li>The string parameter is populated with a data-bound value from the Repeater.</li>
</ul>
<p>I need the "double quotes" for the <code>Container.DataItem</code>.<br />
I need the 'single quotes' for the <code>OnClick</code>.</p>
<p>And I still need <em>one more delimiter</em> (triple quotes?) for the input string parameter of the Javascript function call.</p>
<p>Since I can't use 'single quotes' again, how do I ensure the Javascript function knows the input parameter is a string and not an integer?</p>
<p>Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer.</p>
<p>The anchor:</p>
<pre><code><a id="aShowHide" onclick='ToggleDisplay(<%# DataBinder.Eval(Container.DataItem, "JobCode") %>);' >Show/Hide</a>
</code></pre>
<p>And there is my Javascript:</p>
<pre><code><script language="JavaScript" type="text/javascript">
/* Shows/Hides the Jobs Div */
function ToggleDisplay(jobCode)
{
/* Each div has its ID set dynamically ('d' plus the JobCode) */
var elem = document.getElementById('d' + jobCode);
if (elem)
{
if (elem.style.display != 'block')
{
elem.style.display = 'block';
elem.style.visibility = 'visible';
}
else
{
elem.style.display = 'none';
elem.style.visibility = 'hidden';
}
}
}
</script>
</code></pre>
| [
{
"answer_id": 1875,
"author": "Grant",
"author_id": 30,
"author_profile": "https://Stackoverflow.com/users/30",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an inte... | 2008/08/05 | [
"https://Stackoverflow.com/questions/1873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242/"
] | How do I delimit a Javascript data-bound string parameter in an anchor `OnClick` event?
* I have an anchor tag in an ASP.NET Repeater control.
* The `OnClick` event of the anchor contains a call to a Javascript function.
* The Javascript function takes a string for its input parameter.
* The string parameter is populated with a data-bound value from the Repeater.
I need the "double quotes" for the `Container.DataItem`.
I need the 'single quotes' for the `OnClick`.
And I still need *one more delimiter* (triple quotes?) for the input string parameter of the Javascript function call.
Since I can't use 'single quotes' again, how do I ensure the Javascript function knows the input parameter is a string and not an integer?
Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer.
The anchor:
```
<a id="aShowHide" onclick='ToggleDisplay(<%# DataBinder.Eval(Container.DataItem, "JobCode") %>);' >Show/Hide</a>
```
And there is my Javascript:
```
<script language="JavaScript" type="text/javascript">
/* Shows/Hides the Jobs Div */
function ToggleDisplay(jobCode)
{
/* Each div has its ID set dynamically ('d' plus the JobCode) */
var elem = document.getElementById('d' + jobCode);
if (elem)
{
if (elem.style.display != 'block')
{
elem.style.display = 'block';
elem.style.visibility = 'visible';
}
else
{
elem.style.display = 'none';
elem.style.visibility = 'hidden';
}
}
}
</script>
``` | I had recently similar problem and the only way to solve it was to use plain old HTML codes for single (`'`) and double quotes (`"`).
Source code was total mess of course but it worked.
Try
```
<a id="aShowHide" onclick='ToggleDisplay("<%# DataBinder.Eval(Container.DataItem, "JobCode") %>");'>Show/Hide</a>
```
or
```
<a id="aShowHide" onclick='ToggleDisplay('<%# DataBinder.Eval(Container.DataItem, "JobCode") %>');'>Show/Hide</a>
``` |
1,908 | <p>I have a bunch of latitude/longitude pairs that map to known x/y coordinates on a (geographically distorted) map.</p>
<p>Then I have one more latitude/longitude pair. I want to plot it on the map as best is possible. How do I go about doing this?</p>
<p>At first I decided to create a system of linear equations for the three nearest lat/long points and compute a transformation from these, but this doesn't work well at all. Since that's a linear system, I can't use more nearby points either.</p>
<p>You can't assume North is up: all you have is the existing lat/long->x/y mappings.</p>
<p>EDIT: it's not a Mercator projection, or anything like that. It's arbitrarily distorted for readability (think subway map). I want to use only the nearest 5 to 10 mappings so that distortion on other parts of the map doesn't affect the mapping I'm trying to compute.</p>
<p>Further, the entire map is in a very small geographical area so there's no need to worry about the globe--flat-earth assumptions are good enough.</p>
| [
{
"answer_id": 1926,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 0,
"selected": false,
"text": "<p>the problem is that the sphere can be distorted a number of ways, and having all those points known on the equator, lets sa... | 2008/08/05 | [
"https://Stackoverflow.com/questions/1908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/79/"
] | I have a bunch of latitude/longitude pairs that map to known x/y coordinates on a (geographically distorted) map.
Then I have one more latitude/longitude pair. I want to plot it on the map as best is possible. How do I go about doing this?
At first I decided to create a system of linear equations for the three nearest lat/long points and compute a transformation from these, but this doesn't work well at all. Since that's a linear system, I can't use more nearby points either.
You can't assume North is up: all you have is the existing lat/long->x/y mappings.
EDIT: it's not a Mercator projection, or anything like that. It's arbitrarily distorted for readability (think subway map). I want to use only the nearest 5 to 10 mappings so that distortion on other parts of the map doesn't affect the mapping I'm trying to compute.
Further, the entire map is in a very small geographical area so there's no need to worry about the globe--flat-earth assumptions are good enough. | Are there any more specific details on the kind of distortion? If, for example, your latitudes and longitudes are "distorted" onto your 2D map using a Mercator projection, the conversion math is [readily available](http://www.wikipedia.org/wiki/Mercator_projection).
If the map is distorted truly arbitrarily, there are lots of things you could try, but the simplest would probably be to compute a [weighted average](http://www.wikipedia.org/wiki/Weighted_mean) from your existing point mappings. Your weights could be the squared inverse of the x/y distance from your new point to each of your existing points.
Some pseudocode:
```
estimate-latitude-longitude (x, y)
numerator-latitude := 0
numerator-longitude := 0
denominator := 0
for each point,
deltaX := x - point.x
deltaY := y - point.y
distSq := deltaX * deltaX + deltaY * deltaY
weight := 1 / distSq
numerator-latitude += weight * point.latitude
numerator-longitude += weight * point.longitude
denominator += weight
return (numerator-latitude / denominator, numerator-longitude / denominator)
```
This code will give a relatively simple approximation. If you can be more precise about the way the projection distorts the geographical coordinates, you can probably do much better. |
1,936 | <p>Using ASP.NET MVC there are situations (such as form submission) that may require a <code>RedirectToAction</code>. </p>
<p>One such situation is when you encounter validation errors after a form submission and need to redirect back to the form, but would like the URL to reflect the URL of the form, not the action page it submits to.</p>
<p>As I require the form to contain the originally <code>POST</code>ed data, for user convenience, as well as validation purposes, how can I pass the data through the <code>RedirectToAction()</code>? If I use the viewData parameter, my <code>POST</code> parameters will be changed to <code>GET</code> parameters.</p>
| [
{
"answer_id": 1940,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 7,
"selected": true,
"text": "<p>The solution is to use the TempData property to store the desired Request components.</p>\n\n<p>For instance:</p>\n\n<pr... | 2008/08/05 | [
"https://Stackoverflow.com/questions/1936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | Using ASP.NET MVC there are situations (such as form submission) that may require a `RedirectToAction`.
One such situation is when you encounter validation errors after a form submission and need to redirect back to the form, but would like the URL to reflect the URL of the form, not the action page it submits to.
As I require the form to contain the originally `POST`ed data, for user convenience, as well as validation purposes, how can I pass the data through the `RedirectToAction()`? If I use the viewData parameter, my `POST` parameters will be changed to `GET` parameters. | The solution is to use the TempData property to store the desired Request components.
For instance:
```
public ActionResult Send()
{
TempData["form"] = Request.Form;
return this.RedirectToAction(a => a.Form());
}
```
Then in your "Form" action you can go:
```
public ActionResult Form()
{
/* Declare viewData etc. */
if (TempData["form"] != null)
{
/* Cast TempData["form"] to
System.Collections.Specialized.NameValueCollection
and use it */
}
return View("Form", viewData);
}
``` |
1,949 | <p>In order to fully use LinqToSql in an ASP.net 3.5 application, it is necessary to create <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.aspx" rel="noreferrer">DataContext</a> <a href="http://dotnetslackers.com/articles/csharp/InsideTheLINQToSQLDataContextClass.aspx" rel="noreferrer">classes</a> (which is usually done using the designer in VS 2008). From the UI perspective, the DataContext is a design of the sections of your database that you would like to expose to through LinqToSql and is integral in setting up the ORM features of LinqToSql.</p>
<p>My question is: I am setting up a project that uses a large database where all tables are interconnected in some way through Foreign Keys. My first inclination is to make one huge DataContext class that models the entire database. That way I could in theory (though I don't know if this would be needed in practice) use the Foreign Key connections that are generated through LinqToSql to easily go between related objects in my code, insert related objects, etc.</p>
<p>However, after giving it some thought, I am now thinking that it may make more sense to create multiple DataContext classes, each one relating to a specific namespace or logical interrelated section within my database. My main concern is that instantiating and disposing one huge DataContext class all the time for individual operations that relate to specific areas of the Database would be impose an unnecessary imposition on application resources. Additionally, it is easier to create and manage smaller DataContext files than one big one. The thing that I would lose is that there would be some distant sections of the database that would not be navigable through LinqToSql (even though a chain of relationships connects them in the actual database). Additionally, there would be some table classes that would exist in more than one DataContext.</p>
<p>Any thoughts or experience on whether multiple DataContexts (corresponding to DB namespaces) are appropriate in place of (or in addition to) one very large DataContext class (corresponding to the whole DB)?</p>
| [
{
"answer_id": 2050,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 2,
"selected": false,
"text": "<p>In my experience with LINQ to SQL and LINQ to Entities a DataContext is synonymous to a connection to the database. So if... | 2008/08/05 | [
"https://Stackoverflow.com/questions/1949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51/"
] | In order to fully use LinqToSql in an ASP.net 3.5 application, it is necessary to create [DataContext](http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.aspx) [classes](http://dotnetslackers.com/articles/csharp/InsideTheLINQToSQLDataContextClass.aspx) (which is usually done using the designer in VS 2008). From the UI perspective, the DataContext is a design of the sections of your database that you would like to expose to through LinqToSql and is integral in setting up the ORM features of LinqToSql.
My question is: I am setting up a project that uses a large database where all tables are interconnected in some way through Foreign Keys. My first inclination is to make one huge DataContext class that models the entire database. That way I could in theory (though I don't know if this would be needed in practice) use the Foreign Key connections that are generated through LinqToSql to easily go between related objects in my code, insert related objects, etc.
However, after giving it some thought, I am now thinking that it may make more sense to create multiple DataContext classes, each one relating to a specific namespace or logical interrelated section within my database. My main concern is that instantiating and disposing one huge DataContext class all the time for individual operations that relate to specific areas of the Database would be impose an unnecessary imposition on application resources. Additionally, it is easier to create and manage smaller DataContext files than one big one. The thing that I would lose is that there would be some distant sections of the database that would not be navigable through LinqToSql (even though a chain of relationships connects them in the actual database). Additionally, there would be some table classes that would exist in more than one DataContext.
Any thoughts or experience on whether multiple DataContexts (corresponding to DB namespaces) are appropriate in place of (or in addition to) one very large DataContext class (corresponding to the whole DB)? | I disagree with John's answer. The DataContext (or Linq to Entities ObjectContext) is more of a "unit of work" than a connection. It manages change tracking, etc. See this blog post for a description:
[Lifetime of a LINQ to SQL DataContext](http://blogs.msdn.com/dinesh.kulkarni/archive/2008/04/27/lifetime-of-a-linq-to-sql-datacontext.aspx)
The four main points of this blog post are that DataContext:
1. Is ideally suited
for a "unit of work" approach
2. Is also designed for
"stateless" server operation
3. Is not designed for
Long-lived usage
4. ```
Should be used very carefully after
any SumbitChanges() operation.
```
Considering that, I don't think using more than one DataContext would do any harm- in fact, creating different DataContexts for different types of work would help make your LinqToSql impelmentation more usuable and organized. The only downside is you wouldn't be able to use sqlmetal to auto-generate your dmbl. |
1,988 | <p>I have read a lot that LISP can redefine syntax on the fly, presumably with macros. I am curious how far does this actually go? Can you redefine the language structure so much that it borderline becomes a compiler for another language? For example, could you change the functional nature of LISP into a more object oriented syntax and semantics, maybe say having syntax closer to something like Ruby?</p>
<p>Especially, is it possible to get rid of the parenthesis hell using macros? I have learned enough (Emacs-)LISP to customize Emacs with my own micro-features, but I am very curious how far macros can go in customizing the language.</p>
| [
{
"answer_id": 1992,
"author": "sparkes",
"author_id": 269,
"author_profile": "https://Stackoverflow.com/users/269",
"pm_score": 2,
"selected": false,
"text": "<p>If you want lisp to look like Ruby use Ruby. </p>\n\n<p>It's possible to use Ruby (and Python) in a very lisp like way which ... | 2008/08/05 | [
"https://Stackoverflow.com/questions/1988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | I have read a lot that LISP can redefine syntax on the fly, presumably with macros. I am curious how far does this actually go? Can you redefine the language structure so much that it borderline becomes a compiler for another language? For example, could you change the functional nature of LISP into a more object oriented syntax and semantics, maybe say having syntax closer to something like Ruby?
Especially, is it possible to get rid of the parenthesis hell using macros? I have learned enough (Emacs-)LISP to customize Emacs with my own micro-features, but I am very curious how far macros can go in customizing the language. | That's a really good question.
I think it's nuanced but definitely answerable:
Macros are not stuck in s-expressions. See the LOOP macro for a very complex language written using keywords (symbols). So, while you may start and end the loop with parentheses, inside it has its own syntax.
Example:
```
(loop for x from 0 below 100
when (even x)
collect x)
```
That being said, most simple macros just use s-expressions. And you'd be "stuck" using them.
But s-expressions, like Sergio has answered, start to feel right. The syntax gets out of the way and you start coding in the syntax tree.
As for reader macros, yes, you could conceivably write something like this:
```
#R{
ruby.code.goes.here
}
```
But you'd need to write your own Ruby syntax parser.
You can also mimic some of the Ruby constructs, like blocks, with macros that compile to the existing Lisp constructs.
```
#B(some lisp (code goes here))
```
would translate to
```
(lambda () (some lisp (code goes here)))
```
See [this page](http://rottcodd.wordpress.com/2007/11/29/lambda-shortcut/) for how to do it. |
1,994 | <p>When you data bind in C#, the thread that changes the data causes the control to change too. But if this thread is not the one on which the control was created, you'll get an Illegal Cross Thread Operation exception.</p>
<p>Is there anyway to prevent this?</p>
| [
{
"answer_id": 1998,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 3,
"selected": false,
"text": "<p>You should be able to do something like:</p>\n\n<pre><code>if (control.InvokeRequired)\n{\n control.Invoke(delegateWith... | 2008/08/05 | [
"https://Stackoverflow.com/questions/1994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/195/"
] | When you data bind in C#, the thread that changes the data causes the control to change too. But if this thread is not the one on which the control was created, you'll get an Illegal Cross Thread Operation exception.
Is there anyway to prevent this? | You should be able to do something like:
```
if (control.InvokeRequired)
{
control.Invoke(delegateWithMyCode);
}
else
{
delegateWithMyCode();
}
```
InvokeRequired is a property on Controls to see if you are on the correct thread, then Invoke will invoke the delegate on the correct thread.
UPDATE: Actually, at my last job we did something like this:
```
private void SomeEventHandler(Object someParam)
{
if (this.InvokeRequired)
{
this.Invoke(new SomeEventHandlerDelegate(SomeEventHandler), someParam);
}
// Regular handling code
}
```
which removes the need for the else block and kind of tightens up the code. |
2,027 | <p>When learning a new programming language, one of the possible roadblocks you might encounter is the question whether the language is, by default, <em>pass-by-value or pass-by-reference</em>.</p>
<p>So here is my question to all of you, in your favorite language, <em>how</em> is it actually done? And what are the <em>possible pitfalls</em>?</p>
<p>Your favorite language can, of course, be anything you have ever played with: <a href="http://www.ruby-lang.org/en/" rel="noreferrer">popular</a>, <a href="http://www.devtopics.com/a-obscure-programming-language-of-the-month/" rel="noreferrer">obscure</a>, <a href="http://en.wikipedia.org/wiki/Brainfuck" rel="noreferrer">esoteric</a>, <a href="http://www.nvidia.com/object/cuda_get.html" rel="noreferrer">new</a>, <a href="http://en.wikipedia.org/wiki/FORTRAN" rel="noreferrer">old</a>...</p>
| [
{
"answer_id": 2028,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 5,
"selected": false,
"text": "<p>Here is my own contribution for the <a href=\"http://en.wikipedia.org/wiki/Java_(programming_language)\" rel=\"nofollow noreferrer... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46/"
] | When learning a new programming language, one of the possible roadblocks you might encounter is the question whether the language is, by default, *pass-by-value or pass-by-reference*.
So here is my question to all of you, in your favorite language, *how* is it actually done? And what are the *possible pitfalls*?
Your favorite language can, of course, be anything you have ever played with: [popular](http://www.ruby-lang.org/en/), [obscure](http://www.devtopics.com/a-obscure-programming-language-of-the-month/), [esoteric](http://en.wikipedia.org/wiki/Brainfuck), [new](http://www.nvidia.com/object/cuda_get.html), [old](http://en.wikipedia.org/wiki/FORTRAN)... | Here is my own contribution for the [Java programming language](http://en.wikipedia.org/wiki/Java_(programming_language)).
first some code:
```
public void swap(int x, int y)
{
int tmp = x;
x = y;
y = tmp;
}
```
calling this method will result in this:
```
int pi = 3;
int everything = 42;
swap(pi, everything);
System.out.println("pi: " + pi);
System.out.println("everything: " + everything);
"Output:
pi: 3
everything: 42"
```
even using 'real' objects will show a similar result:
```
public class MyObj {
private String msg;
private int number;
//getters and setters
public String getMsg() {
return this.msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getNumber() {
return this.number;
}
public void setNumber(int number) {
this.number = number;
}
//constructor
public MyObj(String msg, int number) {
setMsg(msg);
setNumber(number);
}
}
public static void swap(MyObj x, MyObj y)
{
MyObj tmp = x;
x = y;
y = tmp;
}
public static void main(String args[]) {
MyObj x = new MyObj("Hello world", 1);
MyObj y = new MyObj("Goodbye Cruel World", -1);
swap(x, y);
System.out.println(x.getMsg() + " -- "+ x.getNumber());
System.out.println(y.getMsg() + " -- "+ y.getNumber());
}
"Output:
Hello world -- 1
Goodbye Cruel World -- -1"
```
thus it is clear that Java passes its parameters **by value**, as the value for *pi* and *everything* and the *MyObj objects* aren't swapped.
be aware that "by value" is the *only way* in java to pass parameters to a method. (for example a language like c++ allows the developer to pass a parameter by reference using '**&**' after the parameter's type)
now the **tricky part**, or at least the part that will confuse most of the new java developers: (borrowed from [javaworld](http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html))
Original author: Tony Sintes
```
public void tricky(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}
"Output
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0"
```
*tricky* successfully changes the value of pnt1!
This would imply that Objects are passed by reference, this is not the case!
A correct statement would be: **the *Object references* are passed by value.**
more from Tony Sintes:
>
> The method successfully alters the
> value of pnt1, even though it is
> passed by value; however, a swap of
> pnt1 and pnt2 fails! This is the major
> source of confusion. In the main()
> method, pnt1 and pnt2 are nothing more
> than object references. When you pass
> pnt1 and pnt2 to the tricky() method,
> Java passes the references by value
> just like any other parameter. This
> means the references passed to the
> method are actually copies of the
> original references. Figure 1 below
> shows two references pointing to the
> same object after Java passes an
> object to a method.
>
>
>
[](https://i.stack.imgur.com/EXPyo.gif)
(source: [javaworld.com](http://www.javaworld.com/javaworld/javaqa/2000-05/images/03-qa-0512-pass2b.gif))
**Conclusion** or a long story short:
* Java passes it parameters **by value**
* *"by value"* is the **only way** in java to pass a parameter to a method
* using *methods from the object* given as parameter **will alter** the object as the references point to the original objects. (if that method itself alters some values)
useful links:
* <http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html>
* <http://www.ibm.com/developerworks/java/library/j-passbyval/>
* <http://www.ibm.com/developerworks/library/j-praxis/pr1.html>
* <http://javadude.com/articles/passbyvalue.htm> |
2,056 | <p>When looking beyond the <a href="https://en.wikipedia.org/wiki/Rapid_application_development" rel="noreferrer">RAD</a> (drag-drop and configure) way of building user interfaces that many tools encourage you are likely to come across three design patterns called <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="noreferrer">Model-View-Controller</a>, <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter" rel="noreferrer">Model-View-Presenter</a> and <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel" rel="noreferrer">Model-View-ViewModel</a>. My question has three parts to it:</p>
<ol>
<li>What issues do these patterns address?</li>
<li>How are they similar?</li>
<li>How are they different?</li>
</ol>
| [
{
"answer_id": 2067,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 4,
"selected": false,
"text": "<p>Both of these frameworks aim to seperate concerns - for instance, interaction with a data source (model), application l... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/358/"
] | When looking beyond the [RAD](https://en.wikipedia.org/wiki/Rapid_application_development) (drag-drop and configure) way of building user interfaces that many tools encourage you are likely to come across three design patterns called [Model-View-Controller](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller), [Model-View-Presenter](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter) and [Model-View-ViewModel](http://en.wikipedia.org/wiki/Model_View_ViewModel). My question has three parts to it:
1. What issues do these patterns address?
2. How are they similar?
3. How are they different? | Model-View-Presenter
--------------------
In **MVP**, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to the Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed.
MVP tends to be a very natural pattern for achieving separated presentation in WebForms. The reason is that the View is always created first by the ASP.NET runtime. You can [find out more about both variants](https://web.archive.org/web/20071211153445/http://www.codeplex.com/websf/Wiki/View.aspx?title=MVPDocumentation).
### Two primary variations
**Passive View:** The View is as dumb as possible and contains almost zero logic. A Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead, the View exposes setter properties that the Presenter uses to set the data. All state is managed in the Presenter and not the View.
* Pro: maximum testability surface; clean separation of the View and Model
* Con: more work (for example all the setter properties) as you are doing all the data binding yourself.
**Supervising Controller:** The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.
* Pro: by leveraging data binding the amount of code is reduced.
* Con: there's a less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.
Model-View-Controller
---------------------
In the **MVC**, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web, each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application:
```
Action in the View
-> Call to Controller
-> Controller Logic
-> Controller returns the View.
```
One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called.
Presentation Model
------------------
One other pattern to look at is the **Presentation Model** pattern. In this pattern, there is no Presenter. Instead, the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behavior for the view. This pattern is a very strong candidate for use in WPF applications and is also called [Model-View-ViewModel](http://msdn.microsoft.com/en-us/magazine/dd419663.aspx).
There is a [MSDN article about the Presentation Model](http://msdn.microsoft.com/en-us/library/ff921080.aspx) and a section in the [Composite Application Guidance for WPF](http://msdn.microsoft.com/en-us/library/cc707819.aspx) (former Prism) about [Separated Presentation Patterns](http://msdn.microsoft.com/en-us/library/cc707862.aspx) |
2,120 | <p>I want to get the MD5 Hash of a string value in SQL Server 2005. I do this with the following command:</p>
<pre><code>SELECT HashBytes('MD5', 'HelloWorld')
</code></pre>
<p>However, this returns a VarBinary instead of a VarChar value. If I attempt to convert <code>0x68E109F0F40CA72A15E05CC22786F8E6</code> into a VarChar I get <code>há ðô§*à\Â'†øæ</code> instead of <code>68E109F0F40CA72A15E05CC22786F8E6</code>.</p>
<p>Is there any SQL-based solution?</p>
<p><strong><a href="https://stackoverflow.com/questions/2120/#2382">Yes</a></strong></p>
| [
{
"answer_id": 2382,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 8,
"selected": true,
"text": "<p>I have found the solution else where:</p>\n\n<pre><code>SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'Hel... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | I want to get the MD5 Hash of a string value in SQL Server 2005. I do this with the following command:
```
SELECT HashBytes('MD5', 'HelloWorld')
```
However, this returns a VarBinary instead of a VarChar value. If I attempt to convert `0x68E109F0F40CA72A15E05CC22786F8E6` into a VarChar I get `há ðô§*à\Â'†øæ` instead of `68E109F0F40CA72A15E05CC22786F8E6`.
Is there any SQL-based solution?
**[Yes](https://stackoverflow.com/questions/2120/#2382)** | I have found the solution else where:
```
SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32)
``` |
2,123 | <p><code>Checkboxes</code> in <code>HTML</code> forms don't have implicit <em>labels</em> with them. Adding an explicit label (some text) next to it doesn't toggle the <code>checkbox</code>.</p>
<p><strong>How do I make a checkbox toggle from clicking on the text label as well?</strong></p>
| [
{
"answer_id": 2133,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 6,
"selected": false,
"text": "<p>If you correctly markup your HTML code, there is no need for javascript. The following code will allow the user to click o... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193/"
] | `Checkboxes` in `HTML` forms don't have implicit *labels* with them. Adding an explicit label (some text) next to it doesn't toggle the `checkbox`.
**How do I make a checkbox toggle from clicking on the text label as well?** | Set the CSS `display` property for the label to be a block element and use that instead of your div - it keeps the semantic meaning of a label while allowing whatever styling you like.
For example:
```css
label {
width: 100px;
height: 100px;
display: block;
background-color: #e0e0ff;
}
```
```html
<label for="test">
A ticky box! <input type="checkbox" id="test" />
</label>
``` |
2,155 | <p>The web applications I develop often require co-dependent configuration settings and there are also settings that have to change as we move between each of our environments.</p>
<p>All our settings are currently simple key-value pairs but it would be useful to create custom config sections so that it is obvious when two values need to change together or when the settings need to change for an environment.</p>
<p>What's the best way to create custom config sections and are there any special considerations to make when retrieving the values?</p>
| [
{
"answer_id": 2178,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 2,
"selected": false,
"text": "<p>You can accomplish this with Section Handlers. There is a basic overview of how to write one at <a href=\"http://www.code... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/371/"
] | The web applications I develop often require co-dependent configuration settings and there are also settings that have to change as we move between each of our environments.
All our settings are currently simple key-value pairs but it would be useful to create custom config sections so that it is obvious when two values need to change together or when the settings need to change for an environment.
What's the best way to create custom config sections and are there any special considerations to make when retrieving the values? | **Using attributes, child config sections and constraints**
There is also the possibility to use attributes which automatically takes care of the plumbing, as well as providing the ability to easily add constraints.
I here present an example from code I use myself in one of my sites. With a constraint I dictate the maximum amount of disk space any one user is allowed to use.
MailCenterConfiguration.cs:
```
namespace Ani {
public sealed class MailCenterConfiguration : ConfigurationSection
{
[ConfigurationProperty("userDiskSpace", IsRequired = true)]
[IntegerValidator(MinValue = 0, MaxValue = 1000000)]
public int UserDiskSpace
{
get { return (int)base["userDiskSpace"]; }
set { base["userDiskSpace"] = value; }
}
}
}
```
This is set up in web.config like so
```
<configSections>
<!-- Mailcenter configuration file -->
<section name="mailCenter" type="Ani.MailCenterConfiguration" requirePermission="false"/>
</configSections>
...
<mailCenter userDiskSpace="25000">
<mail
host="my.hostname.com"
port="366" />
</mailCenter>
```
**Child elements**
The child xml element *mail* is created in the same .cs file as the one above. Here I've added constraints on the port. If the port is assigned a value not in this range the runtime will complain when the config is loaded.
MailCenterConfiguration.cs:
```
public sealed class MailCenterConfiguration : ConfigurationSection
{
[ConfigurationProperty("mail", IsRequired=true)]
public MailElement Mail
{
get { return (MailElement)base["mail"]; }
set { base["mail"] = value; }
}
public class MailElement : ConfigurationElement
{
[ConfigurationProperty("host", IsRequired = true)]
public string Host
{
get { return (string)base["host"]; }
set { base["host"] = value; }
}
[ConfigurationProperty("port", IsRequired = true)]
[IntegerValidator(MinValue = 0, MaxValue = 65535)]
public int Port
{
get { return (int)base["port"]; }
set { base["port"] = value; }
}
```
**Use**
To then use it practically in code, all you have to do is instantiate the MailCenterConfigurationObject, this will **automatically** read the relevant sections from web.config.
MailCenterConfiguration.cs
```
private static MailCenterConfiguration instance = null;
public static MailCenterConfiguration Instance
{
get
{
if (instance == null)
{
instance = (MailCenterConfiguration)WebConfigurationManager.GetSection("mailCenter");
}
return instance;
}
}
```
AnotherFile.cs
```
public void SendMail()
{
MailCenterConfiguration conf = MailCenterConfiguration.Instance;
SmtpClient smtpClient = new SmtpClient(conf.Mail.Host, conf.Mail.Port);
}
```
**Check for validity**
I previously mentioned that the runtime will complain when the configuration is loaded and some data does not comply to the rules you have set up (e.g. in MailCenterConfiguration.cs). I tend to want to know these things as soon as possible when my site fires up. One way to solve this is load the configuration in \_Global.asax.cx.Application\_Start\_ , if the configuration is invalid you will be notified of this with the means of an exception. Your site won't start and instead you will be presented detailed exception information in the [Yellow screen of death](http://www.codinghorror.com/blog/images/yellow-screen-of-death-large.png).
Global.asax.cs
```
protected void Application_ Start(object sender, EventArgs e)
{
MailCenterConfiguration.Instance;
}
``` |
2,158 | <p>Is there a way to create a <code>JButton</code> with your own button graphic and not just with an image inside the button? </p>
<p>If not, is there another way to create a custom <code>JButton</code> in java?</p>
| [
{
"answer_id": 2181,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 3,
"selected": false,
"text": "<p>I haven't done SWING development since my early CS classes but if it wasn't built in you could just inherit <code>javax.s... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340/"
] | Is there a way to create a `JButton` with your own button graphic and not just with an image inside the button?
If not, is there another way to create a custom `JButton` in java? | When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one `JPanel`. The benefit of extending `Swing` components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a `paint()` method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you.
Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the `DiceContainer` below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value.



Here are the basic steps:
1. Create a class that extends `JComponent`
2. Call parent constructor `super()` in your constructors
3. Make sure you class implements `MouseListener`
4. Put this in the constructor:
```
enableInputMethods(true);
addMouseListener(this);
```
5. Override these methods:
```
public Dimension getPreferredSize()
public Dimension getMinimumSize()
public Dimension getMaximumSize()
```
6. Override this method:
```
public void paintComponent(Graphics g)
```
The amount of space you have to work with when drawing your button is defined by `getPreferredSize()`, assuming `getMinimumSize()` and `getMaximumSize()` return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different.
And finally, the [source code](https://github.com/kdeloach/labs/blob/master/java/yahtzee/src/Dice.java). In case I missed anything. |
2,196 | <p>I've got a web application that I'm trying to optimize. Some of the controls are hidden in dialog-style <code>DIVs</code>. So, I'd like to have them load in via AJAX only when the user wants to see them. This is fine for controls that are mostly literal-based (various menus and widgets), but when I have what I call "dirty" controls - ones that write extensive information to the <code>ViewState</code>, put tons of CSS or script on the page, require lots of references, etc - these are seemingly impossible to move "out of page", especially considering how ASP.NET will react on postback.</p>
<p>I was considering some kind of step where I override Render, find markers for the bits I want to move out and put AJAX placeholders in there, but not only does the server overhead seem extreme, it also feels like a complete hack. Besides, the key element here is the dialog boxes that contain forms with validation controls on them, and I can't imagine how I would move the controls <em>and</em> their required scripts.</p>
<p><strong>In my fevered imagination, I want to do this:</strong></p>
<pre><code>AJAXifier.AJAXify(ctlEditForm);
</code></pre>
<p>Sadly, I know this is a dream. </p>
<p>How close can I really get to a quick-and-easy AJAXification without causing too much load on the server?</p>
| [
{
"answer_id": 2372,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 1,
"selected": false,
"text": "<p>Step one is to make your \"dirty\" pieces self contained user controls</p>\n\n<p>Step two is to embed those controls on you... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] | I've got a web application that I'm trying to optimize. Some of the controls are hidden in dialog-style `DIVs`. So, I'd like to have them load in via AJAX only when the user wants to see them. This is fine for controls that are mostly literal-based (various menus and widgets), but when I have what I call "dirty" controls - ones that write extensive information to the `ViewState`, put tons of CSS or script on the page, require lots of references, etc - these are seemingly impossible to move "out of page", especially considering how ASP.NET will react on postback.
I was considering some kind of step where I override Render, find markers for the bits I want to move out and put AJAX placeholders in there, but not only does the server overhead seem extreme, it also feels like a complete hack. Besides, the key element here is the dialog boxes that contain forms with validation controls on them, and I can't imagine how I would move the controls *and* their required scripts.
**In my fevered imagination, I want to do this:**
```
AJAXifier.AJAXify(ctlEditForm);
```
Sadly, I know this is a dream.
How close can I really get to a quick-and-easy AJAXification without causing too much load on the server? | Check out the [RadAjax](http://www.telerik.com/products/aspnet-ajax/controls/ajax/overview.aspx) control from Telerik - it allows you to avoid using UpdatePanels, and limit the amount of info passed back and forth between server and client by declaring direct relationships between calling controls, and controls that should be "Ajaxified" when the calling controls submit postbacks. |
2,209 | <p>I specifically want to add the style of <code>background-color</code> to the <code><body></code> tag of a master page, from the code behind (C#) of a content page that uses that master page. </p>
<p>I have different content pages that need to make the master page has different colors depending on which content page is loaded, so that the master page matches the content page's theme.</p>
<p>I have a solution below:</p>
<hr>
<p>I'm looking for something more like:</p>
<pre><code>Master.Attributes.Add("style", "background-color: 2e6095");
</code></pre>
<p>Inside of the page load function of the content page. But I can't get the above line to work. I only need to change the <code>background-color</code> for the <code><body></code> tag of the page.</p>
| [
{
"answer_id": 2212,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<p>I believe you are talking about a content management system. The way I have delt with this situation in the past is to eit... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396/"
] | I specifically want to add the style of `background-color` to the `<body>` tag of a master page, from the code behind (C#) of a content page that uses that master page.
I have different content pages that need to make the master page has different colors depending on which content page is loaded, so that the master page matches the content page's theme.
I have a solution below:
---
I'm looking for something more like:
```
Master.Attributes.Add("style", "background-color: 2e6095");
```
Inside of the page load function of the content page. But I can't get the above line to work. I only need to change the `background-color` for the `<body>` tag of the page. | What I would do for the particular case is:
i. Define the body as a server side control
```
<body runat="server" id="masterpageBody">
```
ii. In your content aspx page, register the MasterPage with the register:
```
<% MasterPageFile="..." %>
```
iii. In the Content Page, you can now simply use
```
Master.FindControl("masterpageBody")
```
and have access to the control. Now, you can change whatever properties/style that you like! |
2,222 | <p>I'm currently working on an application with a frontend written in Adobe Flex 3. I'm aware of <a href="http://code.google.com/p/as3flexunitlib/" rel="noreferrer">FlexUnit</a> but what I'd really like is a unit test runner for Ant/NAnt and a runner that integrates with the Flex Builder IDE (AKA Eclipse). Does one exist? </p>
<p>Also, are there any other resources on how to do Flex development "the right way" besides the <a href="http://labs.adobe.com/wiki/index.php/Cairngorm" rel="noreferrer">Cairngorm microarchitecture</a> example?</p>
| [
{
"answer_id": 8753,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 4,
"selected": true,
"text": "<p>The <a href=\"http://code.google.com/p/dpuint/\" rel=\"noreferrer\">dpUint</a> testing framework has a test runner built with A... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/266/"
] | I'm currently working on an application with a frontend written in Adobe Flex 3. I'm aware of [FlexUnit](http://code.google.com/p/as3flexunitlib/) but what I'd really like is a unit test runner for Ant/NAnt and a runner that integrates with the Flex Builder IDE (AKA Eclipse). Does one exist?
Also, are there any other resources on how to do Flex development "the right way" besides the [Cairngorm microarchitecture](http://labs.adobe.com/wiki/index.php/Cairngorm) example? | The [dpUint](http://code.google.com/p/dpuint/) testing framework has a test runner built with AIR which can be integrated with a build script.
There is also my [FlexUnit](http://developer.iconara.net/objectlib/flexunitautomation.html) automation kit which does more or less the same for FlexUnit. It has an Ant macro that makes it possible to run the tests as a part of an Ant script, for example:
```
<target name="run-tests" depends="compile-tests">
<flexunit swf="${build.home}/tests.swf" failonerror="true"/>
</target>
``` |
2,232 | <p>How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?</p>
| [
{
"answer_id": 2280,
"author": "Steve Willard",
"author_id": 402,
"author_profile": "https://Stackoverflow.com/users/402",
"pm_score": 5,
"selected": false,
"text": "<p>I'm definitely not a Ruby expert, but I'll give it a shot:</p>\n\n<pre><code>$ irb \nsystem \"echo Hi\"\nHi\n=> true... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25/"
] | How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby? | This explanation is based on a commented [Ruby script](http://gist.github.com/4069) from a friend of mine. If you want to improve the script, feel free to update it at the link.
First, note that when Ruby calls out to a shell, it typically calls `/bin/sh`, *not* Bash. Some Bash syntax is not supported by `/bin/sh` on all systems.
Here are ways to execute a shell script:
```
cmd = "echo 'hi'" # Sample string that can be used
```
1. `Kernel#`` , commonly called backticks – ``cmd``
This is like many other languages, including Bash, PHP, and Perl.
Returns the result (i.e. standard output) of the shell command.
Docs: <http://ruby-doc.org/core/Kernel.html#method-i-60>
```
value = `echo 'hi'`
value = `#{cmd}`
```
2. Built-in syntax, `%x( cmd )`
Following the `x` character is a delimiter, which can be any character.
If the delimiter is one of the characters `(`, `[`, `{`, or `<`,
the literal consists of the characters up to the matching closing delimiter,
taking account of nested delimiter pairs. For all other delimiters, the
literal comprises the characters up to the next occurrence of the
delimiter character. String interpolation `#{ ... }` is allowed.
Returns the result (i.e. standard output) of the shell command, just like the backticks.
Docs: <https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings>
```
value = %x( echo 'hi' )
value = %x[ #{cmd} ]
```
3. `Kernel#system`
Executes the given command in a subshell.
Returns `true` if the command was found and run successfully, `false` otherwise.
Docs: <http://ruby-doc.org/core/Kernel.html#method-i-system>
```
wasGood = system( "echo 'hi'" )
wasGood = system( cmd )
```
4. `Kernel#exec`
Replaces the current process by running the given external command.
Returns none, the current process is replaced and never continues.
Docs: <http://ruby-doc.org/core/Kernel.html#method-i-exec>
```
exec( "echo 'hi'" )
exec( cmd ) # Note: this will never be reached because of the line above
```
Here's some extra advice:
`$?`, which is the same as `$CHILD_STATUS`, accesses the status of the last system executed command if you use the backticks, `system()` or `%x{}`.
You can then access the `exitstatus` and `pid` properties:
```
$?.exitstatus
```
For more reading see:
* <http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands>
* <http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html>
* <http://tech.natemurray.com/2007/03/ruby-shell-commands.html> |
2,256 | <p>Is there a way of mapping data collected on a stream or array to a data structure or vice-versa?
In C++ this would simply be a matter of casting a pointer to the stream as a data type I want to use (or vice-versa for the reverse)
eg: in C++</p>
<pre><code>Mystruct * pMyStrct = (Mystruct*)&SomeDataStream;
pMyStrct->Item1 = 25;
int iReadData = pMyStrct->Item2;
</code></pre>
<p>obviously the C++ way is pretty unsafe unless you are sure of the quality of the stream data when reading incoming data, but for outgoing data is super quick and easy.</p>
| [
{
"answer_id": 2294,
"author": "gil",
"author_id": 195,
"author_profile": "https://Stackoverflow.com/users/195",
"pm_score": 2,
"selected": false,
"text": "<p>if its .net on both sides:</p>\n\n<p>think you should use binary serialization and send the byte[] result.</p>\n\n<p>trusting you... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/379/"
] | Is there a way of mapping data collected on a stream or array to a data structure or vice-versa?
In C++ this would simply be a matter of casting a pointer to the stream as a data type I want to use (or vice-versa for the reverse)
eg: in C++
```
Mystruct * pMyStrct = (Mystruct*)&SomeDataStream;
pMyStrct->Item1 = 25;
int iReadData = pMyStrct->Item2;
```
obviously the C++ way is pretty unsafe unless you are sure of the quality of the stream data when reading incoming data, but for outgoing data is super quick and easy. | Most people use .NET serialization (there is faster binary and slower XML formatter, they both depend on reflection and are version tolerant to certain degree)
However, if you want the fastest (unsafe) way - why not:
Writing:
```
YourStruct o = new YourStruct();
byte[] buffer = new byte[Marshal.SizeOf(typeof(YourStruct))];
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
Marshal.StructureToPtr(o, handle.AddrOfPinnedObject(), false);
handle.Free();
```
Reading:
```
handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
o = (YourStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(YourStruct));
handle.Free();
``` |
2,262 | <p>How do I rewrite a URL in ASP.NET?</p>
<p>I would like users to be able to go to</p>
<pre><code>http://www.website.com/users/smith
</code></pre>
<p>instead of</p>
<pre><code>http://www.website.com/?user=smith
</code></pre>
| [
{
"answer_id": 2268,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 6,
"selected": true,
"text": "<p>Try the Managed Fusion Url Rewriter and Reverse Proxy:</p>\n\n<p><a href=\"http://urlrewriter.codeplex.com\" rel=\"noreferr... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | How do I rewrite a URL in ASP.NET?
I would like users to be able to go to
```
http://www.website.com/users/smith
```
instead of
```
http://www.website.com/?user=smith
``` | Try the Managed Fusion Url Rewriter and Reverse Proxy:
<http://urlrewriter.codeplex.com>
The rule for rewriting this would be:
```
# clean up old rules and forward to new URL
RewriteRule ^/?user=(.*) /users/$1 [NC,R=301]
# rewrite the rule internally
RewriteRule ^/users/(.*) /?user=$1 [NC,L]
``` |
2,267 | <p>I am building a web page to show a customer what software they purchased and to give them a link to download said software. Unfortunately, the data on what was purchased and the download information are in separate databases so I can't just take care of it with joins in an SQL query.</p>
<p>The common item is SKU. I'll be pulling a list of SKUs from the customer purchases database and on the download table is a comma delineated list of SKUs associated with that download. My intention, at the moment, is to create from this one datatable to populate a <code>GridView</code>.</p>
<p>Any suggestions on how to do this efficiently would be appreciated. If it helps, I can pretty easily pull back the data as a <code>DataSet</code> or a <code>DataReader</code>, if either one would be better for this purpose.</p>
| [
{
"answer_id": 2283,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 0,
"selected": false,
"text": "<p>I am thinking off the top of my head here. If you load both as Data Tables in the same Data Sets, and define a relation betwe... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/111/"
] | I am building a web page to show a customer what software they purchased and to give them a link to download said software. Unfortunately, the data on what was purchased and the download information are in separate databases so I can't just take care of it with joins in an SQL query.
The common item is SKU. I'll be pulling a list of SKUs from the customer purchases database and on the download table is a comma delineated list of SKUs associated with that download. My intention, at the moment, is to create from this one datatable to populate a `GridView`.
Any suggestions on how to do this efficiently would be appreciated. If it helps, I can pretty easily pull back the data as a `DataSet` or a `DataReader`, if either one would be better for this purpose. | As long as the two databases are on the same physical server (assuming MSSQL) and the username/password being used in the connection string has rights to both DBs, then you should be able to perform a join across the two databases. Example:
```
select p.Date,
p.Amount,
d.SoftwareName,
d.DownloadLink
from PurchaseDB.dbo.Purchases as p
join ProductDB.dbo.Products as d on d.sku = p.sku
where p.UserID = 12345
``` |
2,300 | <p>I want to be able to do:</p>
<pre><code>For Each thing In things
End For
</code></pre>
<p>CLASSIC ASP - NOT .NET!</p>
| [
{
"answer_id": 2312,
"author": "Brett Veenstra",
"author_id": 307,
"author_profile": "https://Stackoverflow.com/users/307",
"pm_score": 3,
"selected": true,
"text": "<p>Whatever your [things] are need to be written outside of VBScript.</p>\n\n<p>In VB6, <a href=\"http://www.vb-helper.com... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193/"
] | I want to be able to do:
```
For Each thing In things
End For
```
CLASSIC ASP - NOT .NET! | Whatever your [things] are need to be written outside of VBScript.
In VB6, [you can write a Custom Collection class](http://www.vb-helper.com/howto_custom_collection_with_for_each.html), then you'll need to compile to an ActiveX DLL and register it on your webserver to access it. |
2,311 | <p>I have created a PHP-script to update a web server that is live inside a local directory.
I'm migrating the script into Python. It works fine for the most part, but after a PUT command, the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. </p>
<p>Once I download again the file from the FTP server, the only difference is the CR/LF mark. This annoys me because the same script is comparing the size of the files to update. Also, in case it means anything, the script works perfectly in PHP vía ftp_put.</p>
<pre><code>from ftplib import FTP
ftpserver = "myserver"
ftpuser = "myuser"
ftppass = "mypwd"
locfile = "g:/test/style.css"
ftpfile = "/temp/style.css"
try:
ftp = FTP(ftpserver, ftpuser, ftppass)
except:
exit ("Cannot connect")
f = open (locfile, "r")
try:
ftp.delete (ftpfile)
except:
pass
# ftp.sendcmd ("TYPE I")
# ftp.storlines("STOR %s" % ftpfile, f)
ftp.storbinary("STOR %s" % ftpfile, f)
f.close()
ftp.dir (ftpfile)
ftp.quit()
</code></pre>
<p>Any suggestions?</p>
| [
{
"answer_id": 2316,
"author": "David Sykes",
"author_id": 259,
"author_profile": "https://Stackoverflow.com/users/259",
"pm_score": 5,
"selected": true,
"text": "<p>Do you need to open the locfile in binary using <code>rb</code>?</p>\n\n<pre><code>f = open (locfile, \"rb\")\n</code></pr... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/394/"
] | I have created a PHP-script to update a web server that is live inside a local directory.
I'm migrating the script into Python. It works fine for the most part, but after a PUT command, the size of the file appears to change. Thus, the size of the file is different from that of the file on the server.
Once I download again the file from the FTP server, the only difference is the CR/LF mark. This annoys me because the same script is comparing the size of the files to update. Also, in case it means anything, the script works perfectly in PHP vía ftp\_put.
```
from ftplib import FTP
ftpserver = "myserver"
ftpuser = "myuser"
ftppass = "mypwd"
locfile = "g:/test/style.css"
ftpfile = "/temp/style.css"
try:
ftp = FTP(ftpserver, ftpuser, ftppass)
except:
exit ("Cannot connect")
f = open (locfile, "r")
try:
ftp.delete (ftpfile)
except:
pass
# ftp.sendcmd ("TYPE I")
# ftp.storlines("STOR %s" % ftpfile, f)
ftp.storbinary("STOR %s" % ftpfile, f)
f.close()
ftp.dir (ftpfile)
ftp.quit()
```
Any suggestions? | Do you need to open the locfile in binary using `rb`?
```
f = open (locfile, "rb")
``` |
2,348 | <p>In the code below</p>
<pre><code>For i = LBound(arr) To UBound(arr)
</code></pre>
<p>What is the point in asking using <code>LBound</code>? Surely that is always 0.</p>
| [
{
"answer_id": 2378,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 2,
"selected": false,
"text": "<p>Probably it comes from VB6. Because with <a href=\"http://msdn.microsoft.com/en-us/library/aa266179(VS.60).aspx\" rel=\"nofoll... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193/"
] | In the code below
```
For i = LBound(arr) To UBound(arr)
```
What is the point in asking using `LBound`? Surely that is always 0. | Why not use `For Each`? That way you don't need to care what the `LBound` and `UBound` are.
```
Dim x, y, z
x = Array(1, 2, 3)
For Each y In x
z = DoSomethingWith(y)
Next
``` |
2,384 | <p>I'm trying to read binary data using C#. I have all the information about the layout of the data in the files I want to read. I'm able to read the data "chunk by chunk", i.e. getting the first 40 bytes of data converting it to a string, get the next 40 bytes.</p>
<p>Since there are at least three slightly different version of the data, I would like to read the data directly into a struct. It just feels so much more right than by reading it "line by line".</p>
<p><strong>I have tried the following approach but to no avail:</strong></p>
<pre><code>StructType aStruct;
int count = Marshal.SizeOf(typeof(StructType));
byte[] readBuffer = new byte[count];
BinaryReader reader = new BinaryReader(stream);
readBuffer = reader.ReadBytes(count);
GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned);
aStruct = (StructType) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(StructType));
handle.Free();
</code></pre>
<p>The stream is an opened FileStream from which I have began to read from. I get an <code>AccessViolationExceptio</code>n when using <code>Marshal.PtrToStructure</code>.</p>
<p>The stream contains more information than I'm trying to read since I'm not interested in data at the end of the file.</p>
<p><strong>The struct is defined like:</strong></p>
<pre><code>[StructLayout(LayoutKind.Explicit)]
struct StructType
{
[FieldOffset(0)]
public string FileDate;
[FieldOffset(8)]
public string FileTime;
[FieldOffset(16)]
public int Id1;
[FieldOffset(20)]
public string Id2;
}
</code></pre>
<p>The examples code is changed from original to make this question shorter.</p>
<p>How would I read binary data from a file into a struct?</p>
| [
{
"answer_id": 2436,
"author": "urini",
"author_id": 373,
"author_profile": "https://Stackoverflow.com/users/373",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>using (FileStream stream = new FileStream(fileName, FileMode.Open))\n{\n BinaryFormatter formatt... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143/"
] | I'm trying to read binary data using C#. I have all the information about the layout of the data in the files I want to read. I'm able to read the data "chunk by chunk", i.e. getting the first 40 bytes of data converting it to a string, get the next 40 bytes.
Since there are at least three slightly different version of the data, I would like to read the data directly into a struct. It just feels so much more right than by reading it "line by line".
**I have tried the following approach but to no avail:**
```
StructType aStruct;
int count = Marshal.SizeOf(typeof(StructType));
byte[] readBuffer = new byte[count];
BinaryReader reader = new BinaryReader(stream);
readBuffer = reader.ReadBytes(count);
GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned);
aStruct = (StructType) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(StructType));
handle.Free();
```
The stream is an opened FileStream from which I have began to read from. I get an `AccessViolationExceptio`n when using `Marshal.PtrToStructure`.
The stream contains more information than I'm trying to read since I'm not interested in data at the end of the file.
**The struct is defined like:**
```
[StructLayout(LayoutKind.Explicit)]
struct StructType
{
[FieldOffset(0)]
public string FileDate;
[FieldOffset(8)]
public string FileTime;
[FieldOffset(16)]
public int Id1;
[FieldOffset(20)]
public string Id2;
}
```
The examples code is changed from original to make this question shorter.
How would I read binary data from a file into a struct? | The problem is the **string**s in your struct. I found that marshaling types like byte/short/int is not a problem; but when you need to marshal into a complex type such as a string, you need your struct to explicitly mimic an unmanaged type. You can do this with the MarshalAs attrib.
For your example, the following should work:
```
[StructLayout(LayoutKind.Explicit)]
struct StructType
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
public string FileDate;
[FieldOffset(8)]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
public string FileTime;
[FieldOffset(16)]
public int Id1;
[FieldOffset(20)]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 66)] //Or however long Id2 is.
public string Id2;
}
``` |
2,483 | <p>What is actually the difference between these two casts?</p>
<pre><code>SomeClass sc = (SomeClass)SomeObject;
SomeClass sc2 = SomeObject as SomeClass;
</code></pre>
<p>Normally, shouldn't they both be explicit casts to the specified type?</p>
| [
{
"answer_id": 2487,
"author": "Rytmis",
"author_id": 266,
"author_profile": "https://Stackoverflow.com/users/266",
"pm_score": 7,
"selected": true,
"text": "<p>The former will throw an exception if the source type can't be cast to the target type. The latter will result in sc2 being a n... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | What is actually the difference between these two casts?
```
SomeClass sc = (SomeClass)SomeObject;
SomeClass sc2 = SomeObject as SomeClass;
```
Normally, shouldn't they both be explicit casts to the specified type? | The former will throw an exception if the source type can't be cast to the target type. The latter will result in sc2 being a null reference, but no exception.
[Edit]
My original answer is certainly the most pronounced difference, but as Eric Lippert [points out](http://blogs.msdn.com/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx), it's not the only one. Other differences include:
* You can't use the 'as' operator to cast to a type that doesn't accept 'null' as a value
* You can't use 'as' to *convert* things, like numbers to a different representation (float to int, for example).
And finally, using 'as' vs. the cast operator, you're also saying "I'm not sure if this will succeed." |
2,509 | <p>Test Driven Development has been the rage in the .NET community for the last few years. Recently, I have heard grumblings in the ALT.NET community about BDD. What is it? What makes it different from TDD?</p>
| [
{
"answer_id": 2515,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 2,
"selected": false,
"text": "<p>Behaviour Driven Development seems to focus more on the interaction and communication between Developers and also between ... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/303/"
] | Test Driven Development has been the rage in the .NET community for the last few years. Recently, I have heard grumblings in the ALT.NET community about BDD. What is it? What makes it different from TDD? | I understand BDD to be more about **specification** than **testing**. It is linked to Domain Driven Design (don't you love these \*DD acronyms?).
It is linked with a certain way to write user stories, including high-level tests. An example by [Tom ten Thij](http://tomtenthij.nl/2008/1/25/rspec-plain-text-story-runner-on-a-fresh-rails-app):
```
Story: User logging in
As a user
I want to login with my details
So that I can get access to the site
Scenario: User uses wrong password
Given a username 'jdoe'
And a password 'letmein'
When the user logs in with username and password
Then the login form should be shown again
```
(In his article, Tom goes on to directly execute this test specification in Ruby.)
The pope of BDD is [Dan North](http://dannorth.net/). You'll find a great introduction in his [Introducing BDD](http://dannorth.net/introducing-bdd) article.
You will find a comparison of BDD and TDD in this [video](http://video.google.com/videoplay?docid=8135690990081075324). Also an opinion about BDD as "TDD done right" by [Jeremy D. Miller](http://codebetter.com/blogs/jeremy.miller/archive/2007/09/06/bdd-tdd-and-the-other-double-d-s.aspx)
**March 25, 2013 update**
The video above has been missing for a while. Here is a recent one by Llewellyn Falco, [BDD vs TDD (explained)](https://www.youtube.com/watch?v=mT8QDNNhExg). I find his explanation clear and to the point. |
2,518 | <p>I have 2 SQLite databases, one downloaded from a server (<code>server.db</code>), and one used as storage on the client (<code>client.db</code>). I need to perform various sync queries on the client database, using data from the server database.</p>
<p>For example, I want to delete all rows in the <code>client.db tRole</code> table, and repopulate with all rows in the <code>server.db tRole</code> table.</p>
<p>Another example, I want to delete all rows in the <code>client.db tFile</code> table where the <code>fileID</code> is not in the <code>server.db tFile</code> table.</p>
<p>In SQL Server you can just prefix the table with the name of the database. Is there anyway to do this in SQLite using Adobe Air?</p>
| [
{
"answer_id": 8783,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 2,
"selected": false,
"text": "<p>It's possible to open multiple databases at once in SQLite, but it's doubtful if can be done when working from Flex/AIR. In th... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] | I have 2 SQLite databases, one downloaded from a server (`server.db`), and one used as storage on the client (`client.db`). I need to perform various sync queries on the client database, using data from the server database.
For example, I want to delete all rows in the `client.db tRole` table, and repopulate with all rows in the `server.db tRole` table.
Another example, I want to delete all rows in the `client.db tFile` table where the `fileID` is not in the `server.db tFile` table.
In SQL Server you can just prefix the table with the name of the database. Is there anyway to do this in SQLite using Adobe Air? | I just looked at the AIR SQL API, and there's an `attach` method on `SQLConnection` it looks exactly what you need.
I haven't tested this, but according to the documentation it should work:
```
var connection : SQLConnection = new SQLConnection();
connection.open(firstDbFile);
connection.attach(secondDbFile, "otherDb");
var statement : SQLStatement = new SQLStatement();
statement.connection = connection;
statement.text = "INSERT INTO main.myTable SELECT * FROM otherDb.myTable";
statement.execute();
```
There may be errors in that code snippet, I haven't worked much with the AIR SQL API lately. Notice that the tables of the database opened with `open` are available using `main.tableName`, any attached database can be given any name at all (`otherDb` in the example above). |
2,527 | <p>How can I find out which node in a tree list the context menu has been activated? For instance right-clicking a node and selecting an option from the menu. </p>
<p>I can't use the TreeViews' <code>SelectedNode</code> property because the node is only been right-clicked and not selected.</p>
| [
{
"answer_id": 2546,
"author": "Jonesinator",
"author_id": 152,
"author_profile": "https://Stackoverflow.com/users/152",
"pm_score": 8,
"selected": true,
"text": "<p>You can add a mouse click event to the TreeView, then select the correct node using GetNodeAt given the mouse coordinates ... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428/"
] | How can I find out which node in a tree list the context menu has been activated? For instance right-clicking a node and selecting an option from the menu.
I can't use the TreeViews' `SelectedNode` property because the node is only been right-clicked and not selected. | You can add a mouse click event to the TreeView, then select the correct node using GetNodeAt given the mouse coordinates provided by the MouseEventArgs.
```
void treeView1MouseUp(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
// Select the clicked node
treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y);
if(treeView1.SelectedNode != null)
{
myContextMenuStrip.Show(treeView1, e.Location);
}
}
}
``` |
2,530 | <p>How do you disable autocomplete in the major browsers for a specific input (or form field)?</p>
| [
{
"answer_id": 2531,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 12,
"selected": true,
"text": "<p>Firefox 30 ignores <code>autocomplete="off"</code> for passwords, opting to prompt the user instead whether the p... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/307/"
] | How do you disable autocomplete in the major browsers for a specific input (or form field)? | Firefox 30 ignores `autocomplete="off"` for passwords, opting to prompt the user instead whether the password should be stored on the client. Note the following [commentary](https://bugzilla.mozilla.org/show_bug.cgi?id=956906#c100) from May 5, 2014:
>
> * The password manager *always* prompts if it wants to save a password. Passwords are not saved without permission from the user.
> * We are the third browser to implement this change, after IE and Chrome.
>
>
>
According to the [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion) documentation, the Boolean form element attribute `autocomplete` prevents form data from being cached in older browsers.
```
<input type="text" name="foo" autocomplete="off" />
``` |
2,647 | <p>Using SQL Server, how do I split a string so I can access item x?</p>
<p>Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?</p>
| [
{
"answer_id": 2657,
"author": "Jonesinator",
"author_id": 152,
"author_profile": "https://Stackoverflow.com/users/152",
"pm_score": 9,
"selected": true,
"text": "<p>You may find the solution in <em><a href=\"http://www.codeproject.com/KB/database/SQL_UDF_to_Parse_a_String.aspx\" rel=\"n... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | Using SQL Server, how do I split a string so I can access item x?
Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"? | You may find the solution in *[SQL User Defined Function to Parse a Delimited String](http://www.codeproject.com/KB/database/SQL_UDF_to_Parse_a_String.aspx)* helpful (from [The Code Project](http://en.wikipedia.org/wiki/The_Code_Project)).
You can use this simple logic:
```
Declare @products varchar(200) = '1|20|3|343|44|6|8765'
Declare @individual varchar(20) = null
WHILE LEN(@products) > 0
BEGIN
IF PATINDEX('%|%', @products) > 0
BEGIN
SET @individual = SUBSTRING(@products,
0,
PATINDEX('%|%', @products))
SELECT @individual
SET @products = SUBSTRING(@products,
LEN(@individual + '|') + 1,
LEN(@products))
END
ELSE
BEGIN
SET @individual = @products
SET @products = NULL
SELECT @individual
END
END
``` |
2,649 | <p>When writing a T-SQL script that I plan on re-running, often times I use temporary tables to store temporary data. Since the temp table is created on the fly, I'd like to be able to drop that table only if it exists (before I create it).</p>
<p>I'll post the method that I use, but I'd like to see if there is a better way.</p>
| [
{
"answer_id": 2652,
"author": "Nathan Bedford",
"author_id": 434,
"author_profile": "https://Stackoverflow.com/users/434",
"pm_score": 4,
"selected": false,
"text": "<p>The OBJECT_ID function returns the internal object id for the given object name and type. 'tempdb..#t1' refers to the... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/434/"
] | When writing a T-SQL script that I plan on re-running, often times I use temporary tables to store temporary data. Since the temp table is created on the fly, I'd like to be able to drop that table only if it exists (before I create it).
I'll post the method that I use, but I'd like to see if there is a better way. | ```
IF Object_Id('TempDB..#TempTable') IS NOT NULL
BEGIN
DROP TABLE #TempTable
END
``` |
2,658 | <p>I need to implement version control, even for just the developing I do at home. I have read about how great subversion is for the past couple of years and was about to dedicate myself to learning this on the side until I heard about Git being the up and coming version control system.</p>
<p>Given the situation, should I hold off and see which one comes out on top? What are their relative advantages?</p>
<p>One issue I noticed with Git is, there are not many full featured GUIs, which is important to many users on my team.</p>
<p>Also, wouldn't mind suggestions on how to get started with one or the other. (tutorials, etc.)</p>
| [
{
"answer_id": 2665,
"author": "Karl Seguin",
"author_id": 34,
"author_profile": "https://Stackoverflow.com/users/34",
"pm_score": 4,
"selected": false,
"text": "<p>Use subversion, it's easy to setup, easy to use, and has plenty of tools. Any future revision system will have an import fr... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/406/"
] | I need to implement version control, even for just the developing I do at home. I have read about how great subversion is for the past couple of years and was about to dedicate myself to learning this on the side until I heard about Git being the up and coming version control system.
Given the situation, should I hold off and see which one comes out on top? What are their relative advantages?
One issue I noticed with Git is, there are not many full featured GUIs, which is important to many users on my team.
Also, wouldn't mind suggestions on how to get started with one or the other. (tutorials, etc.) | The most important thing about version control is:
***JUST START USING IT***
Not using version control is a horrible idea. If you are not using version control, stop reading right now and start using it.
It is very easy to convert from
```
cvs<->svn<->git<->hg
```
It doesn't matter which one you choose. Just pick the easiest one for you to use and start recording the history of your code. You can always migrate to another (D)VCS later.
If you are looking for a easy to use GUI look at [TortoiseSVN (Windows)](http://tortoisesvn.tigris.org/%22TortoiseSVN%22) and [Versions (Mac)](http://www.versionsapp.com/) (Suggested by [codingwithoutcomments](https://stackoverflow.com/questions/2658?sort=newest#2708))
---
Edit:
>
> [pix0r said:](https://stackoverflow.com/questions/2658/#2672)
>
>
> Git has some nice features, but you won't be able to appreciate them unless you've already used something more standard like CVS or Subversion.
>
>
>
This. Using git is pointless if you don't know what version control can do for you.
Edit 2:
Just saw this link on reddit: [Subversion Cheat Sheet](http://www.addedbytes.com/cheat-sheets/subversion-cheat-sheet/). Good quick reference for the svn command line. |
2,702 | <p>I know I need to have (although I don't know why) a <code>GROUP BY</code> clause on the end of a SQL query that uses any aggregate functions like <code>count</code>, <code>sum</code>, <code>avg</code>, etc:</p>
<pre><code>SELECT count(userID), userName
FROM users
GROUP BY userName
</code></pre>
<p>When else would <code>GROUP BY</code> be useful, and what are the performance ramifications?</p>
| [
{
"answer_id": 2704,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 2,
"selected": false,
"text": "<p>Counting the number of times tags are used might be a google example:</p>\n\n<pre><code>SELECT TagName, Count(*)\nAS Times... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] | I know I need to have (although I don't know why) a `GROUP BY` clause on the end of a SQL query that uses any aggregate functions like `count`, `sum`, `avg`, etc:
```
SELECT count(userID), userName
FROM users
GROUP BY userName
```
When else would `GROUP BY` be useful, and what are the performance ramifications? | To retrieve the number of widgets from each widget category that has more than 5 widgets, you could do this:
```
SELECT WidgetCategory, count(*)
FROM Widgets
GROUP BY WidgetCategory
HAVING count(*) > 5
```
The "having" clause is something people often forget about, instead opting to retrieve all their data to the client and iterating through it there. |
2,714 | <p>I think most people know how to do this via the GUI (right click table, properties), but doing this in T-SQL totally rocks.</p>
| [
{
"answer_id": 2715,
"author": "Nathan Bedford",
"author_id": 434,
"author_profile": "https://Stackoverflow.com/users/434",
"pm_score": 5,
"selected": true,
"text": "<pre>\nCREATE TABLE #tmpSizeChar (\n table_name sysname ,\n row_count int,\n reserved_size varchar(50),\n ... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/434/"
] | I think most people know how to do this via the GUI (right click table, properties), but doing this in T-SQL totally rocks. | ```
CREATE TABLE #tmpSizeChar (
table_name sysname ,
row_count int,
reserved_size varchar(50),
data_size varchar(50),
index_size varchar(50),
unused_size varchar(50))
CREATE TABLE #tmpSizeInt (
table_name sysname ,
row_count int,
reserved_size_KB int,
data_size_KB int,
index_size_KB int,
unused_size_KB int)
SET NOCOUNT ON
INSERT #tmpSizeChar
EXEC sp_msforeachtable 'sp_spaceused ''?'''
INSERT INTO #tmpSizeInt (
table_name,
row_count,
reserved_size_KB,
data_size_KB,
index_size_KB,
unused_size_KB
)
SELECT [table_name],
row_count,
CAST(SUBSTRING(reserved_size, 0, PATINDEX('% %', reserved_size)) AS int)reserved_size,
CAST(SUBSTRING(data_size, 0, PATINDEX('% %', data_size)) AS int)data_size,
CAST(SUBSTRING(index_size, 0, PATINDEX('% %', index_size)) AS int)index_size,
CAST(SUBSTRING(unused_size, 0, PATINDEX('% %', unused_size)) AS int)unused_size
FROM #tmpSizeChar
/*
DROP TABLE #tmpSizeChar
DROP TABLE #tmpSizeInt
*/
SELECT * FROM #tmpSizeInt
ORDER BY reserved_size_KB DESC
``` |
2,732 | <p>Can anyone explain this behavior?
Running:</p>
<pre><code>#!/bin/sh
echo "hello world" | read var1 var2
echo $var1
echo $var2
</code></pre>
<p>results in nothing being ouput, while:</p>
<pre><code>#!/bin/sh
echo "hello world" > test.file
read var1 var2 < test.file
echo $var1
echo $var2
</code></pre>
<p>produces the expected output:</p>
<pre><code>hello
world
</code></pre>
<p>Shouldn't the pipe do in one step what the redirection to test.file did in the second example? I tried the same code with both the dash and bash shells and got the same behavior from both of them.</p>
| [
{
"answer_id": 2764,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 3,
"selected": false,
"text": "<p>It's because the pipe version is creating a subshell, which reads the variable into its local space which then is destr... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75/"
] | Can anyone explain this behavior?
Running:
```
#!/bin/sh
echo "hello world" | read var1 var2
echo $var1
echo $var2
```
results in nothing being ouput, while:
```
#!/bin/sh
echo "hello world" > test.file
read var1 var2 < test.file
echo $var1
echo $var2
```
produces the expected output:
```
hello
world
```
Shouldn't the pipe do in one step what the redirection to test.file did in the second example? I tried the same code with both the dash and bash shells and got the same behavior from both of them. | A recent addition to `bash` is the `lastpipe` option, which allows the last command in a pipeline to run in the current shell, not a subshell, when job control is deactivated.
```
#!/bin/bash
set +m # Deactiveate job control
shopt -s lastpipe
echo "hello world" | read var1 var2
echo $var1
echo $var2
```
will indeed output
```
hello
world
``` |
2,775 | <p>Here's what I use:</p>
<pre><code>SELECT CAST(FLOOR(CAST(getdate() as FLOAT)) as DATETIME)
</code></pre>
<p>I'm thinking there may be a better and more elegant way.</p>
<p>Requirements:</p>
<ul>
<li>It has to be as fast as possible (the less casting, the better).</li>
<li>The final result has to be a <code>datetime</code> type, not a string.</li>
</ul>
| [
{
"answer_id": 2781,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 4,
"selected": false,
"text": "<p>Your <code>CAST</code>-<code>FLOOR</code>-<code>CAST</code> already seems to be the optimum way, at least on MS SQL Server... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/434/"
] | Here's what I use:
```
SELECT CAST(FLOOR(CAST(getdate() as FLOAT)) as DATETIME)
```
I'm thinking there may be a better and more elegant way.
Requirements:
* It has to be as fast as possible (the less casting, the better).
* The final result has to be a `datetime` type, not a string. | **SQL Server 2008 and up**
In SQL Server 2008 and up, of course the fastest way is `Convert(date, @date)`. This can be cast back to a `datetime` or `datetime2` if necessary.
**What Is Really Best In SQL Server 2005 and Older?**
I've seen inconsistent claims about what's fastest for truncating the time from a date in SQL Server, and some people even said they did testing, but my experience has been different. So let's do some more stringent testing and let everyone have the script so if I make any mistakes people can correct me.
**Float Conversions Are Not Accurate**
First, I would stay away from converting `datetime` to `float`, because it does not convert correctly. You may get away with doing the time-removal thing accurately, but I think it's a bad idea to use it because it implicitly communicates to developers that this is a safe operation and **it is not**. Take a look:
```
declare @d datetime;
set @d = '2010-09-12 00:00:00.003';
select Convert(datetime, Convert(float, @d));
-- result: 2010-09-12 00:00:00.000 -- oops
```
This is not something we should be teaching people in our code or in our examples online.
Also, it is not even the fastest way!
**Proof – Performance Testing**
If you want to perform some tests yourself to see how the different methods really do stack up, then you'll need this setup script to run the tests farther down:
```
create table AllDay (Tm datetime NOT NULL CONSTRAINT PK_AllDay PRIMARY KEY CLUSTERED);
declare @d datetime;
set @d = DateDiff(Day, 0, GetDate());
insert AllDay select @d;
while @@ROWCOUNT != 0
insert AllDay
select * from (
select Tm =
DateAdd(ms, (select Max(DateDiff(ms, @d, Tm)) from AllDay) + 3, Tm)
from AllDay
) X
where Tm < DateAdd(Day, 1, @d);
exec sp_spaceused AllDay; -- 25,920,000 rows
```
Please note that this creates a 427.57 MB table in your database and will take something like 15-30 minutes to run. If your database is small and set to 10% growth it will take longer than if you size big enough first.
Now for the actual performance testing script. Please note that it's purposeful to not return rows back to the client as this is crazy expensive on 26 million rows and would hide the performance differences between the methods.
**Performance Results**
```
set statistics time on;
-- (All queries are the same on io: logical reads 54712)
GO
declare
@dd date,
@d datetime,
@di int,
@df float,
@dv varchar(10);
-- Round trip back to datetime
select @d = CONVERT(date, Tm) from AllDay; -- CPU time = 21234 ms, elapsed time = 22301 ms.
select @d = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 23031 ms, elapsed = 24091 ms.
select @d = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23782 ms, elapsed = 24818 ms.
select @d = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 36891 ms, elapsed = 38414 ms.
select @d = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 102984 ms, elapsed = 109897 ms.
select @d = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 103390 ms, elapsed = 108236 ms.
select @d = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 123375 ms, elapsed = 135179 ms.
-- Only to another type but not back
select @dd = Tm from AllDay; -- CPU time = 19891 ms, elapsed time = 20937 ms.
select @di = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 21453 ms, elapsed = 23079 ms.
select @di = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23218 ms, elapsed = 24700 ms
select @df = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 29312 ms, elapsed = 31101 ms.
select @dv = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 64016 ms, elapsed = 67815 ms.
select @dv = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 64297 ms, elapsed = 67987 ms.
select @dv = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 65609 ms, elapsed = 68173 ms.
GO
set statistics time off;
```
**Some Rambling Analysis**
Some notes about this. First of all, if just performing a GROUP BY or a comparison, there's no need to convert back to `datetime`. So you can save some CPU by avoiding that, unless you need the final value for display purposes. You can even GROUP BY the unconverted value and put the conversion only in the SELECT clause:
```
select Convert(datetime, DateDiff(dd, 0, Tm))
from (select '2010-09-12 00:00:00.003') X (Tm)
group by DateDiff(dd, 0, Tm)
```
Also, see how the numeric conversions only take slightly more time to convert back to `datetime`, but the `varchar` conversion almost doubles? This reveals the portion of the CPU that is devoted to date calculation in the queries. There are parts of the CPU usage that don't involve date calculation, and this appears to be something close to 19875 ms in the above queries. Then the conversion takes some additional amount, so if there are two conversions, that amount is used up approximately twice.
More examination reveals that compared to `Convert(, 112)`, the `Convert(, 101)` query has some additional CPU expense (since it uses a longer `varchar`?), because the second conversion back to `date` doesn't cost as much as the initial conversion to `varchar`, but with `Convert(, 112)` it is closer to the same 20000 ms CPU base cost.
Here are those calculations on the CPU time that I used for the above analysis:
```
method round single base
----------- ------ ------ -----
date 21324 19891 18458
int 23031 21453 19875
datediff 23782 23218 22654
float 36891 29312 21733
varchar-112 102984 64016 25048
varchar-101 123375 65609 7843
```
* *round* is the CPU time for a round trip back to `datetime`.
* *single* is CPU time for a single conversion to the alternate data type (the one that has the side effect of removing the time portion).
* *base* is the calculation of subtracting from `single` the difference between the two invocations: `single - (round - single)`. It's a ballpark figure that assumes the conversion to and from that data type and `datetime` is approximately the same in either direction. It appears this assumption is not perfect but is close because the values are all close to 20000 ms with only one exception.
One more interesting thing is that the base cost is nearly equal to the single `Convert(date)` method (which has to be almost 0 cost, as the server can internally extract the integer day portion right out of the first four bytes of the `datetime` data type).
**Conclusion**
So what it looks like is that the single-direction `varchar` conversion method takes about 1.8 μs and the single-direction `DateDiff` method takes about 0.18 μs. I'm basing this on the most conservative "base CPU" time in my testing of 18458 ms total for 25,920,000 rows, so 23218 ms / 25920000 = 0.18 μs. The apparent 10x improvement seems like a lot, but it is frankly pretty small until you are dealing with hundreds of thousands of rows (617k rows = 1 second savings).
Even given this small absolute improvement, in my opinion, the `DateAdd` method wins because it is the best combination of performance and clarity. The answer that requires a "magic number" of `0.50000004` is going to bite someone some day (five zeroes or six???), plus it's harder to understand.
**Additional Notes**
When I get some time I'm going to change `0.50000004` to `'12:00:00.003'` and see how it does. It is converted to the same `datetime` value and I find it much easier to remember.
For those interested, the above tests were run on a server where @@Version returns the following:
>
> Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) Jul 9 2008 14:43:34 Copyright (c) 1988-2008 Microsoft Corporation Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)
>
>
> |
2,780 | <p>Let's say that we have an ARGB color:</p>
<pre><code>Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple.
</code></pre>
<p>When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is <code>Color.FromARGB(255, 162, 133, 255);</code></p>
<p>The solution should work like this:</p>
<pre><code>Color blend = Color.White;
Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple.
Color rgb = ToRGB(argb, blend); //Same as Color.FromARGB(255, 162, 133, 255);
</code></pre>
<p>What is <code>ToRGB</code>'s implementation? </p>
| [
{
"answer_id": 2789,
"author": "Louis Brandy",
"author_id": 2089740,
"author_profile": "https://Stackoverflow.com/users/2089740",
"pm_score": 5,
"selected": true,
"text": "<p>It's called <a href=\"http://en.wikipedia.org/wiki/Alpha_compositing\" rel=\"noreferrer\">alpha blending</a>.</p>... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45/"
] | Let's say that we have an ARGB color:
```
Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple.
```
When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is `Color.FromARGB(255, 162, 133, 255);`
The solution should work like this:
```
Color blend = Color.White;
Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple.
Color rgb = ToRGB(argb, blend); //Same as Color.FromARGB(255, 162, 133, 255);
```
What is `ToRGB`'s implementation? | It's called [alpha blending](http://en.wikipedia.org/wiki/Alpha_compositing).
In psuedocode, assuming the background color (blend) always has 255 alpha. Also assumes alpha is 0-255.
```
alpha=argb.alpha()
r = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r()
g = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g()
b = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b()
```
*note: you probably need to be a bit (more) careful about floating-point/int math and rounding issues, depending on language. Cast intermediates accordingly*
**Edited to add:**
If you don't have a background color with an alpha of 255, the algebra gets alot more complicated. I've done it before and it's a fun exercise left to the reader (if you really need to know, ask another question :).
In other words, what color C blends into some background the same as blending A, then blending B. This is sort of like calculating A+B (which isn't the same as B+A). |
2,811 | <p>I have a table with a structure like the following:</p>
<hr />
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>LocationID</th>
<th>AccountNumber</th>
</tr>
</thead>
<tbody>
<tr>
<td>long-guid-here</td>
<td>12345</td>
</tr>
<tr>
<td>long-guid-here</td>
<td>54321</td>
</tr>
</tbody>
</table>
</div>
<p>To pass into another stored procedure, I need the XML to look like this:</p>
<pre><code><root>
<clientID>12345</clientID>
<clientID>54321</clientID>
</root>
</code></pre>
<p>The best I've been able to do so far was getting it like this:</p>
<pre><code><root clientID="10705"/>
</code></pre>
<p>I'm using this SQL statement:</p>
<pre><code>SELECT
1 as tag,
null as parent,
AccountNumber as 'root!1!clientID'
FROM
Location.LocationMDAccount
WHERE
locationid = 'long-guid-here'
FOR XML EXPLICIT
</code></pre>
<p>So far, I've looked at the documentation on <a href="http://msdn.microsoft.com/en-us/library/ms345137.aspx" rel="nofollow noreferrer">the MSDN page</a>, but I've not come out with the desired results.</p>
<hr />
<p>@KG,</p>
<p>Yours gave me this output actually:</p>
<pre><code><root>
<Location.LocationMDAccount>
<clientId>10705</clientId>
</Location.LocationMDAccount>
</root>
</code></pre>
<p>I'm going to stick with the <code>FOR XML EXPLICIT</code> from Chris Leon for now.</p>
| [
{
"answer_id": 2825,
"author": "Chris Leon",
"author_id": 289,
"author_profile": "https://Stackoverflow.com/users/289",
"pm_score": 3,
"selected": true,
"text": "<p>try</p>\n\n<pre><code>SELECT\n 1 AS Tag,\n 0 AS Parent,\n AccountNumber AS [Root!1!AccountNumber!element]\nFROM\n ... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/448/"
] | I have a table with a structure like the following:
---
| LocationID | AccountNumber |
| --- | --- |
| long-guid-here | 12345 |
| long-guid-here | 54321 |
To pass into another stored procedure, I need the XML to look like this:
```
<root>
<clientID>12345</clientID>
<clientID>54321</clientID>
</root>
```
The best I've been able to do so far was getting it like this:
```
<root clientID="10705"/>
```
I'm using this SQL statement:
```
SELECT
1 as tag,
null as parent,
AccountNumber as 'root!1!clientID'
FROM
Location.LocationMDAccount
WHERE
locationid = 'long-guid-here'
FOR XML EXPLICIT
```
So far, I've looked at the documentation on [the MSDN page](http://msdn.microsoft.com/en-us/library/ms345137.aspx), but I've not come out with the desired results.
---
@KG,
Yours gave me this output actually:
```
<root>
<Location.LocationMDAccount>
<clientId>10705</clientId>
</Location.LocationMDAccount>
</root>
```
I'm going to stick with the `FOR XML EXPLICIT` from Chris Leon for now. | try
```
SELECT
1 AS Tag,
0 AS Parent,
AccountNumber AS [Root!1!AccountNumber!element]
FROM
Location.LocationMDAccount
WHERE
LocationID = 'long-guid-here'
FOR XML EXPLICIT
``` |
2,815 | <p>I would like to make a nightly cron job that fetches my stackoverflow page and diffs it from the previous day's page, so I can see a change summary of my questions, answers, ranking, etc.</p>
<p>Unfortunately, I couldn't get the right set of cookies, etc, to make this work. Any ideas?</p>
<p>Also, when the beta is finished, will my status page be accessible without logging in?</p>
| [
{
"answer_id": 2818,
"author": "sparkes",
"author_id": 269,
"author_profile": "https://Stackoverflow.com/users/269",
"pm_score": 2,
"selected": false,
"text": "<p>Nice idea :)</p>\n\n<p>I presume you've used wget's</p>\n\n<pre><code>--load-cookies (filename)\n</code></pre>\n\n<p>might he... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | I would like to make a nightly cron job that fetches my stackoverflow page and diffs it from the previous day's page, so I can see a change summary of my questions, answers, ranking, etc.
Unfortunately, I couldn't get the right set of cookies, etc, to make this work. Any ideas?
Also, when the beta is finished, will my status page be accessible without logging in? | Your status page is available now without logging in (click [logout](https://stackoverflow.com/users/logout?returnurl=%2fquestions%2f2815%2fhow-to-curl-or-wget-a-stackoverflow-page) and try it). When the beta-cookie is disabled, there will be nothing between you and your status page.
For wget:
```
wget --no-cookies --header "Cookie: soba=(LookItUpYourself)" https://stackoverflow.com/users/30/myProfile.html
``` |
2,840 | <p>How do I page results in SQL Server 2005?</p>
<p>I tried it in SQL Server 2000, but there was no reliable way to do this. I'm now wondering if SQL Server 2005 has any built in method?</p>
<p>What I mean by paging is, for example, if I list users by their username, I want to be able to only return the first 10 records, then the next 10 records and so on.</p>
<p>Any help would be much appreciated.</p>
| [
{
"answer_id": 2843,
"author": "Pat",
"author_id": 36,
"author_profile": "https://Stackoverflow.com/users/36",
"pm_score": 6,
"selected": true,
"text": "<p>You can use <code>the Row_Number()</code> function.\nIts used as follows:</p>\n\n<pre><code>SELECT Row_Number() OVER(ORDER BY UserNa... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | How do I page results in SQL Server 2005?
I tried it in SQL Server 2000, but there was no reliable way to do this. I'm now wondering if SQL Server 2005 has any built in method?
What I mean by paging is, for example, if I list users by their username, I want to be able to only return the first 10 records, then the next 10 records and so on.
Any help would be much appreciated. | You can use `the Row_Number()` function.
Its used as follows:
```
SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName
FROM Users
```
From which it will yield a result set with a `RowID` field which you can use to page between.
```
SELECT *
FROM
( SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName
FROM Users
) As RowResults
WHERE RowID Between 5 AND 10
```
etc |
2,844 | <pre><code>#include <stdio.h>
int main() {
unsigned long long int num = 285212672; //FYI: fits in 29 bits
int normalInt = 5;
printf("My number is %d bytes wide and its value is %ul. A normal number is %d.\n", sizeof(num), num, normalInt);
return 0;
}
</code></pre>
<p>Output:</p>
<pre><code>My number is 8 bytes wide and its value is 285212672l. A normal number is 0.
</code></pre>
<p>I assume this unexpected result is from printing the <code>unsigned long long int</code>. How do you <code>printf()</code> an <code>unsigned long long int</code>?</p>
| [
{
"answer_id": 2850,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 10,
"selected": true,
"text": "<p>Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU).</p>\n\n<pre><code>printf... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | ```
#include <stdio.h>
int main() {
unsigned long long int num = 285212672; //FYI: fits in 29 bits
int normalInt = 5;
printf("My number is %d bytes wide and its value is %ul. A normal number is %d.\n", sizeof(num), num, normalInt);
return 0;
}
```
Output:
```
My number is 8 bytes wide and its value is 285212672l. A normal number is 0.
```
I assume this unexpected result is from printing the `unsigned long long int`. How do you `printf()` an `unsigned long long int`? | Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU).
```
printf("%llu", 285212672);
``` |
2,871 | <p>What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct? The C struct would look something like this (my C is very rusty):</p>
<pre><code>typedef OldStuff {
CHAR Name[8];
UInt32 User;
CHAR Location[8];
UInt32 TimeStamp;
UInt32 Sequence;
CHAR Tracking[16];
CHAR Filler[12];
}
</code></pre>
<p>And would fill something like this:</p>
<pre><code>[StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)]
public struct NewStuff
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
[FieldOffset(0)]
public string Name;
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(8)]
public uint User;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
[FieldOffset(12)]
public string Location;
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(20)]
public uint TimeStamp;
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(24)]
public uint Sequence;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
[FieldOffset(28)]
public string Tracking;
}
</code></pre>
<p>What is best way to copy <code>OldStuff</code> to <code>NewStuff</code>, if <code>OldStuff</code> was passed as byte[] array?</p>
<p>I'm currently doing something like the following, but it feels kind of clunky.</p>
<pre><code>GCHandle handle;
NewStuff MyStuff;
int BufferSize = Marshal.SizeOf(typeof(NewStuff));
byte[] buff = new byte[BufferSize];
Array.Copy(SomeByteArray, 0, buff, 0, BufferSize);
handle = GCHandle.Alloc(buff, GCHandleType.Pinned);
MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));
handle.Free();
</code></pre>
<p>Is there better way to accomplish this?</p>
<hr>
<p>Would using the <code>BinaryReader</code> class offer any performance gains over pinning the memory and using <code>Marshal.PtrStructure</code>?</p>
| [
{
"answer_id": 2881,
"author": "Mufaka",
"author_id": 449,
"author_profile": "https://Stackoverflow.com/users/449",
"pm_score": -1,
"selected": false,
"text": "<p>If you have a byte[] you should be able to use the BinaryReader class and set values on NewStuff using the available ReadX me... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/206/"
] | What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct? The C struct would look something like this (my C is very rusty):
```
typedef OldStuff {
CHAR Name[8];
UInt32 User;
CHAR Location[8];
UInt32 TimeStamp;
UInt32 Sequence;
CHAR Tracking[16];
CHAR Filler[12];
}
```
And would fill something like this:
```
[StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)]
public struct NewStuff
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
[FieldOffset(0)]
public string Name;
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(8)]
public uint User;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
[FieldOffset(12)]
public string Location;
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(20)]
public uint TimeStamp;
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(24)]
public uint Sequence;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
[FieldOffset(28)]
public string Tracking;
}
```
What is best way to copy `OldStuff` to `NewStuff`, if `OldStuff` was passed as byte[] array?
I'm currently doing something like the following, but it feels kind of clunky.
```
GCHandle handle;
NewStuff MyStuff;
int BufferSize = Marshal.SizeOf(typeof(NewStuff));
byte[] buff = new byte[BufferSize];
Array.Copy(SomeByteArray, 0, buff, 0, BufferSize);
handle = GCHandle.Alloc(buff, GCHandleType.Pinned);
MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));
handle.Free();
```
Is there better way to accomplish this?
---
Would using the `BinaryReader` class offer any performance gains over pinning the memory and using `Marshal.PtrStructure`? | From what I can see in that context, you don't need to copy `SomeByteArray` into a buffer. You simply need to get the handle from `SomeByteArray`, pin it, copy the `IntPtr` data using `PtrToStructure` and then release. No need for a copy.
That would be:
```
NewStuff ByteArrayToNewStuff(byte[] bytes)
{
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try
{
NewStuff stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));
}
finally
{
handle.Free();
}
return stuff;
}
```
Generic version:
```
T ByteArrayToStructure<T>(byte[] bytes) where T: struct
{
T stuff;
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try
{
stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
}
finally
{
handle.Free();
}
return stuff;
}
```
Simpler version (requires `unsafe` switch):
```
unsafe T ByteArrayToStructure<T>(byte[] bytes) where T : struct
{
fixed (byte* ptr = &bytes[0])
{
return (T)Marshal.PtrToStructure((IntPtr)ptr, typeof(T));
}
}
``` |
2,872 | <p><strong>My Goal</strong></p>
<p>I would like to have a main processing thread (non GUI), and be able to spin off GUIs in their own background threads as needed, and having my main non GUI thread keep working. Put another way, I want my main non GUI-thread to be the owner of the GUI-thread and not vice versa. I'm not sure this is even possible with Windows Forms(?)</p>
<p><strong>Background</strong></p>
<p>I have a component based system in which a controller dynamically load assemblies and instantiates and run classes implementing a common <code>IComponent</code> interface with a single method <code>DoStuff()</code>.</p>
<p>Which components that gets loaded is configured via a xml configuration file and by adding new assemblies containing different implementations of <code>IComponent</code>. The components provides utility functions to the main application. While the main program is doing it's thing, e.g. controlling a nuclear plant, the components might be performing utility tasks (in their own threads), e.g. cleaning the database, sending emails, printing funny jokes on the printer, what have you. What I would like, is to have one of these components be able to display a GUI, e.g. with status information for the said email sending component.</p>
<p>The lifetime of the complete system looks like this</p>
<ol>
<li>Application starts.</li>
<li>Check configuration file for components to load. Load them.</li>
<li><strong>For each component, run <code>DoStuff()</code> to initialize it and make it live its own life in their own threads.</strong></li>
<li>Continue to do main application-thingy king of work, forever.</li>
</ol>
<p>I have not yet been able to successfully perform point 3 if the component fires up a GUI in <code>DoStuff()</code>. It simply just halts until the GUI is closed. And not until the GUI is closed does the program progress to point 4.</p>
<p>It would be great if these components were allowed to start up their own Windows Forms GUIs.</p>
<p><strong>Problem</strong></p>
<p>When a component tries to fire up a GUI in <code>DoStuff()</code> (the exact line of code is when the component runs <code>Application.Run(theForm)</code>), the component and hence our system "hangs" at the <code>Application.Run()</code> line until the GUI is closed. Well, the just fired up GUI works fine, as expected.</p>
<p>Example of components. One hasn't nothing to do with GUI, whilst the second fires up a cute windows with pink fluffy bunnies in them.</p>
<pre><code>public class MyComponent1: IComponent
{
public string DoStuff(...) { // write something to the database }
}
public class MyComponent2: IComponent
{
public void DoStuff()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form());
// I want the thread to immediately return after the GUI
// is fired up, so that my main thread can continue to work.
}
}
</code></pre>
<p>I have tried this with no luck. Even when I try to fire up the GUI in it's own thread, the execution halts until the GUI as closed.</p>
<pre><code>public void DoStuff()
{
new Thread(ThreadedInitialize).Start()
}
private void ThreadedInitialize()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form());
}
</code></pre>
<p>Is it possible to spin off a GUI and return after <code>Application.Run()</code>?</p>
| [
{
"answer_id": 2901,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 5,
"selected": true,
"text": "<p><strong>Application.Run</strong> method displays one (or more) forms and initiates the standard message loop which runs until... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446/"
] | **My Goal**
I would like to have a main processing thread (non GUI), and be able to spin off GUIs in their own background threads as needed, and having my main non GUI thread keep working. Put another way, I want my main non GUI-thread to be the owner of the GUI-thread and not vice versa. I'm not sure this is even possible with Windows Forms(?)
**Background**
I have a component based system in which a controller dynamically load assemblies and instantiates and run classes implementing a common `IComponent` interface with a single method `DoStuff()`.
Which components that gets loaded is configured via a xml configuration file and by adding new assemblies containing different implementations of `IComponent`. The components provides utility functions to the main application. While the main program is doing it's thing, e.g. controlling a nuclear plant, the components might be performing utility tasks (in their own threads), e.g. cleaning the database, sending emails, printing funny jokes on the printer, what have you. What I would like, is to have one of these components be able to display a GUI, e.g. with status information for the said email sending component.
The lifetime of the complete system looks like this
1. Application starts.
2. Check configuration file for components to load. Load them.
3. **For each component, run `DoStuff()` to initialize it and make it live its own life in their own threads.**
4. Continue to do main application-thingy king of work, forever.
I have not yet been able to successfully perform point 3 if the component fires up a GUI in `DoStuff()`. It simply just halts until the GUI is closed. And not until the GUI is closed does the program progress to point 4.
It would be great if these components were allowed to start up their own Windows Forms GUIs.
**Problem**
When a component tries to fire up a GUI in `DoStuff()` (the exact line of code is when the component runs `Application.Run(theForm)`), the component and hence our system "hangs" at the `Application.Run()` line until the GUI is closed. Well, the just fired up GUI works fine, as expected.
Example of components. One hasn't nothing to do with GUI, whilst the second fires up a cute windows with pink fluffy bunnies in them.
```
public class MyComponent1: IComponent
{
public string DoStuff(...) { // write something to the database }
}
public class MyComponent2: IComponent
{
public void DoStuff()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form());
// I want the thread to immediately return after the GUI
// is fired up, so that my main thread can continue to work.
}
}
```
I have tried this with no luck. Even when I try to fire up the GUI in it's own thread, the execution halts until the GUI as closed.
```
public void DoStuff()
{
new Thread(ThreadedInitialize).Start()
}
private void ThreadedInitialize()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form());
}
```
Is it possible to spin off a GUI and return after `Application.Run()`? | **Application.Run** method displays one (or more) forms and initiates the standard message loop which runs until all the forms are closed. You cannot force a return from that method except by closing all your forms or forcing an application shutdown.
You can, however, pass an **ApplicationContext** (instad of a new Form()) to Application.Run method and ApplicationContext can be used to launch several forms at once. Your application will only end when all of those are closed. See here: <http://msdn.microsoft.com/en-us/library/system.windows.forms.application.run.aspx>
Also, any forms that you Show non-modally will continue to run alongside your main form, which will enable you to have more than one windows that do not block each other. I believe this is actually what you are trying to accomplish. |
2,874 | <p>I have a control that is modelled on a <strong>ComboBox</strong>. I want to render the control so that the control <strong>border</strong> looks like that of a standard <strong>Windows ComboBox</strong>. Specifically, I have followed the MSDN documentation and all the rendering of the control is correct except for rendering when the control is disabled.</p>
<p>Just to be clear, this is for a system with <strong>Visual Styles</strong> enabled. Also, all parts of the control render properly except the border around a disabled control, which does not match the disabled <strong>ComboBox border</strong> colour.</p>
<p>I am using the <strong>VisualStyleRenderer</strong> class. MSDN suggests using the <code>VisualStyleElement.TextBox</code> element for the <strong>TextBox</strong> part of the <strong>ComboBox</strong> control but a standard disabled <strong>TextBox</strong> and a standard disabled <strong>ComboBox</strong> draw slightly differently (one has a light grey border, the other a light blue border).</p>
<p>How can I get correct rendering of the control in a disabled state?</p>
| [
{
"answer_id": 13319,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 1,
"selected": false,
"text": "<p>Are any of the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.controlpaint_members.aspx\" rel=\"nofol... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/441/"
] | I have a control that is modelled on a **ComboBox**. I want to render the control so that the control **border** looks like that of a standard **Windows ComboBox**. Specifically, I have followed the MSDN documentation and all the rendering of the control is correct except for rendering when the control is disabled.
Just to be clear, this is for a system with **Visual Styles** enabled. Also, all parts of the control render properly except the border around a disabled control, which does not match the disabled **ComboBox border** colour.
I am using the **VisualStyleRenderer** class. MSDN suggests using the `VisualStyleElement.TextBox` element for the **TextBox** part of the **ComboBox** control but a standard disabled **TextBox** and a standard disabled **ComboBox** draw slightly differently (one has a light grey border, the other a light blue border).
How can I get correct rendering of the control in a disabled state? | I'm not 100% sure if this is what you are looking for but you should check out the **VisualStyleRenderer** in the System.Windows.Forms.VisualStyles-namespace.
1. [VisualStyleRenderer class](http://msdn.microsoft.com/en-us/library/system.windows.forms.visualstyles.visualstylerenderer.aspx) (MSDN)
2. [How to: Render a Visual Style Element](http://msdn.microsoft.com/en-us/library/ms171735.aspx) (MSDN)
3. [VisualStyleElement.ComboBox.DropDownButton.Disabled](http://msdn.microsoft.com/en-us/library/system.windows.forms.visualstyles.visualstyleelement.combobox.dropdownbutton.disabled.aspx) (MSDN)
Since VisualStyleRenderer won't work if the user don't have visual styles enabled (he/she might be running 'classic mode' or an operative system prior to Windows XP) you should always have a fallback to the ControlPaint class.
```
// Create the renderer.
if (VisualStyleInformation.IsSupportedByOS
&& VisualStyleInformation.IsEnabledByUser)
{
renderer = new VisualStyleRenderer(
VisualStyleElement.ComboBox.DropDownButton.Disabled);
}
```
and then do like this when drawing:
```
if(renderer != null)
{
// Use visual style renderer.
}
else
{
// Use ControlPaint renderer.
}
```
Hope it helps! |
2,900 | <p>I am getting the following error:</p>
<blockquote>
<p>Access denied for user 'apache'@'localhost' (using password: NO)</p>
</blockquote>
<p>When using the following code:</p>
<pre><code><?php
include("../includes/connect.php");
$query = "SELECT * from story";
$result = mysql_query($query) or die(mysql_error());
echo "<h1>Delete Story</h1>";
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)){
echo '<b>'.$row[1].'</b><span align="right"><a href="../process/delete_story.php?id='.$row[0].'">Delete</a></span>';
echo '<br /><i>'.$row[2].'</i>';
}
}
else {
echo "No stories available.";
}
?>
</code></pre>
<p>The <code>connect.php</code> file contains my MySQL connect calls that are working fine with my <code>INSERT</code> queries in another portion of the software. If I comment out the <code>$result = mysql_query</code> line, then it goes through to the else statement. So, it is that line or the content in the if.</p>
<p>I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions.</p>
| [
{
"answer_id": 2908,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": 1,
"selected": false,
"text": "<p>Just to check, if you use <strong>just</strong> this part you get an error?</p>\n\n<pre><code><?php\ninclude(\"../... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/454/"
] | I am getting the following error:
>
> Access denied for user 'apache'@'localhost' (using password: NO)
>
>
>
When using the following code:
```
<?php
include("../includes/connect.php");
$query = "SELECT * from story";
$result = mysql_query($query) or die(mysql_error());
echo "<h1>Delete Story</h1>";
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)){
echo '<b>'.$row[1].'</b><span align="right"><a href="../process/delete_story.php?id='.$row[0].'">Delete</a></span>';
echo '<br /><i>'.$row[2].'</i>';
}
}
else {
echo "No stories available.";
}
?>
```
The `connect.php` file contains my MySQL connect calls that are working fine with my `INSERT` queries in another portion of the software. If I comment out the `$result = mysql_query` line, then it goes through to the else statement. So, it is that line or the content in the if.
I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions. | >
> And if it matters at all, apache@localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter.
>
>
>
If it is saying 'apache@localhost' the username is not getting passed correctly to the MySQL connection. 'apache' is normally the user that runs the httpd process (at least on Redhat-based systems) and if no username is passed during the connection MySQL uses whomever is calling for the connection.
If you do the connection right in your script, not in a called file, do you get the same error? |
2,914 | <p>Occasionally, I've come across a webpage that tries to pop open a new window (for user input, or something important), but the popup blocker prevents this from happening.</p>
<p>What methods can the calling window use to make sure the new window launched properly?</p>
| [
{
"answer_id": 2917,
"author": "omar",
"author_id": 453,
"author_profile": "https://Stackoverflow.com/users/453",
"pm_score": 9,
"selected": true,
"text": "<p>If you use JavaScript to open the popup, you can use something like this:</p>\n\n<pre><code>var newWin = window.open(url); ... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/434/"
] | Occasionally, I've come across a webpage that tries to pop open a new window (for user input, or something important), but the popup blocker prevents this from happening.
What methods can the calling window use to make sure the new window launched properly? | If you use JavaScript to open the popup, you can use something like this:
```
var newWin = window.open(url);
if(!newWin || newWin.closed || typeof newWin.closed=='undefined')
{
//POPUP BLOCKED
}
``` |
2,970 | <p>My dad called me today and said people going to his website were getting 168 viruses trying to download to their computers. He isn't technical at all, and built the whole thing with a WYSIWYG editor.</p>
<p>I popped his site open and viewed the source, and there was a line of Javascript includes at the bottom of the source right before the closing HTML tag. They included this file (among many others): <a href="http://www.98hs.ru/js.js" rel="noreferrer">http://www.98hs.ru/js.js</a> <-- <strong>TURN OFF JAVASCRIPT BEFORE YOU GO TO THAT URL.</strong></p>
<p>So I commented it out for now. It turns out his FTP password was a plain dictionary word six letters long, so we think that's how it got hacked. We've changed his password to an 8+ digit non-word string (he wouldn't go for a passphrase since he is a hunt-n-peck typer).</p>
<p>I did a <a href="http://whois.domaintools.com/98hs.ru" rel="noreferrer">whois on 98hs.ru</a> and found it is hosted from a server in Chile. There is actually an e-mail address associated with it too, but I seriously doubt this person is the culprit. Probably just some other site that got hacked...</p>
<p>I have no idea what to do at this point though as I've never dealt with this sort of thing before. Anyone have any suggestions?</p>
<p>He was using plain jane un-secured ftp through webhost4life.com. I don't even see a way to <em>do</em> sftp on their site. I'm thinking his username and password got intercepted?</p>
<p><strong>So, to make this more relevant to the community, what are the steps you should take/best practices you should follow to protect your website from getting hacked?</strong></p>
<p>For the record, here is the line of code that "magically" got added to his file (and isn't in his file on his computer -- I've left it commented out just to make absolute sure it won't do anything on this page, although I'm sure Jeff would guard against this):</p>
<pre><code><!--script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script-->
</code></pre>
| [
{
"answer_id": 2973,
"author": "Justin Standard",
"author_id": 92,
"author_profile": "https://Stackoverflow.com/users/92",
"pm_score": 2,
"selected": false,
"text": "<p>With a six word character password, he may have been brute forced. That is more likely than his ftp being intercepted,... | 2008/08/05 | [
"https://Stackoverflow.com/questions/2970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58/"
] | My dad called me today and said people going to his website were getting 168 viruses trying to download to their computers. He isn't technical at all, and built the whole thing with a WYSIWYG editor.
I popped his site open and viewed the source, and there was a line of Javascript includes at the bottom of the source right before the closing HTML tag. They included this file (among many others): <http://www.98hs.ru/js.js> <-- **TURN OFF JAVASCRIPT BEFORE YOU GO TO THAT URL.**
So I commented it out for now. It turns out his FTP password was a plain dictionary word six letters long, so we think that's how it got hacked. We've changed his password to an 8+ digit non-word string (he wouldn't go for a passphrase since he is a hunt-n-peck typer).
I did a [whois on 98hs.ru](http://whois.domaintools.com/98hs.ru) and found it is hosted from a server in Chile. There is actually an e-mail address associated with it too, but I seriously doubt this person is the culprit. Probably just some other site that got hacked...
I have no idea what to do at this point though as I've never dealt with this sort of thing before. Anyone have any suggestions?
He was using plain jane un-secured ftp through webhost4life.com. I don't even see a way to *do* sftp on their site. I'm thinking his username and password got intercepted?
**So, to make this more relevant to the community, what are the steps you should take/best practices you should follow to protect your website from getting hacked?**
For the record, here is the line of code that "magically" got added to his file (and isn't in his file on his computer -- I've left it commented out just to make absolute sure it won't do anything on this page, although I'm sure Jeff would guard against this):
```
<!--script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script-->
``` | Try and gather as much information as you can. See if the host can give you a log showing all the FTP connections that were made to your account. You can use those to see if it was even an FTP connection that was used to make the change and possibly get an IP address.
If you're using a prepacked software like Wordpress, Drupal, or anything else that you didn't code there may be vulnerabilities in upload code that allows for this sort of modification. If it is custom built, double check any places where you allow users to upload files or modify existing files.
The second thing would be to take a dump of the site as-is and check everything for other modifications. It may just be one single modification they made, but if they got in via FTP who knows what else is up there.
Revert your site back to a known good status and, if need be, upgrade to the latest version.
There is a level of return you have to take into account too. Is the damage worth trying to track the person down or is this something where you just live and learn and use stronger passwords? |
2,993 | <p>I'm in an environment with a lot of computers that haven't been
properly inventoried. Basically, no one knows which IP goes with which
mac address and which hostname. So I wrote the following:</p>
<pre><code># This script goes down the entire IP range and attempts to
# retrieve the Hostname and mac address and outputs them
# into a file. Yay!
require "socket"
TwoOctets = "10.26"
def computer_exists?(computerip)
system("ping -c 1 -W 1 #{computerip}")
end
def append_to_file(line)
file = File.open("output.txt", "a")
file.puts(line)
file.close
end
def getInfo(current_ip)
begin
if computer_exists?(current_ip)
arp_output = `arp -v #{current_ip}`
mac_addr = arp_output.to_s.match(/..:..:..:..:..:../)
host_name = Socket.gethostbyname(current_ip)
append_to_file("#{host_name[0]} - #{current_ip} - #{mac_addr}\n")
end
rescue SocketError => mySocketError
append_to_file("unknown - #{current_ip} - #{mac_addr}")
end
end
(6..8).each do |i|
case i
when 6
for j in (1..190)
current_ip = "#{TwoOctets}.#{i}.#{j}"
getInfo(current_ip)
end
when 7
for j in (1..255)
current_ip = "#{TwoOctets}.#{i}.#{j}"
getInfo(current_ip)
end
when 8
for j in (1..52)
current_ip = "#{TwoOctets}.#{i}.#{j}"
getInfo(current_ip)
end
end
end
</code></pre>
<p>Everything works except it does not find a Reverse DNS.</p>
<p>Sample output that I'm getting is this:</p>
<pre><code>10.26.6.12 - 10.26.6.12 - 00:11:11:9B:13:9F
10.26.6.17 - 10.26.6.17 - 08:00:69:9A:97:C3
10.26.6.18 - 10.26.6.18 - 08:00:69:93:2C:E2
</code></pre>
<p>If I do <code>nslookup 10.26.6.12</code> then I get the correct reverse DNS so
that shows that my machine is seeing the DNS server.</p>
<p>I have tried <code>Socket.gethostbyname</code>, <code>gethostbyaddr</code>, but it doesn't work.</p>
<p>Any guidance will be much appreciated.</p>
| [
{
"answer_id": 3012,
"author": "Ecton",
"author_id": 457,
"author_profile": "https://Stackoverflow.com/users/457",
"pm_score": 3,
"selected": false,
"text": "<p>I would check out <code>getaddrinfo</code>. If you replace the line:</p>\n\n<pre><code>host_name = Socket.gethostbyname(current... | 2008/08/06 | [
"https://Stackoverflow.com/questions/2993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155/"
] | I'm in an environment with a lot of computers that haven't been
properly inventoried. Basically, no one knows which IP goes with which
mac address and which hostname. So I wrote the following:
```
# This script goes down the entire IP range and attempts to
# retrieve the Hostname and mac address and outputs them
# into a file. Yay!
require "socket"
TwoOctets = "10.26"
def computer_exists?(computerip)
system("ping -c 1 -W 1 #{computerip}")
end
def append_to_file(line)
file = File.open("output.txt", "a")
file.puts(line)
file.close
end
def getInfo(current_ip)
begin
if computer_exists?(current_ip)
arp_output = `arp -v #{current_ip}`
mac_addr = arp_output.to_s.match(/..:..:..:..:..:../)
host_name = Socket.gethostbyname(current_ip)
append_to_file("#{host_name[0]} - #{current_ip} - #{mac_addr}\n")
end
rescue SocketError => mySocketError
append_to_file("unknown - #{current_ip} - #{mac_addr}")
end
end
(6..8).each do |i|
case i
when 6
for j in (1..190)
current_ip = "#{TwoOctets}.#{i}.#{j}"
getInfo(current_ip)
end
when 7
for j in (1..255)
current_ip = "#{TwoOctets}.#{i}.#{j}"
getInfo(current_ip)
end
when 8
for j in (1..52)
current_ip = "#{TwoOctets}.#{i}.#{j}"
getInfo(current_ip)
end
end
end
```
Everything works except it does not find a Reverse DNS.
Sample output that I'm getting is this:
```
10.26.6.12 - 10.26.6.12 - 00:11:11:9B:13:9F
10.26.6.17 - 10.26.6.17 - 08:00:69:9A:97:C3
10.26.6.18 - 10.26.6.18 - 08:00:69:93:2C:E2
```
If I do `nslookup 10.26.6.12` then I get the correct reverse DNS so
that shows that my machine is seeing the DNS server.
I have tried `Socket.gethostbyname`, `gethostbyaddr`, but it doesn't work.
Any guidance will be much appreciated. | Today I also needed reverse DNS lookup and I've found very simple standard solution:
```
require 'resolv'
host_name = Resolv.getname(ip_address_here)
```
It seems it uses timeout which helps in rough cases. |
3,033 | <p>If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys? I have heard that using <code>each</code> may in some way have unintended side effects. So, is that true, and is one of the two following methods best, or is there a better way?</p>
<pre><code># Method 1
while (my ($key, $value) = each(%hash)) {
# Something
}
# Method 2
foreach my $key (keys(%hash)) {
# Something
}
</code></pre>
| [
{
"answer_id": 3066,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 2,
"selected": false,
"text": "<p>I may get bitten by this one but I think that it's personal preference. I can't find any reference in the docs to each() being ... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/219/"
] | If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys? I have heard that using `each` may in some way have unintended side effects. So, is that true, and is one of the two following methods best, or is there a better way?
```
# Method 1
while (my ($key, $value) = each(%hash)) {
# Something
}
# Method 2
foreach my $key (keys(%hash)) {
# Something
}
``` | The rule of thumb is to use the function most suited to your needs.
If you just want the keys and do not plan to ever *read* any of the values, use keys():
```
foreach my $key (keys %hash) { ... }
```
If you just want the values, use values():
```
foreach my $val (values %hash) { ... }
```
If you need the keys *and* the values, use each():
```
keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop
while(my($k, $v) = each %hash) { ... }
```
If you plan to change the keys of the hash in any way *except* for deleting the current key during the iteration, then you must not use each(). For example, this code to create a new set of uppercase keys with doubled values works fine using keys():
```
%h = (a => 1, b => 2);
foreach my $k (keys %h)
{
$h{uc $k} = $h{$k} * 2;
}
```
producing the expected resulting hash:
```
(a => 1, A => 2, b => 2, B => 4)
```
But using each() to do the same thing:
```
%h = (a => 1, b => 2);
keys %h;
while(my($k, $v) = each %h)
{
$h{uc $k} = $h{$k} * 2; # BAD IDEA!
}
```
produces incorrect results in hard-to-predict ways. For example:
```
(a => 1, A => 2, b => 2, B => 8)
```
This, however, is safe:
```
keys %h;
while(my($k, $v) = each %h)
{
if(...)
{
delete $h{$k}; # This is safe
}
}
```
All of this is described in the perl documentation:
```
% perldoc -f keys
% perldoc -f each
``` |
3,058 | <p>Inversion of Control (IoC) can be quite confusing when it is first encountered.</p>
<ol>
<li>What is it?</li>
<li>Which problem does it solve?</li>
<li>When is it appropriate to use and when not?</li>
</ol>
| [
{
"answer_id": 3082,
"author": "Ecton",
"author_id": 457,
"author_profile": "https://Stackoverflow.com/users/457",
"pm_score": 6,
"selected": false,
"text": "<ol>\n<li><p><a href=\"http://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"noreferrer\">Wikipedia Article</a>. To me, invers... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/358/"
] | Inversion of Control (IoC) can be quite confusing when it is first encountered.
1. What is it?
2. Which problem does it solve?
3. When is it appropriate to use and when not? | The **`Inversion-of-Control` (IoC)** pattern, is about providing *any kind* of `callback` (which controls reaction), instead of acting ourself directly (in other words, inversion and/or redirecting control to external handler/controller). The **`Dependency-Injection` (DI)** pattern is a more specific version of IoC pattern, and is all about removing dependencies from your code.
>
> Every `DI` implementation can be considered `IoC`, but one should not call it `IoC`, because implementing Dependency-Injection is harder than callback (Don't lower your product's worth by using general term "IoC" instead).
>
>
>
For DI example, say your application has a text-editor component, and you want to provide spell checking. Your standard code would look something like this:
```cs
public class TextEditor {
private SpellChecker checker;
public TextEditor() {
this.checker = new SpellChecker();
}
}
```
What we've done here creates a dependency between the `TextEditor` and the `SpellChecker`.
In an IoC scenario we would instead do something like this:
```cs
public class TextEditor {
private IocSpellChecker checker;
public TextEditor(IocSpellChecker checker) {
this.checker = checker;
}
}
```
In the first code example we are instantiating `SpellChecker` (`this.checker = new SpellChecker();`), which means the `TextEditor` class directly depends on the `SpellChecker` class.
In the second code example we are creating an abstraction by having the `SpellChecker` dependency class in `TextEditor`'s constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so:
```cs
SpellChecker sc = new SpellChecker(); // dependency
TextEditor textEditor = new TextEditor(sc);
```
Now the client creating the `TextEditor` class has control over which `SpellChecker` implementation to use because we're injecting the dependency into the `TextEditor` signature. |
3,061 | <p>How do I call a function, using a string with the function's name? For example:</p>
<pre><code>import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
</code></pre>
| [
{
"answer_id": 3071,
"author": "Patrick Johnmeyer",
"author_id": 363,
"author_profile": "https://Stackoverflow.com/users/363",
"pm_score": 12,
"selected": true,
"text": "<p>Given a module <code>foo</code> with method <code>bar</code>:</p>\n<pre><code>import foo\nbar = getattr(foo, 'bar')... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121/"
] | How do I call a function, using a string with the function's name? For example:
```
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
``` | Given a module `foo` with method `bar`:
```
import foo
bar = getattr(foo, 'bar')
result = bar()
```
[`getattr`](https://docs.python.org/library/functions.html#getattr) can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on. |
3,112 | <p>I have a perl variable <code>$results</code> that gets returned from a service. The value is supposed to be an array, and <code>$results</code> should be an array reference. However, when the array has only one item in it, <code>$results</code> will be set to that value, and not a referenced array that contains that one item.</p>
<p>I want to do a <code>foreach</code> loop on the expected array. Without checking <code>ref($results) eq 'ARRAY'</code>, is there any way to have something equivalent to the following:</p>
<pre><code>foreach my $result (@$results) {
# Process $result
}
</code></pre>
<p>That particular code sample will work for the reference, but will complain for the simple scalar.</p>
<p>EDIT: I should clarify that there is no way for me to change what is returned from the service. The problem is that the value will be a scalar when there is only one value and it will be an array reference when there is more than one value.</p>
| [
{
"answer_id": 3126,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": -1,
"selected": false,
"text": "<p>I've just tested this with:</p>\n\n<blockquote>\n<pre><code>#!/usr/bin/perl -w\nuse strict;\n\nsub testit {\n\n my @ret = ();\n... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/219/"
] | I have a perl variable `$results` that gets returned from a service. The value is supposed to be an array, and `$results` should be an array reference. However, when the array has only one item in it, `$results` will be set to that value, and not a referenced array that contains that one item.
I want to do a `foreach` loop on the expected array. Without checking `ref($results) eq 'ARRAY'`, is there any way to have something equivalent to the following:
```
foreach my $result (@$results) {
# Process $result
}
```
That particular code sample will work for the reference, but will complain for the simple scalar.
EDIT: I should clarify that there is no way for me to change what is returned from the service. The problem is that the value will be a scalar when there is only one value and it will be an array reference when there is more than one value. | im not sure there's any other way than:
>
>
> ```
> $result = [ $result ] if ref($result) ne 'ARRAY';
> foreach .....
>
> ```
>
> |
3,136 | <p>How can I set up my crontab to execute X script at 11:59PM every day without emailing me or creating any logs?</p>
<p>Right now my crontab looks something like this</p>
<pre><code>@daily /path/to/script.sh
</code></pre>
| [
{
"answer_id": 3139,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 4,
"selected": true,
"text": "<p>When you do crontab -e, try this:</p>\n\n<pre><code>59 23 * * * /usr/sbin/myscript > /dev/null\n</code></pre>\n\n<p>That... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/87/"
] | How can I set up my crontab to execute X script at 11:59PM every day without emailing me or creating any logs?
Right now my crontab looks something like this
```
@daily /path/to/script.sh
``` | When you do crontab -e, try this:
```
59 23 * * * /usr/sbin/myscript > /dev/null
```
That means: At 59 Minutes and 23 Hours on every day (\*) on every month on every weekday, execute myscript.
See **man crontab** for some more info and examples. |
3,157 | <p>In an application that heavily relies on <code>.htaccess</code> RewriteRules for its PrettyURLs (CakePHP in my case), how do I correctly set up directives to exclude certain directories from this rewriting? That is:</p>
<pre><code>/appRoot/.htaccess
app/
static/
</code></pre>
<p>By default every request to <code>/appRoot/*</code> is being rewritten to be picked up by <code>app/webroot/index.php</code>, where it's being analysed and corresponding controller actions are being invoked. This is done by these directives in <code>.htaccess</code>:</p>
<pre><code>RewriteBase /appRoot
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]
</code></pre>
<p>I now want to exclude a few directories like static/ from this rewriting. I tried with this <em>before</em> the Cake RewriteRules:</p>
<pre><code>RewriteCond $1 ^(static|otherDir).*$ [NC]
RewriteRule (.*) - [L]
</code></pre>
<p>It works in so far that requests are no longer rewritten, but now <strong>all</strong> requests are being skipped, even legitimate Cake requests which should not match <code>^(static|otherDir).*$</code>.</p>
<p>I tried several variations of these rules but can't get it to work the way I want.</p>
| [
{
"answer_id": 3159,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 1,
"selected": false,
"text": "<p>Remove the [L] from the previous rules:</p>\n\n<pre><code>RewriteBase /appRoot\n\nRewriteRule ^$ app/webroot/ &nbsp; &... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/476/"
] | In an application that heavily relies on `.htaccess` RewriteRules for its PrettyURLs (CakePHP in my case), how do I correctly set up directives to exclude certain directories from this rewriting? That is:
```
/appRoot/.htaccess
app/
static/
```
By default every request to `/appRoot/*` is being rewritten to be picked up by `app/webroot/index.php`, where it's being analysed and corresponding controller actions are being invoked. This is done by these directives in `.htaccess`:
```
RewriteBase /appRoot
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]
```
I now want to exclude a few directories like static/ from this rewriting. I tried with this *before* the Cake RewriteRules:
```
RewriteCond $1 ^(static|otherDir).*$ [NC]
RewriteRule (.*) - [L]
```
It works in so far that requests are no longer rewritten, but now **all** requests are being skipped, even legitimate Cake requests which should not match `^(static|otherDir).*$`.
I tried several variations of these rules but can't get it to work the way I want. | And the correct answer iiiiis...
```
RewriteRule ^(a|bunch|of|old|directories).* - [NC,L]
# all other requests will be forwarded to Cake
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]
```
I still don't get why the index.php file in the root directory was called initially even with these directives in place. It is now located in
```
/appRoot/app/views/pages/home.ctp
```
and handled through Cake as well. With this in place now, I suppose this would have worked as well (slightly altered version of Mike's suggestion, untested):
```
RewriteCond $1 !^(a|bunch|of|old|directories).*$ [NC]
RewriteRule ^(.*)$ app/webroot/$1 [L]
``` |
3,163 | <p>I have been trying to find a really fast way to parse yyyy-mm-dd [hh:mm:ss] into a Date object. Here are the 3 ways I have tried doing it and the times it takes each method to parse 50,000 date time strings.</p>
<p>Does anyone know any faster ways of doing this or tips to speed up the methods?</p>
<pre><code>castMethod1 takes 3673 ms
castMethod2 takes 3812 ms
castMethod3 takes 3931 ms
</code></pre>
<p>Code:</p>
<pre><code>private function castMethod1(dateString:String):Date {
if ( dateString == null ) {
return null;
}
var year:int = int(dateString.substr(0,4));
var month:int = int(dateString.substr(5,2))-1;
var day:int = int(dateString.substr(8,2));
if ( year == 0 && month == 0 && day == 0 ) {
return null;
}
if ( dateString.length == 10 ) {
return new Date(year, month, day);
}
var hour:int = int(dateString.substr(11,2));
var minute:int = int(dateString.substr(14,2));
var second:int = int(dateString.substr(17,2));
return new Date(year, month, day, hour, minute, second);
}
</code></pre>
<p>-</p>
<pre><code>private function castMethod2(dateString:String):Date {
if ( dateString == null ) {
return null;
}
if ( dateString.indexOf("0000-00-00") != -1 ) {
return null;
}
dateString = dateString.split("-").join("/");
return new Date(Date.parse( dateString ));
}
</code></pre>
<p>-</p>
<pre><code>private function castMethod3(dateString:String):Date {
if ( dateString == null ) {
return null;
}
var mainParts:Array = dateString.split(" ");
var dateParts:Array = mainParts[0].split("-");
if ( Number(dateParts[0])+Number(dateParts[1])+Number(dateParts[2]) == 0 ) {
return null;
}
return new Date( Date.parse( dateParts.join("/")+(mainParts[1]?" "+mainParts[1]:" ") ) );
}
</code></pre>
<hr>
<p>No, Date.parse will not handle dashes by default. And I need to return null for date time strings like <code>"0000-00-00"</code>.</p>
| [
{
"answer_id": 3185,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 2,
"selected": false,
"text": "<p>I'm guessing Date.Parse() doesn't work?</p>\n"
},
{
"answer_id": 3194,
"author": "GateKiller",
"author_id"... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22/"
] | I have been trying to find a really fast way to parse yyyy-mm-dd [hh:mm:ss] into a Date object. Here are the 3 ways I have tried doing it and the times it takes each method to parse 50,000 date time strings.
Does anyone know any faster ways of doing this or tips to speed up the methods?
```
castMethod1 takes 3673 ms
castMethod2 takes 3812 ms
castMethod3 takes 3931 ms
```
Code:
```
private function castMethod1(dateString:String):Date {
if ( dateString == null ) {
return null;
}
var year:int = int(dateString.substr(0,4));
var month:int = int(dateString.substr(5,2))-1;
var day:int = int(dateString.substr(8,2));
if ( year == 0 && month == 0 && day == 0 ) {
return null;
}
if ( dateString.length == 10 ) {
return new Date(year, month, day);
}
var hour:int = int(dateString.substr(11,2));
var minute:int = int(dateString.substr(14,2));
var second:int = int(dateString.substr(17,2));
return new Date(year, month, day, hour, minute, second);
}
```
-
```
private function castMethod2(dateString:String):Date {
if ( dateString == null ) {
return null;
}
if ( dateString.indexOf("0000-00-00") != -1 ) {
return null;
}
dateString = dateString.split("-").join("/");
return new Date(Date.parse( dateString ));
}
```
-
```
private function castMethod3(dateString:String):Date {
if ( dateString == null ) {
return null;
}
var mainParts:Array = dateString.split(" ");
var dateParts:Array = mainParts[0].split("-");
if ( Number(dateParts[0])+Number(dateParts[1])+Number(dateParts[2]) == 0 ) {
return null;
}
return new Date( Date.parse( dateParts.join("/")+(mainParts[1]?" "+mainParts[1]:" ") ) );
}
```
---
No, Date.parse will not handle dashes by default. And I need to return null for date time strings like `"0000-00-00"`. | I've been using the following snipplet to parse UTC date strings:
```
private function parseUTCDate( str : String ) : Date {
var matches : Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)Z/);
var d : Date = new Date();
d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3]));
d.setUTCHours(int(matches[4]), int(matches[5]), int(matches[6]), 0);
return d;
}
```
Just remove the time part and it should work fine for your needs:
```
private function parseDate( str : String ) : Date {
var matches : Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d)/);
var d : Date = new Date();
d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3]));
return d;
}
```
No idea about the speed, I haven't been worried about that in my applications. 50K iterations in significantly less than a second on my machine. |
3,164 | <p>If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the <strong>fastest</strong> way to convert that absolute path back into a relative web path?</p>
| [
{
"answer_id": 3178,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 2,
"selected": false,
"text": "<p>If you used Server.MapPath, then you should already have the relative web path. According to the <a href=\"http://msdn.mic... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] | If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the **fastest** way to convert that absolute path back into a relative web path? | Perhaps this might work:
```
String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
```
*I'm using c# but could be adapted to vb.* |
3,196 | <p>If I have data like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Key</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Dan</td>
</tr>
<tr>
<td>2</td>
<td>Tom</td>
</tr>
<tr>
<td>3</td>
<td>Jon</td>
</tr>
<tr>
<td>4</td>
<td>Tom</td>
</tr>
<tr>
<td>5</td>
<td>Sam</td>
</tr>
<tr>
<td>6</td>
<td>Dan</td>
</tr>
</tbody>
</table>
</div>
<p>What is the SQL query to bring back the records where <code>Name</code> is repeated 2 or more times?</p>
<p>So the result I would want is</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Tom</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dan</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 3197,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 6,
"selected": true,
"text": "<p>Couldn't be simpler...</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>Select Name, Count(Name) As Count \n Fr... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] | If I have data like this:
| Key | Name |
| --- | --- |
| 1 | Dan |
| 2 | Tom |
| 3 | Jon |
| 4 | Tom |
| 5 | Sam |
| 6 | Dan |
What is the SQL query to bring back the records where `Name` is repeated 2 or more times?
So the result I would want is
| Tom |
| --- |
| Dan | | Couldn't be simpler...
```sql
Select Name, Count(Name) As Count
From Table
Group By Name
Having Count(Name) > 1
Order By Count(Name) Desc
```
This could also be extended to delete duplicates:
```sql
Delete From Table
Where Key In (
Select Max(Key)
From Table
Group By Name
Having Count(Name) > 1
)
``` |
3,213 | <p>Is there an efficient method of converting an integer into the written numbers, for example:</p>
<pre><code>string Written = IntegerToWritten(21);
</code></pre>
<p>would return "Twenty One".</p>
<p>Is there any way of doing this that doesn't involve a massive look-up table?</p>
| [
{
"answer_id": 3215,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 2,
"selected": false,
"text": "<p>why massive lookup table?</p>\n\n<pre><code>string GetWrittenInteger(int n)\n{\n string[] a = new string[] {\"One\", \"T... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | Is there an efficient method of converting an integer into the written numbers, for example:
```
string Written = IntegerToWritten(21);
```
would return "Twenty One".
Is there any way of doing this that doesn't involve a massive look-up table? | This should work reasonably well:
```
public static class HumanFriendlyInteger
{
static string[] ones = new string[] { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
static string[] teens = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
static string[] tens = new string[] { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
static string[] thousandsGroups = { "", " Thousand", " Million", " Billion" };
private static string FriendlyInteger(int n, string leftDigits, int thousands)
{
if (n == 0)
{
return leftDigits;
}
string friendlyInt = leftDigits;
if (friendlyInt.Length > 0)
{
friendlyInt += " ";
}
if (n < 10)
{
friendlyInt += ones[n];
}
else if (n < 20)
{
friendlyInt += teens[n - 10];
}
else if (n < 100)
{
friendlyInt += FriendlyInteger(n % 10, tens[n / 10 - 2], 0);
}
else if (n < 1000)
{
friendlyInt += FriendlyInteger(n % 100, (ones[n / 100] + " Hundred"), 0);
}
else
{
friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, "", thousands+1), 0);
if (n % 1000 == 0)
{
return friendlyInt;
}
}
return friendlyInt + thousandsGroups[thousands];
}
public static string IntegerToWritten(int n)
{
if (n == 0)
{
return "Zero";
}
else if (n < 0)
{
return "Negative " + IntegerToWritten(-n);
}
return FriendlyInteger(n, "", 0);
}
}
```
(Edited to fix a bug w/ million, billion, etc.) |
3,224 | <p>CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion.</p>
<hr />
<blockquote>
<p>Some solutions I have seen involve adding a version number to the end of the file in the form of a query string.</p>
<p>Could use the SVN revision number to automate this for you: <a href="https://stackoverflow.com/questions/2308/aspnet-display-svn-revision-number">ASP.NET Display SVN Revision Number</a></p>
</blockquote>
<p>Can you specify how you include the <a href="http://svnbook.red-bean.com/en/1.4/svn.advanced.props.special.keywords.html" rel="noreferrer">Revision</a> variable of another file? That is in the HTML file I can include the Revision number in the URL to the CSS or Javascript file.</p>
<p>In the <a href="http://svnbook.red-bean.com" rel="noreferrer">Subversion book</a> it says about Revision: "This keyword describes the last known revision in which this file changed in the repository".</p>
<blockquote>
<p>Firefox also allows pressing <kbd>CTRL</kbd>+<kbd>R</kbd> to reload everything on a particular page.</p>
</blockquote>
<p>To clarify I am looking for solutions that don't require the user to do anything on their part.</p>
| [
{
"answer_id": 3225,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 6,
"selected": true,
"text": "<p>I found that if you append the last modified timestamp of the file onto the end of the URL the browser will request the files whe... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486/"
] | CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion.
---
>
> Some solutions I have seen involve adding a version number to the end of the file in the form of a query string.
>
>
> Could use the SVN revision number to automate this for you: [ASP.NET Display SVN Revision Number](https://stackoverflow.com/questions/2308/aspnet-display-svn-revision-number)
>
>
>
Can you specify how you include the [Revision](http://svnbook.red-bean.com/en/1.4/svn.advanced.props.special.keywords.html) variable of another file? That is in the HTML file I can include the Revision number in the URL to the CSS or Javascript file.
In the [Subversion book](http://svnbook.red-bean.com) it says about Revision: "This keyword describes the last known revision in which this file changed in the repository".
>
> Firefox also allows pressing `CTRL`+`R` to reload everything on a particular page.
>
>
>
To clarify I am looking for solutions that don't require the user to do anything on their part. | I found that if you append the last modified timestamp of the file onto the end of the URL the browser will request the files when it is modified. For example in PHP:
```
function urlmtime($url) {
$parsed_url = parse_url($url);
$path = $parsed_url['path'];
if ($path[0] == "/") {
$filename = $_SERVER['DOCUMENT_ROOT'] . "/" . $path;
} else {
$filename = $path;
}
if (!file_exists($filename)) {
// If not a file then use the current time
$lastModified = date('YmdHis');
} else {
$lastModified = date('YmdHis', filemtime($filename));
}
if (strpos($url, '?') === false) {
$url .= '?ts=' . $lastModified;
} else {
$url .= '&ts=' . $lastModified;
}
return $url;
}
function include_css($css_url, $media='all') {
// According to Yahoo, using link allows for progressive
// rendering in IE where as @import url($css_url) does not
echo '<link rel="stylesheet" type="text/css" media="' .
$media . '" href="' . urlmtime($css_url) . '">'."\n";
}
function include_javascript($javascript_url) {
echo '<script type="text/javascript" src="' . urlmtime($javascript_url) .
'"></script>'."\n";
}
``` |
3,234 | <p>How would one display any add content from a "dynamic" aspx page? Currently I am working on using the System.Web.HttpResponse "Page.Response" to write a file that is stored on a web server to a web request.</p>
<p>This would allow people to hit a url to the type <a href="http://www.foo.com?Image=test.jpg" rel="noreferrer">http://www.foo.com?Image=test.jpg</a> and have the image display in their browser. So as you may know this revolves around the use of Response.ContentType.</p>
<p>By using </p>
<pre><code>Response.ContentType = "application/octet-stream";
</code></pre>
<p>I am able to display images of type gif/jpeg/png (all i have tested so far), bit trying to display .swf or .ico files gives me a nice little error.</p>
<p>using</p>
<pre><code>Response.ContentType = "application/x-shockwave-flash";
</code></pre>
<p>I can get flash files to play, but then the images are messed.</p>
<p>So how do i <strong>easily</strong> choose the contenttype?</p>
| [
{
"answer_id": 3240,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<p>This is part of a solution I use on a local intranet. Some of the variables you will have to collect yourself as I pull th... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231/"
] | How would one display any add content from a "dynamic" aspx page? Currently I am working on using the System.Web.HttpResponse "Page.Response" to write a file that is stored on a web server to a web request.
This would allow people to hit a url to the type <http://www.foo.com?Image=test.jpg> and have the image display in their browser. So as you may know this revolves around the use of Response.ContentType.
By using
```
Response.ContentType = "application/octet-stream";
```
I am able to display images of type gif/jpeg/png (all i have tested so far), bit trying to display .swf or .ico files gives me a nice little error.
using
```
Response.ContentType = "application/x-shockwave-flash";
```
I can get flash files to play, but then the images are messed.
So how do i **easily** choose the contenttype? | This is ugly, but the best way is to look at the file and set the content type as appropriate:
```
switch ( fileExtension )
{
case "pdf": Response.ContentType = "application/pdf"; break;
case "swf": Response.ContentType = "application/x-shockwave-flash"; break;
case "gif": Response.ContentType = "image/gif"; break;
case "jpeg": Response.ContentType = "image/jpg"; break;
case "jpg": Response.ContentType = "image/jpg"; break;
case "png": Response.ContentType = "image/png"; break;
case "mp4": Response.ContentType = "video/mp4"; break;
case "mpeg": Response.ContentType = "video/mpeg"; break;
case "mov": Response.ContentType = "video/quicktime"; break;
case "wmv":
case "avi": Response.ContentType = "video/x-ms-wmv"; break;
//and so on
default: Response.ContentType = "application/octet-stream"; break;
}
``` |
3,255 | <p>Most people with a degree in CS will certainly know what <a href="http://www.nist.gov/dads/HTML/bigOnotation.html" rel="noreferrer">Big O stands for</a>.
It helps us to measure how well an algorithm scales. </p>
<p>But I'm curious, how do <em>you</em> calculate or approximate the complexity of your algorithms?</p>
| [
{
"answer_id": 3280,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 3,
"selected": false,
"text": "<p>Familiarity with the algorithms/data structures I use and/or quick glance analysis of iteration nesting. The difficult... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46/"
] | Most people with a degree in CS will certainly know what [Big O stands for](http://www.nist.gov/dads/HTML/bigOnotation.html).
It helps us to measure how well an algorithm scales.
But I'm curious, how do *you* calculate or approximate the complexity of your algorithms? | I'll do my best to explain it here on simple terms, but be warned that this topic takes my students a couple of months to finally grasp. You can find more information on the Chapter 2 of the [Data Structures and Algorithms in Java](https://rads.stackoverflow.com/amzn/click/com/0321370139) book.
---
There is no [mechanical procedure](http://en.wikipedia.org/wiki/Halting_problem) that can be used to get the BigOh.
As a "cookbook", to obtain the [BigOh](http://en.wikipedia.org/wiki/Big_Oh_notation) from a piece of code you first need to realize that you are creating a math formula to count how many steps of computations get executed given an input of some size.
The purpose is simple: to compare algorithms from a theoretical point of view, without the need to execute the code. The lesser the number of steps, the faster the algorithm.
For example, let's say you have this piece of code:
```
int sum(int* data, int N) {
int result = 0; // 1
for (int i = 0; i < N; i++) { // 2
result += data[i]; // 3
}
return result; // 4
}
```
This function returns the sum of all the elements of the array, and we want to create a formula to count the [computational complexity](http://en.wikipedia.org/wiki/Computational_complexity_theory) of that function:
```
Number_Of_Steps = f(N)
```
So we have `f(N)`, a function to count the number of computational steps. The input of the function is the size of the structure to process. It means that this function is called such as:
```
Number_Of_Steps = f(data.length)
```
The parameter `N` takes the `data.length` value. Now we need the actual definition of the function `f()`. This is done from the source code, in which each interesting line is numbered from 1 to 4.
There are many ways to calculate the BigOh. From this point forward we are going to assume that every sentence that doesn't depend on the size of the input data takes a constant `C` number computational steps.
We are going to add the individual number of steps of the function, and neither the local variable declaration nor the return statement depends on the size of the `data` array.
That means that lines 1 and 4 takes C amount of steps each, and the function is somewhat like this:
```
f(N) = C + ??? + C
```
The next part is to define the value of the `for` statement. Remember that we are counting the number of computational steps, meaning that the body of the `for` statement gets executed `N` times. That's the same as adding `C`, `N` times:
```
f(N) = C + (C + C + ... + C) + C = C + N * C + C
```
There is no mechanical rule to count how many times the body of the `for` gets executed, you need to count it by looking at what does the code do. To simplify the calculations, we are ignoring the variable initialization, condition and increment parts of the `for` statement.
To get the actual BigOh we need the [Asymptotic analysis](http://en.wikipedia.org/wiki/Asymptotic_analysis) of the function. This is roughly done like this:
1. Take away all the constants `C`.
2. From `f()` get the [polynomium](http://en.wikipedia.org/wiki/Polynomial) in its `standard form`.
3. Divide the terms of the polynomium and sort them by the rate of growth.
4. Keep the one that grows bigger when `N` approaches `infinity`.
Our `f()` has two terms:
```
f(N) = 2 * C * N ^ 0 + 1 * C * N ^ 1
```
Taking away all the `C` constants and redundant parts:
```
f(N) = 1 + N ^ 1
```
Since the last term is the one which grows bigger when `f()` approaches infinity (think on [limits](http://en.wikipedia.org/wiki/Limit_%28mathematics%29)) this is the BigOh argument, and the `sum()` function has a BigOh of:
```
O(N)
```
---
There are a few tricks to solve some tricky ones: use [summations](http://en.wikipedia.org/wiki/Summation) whenever you can.
As an example, this code can be easily solved using summations:
```
for (i = 0; i < 2*n; i += 2) { // 1
for (j=n; j > i; j--) { // 2
foo(); // 3
}
}
```
The first thing you needed to be asked is the order of execution of `foo()`. While the usual is to be `O(1)`, you need to ask your professors about it. `O(1)` means (almost, mostly) constant `C`, independent of the size `N`.
The `for` statement on the sentence number one is tricky. While the index ends at `2 * N`, the increment is done by two. That means that the first `for` gets executed only `N` steps, and we need to divide the count by two.
```
f(N) = Summation(i from 1 to 2 * N / 2)( ... ) =
= Summation(i from 1 to N)( ... )
```
The sentence number *two* is even trickier since it depends on the value of `i`. Take a look: the index i takes the values: 0, 2, 4, 6, 8, ..., 2 \* N, and the second `for` get executed: N times the first one, N - 2 the second, N - 4 the third... up to the N / 2 stage, on which the second `for` never gets executed.
On formula, that means:
```
f(N) = Summation(i from 1 to N)( Summation(j = ???)( ) )
```
Again, we are counting **the number of steps**. And by definition, every summation should always start at one, and end at a number bigger-or-equal than one.
```
f(N) = Summation(i from 1 to N)( Summation(j = 1 to (N - (i - 1) * 2)( C ) )
```
(We are assuming that `foo()` is `O(1)` and takes `C` steps.)
We have a problem here: when `i` takes the value `N / 2 + 1` upwards, the inner Summation ends at a negative number! That's impossible and wrong. We need to split the summation in two, being the pivotal point the moment `i` takes `N / 2 + 1`.
```
f(N) = Summation(i from 1 to N / 2)( Summation(j = 1 to (N - (i - 1) * 2)) * ( C ) ) + Summation(i from 1 to N / 2) * ( C )
```
Since the pivotal moment `i > N / 2`, the inner `for` won't get executed, and we are assuming a constant C execution complexity on its body.
Now the summations can be simplified using some identity rules:
1. Summation(w from 1 to N)( C ) = N \* C
2. Summation(w from 1 to N)( A (+/-) B ) = Summation(w from 1 to N)( A ) (+/-) Summation(w from 1 to N)( B )
3. Summation(w from 1 to N)( w \* C ) = C \* Summation(w from 1 to N)( w ) (C is a constant, independent of `w`)
4. Summation(w from 1 to N)( w ) = (N \* (N + 1)) / 2
Applying some algebra:
```
f(N) = Summation(i from 1 to N / 2)( (N - (i - 1) * 2) * ( C ) ) + (N / 2)( C )
f(N) = C * Summation(i from 1 to N / 2)( (N - (i - 1) * 2)) + (N / 2)( C )
f(N) = C * (Summation(i from 1 to N / 2)( N ) - Summation(i from 1 to N / 2)( (i - 1) * 2)) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2)( i - 1 )) + (N / 2)( C )
=> Summation(i from 1 to N / 2)( i - 1 ) = Summation(i from 1 to N / 2 - 1)( i )
f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2 - 1)( i )) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N / 2 - 1) * (N / 2 - 1 + 1) / 2) ) + (N / 2)( C )
=> (N / 2 - 1) * (N / 2 - 1 + 1) / 2 =
(N / 2 - 1) * (N / 2) / 2 =
((N ^ 2 / 4) - (N / 2)) / 2 =
(N ^ 2 / 8) - (N / 4)
f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N ^ 2 / 8) - (N / 4) )) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - ( (N ^ 2 / 4) - (N / 2) )) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - (N ^ 2 / 4) + (N / 2)) + (N / 2)( C )
f(N) = C * ( N ^ 2 / 4 ) + C * (N / 2) + C * (N / 2)
f(N) = C * ( N ^ 2 / 4 ) + 2 * C * (N / 2)
f(N) = C * ( N ^ 2 / 4 ) + C * N
f(N) = C * 1/4 * N ^ 2 + C * N
```
And the BigOh is:
```
O(N²)
``` |
3,281 | <p>I'm wondering if there's a way to do what I can do below with Python, in Ruby:</p>
<pre><code>sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data))
</code></pre>
<p>I have two arrays of equal sizes with the weights and data but I can't seem to find a function similar to map in Ruby, reduce I have working.</p>
| [
{
"answer_id": 3314,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 2,
"selected": false,
"text": "<p>The Array.zip function does an elementwise combination of arrays. It's not quite as clean as the Python syntax, but ... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/484/"
] | I'm wondering if there's a way to do what I can do below with Python, in Ruby:
```
sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data))
```
I have two arrays of equal sizes with the weights and data but I can't seem to find a function similar to map in Ruby, reduce I have working. | @Michiel de Mare
Your Ruby 1.9 example can be shortened a bit further:
```
weights.zip(data).map(:*).reduce(:+)
```
Also note that in Ruby 1.8, if you require ActiveSupport (from Rails) you can use:
```
weights.zip(data).map(&:*).reduce(&:+)
``` |
3,284 | <p>I've been working with <a href="http://msdn.microsoft.com/en-us/library/aa479030.aspx" rel="noreferrer">providers</a> a fair bit lately, and I came across an interesting situation where I wanted to have an abstract class that had an abstract static method. I read a few posts on the topic, and it sort of made sense, but is there a nice clear explanation?</p>
| [
{
"answer_id": 3291,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 6,
"selected": false,
"text": "<p>Static methods cannot be inherited or overridden, and that is why they can't be abstract. Since static methods are defi... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] | I've been working with [providers](http://msdn.microsoft.com/en-us/library/aa479030.aspx) a fair bit lately, and I came across an interesting situation where I wanted to have an abstract class that had an abstract static method. I read a few posts on the topic, and it sort of made sense, but is there a nice clear explanation? | Static methods are not *instantiated* as such, they're just available without an object reference.
A call to a static method is done through the class name, not through an object reference, and the Intermediate Language (IL) code to call it will call the abstract method through the name of the class that defined it, not necessarily the name of the class you used.
Let me show an example.
With the following code:
```
public class A
{
public static void Test()
{
}
}
public class B : A
{
}
```
If you call B.Test, like this:
```
class Program
{
static void Main(string[] args)
{
B.Test();
}
}
```
Then the actual code inside the Main method is as follows:
```
.entrypoint
.maxstack 8
L0000: nop
L0001: call void ConsoleApplication1.A::Test()
L0006: nop
L0007: ret
```
As you can see, the call is made to A.Test, because it was the A class that defined it, and not to B.Test, even though you can write the code that way.
If you had *class types*, like in Delphi, where you can make a variable referring to a type and not an object, you would have more use for virtual and thus abstract static methods (and also constructors), but they aren't available and thus static calls are non-virtual in .NET.
I realize that the IL designers could allow the code to be compiled to call B.Test, and resolve the call at runtime, but it still wouldn't be virtual, as you would still have to write some kind of class name there.
Virtual methods, and thus abstract ones, are only useful when you're using a variable which, at runtime, can contain many different types of objects, and you thus want to call the right method for the current object you have in the variable. With static methods you need to go through a class name anyway, so the exact method to call is known at compile time because it can't and won't change.
Thus, virtual/abstract static methods are not available in .NET. |
3,315 | <p>I need to set the height of every textbox on my form, some of which are nested within other controls. I thought I could do something like this:</p>
<pre><code>private static IEnumerator<TextBox> FindTextBoxes(Control rootControl)
{
foreach (Control control in rootControl.Controls)
{
if (control.Controls.Count > 0)
{
// Recursively search for any TextBoxes within each child control
foreach (TextBox textBox in FindTextBoxes(control))
{
yield return textBox;
}
}
TextBox textBox2 = control as TextBox;
if (textBox2 != null)
{
yield return textBox2;
}
}
}
</code></pre>
<p>Using it like this:</p>
<pre><code>foreach(TextBox textBox in FindTextBoxes(this))
{
textBox.Height = height;
}
</code></pre>
<p>But of course the compiler spits its dummy, because <em>foreach</em> expects an <strong>IEnumerable</strong> rather than an <strong>IEnumerator</strong>.</p>
<p>Is there a way to do this without having to create a separate class with a <strong>GetEnumerator()</strong> method?</p>
| [
{
"answer_id": 3316,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 5,
"selected": true,
"text": "<p>As the compiler is telling you, you need to change your return type to IEnumerable. That is how the yield return syntax ... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/503/"
] | I need to set the height of every textbox on my form, some of which are nested within other controls. I thought I could do something like this:
```
private static IEnumerator<TextBox> FindTextBoxes(Control rootControl)
{
foreach (Control control in rootControl.Controls)
{
if (control.Controls.Count > 0)
{
// Recursively search for any TextBoxes within each child control
foreach (TextBox textBox in FindTextBoxes(control))
{
yield return textBox;
}
}
TextBox textBox2 = control as TextBox;
if (textBox2 != null)
{
yield return textBox2;
}
}
}
```
Using it like this:
```
foreach(TextBox textBox in FindTextBoxes(this))
{
textBox.Height = height;
}
```
But of course the compiler spits its dummy, because *foreach* expects an **IEnumerable** rather than an **IEnumerator**.
Is there a way to do this without having to create a separate class with a **GetEnumerator()** method? | As the compiler is telling you, you need to change your return type to IEnumerable. That is how the yield return syntax works. |
3,319 | <p>How can I set the background color of an HTML element using css in JavaScript?</p>
| [
{
"answer_id": 3320,
"author": "tags2k",
"author_id": 192,
"author_profile": "https://Stackoverflow.com/users/192",
"pm_score": 5,
"selected": false,
"text": "<pre><code>var element = document.getElementById('element');\nelement.style.background = '#FF00AA';\n</code></pre>\n"
},
{
... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | How can I set the background color of an HTML element using css in JavaScript? | In general, CSS properties are converted to JavaScript by making them camelCase without any dashes. So `background-color` becomes `backgroundColor`.
```
function setColor(element, color)
{
element.style.backgroundColor = color;
}
// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');
``` |
3,362 | <p>I would like to be able to use the <kbd>Tab</kbd> key within a text box to tab over four spaces. The way it is now, the Tab key jumps my cursor to the next input.</p>
<p>Is there some JavaScript that will capture the Tab key in the text box before it bubbles up to the UI?</p>
<p>I understand some browsers (i.e. FireFox) may not allow this. How about a custom key-combo like <kbd>Shift</kbd>+<kbd>Tab</kbd>, or <kbd>Ctrl</kbd>+<kbd>Q</kbd>?</p>
| [
{
"answer_id": 3370,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 4,
"selected": false,
"text": "<p>The previous answer is fine, but I'm one of those guys that's firmly against mixing behavior with presentation (putting JavaScript ... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] | I would like to be able to use the `Tab` key within a text box to tab over four spaces. The way it is now, the Tab key jumps my cursor to the next input.
Is there some JavaScript that will capture the Tab key in the text box before it bubbles up to the UI?
I understand some browsers (i.e. FireFox) may not allow this. How about a custom key-combo like `Shift`+`Tab`, or `Ctrl`+`Q`? | Even if you capture the `keydown`/`keyup` event, those are the only events that the tab key fires, you still need some way to prevent the default action, moving to the next item in the tab order, from occurring.
In Firefox you can call the `preventDefault()` method on the event object passed to your event handler. In IE, you have to return false from the event handle. The JQuery library provides a `preventDefault` method on its event object that works in IE and FF.
```
<body>
<input type="text" id="myInput">
<script type="text/javascript">
var myInput = document.getElementById("myInput");
if(myInput.addEventListener ) {
myInput.addEventListener('keydown',this.keyHandler,false);
} else if(myInput.attachEvent ) {
myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
}
function keyHandler(e) {
var TABKEY = 9;
if(e.keyCode == TABKEY) {
this.value += " ";
if(e.preventDefault) {
e.preventDefault();
}
return false;
}
}
</script>
</body>
``` |
3,400 | <p><strong>Note:</strong> I <em>am</em> using SQL's Full-text search capabilities, CONTAINS clauses and all - the * is the wildcard in full-text, % is for LIKE clauses only.</p>
<p>I've read in several places now that "leading wildcard" searches (e.g. using "*overflow" to match "stackoverflow") is not supported in MS SQL. I'm considering using a <a href="http://blogs.msdn.com/sqlclr/archive/2005/06/29/regex.aspx" rel="noreferrer" title="SQL CLR Blog">CLR function to add regex matching</a>, but I'm curious to see what other solutions people might have.</p>
<p><strong>More Info</strong>: <a href="http://msdn.microsoft.com/en-us/library/ms552152.aspx" rel="noreferrer" title="MSDN">You can add the asterisk only at the end of the word or phrase.</a> - along with my empirical experience: When matching "myvalue", "my*" works, but "(asterisk)value" returns no match, when doing a query as simple as:</p>
<pre><code>SELECT * FROM TABLENAME WHERE CONTAINS(TextColumn, '"*searchterm"');
</code></pre>
<p>Thus, my need for a workaround. I'm only using search in my site on an actual search page - so it needs to work basically the same way that Google works (in the eyes on a Joe Sixpack-type user). Not nearly as complicated, but this sort of match really shouldn't fail.</p>
| [
{
"answer_id": 3405,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Note</strong>: this was the answer I submitted for the original version #1 of the question before the <code>CONTAINS</cod... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35/"
] | **Note:** I *am* using SQL's Full-text search capabilities, CONTAINS clauses and all - the \* is the wildcard in full-text, % is for LIKE clauses only.
I've read in several places now that "leading wildcard" searches (e.g. using "\*overflow" to match "stackoverflow") is not supported in MS SQL. I'm considering using a [CLR function to add regex matching](http://blogs.msdn.com/sqlclr/archive/2005/06/29/regex.aspx "SQL CLR Blog"), but I'm curious to see what other solutions people might have.
**More Info**: [You can add the asterisk only at the end of the word or phrase.](http://msdn.microsoft.com/en-us/library/ms552152.aspx "MSDN") - along with my empirical experience: When matching "myvalue", "my\*" works, but "(asterisk)value" returns no match, when doing a query as simple as:
```
SELECT * FROM TABLENAME WHERE CONTAINS(TextColumn, '"*searchterm"');
```
Thus, my need for a workaround. I'm only using search in my site on an actual search page - so it needs to work basically the same way that Google works (in the eyes on a Joe Sixpack-type user). Not nearly as complicated, but this sort of match really shouldn't fail. | Workaround only for leading wildcard:
* store the text reversed in a different field (or in materialised view)
* create a full text index on this column
* find the reversed text with an \*
```
SELECT *
FROM TABLENAME
WHERE CONTAINS(TextColumnREV, '"mrethcraes*"');
```
Of course there are many drawbacks, just for quick workaround...
Not to mention CONTAINSTABLE... |
3,432 | <p>I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL?</p>
<p>Edit:
For example I have the following</p>
<pre><code>Name id Col1 Col2
Row1 1 6 1
Row2 2 2 3
Row3 3 9 5
Row4 4 16 8
</code></pre>
<p>I want to combine all the following Updates into one query</p>
<pre><code>UPDATE table SET Col1 = 1 WHERE id = 1;
UPDATE table SET Col1 = 2 WHERE id = 2;
UPDATE table SET Col2 = 3 WHERE id = 3;
UPDATE table SET Col1 = 10 WHERE id = 4;
UPDATE table SET Col2 = 12 WHERE id = 4;
</code></pre>
| [
{
"answer_id": 3439,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 3,
"selected": false,
"text": "<pre><code>UPDATE table1, table2 SET table1.col1='value', table2.col1='value' WHERE table1.col3='567' AND table2.col6='567'\n<... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL?
Edit:
For example I have the following
```
Name id Col1 Col2
Row1 1 6 1
Row2 2 2 3
Row3 3 9 5
Row4 4 16 8
```
I want to combine all the following Updates into one query
```
UPDATE table SET Col1 = 1 WHERE id = 1;
UPDATE table SET Col1 = 2 WHERE id = 2;
UPDATE table SET Col2 = 3 WHERE id = 3;
UPDATE table SET Col1 = 10 WHERE id = 4;
UPDATE table SET Col2 = 12 WHERE id = 4;
``` | Yes, that's possible - you can use INSERT ... ON DUPLICATE KEY UPDATE.
Using your example:
```
INSERT INTO table (id,Col1,Col2) VALUES (1,1,1),(2,2,3),(3,9,3),(4,10,12)
ON DUPLICATE KEY UPDATE Col1=VALUES(Col1),Col2=VALUES(Col2);
``` |
3,437 | <p>We recently discovered that the Google Maps API does not play nicely with SSL. Fair enough, but what are some options for overcoming this that others have used effectively?</p>
<blockquote>
<p><a href="http://code.google.com/support/bin/answer.py?answer=65301&topic=10945" rel="noreferrer">Will the Maps API work over SSL (HTTPS)?</a></p>
<p>At this time, the Maps API is not
available over a secure (SSL)
connection. If you are running the
Maps API on a secure site, the browser
may warn the user about non-secure
objects on the screen.</p>
</blockquote>
<p>We have considered the following options</p>
<ol>
<li>Splitting the page so that credit card collection (the requirement for SSL) is not on the same page as the Google Map.</li>
<li>Switching to another map provider, such as Virtual Earth. Rumor has it that they support SSL.</li>
<li>Playing tricks with IFRAMEs. Sounds kludgy.</li>
<li>Proxying the calls to Google. Sounds like a lot of overhead.</li>
</ol>
<p>Are there other options, or does anyone have insight into the options that we have considered?</p>
| [
{
"answer_id": 3476,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 2,
"selected": false,
"text": "<p>I would go with your first solution. This allows the user to focus on entering their credit card details.</p>\n\n<p>You ca... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/308/"
] | We recently discovered that the Google Maps API does not play nicely with SSL. Fair enough, but what are some options for overcoming this that others have used effectively?
>
> [Will the Maps API work over SSL (HTTPS)?](http://code.google.com/support/bin/answer.py?answer=65301&topic=10945)
>
>
> At this time, the Maps API is not
> available over a secure (SSL)
> connection. If you are running the
> Maps API on a secure site, the browser
> may warn the user about non-secure
> objects on the screen.
>
>
>
We have considered the following options
1. Splitting the page so that credit card collection (the requirement for SSL) is not on the same page as the Google Map.
2. Switching to another map provider, such as Virtual Earth. Rumor has it that they support SSL.
3. Playing tricks with IFRAMEs. Sounds kludgy.
4. Proxying the calls to Google. Sounds like a lot of overhead.
Are there other options, or does anyone have insight into the options that we have considered? | I'd agree with the previous two answers that in this instance it may be better from a usability perspective to split the two functions into separate screens. You really want your users to be focussed on entering complete and accurate credit card information, and having a map on the same screen may be distracting.
For the record though, Virtual Earth certainly does fully support SSL. To enable it you simple need to change the script reference from http:// to https:// and append &s=1 to the URL, e.g.
```
<script src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1" type="text/javascript"></script>
```
becomes
```
<script src="https://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1&s=1" type="text/javascript"></script>
``` |
3,470 | <p>I have a very simple problem which requires a very quick and simple solution in SQL Server 2005.</p>
<p>I have a table with x Columns. I want to be able to select one row from the table and then transform the columns into rows.</p>
<pre><code>TableA
Column1, Column2, Column3
</code></pre>
<p>SQL Statement to ruturn</p>
<pre><code>ResultA
Value of Column1
Value of Column2
Value of Column3
</code></pre>
<hr>
<p><strong>@Kevin:</strong> I've had a google search on the topic but alot of the example where overly complex for my example, <strong>are you able to help further?</strong></p>
<p>@Mario: The solution I am creating has 10 columns which stores the values 0 to 6 and I must work out how many columns have the value 3 or more. So I thought about creating a query to turn that into rows and then using the generated table in a subquery to say count the number of rows with Column >= 3</p>
| [
{
"answer_id": 3473,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 4,
"selected": true,
"text": "<p>You should take a look at the UNPIVOT clause.</p>\n\n<p><strong>Update1</strong>: GateKiller, strangely enough I read an article (... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | I have a very simple problem which requires a very quick and simple solution in SQL Server 2005.
I have a table with x Columns. I want to be able to select one row from the table and then transform the columns into rows.
```
TableA
Column1, Column2, Column3
```
SQL Statement to ruturn
```
ResultA
Value of Column1
Value of Column2
Value of Column3
```
---
**@Kevin:** I've had a google search on the topic but alot of the example where overly complex for my example, **are you able to help further?**
@Mario: The solution I am creating has 10 columns which stores the values 0 to 6 and I must work out how many columns have the value 3 or more. So I thought about creating a query to turn that into rows and then using the generated table in a subquery to say count the number of rows with Column >= 3 | You should take a look at the UNPIVOT clause.
**Update1**: GateKiller, strangely enough I read an article (about something unrelated) about it this morning and I'm trying to jog my memory where I saw it again, had some decent looking examples too. It'll come back to me I'm sure.
**Update2**: Found it: <http://weblogs.sqlteam.com/jeffs/archive/2008/04/23/unpivot.aspx> |
3,486 | <p>I have control over the HttpServer but not over the ApplicationServer or the Java Applications sitting there but I need to block direct access to certain pages on those applications. Precisely, I don't want users automating access to forms issuing direct GET/POST HTTP requests to the appropriate servlet. </p>
<p>So, I decided to block users based on the value of <code>HTTP_REFERER</code>. After all, if the user is navigating inside the site, it will have an appropriate <code>HTTP_REFERER</code>. Well, that was what I thought. </p>
<p>I implemented a rewrite rule in the .htaccess file that says: </p>
<pre><code>RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} !^http://mywebaddress(.cl)?/.* [NC]
RewriteRule (servlet1|servlet2)/.+\?.+ - [F]
</code></pre>
<p>I expected to forbid access to users that didn't navigate the site but issue direct GET requests to the "servlet1" or "servlet2" servlets using querystrings. But my expectations ended abruptly because the regular expression <code>(servlet1|servlet2)/.+\?.+</code> didn't worked at all. </p>
<p>I was really disappointed when I changed that expression to <code>(servlet1|servlet2)/.+</code> and it worked so well that my users were blocked no matter if they navigated the site or not. </p>
<p>So, my question is: How do I can accomplish this thing of not allowing "robots" with direct access to certain pages if I have no access/privileges/time to modify the application?</p>
| [
{
"answer_id": 3502,
"author": "Rytmis",
"author_id": 266,
"author_profile": "https://Stackoverflow.com/users/266",
"pm_score": 1,
"selected": false,
"text": "<p>I don't have a solution, but I'm betting that relying on the referrer will never work because user-agents are free to not send... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/527/"
] | I have control over the HttpServer but not over the ApplicationServer or the Java Applications sitting there but I need to block direct access to certain pages on those applications. Precisely, I don't want users automating access to forms issuing direct GET/POST HTTP requests to the appropriate servlet.
So, I decided to block users based on the value of `HTTP_REFERER`. After all, if the user is navigating inside the site, it will have an appropriate `HTTP_REFERER`. Well, that was what I thought.
I implemented a rewrite rule in the .htaccess file that says:
```
RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} !^http://mywebaddress(.cl)?/.* [NC]
RewriteRule (servlet1|servlet2)/.+\?.+ - [F]
```
I expected to forbid access to users that didn't navigate the site but issue direct GET requests to the "servlet1" or "servlet2" servlets using querystrings. But my expectations ended abruptly because the regular expression `(servlet1|servlet2)/.+\?.+` didn't worked at all.
I was really disappointed when I changed that expression to `(servlet1|servlet2)/.+` and it worked so well that my users were blocked no matter if they navigated the site or not.
So, my question is: How do I can accomplish this thing of not allowing "robots" with direct access to certain pages if I have no access/privileges/time to modify the application? | I'm not sure if I can solve this in one go, but we can go back and forth as necessary.
First, I want to repeat what I think you are saying and make sure I'm clear. You want to disallow requests to servlet1 and servlet2 is the request doesn't have the proper referer and it **does** have a query string? I'm not sure I understand (servlet1|servlet2)/.+\?.+ because it looks like you are requiring a file under servlet1 and 2. I think maybe you are combining PATH\_INFO (before the "?") with a GET query string (after the "?"). It appears that the PATH\_INFO part will work but the GET query test will not. I made a quick test on my server using script1.cgi and script2.cgi and the following rules worked to accomplish what you are asking for. They are obviously edited a little to match my environment:
```
RewriteCond %{HTTP_REFERER} !^http://(www.)?example.(com|org) [NC]
RewriteCond %{QUERY_STRING} ^.+$
RewriteRule ^(script1|script2)\.cgi - [F]
```
The above caught all wrong-referer requests to script1.cgi and script2.cgi that tried to submit data using a query string. However, you can also submit data using a path\_info and by posting data. I used this form to protect against any of the three methods being used with incorrect referer:
```
RewriteCond %{HTTP_REFERER} !^http://(www.)?example.(com|org) [NC]
RewriteCond %{QUERY_STRING} ^.+$ [OR]
RewriteCond %{REQUEST_METHOD} ^POST$ [OR]
RewriteCond %{PATH_INFO} ^.+$
RewriteRule ^(script1|script2)\.cgi - [F]
```
Based on the example you were trying to get working, I think this is what you want:
```
RewriteCond %{HTTP_REFERER} !^http://mywebaddress(.cl)?/.* [NC]
RewriteCond %{QUERY_STRING} ^.+$ [OR]
RewriteCond %{REQUEST_METHOD} ^POST$ [OR]
RewriteCond %{PATH_INFO} ^.+$
RewriteRule (servlet1|servlet2)\b - [F]
```
Hopefully this at least gets you closer to your goal. Please let us know how it works, I'm interested in your problem.
(BTW, I agree that referer blocking is poor security, but I also understand that relaity forces imperfect and partial solutions sometimes, which you seem to already acknowledge.) |
3,510 | <p>What is BODMAS and why is it useful in programming?</p>
| [
{
"answer_id": 3511,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://www.easymaths.com/What_on_earth_is_Bodmas.htm\" rel=\"noreferrer\">http://www.easymaths.com/What_on_earth_... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | What is BODMAS and why is it useful in programming? | <http://www.easymaths.com/What_on_earth_is_Bodmas.htm>:
>
> What do you think the answer to 2 + 3 x 5 is?
>
>
> Is it (2 + 3) x 5 = 5 x 5 = 25 ?
>
>
> or 2 + (3 x 5) = 2 + 15 = 17 ?
>
>
> BODMAS can come to the rescue and give us rules to follow so that we always get the right answer:
>
>
> (B)rackets (O)rder (D)ivision (M)ultiplication (A)ddition (S)ubtraction
>
>
> According to BODMAS, multiplication should always be done before addition, therefore 17 is actually the correct answer according to BODMAS and will also be the answer which your calculator will give if you type in 2 + 3 x 5 .
>
>
>
Why it is useful in programming? No idea, but i assume it's because you can get rid of some brackets? I am a quite defensive programmer, so my lines can look like this:
```
result = (((i + 4) - (a + b)) * MAGIC_NUMBER) - ANOTHER_MAGIC_NUMBER;
```
with BODMAS you can make this a bit clearer:
```
result = (i + 4 - (a + b)) * MAGIC_NUMBER - ANOTHER_MAGIC_NUMBER;
```
I think i'd still use the first variant - more brackets, but that way i do not have to learn yet another rule and i run into less risk of forgetting it and causing those weird hard to debug errors?
Just guessing at that part though.
Mike Stone EDIT: Fixed math as Gaius points out |
3,530 | <p>I have a <code>Rakefile</code> with a Rake task that I would normally call from the command line:</p>
<pre><code>rake blog:post Title
</code></pre>
<p>I'd like to write a Ruby script that calls that Rake task multiple times, but the only solution I see is shelling out using `` (backticks) or <code>system</code>.</p>
<p>What's the right way to do this?</p>
| [
{
"answer_id": 3543,
"author": "titanous",
"author_id": 399,
"author_profile": "https://Stackoverflow.com/users/399",
"pm_score": 7,
"selected": true,
"text": "<p>from <a href=\"http://web.archive.org/web/20090412040557/http://timocracy.com:80/articles/2008/02/21/calling-invoking-rails-r... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1388162/"
] | I have a `Rakefile` with a Rake task that I would normally call from the command line:
```
rake blog:post Title
```
I'd like to write a Ruby script that calls that Rake task multiple times, but the only solution I see is shelling out using `` (backticks) or `system`.
What's the right way to do this? | from [timocracy.com](http://web.archive.org/web/20090412040557/http://timocracy.com:80/articles/2008/02/21/calling-invoking-rails-rake-tasks-from-within-ruby-for-testing-try-2):
```
require 'rake'
def capture_stdout
s = StringIO.new
oldstdout = $stdout
$stdout = s
yield
s.string
ensure
$stdout = oldstdout
end
Rake.application.rake_require 'metric_fetcher', ['../../lib/tasks']
results = capture_stdout {Rake.application['metric_fetcher'].invoke}
``` |
3,567 | <p>In SQL Server how do you query a database to bring back all the tables that have a field of a specific name?</p>
| [
{
"answer_id": 3574,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SELECT Table_Name\nFROM Information_Schema.Columns\nWHERE Column_Name = 'YourFieldName'\n</code></pre>\n"
},
{
"a... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] | In SQL Server how do you query a database to bring back all the tables that have a field of a specific name? | The following query will bring back a unique list of tables where `Column_Name` is equal to the column you are looking for:
```
SELECT Table_Name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE Column_Name = 'Desired_Column_Name'
GROUP BY Table_Name
``` |
3,585 | <p>I want to create my Rails application with MySQL, because I like it so much. How can I do that in the latest version of Rails instead of the default SQLite?</p>
| [
{
"answer_id": 3586,
"author": "Daniel Broekman",
"author_id": 124,
"author_profile": "https://Stackoverflow.com/users/124",
"pm_score": 8,
"selected": false,
"text": "<p>Normally, you would create a new Rails app using</p>\n\n<pre><code>rails ProjectName\n</code></pre>\n\n<p>To use MySQ... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124/"
] | I want to create my Rails application with MySQL, because I like it so much. How can I do that in the latest version of Rails instead of the default SQLite? | If you already have a rails project, change the adapter in the `config/database.yml` file to `mysql` and make sure you specify a valid username and password, and optionally, a socket:
```
development:
adapter: mysql2
database: db_name_dev
username: koploper
password:
host: localhost
socket: /tmp/mysql.sock
```
Next, make sure you edit your Gemfile to include the mysql2 or activerecord-jdbcmysql-adapter (if using jruby). |
3,607 | <p>I've got TotroiseSVN installed and have a majority of my repositories checking in and out from C:\subversion\ <em>and a couple checking in and out from a network share (I forgot about this when I originally posted this question)</em>.</p>
<p>This means that I don't have a "subversion" server per-se.</p>
<p>How do I integrate TortoiseSVN and Fogbugz?</p>
<p><em>Edit: inserted italics</em></p>
| [
{
"answer_id": 3610,
"author": "cmcculloh",
"author_id": 58,
"author_profile": "https://Stackoverflow.com/users/58",
"pm_score": 4,
"selected": false,
"text": "<p><strong>This answer is incomplete and flawed! It only works from TortoisSVN to Fogbugz, but not the other way around. I still... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58/"
] | I've got TotroiseSVN installed and have a majority of my repositories checking in and out from C:\subversion\ *and a couple checking in and out from a network share (I forgot about this when I originally posted this question)*.
This means that I don't have a "subversion" server per-se.
How do I integrate TortoiseSVN and Fogbugz?
*Edit: inserted italics* | I've been investigating this issue and have managed to get it working. There are a couple of minor problems but they can be worked-around.
There are 3 distinct parts to this problem, as follows:
1. **The TortoiseSVN part** - getting TortoiseSVN to insert the Bugid and hyperlink in the svn log
2. **The FogBugz part** - getting FogBugz to insert the SVN info and corresponding links
3. **The WebSVN part** - ensuring the links from FogBugz actually work
Instructions for part 1 are in another answer, although it actually does more than required. The stuff about the hooks is actually for part 2, and as is pointed out - it doesn't work "out of the box"
**Just to confirm, we are looking at using TortoiseSVN *WITHOUT* an SVN server (ie. file-based repositories)**
I'm accessing the repositories using UNC paths, but it also works for local drives or mapped drives.
All of this works with TortoiseSVN v1.5.3 and SVN Server v1.5.2 (You need to install SVN Server because part 2 needs `svnlook.exe` which is in the server package. You don't actually configure it to work as an SVN Server) It may even be possible to just copy `svnlook.exe` from another computer and put it somewhere in your path.
Part 1 - TortoiseSVN
====================
Creating the TortoiseSVN properties is all that is required in order to get the links in the SVN log.
Previous instructions work fine, I'll quote them here for convenience:
>
> Configure the Properties
> ------------------------
>
>
> 1. Right click on the root directory of the checked out project you want to work with.
> 2. Select "TortoiseSVN -> Properties"
> 3. Add five property value pairs by clicking "New..." and inserting the following in "Property Name" and "Property Value" respectively: (make sure you tick "Apply property recursively" for each one)
>
>
>
> ```
> bugtraq:label BugzID:
> bugtraq:message BugzID: %BUGID%
> bugtraq:number true
> bugtraq:url http://[your fogbugz URL here]/default.asp?%BUGID%
> bugtraq:warnifnoissue false
>
> ```
> 4. Click "OK"
>
>
>
As Jeff says, you'll need to do that for each working copy, so follow his instructions for migrating the properties.
That's it. TortoiseSVN will now add a link to the corresponding FogBugz bugID when you commit. If that's all you want, you can stop here.
Part 2 - FogBugz
================
For this to work we need to set up the hook scripts. Basically the batch file is called after each commit, and this in turn calls the VBS script which does the submission to FogBugz. The VBS script actually works fine in this situation so we don't need to modify it.
The problem is that the batch file is written to work as a *server* hook, but we need a *client* hook.
SVN server calls the post-commit hook with these parameters:
```
<repository-path> <revision>
```
TortoiseSVN calls the post-commit hook with these parameters:
```
<affected-files> <depth> <messagefile> <revision> <error> <working-copy-path>
```
So that's why it doesn't work - the parameters are wrong. We need to amend the batch file so it passes the correct parameters to the VBS script.
You'll notice that TSVN doesn't pass the repository path, which is a problem, but it does work in the following circumstances:
* The repository name and working copy name are the same
* You do the commit at the root of the working copy, not a subfolder.
I'm going to see if I can fix this problem and will post back here if I do.
Here's my amended batch file which does work (please excuse the excessive comments...)
You'll need to set the hook and repository directories to match your setup.
```
rem @echo off
rem SubVersion -> FogBugz post-commit hook file
rem Put this into the Hooks directory in your subversion repository
rem along with the logBugDataSVN.vbs file
rem TSVN calls this with args <PATH> <DEPTH> <MESSAGEFILE> <REVISION> <ERROR> <CWD>
rem The ones we're interested in are <REVISION> and <CWD> which are %4 and %6
rem YOU NEED TO EDIT THE LINE WHICH SETS RepoRoot TO POINT AT THE DIRECTORY
rem THAT CONTAINS YOUR REPOSITORIES AND ALSO YOU MUST SET THE HOOKS DIRECTORY
setlocal
rem debugging
rem echo %1 %2 %3 %4 %5 %6 > c:\temp\test.txt
rem Set Hooks directory location (no trailing slash)
set HooksDir=\\myserver\svn\hooks
rem Set Repo Root location (ie. the directory containing all the repos)
rem (no trailing slash)
set RepoRoot=\\myserver\svn
rem Build full repo location
set Repo=%RepoRoot%\%~n6
rem debugging
rem echo %Repo% >> c:\temp\test.txt
rem Grab the last two digits of the revision number
rem and append them to the log of svn changes
rem to avoid simultaneous commit scenarios causing overwrites
set ChangeFileSuffix=%~4
set LogSvnChangeFile=svn%ChangeFileSuffix:~-2,2%.txt
set LogBugDataScript=logBugDataSVN.vbs
set ScriptCommand=cscript
rem Could remove the need for svnlook on the client since TSVN
rem provides as parameters the info we need to call the script.
rem However, it's in a slightly different format than the script is expecting
rem for parsing, therefore we would have to amend the script too, so I won't bother.
rem @echo on
svnlook changed -r %4 %Repo% > %temp%\%LogSvnChangeFile%
svnlook log -r %4 %Repo% | %ScriptCommand% %HooksDir%\%LogBugDataScript% %4 %temp%\%LogSvnChangeFile% %~n6
del %temp%\%LogSvnChangeFile%
endlocal
```
I'm going to assume the repositories are at `\\myserver\svn\` and working copies are all under `C:\Projects\
1. Go into your FogBugz account and click Extras -> Configure Source Control Integration
2. Download the VBScript file for Subversion (don't bother with the batch file)
3. Create a folder to store the hook scripts. I put it in the same folder as my repositories. eg. `\\myserver\svn\hooks\`
4. Rename VBscript to remove the `.safe` at the end of the filename.
5. Save my version of the batch file in your hooks directory, as `post-commit-tsvn.bat`
6. Right click on any directory.
7. Select "TortoiseSVN > Settings" (in the right click menu from the last step)
8. Select "Hook Scripts"
9. Click "Add" and set the properties as follows:
* Hook Type: Post-Commit Hook
* Working Copy Path: `C:\Projects` (or whatever your root directory for all of your projects is.)
* Command Line To Execute: `\\myserver\svn\hooks\post-commit-tsvn.bat` (this needs to point to wherever you put your hooks directory in step 3)
* Tick "Wait for the script to finish"
10. Click OK twice.
Next time you commit and enter a Bugid, it will be submitted to FogBugz. The links won't work but at least the revision info is there and you can manually look up the log in TortoiseSVN.
NOTE: You'll notice that the repository root is hard-coded into the batch file. As a result, if you check out from repositories that don't have the same root (eg. one on local drive and one on network) then you'll need to use 2 batch files and 2 corresponding entries under Hook Scripts in the TSVN settings. The way to do this would be to have 2 separate Working Copy trees - one for each repository root.
Part 3 - WebSVN
===============
Errr, I haven't done this :-)
From reading the WebSVN docs, it seems that WebSVN doesn't actually integrate with the SVN server, it just behaves like any other SVN client but presents a web interface. In theory then it should work fine with a file-based repository. I haven't tried it though. |
3,611 | <p>I'm trying to write some PHP to upload a file to a folder on my webserver. Here's what I have:</p>
<pre><code><?php
if ( !empty($_FILES['file']['tmp_name']) ) {
move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']);
header('Location: http://www.mywebsite.com/dump/');
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Dump Upload</title>
</head>
<body>
<h1>Upload a File</h1>
<form action="upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000000" />
Select the File:<br /><input type="file" name="file" /><br />
<input type="submit" value="Upload" />
</form>
</body>
</html>
</code></pre>
<p>I'm getting these errors:</p>
<blockquote>
<p>Warning: move_uploaded_file(./test.txt) [function.move-uploaded-file]: failed to open stream: Permission denied in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3</p>
<p>Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\WINDOWS\Temp\phpA30E.tmp' to './test.txt' in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3</p>
<p>Warning: Cannot modify header information - headers already sent by (output started at E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php:3) in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 4</p>
</blockquote>
<p>PHP version 4.4.7
Running IIS on a Windows box. This particular file/folder has 777 permissions.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 3617,
"author": "sparkes",
"author_id": 269,
"author_profile": "https://Stackoverflow.com/users/269",
"pm_score": 1,
"selected": false,
"text": "<p>Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\\WINDOWS\\Temp\\phpA30E.tmp' to './people.xml... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402/"
] | I'm trying to write some PHP to upload a file to a folder on my webserver. Here's what I have:
```
<?php
if ( !empty($_FILES['file']['tmp_name']) ) {
move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']);
header('Location: http://www.mywebsite.com/dump/');
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Dump Upload</title>
</head>
<body>
<h1>Upload a File</h1>
<form action="upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000000" />
Select the File:<br /><input type="file" name="file" /><br />
<input type="submit" value="Upload" />
</form>
</body>
</html>
```
I'm getting these errors:
>
> Warning: move\_uploaded\_file(./test.txt) [function.move-uploaded-file]: failed to open stream: Permission denied in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3
>
>
> Warning: move\_uploaded\_file() [function.move-uploaded-file]: Unable to move 'C:\WINDOWS\Temp\phpA30E.tmp' to './test.txt' in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3
>
>
> Warning: Cannot modify header information - headers already sent by (output started at E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php:3) in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 4
>
>
>
PHP version 4.4.7
Running IIS on a Windows box. This particular file/folder has 777 permissions.
Any ideas? | As it's Windows, there is no real 777. If you're using [chmod](http://fr2.php.net/manual/en/function.chmod.php), check the Windows-related comments.
Check that the IIS Account can access (read, write, modify) these two folders:
```
E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\
C:\WINDOWS\Temp\
``` |
3,625 | <p>I can't seem to find Developer Express' version of the <code>LinkButton</code>. (The Windows Forms linkbutton, not the <code>ASP.NET</code> linkbutton.) <code>HyperLinkEdit</code> doesn't seem to be what I'm looking for since it looks like a TextEdit/TextBox.</p>
<p>Anyone know what their version of it is? I'm using the latest DevX controls: 8.2.1.</p>
| [
{
"answer_id": 3785,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 0,
"selected": false,
"text": "<p>You should probably just use the standard ASP.Net LinkButton, unless it's really missing something you need.</p>\n"
},
... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/549/"
] | I can't seem to find Developer Express' version of the `LinkButton`. (The Windows Forms linkbutton, not the `ASP.NET` linkbutton.) `HyperLinkEdit` doesn't seem to be what I'm looking for since it looks like a TextEdit/TextBox.
Anyone know what their version of it is? I'm using the latest DevX controls: 8.2.1. | The control is called the HyperLinkEdit. You have to adjust the properties to get it to behave like the System.Windows.Forms control like so:
```
control.BorderStyle = BorderStyles.NoBorder;
control.Properties.Appearance.BackColor = Color.Transparent;
control.Properties.AppearanceFocused.BackColor = Color.Transparent;
control.Properties.ReadOnly = true;
``` |
3,682 | <p>I have a MySQL table with approximately 3000 rows per user. One of the columns is a datetime field, which is mutable, so the rows aren't in chronological order.</p>
<p>I'd like to visualize the time distribution in a chart, so I need a number of individual datapoints. 20 datapoints would be enough.</p>
<p>I could do this:</p>
<pre><code>select timefield from entries where uid = ? order by timefield;
</code></pre>
<p>and look at every 150th row.</p>
<p>Or I could do 20 separate queries and use <code>limit 1</code> and <code>offset</code>. </p>
<p>But there must be a more efficient solution...</p>
| [
{
"answer_id": 3691,
"author": "Michal Sznajder",
"author_id": 501,
"author_profile": "https://Stackoverflow.com/users/501",
"pm_score": 1,
"selected": false,
"text": "<p>Something like this came to my mind</p>\n\n<pre><code>select @rownum:=@rownum+1 rownum, entries.* \nfrom (select @row... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136/"
] | I have a MySQL table with approximately 3000 rows per user. One of the columns is a datetime field, which is mutable, so the rows aren't in chronological order.
I'd like to visualize the time distribution in a chart, so I need a number of individual datapoints. 20 datapoints would be enough.
I could do this:
```
select timefield from entries where uid = ? order by timefield;
```
and look at every 150th row.
Or I could do 20 separate queries and use `limit 1` and `offset`.
But there must be a more efficient solution... | Michal Sznajder almost had it, but you can't use column aliases in a WHERE clause in SQL. So you have to wrap it as a derived table. I tried this and it returns 20 rows:
```
SELECT * FROM (
SELECT @rownum:=@rownum+1 AS rownum, e.*
FROM (SELECT @rownum := 0) r, entries e) AS e2
WHERE uid = ? AND rownum % 150 = 0;
``` |
3,713 | <p>I'm writing a web page in ASP.NET. I have some JavaScript code, and I have a submit button with a click event.</p>
<p>Is it possible to call a method I created in ASP with JavaScript's click event?</p>
| [
{
"answer_id": 3726,
"author": "brendan",
"author_id": 225,
"author_profile": "https://Stackoverflow.com/users/225",
"pm_score": 4,
"selected": false,
"text": "<p>You can do it asynchronously using .NET Ajax PageMethods. See <a href=\"http://web.archive.org/web/20170818234231/http://www.... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/557/"
] | I'm writing a web page in ASP.NET. I have some JavaScript code, and I have a submit button with a click event.
Is it possible to call a method I created in ASP with JavaScript's click event? | Well, if you don't want to do it using Ajax or any other way and just want a normal ASP.NET postback to happen, here is how you do it (without using any other libraries):
*It is a little tricky though... :)*
i. In your code file (assuming you are using C# and .NET 2.0 or later) add the following Interface to your Page class to make it look like
```
public partial class Default : System.Web.UI.Page, IPostBackEventHandler{}
```
ii. This should add (using `Tab`-`Tab`) this function to your code file:
```
public void RaisePostBackEvent(string eventArgument) { }
```
iii. In your onclick event in JavaScript, write the following code:
```
var pageId = '<%= Page.ClientID %>';
__doPostBack(pageId, argumentString);
```
This will call the 'RaisePostBackEvent' method in your code file with the 'eventArgument' as the 'argumentString' you passed from the JavaScript. Now, you can call any other event you like.
P.S: That is 'underscore-underscore-doPostBack' ... And, there should be no space in that sequence... Somehow the WMD does not allow me to write to underscores followed by a character! |
3,725 | <p>I'm writing an application that is basically just a preferences dialog, much like the tree-view preferences dialog that Visual Studio itself uses. The function of the application is simply a pass-through for data from a serial device to a file. It performs many, many transformations on the data before writing it to the file, so the GUI for the application is simply all the settings that dictate what those transformations should be.</p>
<p>What's the best way to go about designing/coding a tree-view preferences dialog? The way I've been going about it is building the main window with a docked tree control on the left. Then I have been creating container controls that correspond to each node of the tree. When a node is selected, the app brings that node's corresponding container control to the front, moves it to the right position, and maximizes it in the main window. This seems really, really clunky while designing it. It basically means I have tons of container controls beyond the edge of the main window during design time that I have to keep scrolling the main window over to in order to work with them. I don't know if this totally makes sense the way I'm writing this, but maybe this visual for what I'm talking about will make more sense:</p>
<p><img src="https://i.stack.imgur.com/bVRJB.png" alt="form design"></p>
<p>Basically I have to work with this huge form, with container controls all over the place, and then do a bunch of run-time reformatting to make it all work. This seems like a <em>lot</em> of extra work. Am I doing this in a totally stupid way? Is there some "obvious" easier way of doing this that I'm missing?</p>
| [
{
"answer_id": 3776,
"author": "xyz",
"author_id": 82,
"author_profile": "https://Stackoverflow.com/users/82",
"pm_score": 5,
"selected": true,
"text": "<p>A tidier way is to create separate forms for each 'pane' and, in each form constructor, set</p>\n\n<pre><code>this.TopLevel = false;... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/551/"
] | I'm writing an application that is basically just a preferences dialog, much like the tree-view preferences dialog that Visual Studio itself uses. The function of the application is simply a pass-through for data from a serial device to a file. It performs many, many transformations on the data before writing it to the file, so the GUI for the application is simply all the settings that dictate what those transformations should be.
What's the best way to go about designing/coding a tree-view preferences dialog? The way I've been going about it is building the main window with a docked tree control on the left. Then I have been creating container controls that correspond to each node of the tree. When a node is selected, the app brings that node's corresponding container control to the front, moves it to the right position, and maximizes it in the main window. This seems really, really clunky while designing it. It basically means I have tons of container controls beyond the edge of the main window during design time that I have to keep scrolling the main window over to in order to work with them. I don't know if this totally makes sense the way I'm writing this, but maybe this visual for what I'm talking about will make more sense:

Basically I have to work with this huge form, with container controls all over the place, and then do a bunch of run-time reformatting to make it all work. This seems like a *lot* of extra work. Am I doing this in a totally stupid way? Is there some "obvious" easier way of doing this that I'm missing? | A tidier way is to create separate forms for each 'pane' and, in each form constructor, set
```
this.TopLevel = false;
this.FormBorderStyle = FormBorderStyle.None;
this.Dock = DockStyle.Fill;
```
That way, each of these forms can be laid out in its own designer, instantiated one or more times at runtime, and added to the empty area like a normal control.
Perhaps the main form could use a `SplitContainer` with a static `TreeView` in one panel, and space to add these forms in the other. Once they are added, they could be flipped through using `Hide/Show` or `BringToFront/SendToBack` methods.
```
SeparateForm f = new SeparateForm();
MainFormSplitContainer.Panel2.Controls.Add(f);
f.Show();
``` |
3,739 | <p>I have an unusual situation in which I need a SharePoint timer job to both have local administrator windows privileges and to have <code>SHAREPOINT\System</code> SharePoint privileges.</p>
<p>I can get the windows privileges by simply configuring the timer service to use an account which is a member of local administrators. I understand that this is not a good solution since it gives SharePoint timer service more rights then it is supposed to have. But it at least allows my SharePoint timer job to run <code>stsadm</code>.</p>
<p>Another problem with running the timer service under local administrator is that this user won't necessarily have <code>SHAREPOINT\System</code> SharePoint privileges which I also need for this SharePoint job. It turns out that <code>SPSecurity.RunWithElevatedPrivileges</code> won't work in this case. Reflector shows that <code>RunWithElevatedPrivileges</code> checks if the current process is <code>owstimer</code> (the service process which runs SharePoint jobs) and performs no elevation this is the case (the rational here, I guess, is that the timer service is supposed to run under <code>NT AUTHORITY\NetworkService</code> windows account which which has <code>SHAREPOINT\System</code> SharePoint privileges, and thus there's no need to elevate privileges for a timer job).</p>
<p>The only possible solution here seems to be to run the timer service under its usual NetworkService windows account and to run stsadm as a local administrator by storing the administrator credentials somewhere and passing them to System.Diagnostics.Process.Run() trough the StarInfo's Username, domain and password.</p>
<p>It seems everything should work now, but here is another problem I'm stuck with at the moment. Stsamd is failing with the following error popup (!) (Winternals filemon shows that stsadm is running under the administrator in this case):</p>
<p><code>The application failed to initialize properly (0x0c0000142).</code> <br />
<code>Click OK to terminate the application.</code></p>
<p>Event Viewer registers nothing except the popup.</p>
<p>The local administrator user is my account and when I just run <code>stsadm</code> interactively under this account everything is ok. It also works fine when I configure the timer service to run under this account.</p>
<p>Any suggestions are appreciated :)</p>
| [
{
"answer_id": 3741,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not at work so this is off the top of my head, but: If you get a reference to the Site, can you try to create a new SP... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have an unusual situation in which I need a SharePoint timer job to both have local administrator windows privileges and to have `SHAREPOINT\System` SharePoint privileges.
I can get the windows privileges by simply configuring the timer service to use an account which is a member of local administrators. I understand that this is not a good solution since it gives SharePoint timer service more rights then it is supposed to have. But it at least allows my SharePoint timer job to run `stsadm`.
Another problem with running the timer service under local administrator is that this user won't necessarily have `SHAREPOINT\System` SharePoint privileges which I also need for this SharePoint job. It turns out that `SPSecurity.RunWithElevatedPrivileges` won't work in this case. Reflector shows that `RunWithElevatedPrivileges` checks if the current process is `owstimer` (the service process which runs SharePoint jobs) and performs no elevation this is the case (the rational here, I guess, is that the timer service is supposed to run under `NT AUTHORITY\NetworkService` windows account which which has `SHAREPOINT\System` SharePoint privileges, and thus there's no need to elevate privileges for a timer job).
The only possible solution here seems to be to run the timer service under its usual NetworkService windows account and to run stsadm as a local administrator by storing the administrator credentials somewhere and passing them to System.Diagnostics.Process.Run() trough the StarInfo's Username, domain and password.
It seems everything should work now, but here is another problem I'm stuck with at the moment. Stsamd is failing with the following error popup (!) (Winternals filemon shows that stsadm is running under the administrator in this case):
`The application failed to initialize properly (0x0c0000142).`
`Click OK to terminate the application.`
Event Viewer registers nothing except the popup.
The local administrator user is my account and when I just run `stsadm` interactively under this account everything is ok. It also works fine when I configure the timer service to run under this account.
Any suggestions are appreciated :) | I'm not at work so this is off the top of my head, but: If you get a reference to the Site, can you try to create a new SPSite with the SYSTEM-UserToken?
```
SPUserToken sut = thisSite.RootWeb.AllUsers["SHAREPOINT\SYSTEM"].UserToken;
using (SPSite syssite = new SPSite(thisSite.Url,sut)
{
// Do what you have to do
}
``` |
3,793 | <p>What's the best way to get the contents of the mixed <code>body</code> element in the code below? The element might contain either XHTML or text, but I just want its contents in string form. The <code>XmlElement</code> type has the <code>InnerXml</code> property which is exactly what I'm after.</p>
<p>The code as written <em>almost</em> does what I want, but includes the surrounding <code><body></code>...<code></body></code> element, which I don't want.</p>
<pre class="lang-js prettyprint-override"><code>XDocument doc = XDocument.Load(new StreamReader(s));
var templates = from t in doc.Descendants("template")
where t.Attribute("name").Value == templateName
select new
{
Subject = t.Element("subject").Value,
Body = t.Element("body").ToString()
};
</code></pre>
| [
{
"answer_id": 3794,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 0,
"selected": false,
"text": "<p>Is it possible to use the System.Xml namespace objects to get the job done here instead of using LINQ? As you already men... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205/"
] | What's the best way to get the contents of the mixed `body` element in the code below? The element might contain either XHTML or text, but I just want its contents in string form. The `XmlElement` type has the `InnerXml` property which is exactly what I'm after.
The code as written *almost* does what I want, but includes the surrounding `<body>`...`</body>` element, which I don't want.
```js
XDocument doc = XDocument.Load(new StreamReader(s));
var templates = from t in doc.Descendants("template")
where t.Attribute("name").Value == templateName
select new
{
Subject = t.Element("subject").Value,
Body = t.Element("body").ToString()
};
``` | I wanted to see which of these suggested solutions performed best, so I ran some comparative tests. Out of interest, I also compared the LINQ methods to the plain old **System.Xml** method suggested by Greg. The variation was interesting and not what I expected, with the slowest methods being **more than 3 times slower than the fastest**.
The results ordered by fastest to slowest:
1. CreateReader - Instance Hunter (0.113 seconds)
2. Plain old System.Xml - Greg Hurlman (0.134 seconds)
3. Aggregate with string concatenation - Mike Powell (0.324 seconds)
4. StringBuilder - Vin (0.333 seconds)
5. String.Join on array - Terry (0.360 seconds)
6. String.Concat on array - Marcin Kosieradzki (0.364)
---
**Method**
I used a single XML document with 20 identical nodes (called 'hint'):
```
<hint>
<strong>Thinking of using a fake address?</strong>
<br />
Please don't. If we can't verify your address we might just
have to reject your application.
</hint>
```
The numbers shown as seconds above are the result of extracting the "inner XML" of the 20 nodes, 1000 times in a row, and taking the average (mean) of 5 runs. I didn't include the time it took to load and parse the XML into an `XmlDocument` (for the **System.Xml** method) or `XDocument` (for all the others).
The LINQ algorithms I used were: *(C# - all take an `XElement` "parent" and return the inner XML string)*
**CreateReader:**
```js
var reader = parent.CreateReader();
reader.MoveToContent();
return reader.ReadInnerXml();
```
**Aggregate with string concatenation:**
```js
return parent.Nodes().Aggregate("", (b, node) => b += node.ToString());
```
**StringBuilder:**
```js
StringBuilder sb = new StringBuilder();
foreach(var node in parent.Nodes()) {
sb.Append(node.ToString());
}
return sb.ToString();
```
**String.Join on array:**
```js
return String.Join("", parent.Nodes().Select(x => x.ToString()).ToArray());
```
**String.Concat on array:**
```js
return String.Concat(parent.Nodes().Select(x => x.ToString()).ToArray());
```
I haven't shown the "Plain old System.Xml" algorithm here as it's just calling .InnerXml on nodes.
---
**Conclusion**
If performance is important (e.g. lots of XML, parsed frequently), I'd **use Daniel's `CreateReader` method every time**. If you're just doing a few queries, you might want to use Mike's more concise Aggregate method.
If you're using XML on large elements with lots of nodes (maybe 100's), you'd probably start to see the benefit of using `StringBuilder` over the Aggregate method, but not over `CreateReader`. I don't think the `Join` and `Concat` methods would ever be more efficient in these conditions because of the penalty of converting a large list to a large array (even obvious here with smaller lists). |
3,839 | <p>I'm trying out the following query:</p>
<pre><code>SELECT A,B,C FROM table WHERE field LIKE 'query%'
UNION
SELECT A,B,C FROM table WHERE field LIKE '%query'
UNION
SELECT A,B,C FROM table WHERE field LIKE '%query%'
GROUP BY B ORDER BY B ASC LIMIT 5
</code></pre>
<p>That's three queries stuck together, kinda sorta. However, the result set that comes back reflects results from query #3 before the results from query #1 which is undesired.</p>
<p>Is there any way to prioritize these so that results come as all for query #1, then all for query #2 then all for query #3? I don't want to do this in PHP just yet (not to mention having to control for results that showed up in the first query not to show in the second and so forth).</p>
| [
{
"answer_id": 3852,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "<p>Can you do it as a subselect, something like</p>\n\n<pre><code>SELECT * FROM (\n SELECT A,B,C FROM table WHERE field... | 2008/08/06 | [
"https://Stackoverflow.com/questions/3839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547/"
] | I'm trying out the following query:
```
SELECT A,B,C FROM table WHERE field LIKE 'query%'
UNION
SELECT A,B,C FROM table WHERE field LIKE '%query'
UNION
SELECT A,B,C FROM table WHERE field LIKE '%query%'
GROUP BY B ORDER BY B ASC LIMIT 5
```
That's three queries stuck together, kinda sorta. However, the result set that comes back reflects results from query #3 before the results from query #1 which is undesired.
Is there any way to prioritize these so that results come as all for query #1, then all for query #2 then all for query #3? I don't want to do this in PHP just yet (not to mention having to control for results that showed up in the first query not to show in the second and so forth). | Maybe you should try including a fourth column, stating the table it came from, and then order and group by it:
```
SELECT A,B,C, "query 1" as origin FROM table WHERE field LIKE 'query%'
UNION
SELECT A,B,C, "query 2" as origin FROM table WHERE field LIKE '%query'
UNION
SELECT A,B,C, "query 3" as origin FROM table WHERE field LIKE '%query%'
GROUP BY origin, B ORDER BY origin, B ASC LIMIT 5
``` |