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 |
|---|---|---|---|---|---|---|
51,032 | <p>Consider these two function definitions:</p>
<pre><code>void foo() { }
void foo(void) { }
</code></pre>
<p>Is there any difference between these two? If not, why is the <code>void</code> argument there? Aesthetic reasons?</p>
| [
{
"answer_id": 51041,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "<p>In C, you use a void in an empty function reference so that the compiler has a prototype, and that prototype has \"no... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597/"
] | Consider these two function definitions:
```
void foo() { }
void foo(void) { }
```
Is there any difference between these two? If not, why is the `void` argument there? Aesthetic reasons? | In **C**:
* `void foo()` means "a function `foo` taking an unspecified number of arguments of unspecified type"
* `void foo(void)` means "a function `foo` taking no arguments"
In **C++**:
* `void foo()` means "a function `foo` taking no arguments"
* `void foo(void)` means "a function `foo` taking no arguments"
By writing `foo(void)`, therefore, we achieve the same interpretation across both languages and make our headers multilingual (though we usually need to do some more things to the headers to make them truly cross-language; namely, wrap them in an `extern "C"` if we're compiling C++). |
51,054 | <p>I am looking for a way to delete all files older than 7 days in a batch file. I've searched around the web, and found some examples with hundreds of lines of code, and others that required installing extra command line utilities to accomplish the task.</p>
<p>Similar things can be <a href="https://stackoverflow.com/questions/25785/delete-all-but-the-most-recent-x-files-in-bash">done in BASH</a> in just a couple lines of code. It seems that something at least remotely easy could be done for batch files in Windows. I'm looking for a solution that works in a standard Windows command prompt, without any extra utilities. Please no PowerShell or Cygwin either.</p>
| [
{
"answer_id": 51069,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 11,
"selected": true,
"text": "<p>Enjoy:</p>\n\n<pre><code>forfiles -p \"C:\\what\\ever\" -s -m *.* -d <number of days> -c \"cmd /c del @path\"\n</code></... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1862/"
] | I am looking for a way to delete all files older than 7 days in a batch file. I've searched around the web, and found some examples with hundreds of lines of code, and others that required installing extra command line utilities to accomplish the task.
Similar things can be [done in BASH](https://stackoverflow.com/questions/25785/delete-all-but-the-most-recent-x-files-in-bash) in just a couple lines of code. It seems that something at least remotely easy could be done for batch files in Windows. I'm looking for a solution that works in a standard Windows command prompt, without any extra utilities. Please no PowerShell or Cygwin either. | Enjoy:
```
forfiles -p "C:\what\ever" -s -m *.* -d <number of days> -c "cmd /c del @path"
```
See [`forfiles` documentation](http://ss64.com/nt/forfiles.html) for more details.
For more goodies, refer to *[An A-Z Index of the Windows XP command line](http://www.ss64.com/nt/)*.
If you don't have `forfiles` installed on your machine, copy it from any [Windows Server 2003](http://en.wikipedia.org/wiki/Windows_Server_2003) to your Windows XP machine at `%WinDir%\system32\`. This is possible since the EXE is fully compatible between Windows Server 2003 and Windows XP.
Later versions of Windows and Windows Server have it installed by default.
For Windows 7 and newer (including Windows 10):
The syntax has changed a little. Therefore the updated command is:
```
forfiles /p "C:\what\ever" /s /m *.* /D -<number of days> /C "cmd /c del @path"
``` |
51,092 | <p>Consider the Oracle <code>emp</code> table. I'd like to get the employees with the top salary with <code>department = 20</code> and <code>job = clerk</code>. Also assume that there is no "empno" column, and that the primary key involves a number of columns. You can do this with:</p>
<pre><code>select * from scott.emp
where deptno = 20 and job = 'CLERK'
and sal = (select max(sal) from scott.emp
where deptno = 20 and job = 'CLERK')
</code></pre>
<p>This works, but I have to duplicate the test deptno = 20 and job = 'CLERK', which I would like to avoid. Is there a more elegant way to write this, maybe using a <code>group by</code>? BTW, if this matters, I am using Oracle.</p>
| [
{
"answer_id": 51103,
"author": "Mark Nold",
"author_id": 4134,
"author_profile": "https://Stackoverflow.com/users/4134",
"pm_score": 3,
"selected": true,
"text": "<p>The following is slightly over-engineered, but is a good SQL pattern for \"top x\" queries.</p>\n\n<pre><code>SELECT \n *... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5295/"
] | Consider the Oracle `emp` table. I'd like to get the employees with the top salary with `department = 20` and `job = clerk`. Also assume that there is no "empno" column, and that the primary key involves a number of columns. You can do this with:
```
select * from scott.emp
where deptno = 20 and job = 'CLERK'
and sal = (select max(sal) from scott.emp
where deptno = 20 and job = 'CLERK')
```
This works, but I have to duplicate the test deptno = 20 and job = 'CLERK', which I would like to avoid. Is there a more elegant way to write this, maybe using a `group by`? BTW, if this matters, I am using Oracle. | The following is slightly over-engineered, but is a good SQL pattern for "top x" queries.
```
SELECT
*
FROM
scott.emp
WHERE
(deptno,job,sal) IN
(SELECT
deptno,
job,
max(sal)
FROM
scott.emp
WHERE
deptno = 20
and job = 'CLERK'
GROUP BY
deptno,
job
)
```
Also note that this will work in Oracle and Postgress (i think) but not MS SQL. For something similar in MS SQL see question [SQL Query to get latest price](https://stackoverflow.com/questions/49404/sql-query-to-get-latest-price#49424) |
51,093 | <p>Jeff covered this a while back <a href="http://www.codinghorror.com/blog/archives/000811.html" rel="nofollow noreferrer">on his blog</a> in terms of 32 bit Vista.</p>
<p>Does the same 32 bit 4 GB memory cap that applies in 32 bit Vista apply to 32 bit Ubuntu? Are there any 32 bit operating systems that have creatively solved this problem?</p>
| [
{
"answer_id": 51100,
"author": "Rob Rolnick",
"author_id": 4798,
"author_profile": "https://Stackoverflow.com/users/4798",
"pm_score": 2,
"selected": false,
"text": "<p>In theory, all 32-bit OSes have that problem. You have 32 bits to do addressing.</p>\n\n<pre><code>2^32 bits / 2^10 (b... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] | Jeff covered this a while back [on his blog](http://www.codinghorror.com/blog/archives/000811.html) in terms of 32 bit Vista.
Does the same 32 bit 4 GB memory cap that applies in 32 bit Vista apply to 32 bit Ubuntu? Are there any 32 bit operating systems that have creatively solved this problem? | In theory, all 32-bit OSes have that problem. You have 32 bits to do addressing.
```
2^32 bits / 2^10 (bits per kb) / 2^10 (kb per mb) / 2^10 (mb per gb) = 2^2 = 4gb.
```
Although there are some ways around it. (Look up the jump from 16-bit computing to 32-bit computing. They hit the same problem.) |
51,098 | <p>I have two spreadsheets... when one gets modified in a certain way I want to have a macro run that modifies the second in an appropriate manner. I've already isolated the event I need to act on (the modification of any cell in a particular column), I just can't seem to find any concrete information on accessing and modifying another spreadsheet (this spreadsheet is located on a different LAN share also... the user has access to both, though).</p>
<p>Any help would be great. References on how to do this or something similar are just as good as concrete code samples.</p>
| [
{
"answer_id": 51111,
"author": "Michael Pryor",
"author_id": 245,
"author_profile": "https://Stackoverflow.com/users/245",
"pm_score": 4,
"selected": true,
"text": "<p>In Excel, you would likely just write code to open the other worksheet, modify it and then save the data.</p>\n\n<p>See... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/271/"
] | I have two spreadsheets... when one gets modified in a certain way I want to have a macro run that modifies the second in an appropriate manner. I've already isolated the event I need to act on (the modification of any cell in a particular column), I just can't seem to find any concrete information on accessing and modifying another spreadsheet (this spreadsheet is located on a different LAN share also... the user has access to both, though).
Any help would be great. References on how to do this or something similar are just as good as concrete code samples. | In Excel, you would likely just write code to open the other worksheet, modify it and then save the data.
See [this tutorial](http://pubs.logicalexpressions.com/Pub0009/LPMArticle.asp?ID=302) for more info.
I'll have to edit my VBA later, so pretend this is pseudocode, but it should look something like:
```
Dim xl: Set xl = CreateObject("Excel.Application")
xl.Open "\\the\share\file.xls"
Dim ws: Set ws = xl.Worksheets(1)
ws.Cells(0,1).Value = "New Value"
ws.Save
xl.Quit constSilent
``` |
51,108 | <p>I really enjoyed <a href="http://www.codinghorror.com/blog/archives/001148.html" rel="noreferrer">Jeff's post</a> on <a href="http://ssdl-wiki.cs.technion.ac.il/wiki/index.php/Spartan_programming" rel="noreferrer">Spartan Programming</a>. I agree that code like that is a joy to read. Unfortunately, I'm not so sure it would necessarily be a joy to work with.</p>
<p>For years I have read about and adhered to the "one-expression-per-line" practice. I have fought the good fight and held my ground when many programming books countered this advice with example code like:</p>
<pre><code>while (bytes = read(...))
{
...
}
while (GetMessage(...))
{
...
}
</code></pre>
<p>Recently, I've advocated one expression per line for more practical reasons - debugging and production support. Getting a log file from production that claims a NullPointer exception at "line 65" which reads:</p>
<pre><code>ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber());
</code></pre>
<p>is frustrating and entirely avoidable. Short of grabbing an expert with the code that can choose the "most likely" object that was null ... this is a real practical pain.</p>
<p>One expression per line also helps out quite a bit while stepping through code. I practice this with the assumption that most modern compilers can optimize away all the superfluous temp objects I've just created ...</p>
<p>I try to be neat - but cluttering my code with explicit objects sure feels laborious at times. It does not generally make the code easier to browse - but it really has come in handy when tracing things down in production or stepping through my or someone else's code.</p>
<p>What style do <em>you</em> advocate and can you rationalize it in a practical sense?</p>
| [
{
"answer_id": 51112,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 2,
"selected": false,
"text": "<p>One expression per line.</p>\n\n<p>There is no reason to obfuscate your code. The extra time you take typing the few extra... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4910/"
] | I really enjoyed [Jeff's post](http://www.codinghorror.com/blog/archives/001148.html) on [Spartan Programming](http://ssdl-wiki.cs.technion.ac.il/wiki/index.php/Spartan_programming). I agree that code like that is a joy to read. Unfortunately, I'm not so sure it would necessarily be a joy to work with.
For years I have read about and adhered to the "one-expression-per-line" practice. I have fought the good fight and held my ground when many programming books countered this advice with example code like:
```
while (bytes = read(...))
{
...
}
while (GetMessage(...))
{
...
}
```
Recently, I've advocated one expression per line for more practical reasons - debugging and production support. Getting a log file from production that claims a NullPointer exception at "line 65" which reads:
```
ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber());
```
is frustrating and entirely avoidable. Short of grabbing an expert with the code that can choose the "most likely" object that was null ... this is a real practical pain.
One expression per line also helps out quite a bit while stepping through code. I practice this with the assumption that most modern compilers can optimize away all the superfluous temp objects I've just created ...
I try to be neat - but cluttering my code with explicit objects sure feels laborious at times. It does not generally make the code easier to browse - but it really has come in handy when tracing things down in production or stepping through my or someone else's code.
What style do *you* advocate and can you rationalize it in a practical sense? | In **The Pragmatic Programmer** Hunt and Thomas talk about a study they term the Law of Demeter and it focuses on the coupling of functions to modules other than there own. By allowing a function to never reach a 3rd level in it's coupling you significantly reduce the number of errors and increase the maintainability of the code.
So:
>
> ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber());
>
>
>
Is close to a felony because we are 4 objects down the rat hole. That means to change something in one of those objects I have to know that you called this whole stack right here in this very method. What a pain.
Better:
>
> Account.getUser();
>
>
>
Note this runs counter to the expressive forms of programming that are now really popular with mocking software. The trade off there is that you have a tightly coupled interface anyway, and the expressive syntax just makes it easier to use. |
51,113 | <p>It seems like IDataReader.Read() is always true at least one time (If I'm wrong about this let me know.) So how do you tell if it has no records without just wrapping it in a try/catch?</p>
| [
{
"answer_id": 51120,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 5,
"selected": false,
"text": "<pre><code>if(dr.Read())\n{\n //do stuff\n}\nelse\n{\n //it's empty\n}\n</code></pre>\n\n<p>usually you'll do this th... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] | It seems like IDataReader.Read() is always true at least one time (If I'm wrong about this let me know.) So how do you tell if it has no records without just wrapping it in a try/catch? | ```
if(dr.Read())
{
//do stuff
}
else
{
//it's empty
}
```
usually you'll do this though:
```
while(dr.Read())
{
}
``` |
51,129 | <p>In C#, if I need to open an HTTP connection, download XML and get one value from the result, how would I do that?</p>
<p>For consistency, imagine the webservice is at www.webservice.com and that if you pass it the POST argument fXML=1 it gives you back </p>
<pre><code><xml><somekey>somevalue</somekey></xml>
</code></pre>
<p>I'd like it to spit out "somevalue".</p>
| [
{
"answer_id": 51136,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "<p>I think it will be useful to read this first:</p>\n\n<p><a href=\"https://web.archive.org/web/20211020134836/https://aspn... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245/"
] | In C#, if I need to open an HTTP connection, download XML and get one value from the result, how would I do that?
For consistency, imagine the webservice is at www.webservice.com and that if you pass it the POST argument fXML=1 it gives you back
```
<xml><somekey>somevalue</somekey></xml>
```
I'd like it to spit out "somevalue". | I use this code and it works great:
```
System.Xml.XmlDocument xd = new System.Xml.XmlDocument;
xd.Load("http://www.webservice.com/webservice?fXML=1");
string xPath = "/xml/somekey";
// this node's inner text contains "somevalue"
return xd.SelectSingleNode(xPath).InnerText;
```
---
EDIT: I just realized you're talking about a webservice and not just plain XML. In your Visual Studio Solution, try right clicking on References in Solution Explorer and choose "Add a Web Reference". A dialog will appear asking for a URL, you can just paste it in: "<http://www.webservice.com/webservice.asmx>". VS will autogenerate all the helpers you need. Then you can just call:
```
com.webservice.www.WebService ws = new com.webservice.www.WebService();
// this assumes your web method takes in the fXML as an integer attribute
return ws.SomeWebMethod(1);
``` |
51,139 | <p>I'm trying to create an SSIS package that takes data from an XML data source and for each row inserts another row with some preset values. Any ideas? I'm thinking I could use a DataReader source to generate the preset values by doing the following:</p>
<pre><code>SELECT 'foo' as 'attribute1', 'bar' as 'attribute2'
</code></pre>
<p>The question is, how would I insert one row of this type for every row in the XML data source?</p>
| [
{
"answer_id": 51158,
"author": "Tadmas",
"author_id": 3750,
"author_profile": "https://Stackoverflow.com/users/3750",
"pm_score": 2,
"selected": false,
"text": "<p>I've never tried it, but it looks like you might be able to use a <a href=\"http://msdn.microsoft.com/en-us/library/ms14106... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4550/"
] | I'm trying to create an SSIS package that takes data from an XML data source and for each row inserts another row with some preset values. Any ideas? I'm thinking I could use a DataReader source to generate the preset values by doing the following:
```
SELECT 'foo' as 'attribute1', 'bar' as 'attribute2'
```
The question is, how would I insert one row of this type for every row in the XML data source? | I've never tried it, but it looks like you might be able to use a [Derived Column transformation](http://msdn.microsoft.com/en-us/library/ms141069(SQL.90).aspx) to do it: set the expression for attribute1 to `"foo"` and the expression for attribute2 to `"bar"`.
You'd then transform the original data source, then only use the derived columns in your destination. If you still need the original source, you can Multicast it to create a duplicate.
At least I think this will work, based on the documentation. YMMV. |
51,148 | <p>I have C# winforms application that needs to start an external exe from time to time, but I do not wish to start another process if one is already running, but rather switch to it.</p>
<p>So how in C# would I so this in the example below?</p>
<pre><code>using System.Diagnostics;
...
Process foo = new Process();
foo.StartInfo.FileName = @"C:\bar\foo.exe";
foo.StartInfo.Arguments = "Username Password";
bool isRunning = //TODO: Check to see if process foo.exe is already running
if (isRunning)
{
//TODO: Switch to foo.exe process
}
else
{
foo.Start();
}
</code></pre>
| [
{
"answer_id": 51149,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 6,
"selected": true,
"text": "<p>This should do it for ya.</p>\n\n<p><a href=\"http://www.dreamincode.net/code/snippet1541.htm\" rel=\"noreferrer\">Check Proc... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1292/"
] | I have C# winforms application that needs to start an external exe from time to time, but I do not wish to start another process if one is already running, but rather switch to it.
So how in C# would I so this in the example below?
```
using System.Diagnostics;
...
Process foo = new Process();
foo.StartInfo.FileName = @"C:\bar\foo.exe";
foo.StartInfo.Arguments = "Username Password";
bool isRunning = //TODO: Check to see if process foo.exe is already running
if (isRunning)
{
//TODO: Switch to foo.exe process
}
else
{
foo.Start();
}
``` | This should do it for ya.
[Check Processes](http://www.dreamincode.net/code/snippet1541.htm)
```
//Namespaces we need to use
using System.Diagnostics;
public bool IsProcessOpen(string name)
{
//here we're going to get a list of all running processes on
//the computer
foreach (Process clsProcess in Process.GetProcesses()) {
//now we're going to see if any of the running processes
//match the currently running processes. Be sure to not
//add the .exe to the name you provide, i.e: NOTEPAD,
//not NOTEPAD.EXE or false is always returned even if
//notepad is running.
//Remember, if you have the process running more than once,
//say IE open 4 times the loop thr way it is now will close all 4,
//if you want it to just close the first one it finds
//then add a return; after the Kill
if (clsProcess.ProcessName.Contains(name))
{
//if the process is found to be running then we
//return a true
return true;
}
}
//otherwise we return a false
return false;
}
``` |
51,150 | <p>When an application is behind another applications and
I click on my application's taskbar icon, I expect the entire application to
come to the top of the z-order, even if an app-modal, WS_POPUP dialog box is
open.</p>
<p>However, some of the time, for some of my (and others') dialog boxes, only the dialog box comes to the front; the rest of the application stays behind.</p>
<p>I've looked at Spy++ and for the ones that work correctly, I can see
WM_WINDOWPOSCHANGING being sent to the dialog's parent. For the ones that
leave the rest of the application behind, WM_WINDOWPOSCHANGING is not being
sent to the dialog's parent.</p>
<p>I have an example where one dialog usually brings the whole app with it and the other does not. Both the working dialog box and the non-working dialog box have the same window style, substyle, parent, owner, ontogeny.</p>
<p>In short, both are WS_POPUPWINDOW windows created with DialogBoxParam(),
having passed in identical HWNDs as the third argument.</p>
<p>Has anyone else noticed this behavioral oddity in Windows programs? What messages does the TaskBar send to the application when I click its button? Who's responsibility is it to ensure that <em>all</em> of the application's windows come to the foreground?</p>
<p>In my case the base parentage is an MDI frame...does that factor in somehow?</p>
| [
{
"answer_id": 51160,
"author": "jmatthias",
"author_id": 2768,
"author_profile": "https://Stackoverflow.com/users/2768",
"pm_score": 0,
"selected": false,
"text": "<p>Is the dialog's parent window set correctly?</p>\n\n<p>After I posted this, I started my own Windows Forms application a... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5309/"
] | When an application is behind another applications and
I click on my application's taskbar icon, I expect the entire application to
come to the top of the z-order, even if an app-modal, WS\_POPUP dialog box is
open.
However, some of the time, for some of my (and others') dialog boxes, only the dialog box comes to the front; the rest of the application stays behind.
I've looked at Spy++ and for the ones that work correctly, I can see
WM\_WINDOWPOSCHANGING being sent to the dialog's parent. For the ones that
leave the rest of the application behind, WM\_WINDOWPOSCHANGING is not being
sent to the dialog's parent.
I have an example where one dialog usually brings the whole app with it and the other does not. Both the working dialog box and the non-working dialog box have the same window style, substyle, parent, owner, ontogeny.
In short, both are WS\_POPUPWINDOW windows created with DialogBoxParam(),
having passed in identical HWNDs as the third argument.
Has anyone else noticed this behavioral oddity in Windows programs? What messages does the TaskBar send to the application when I click its button? Who's responsibility is it to ensure that *all* of the application's windows come to the foreground?
In my case the base parentage is an MDI frame...does that factor in somehow? | I know this is very old now, but I just stumbled across it, and I know the answer.
In the applications you've seen (and written) where bringing the dialog box to the foreground did **not** bring the main window up along with it, the developer has simply neglected to specify the owner of the dialog box.
This applies to both modal windows, like dialog boxes and message boxes, as well as to modeless windows. Setting the owner of a modeless popup also keeps the popup above its owner at all times.
In the Win32 API, the functions to bring up a dialog box or a message box take the owner window as a parameter:
```
INT_PTR DialogBox(
HINSTANCE hInstance,
LPCTSTR lpTemplate,
HWND hWndParent, /* this is the owner */
DLGPROC lpDialogFunc
);
int MessageBox(
HWND hWnd, /* this is the owner */
LPCTSTR lpText,
LPCTSTR lpCaption,
UINT uType
);
```
Similary, in .NET WinForms, the owner can be specified:
```
public DialogResult ShowDialog(
IWin32Window owner
)
public static DialogResult Show(
IWin32Window owner,
string text
) /* ...and other overloads that include this first parameter */
```
Additionally, in WinForms, it's easy to set the owner of a modeless window:
```
public void Show(
IWin32Window owner,
)
```
or, equivalently:
```
form.Owner = this;
form.Show();
```
In straight WinAPI code, the owner of a modeless window can be set when the window is created:
```
HWND CreateWindow(
LPCTSTR lpClassName,
LPCTSTR lpWindowName,
DWORD dwStyle,
int x,
int y,
int nWidth,
int nHeight,
HWND hWndParent, /* this is the owner if dwStyle does not contain WS_CHILD */
HMENU hMenu,
HINSTANCE hInstance,
LPVOID lpParam
);
```
or afterwards:
```
SetWindowLong(hWndPopup, GWL_HWNDPARENT, (LONG)hWndOwner);
```
or (64-bit compatible)
```
SetWindowLongPtr(hWndPopup, GWLP_HWNDPARENT, (LONG_PTR)hWndOwner);
```
Note that MSDN has the following to say about [SetWindowLong[Ptr]](http://msdn.microsoft.com/en-us/library/ms644898(VS.85).aspx):
>
> Do not call **SetWindowLongPtr** with the GWLP\_HWNDPARENT index to change the parent of a child window. Instead, use the [SetParent](http://msdn.microsoft.com/en-us/library/ms633541(VS.85).aspx) function.
>
>
>
This is somewhat misleading, as it seems to imply that the last two snippets above are wrong. This isn't so. Calling `SetParent` will turn the intended popup into a *child* of the parent window (setting its `WS_CHILD` bit), rather than making it an owned window. The code above is the correct way to make an existing popup an owned window. |
51,165 | <p>I have a list of objects I wish to sort based on a field <code>attr</code> of type string. I tried using <code>-</code></p>
<pre><code>list.sort(function (a, b) {
return a.attr - b.attr
})
</code></pre>
<p>but found that <code>-</code> doesn't appear to work with strings in JavaScript. How can I sort a list of objects based on an attribute with type string?</p>
| [
{
"answer_id": 51169,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 11,
"selected": true,
"text": "<p>Use <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/localeCompare\" rel=\"norefe... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5304/"
] | I have a list of objects I wish to sort based on a field `attr` of type string. I tried using `-`
```
list.sort(function (a, b) {
return a.attr - b.attr
})
```
but found that `-` doesn't appear to work with strings in JavaScript. How can I sort a list of objects based on an attribute with type string? | Use [`String.prototype.localeCompare`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/localeCompare) a per your example:
```
list.sort(function (a, b) {
return ('' + a.attr).localeCompare(b.attr);
})
```
We force a.attr to be a string to avoid exceptions. `localeCompare` has been supported [since Internet Explorer 6](https://learn.microsoft.com/en-us/scripting/javascript/reference/localecompare-method-string-javascript) and Firefox 1. You may also see the following code used that doesn't respect a locale:
```
if (item1.attr < item2.attr)
return -1;
if ( item1.attr > item2.attr)
return 1;
return 0;
``` |
51,176 | <p>I recently started a new webforms project and decided to separate the business classes from any DBML references. My business layer classes instead access discrete Data layer methods and are returned collections of DTO's. So the data layer might project DTO's like the following:</p>
<pre><code>(from c in dataContext.Customers
where c.Active == true
select new DTO.Customer
{
CustomerID = c.CustomerID,
Name = c.CustomerName,
...
}).ToList()
</code></pre>
<p>Although building the DTO objects adds work, this feels like a better approach to a tight binding between Business & Data layers and means I can test the Business layer without a database being present.</p>
<p>My question is, is this good practice?, Is there a way of generating the DTO's (maybe via SQLMetal), and what other problems might I strike as the project progresses.</p>
| [
{
"answer_id": 51186,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>In my opinion in most cases DTO objects are not needed when dealing with LINQ. Generated LINQ classes can be easily tested. LI... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5136/"
] | I recently started a new webforms project and decided to separate the business classes from any DBML references. My business layer classes instead access discrete Data layer methods and are returned collections of DTO's. So the data layer might project DTO's like the following:
```
(from c in dataContext.Customers
where c.Active == true
select new DTO.Customer
{
CustomerID = c.CustomerID,
Name = c.CustomerName,
...
}).ToList()
```
Although building the DTO objects adds work, this feels like a better approach to a tight binding between Business & Data layers and means I can test the Business layer without a database being present.
My question is, is this good practice?, Is there a way of generating the DTO's (maybe via SQLMetal), and what other problems might I strike as the project progresses. | I don't know if it's best practice but I have written similar code in the not so recent past because I too felt that I could improve the separation of concerns by using my own classes instead of the LINQ-designer-generated ones within my application.
You may want to consider just returning an IQueryable<Customer> instead of an IList<Customer> from your data-access method. Since IQueryable<T> inherits from IEnumerable<T> the rest of your app should be able to deal with it quite well. You can also convert it to a List when you really need to.
The advantage of this is that you can dynamically modify your query quite easily and minimze the amount of data returned from SQL Server.
E.g. if your method signature is
IQueryable<Customer> GetCustomers() you could get a single customer by calling GetCustomers().Where(c => c.CustomerID == 101).Single();
In this example only one record would be returned from the database whereas I imagine currently your code would return either all customers or you'd be required to write separate methods (and thus very repetitive code) to cater for all the different things you may want to filter by. |
51,180 | <p>I'm tearing my hair out with this one. If I start a block comment <code>/*</code> in VS.NET 2005+ then carriage return, Visual Studio insists that I have another asterisk <code>*</code>. I know there's an option to turn this off but I just can't find it. Anyone know how to turn this feature off?</p>
| [
{
"answer_id": 51194,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 6,
"selected": true,
"text": "<p><strong>Update: this setting was changed in VS 2015 update 2. See <a href=\"https://stackoverflow.com/a/36319097/4294399\... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4458/"
] | I'm tearing my hair out with this one. If I start a block comment `/*` in VS.NET 2005+ then carriage return, Visual Studio insists that I have another asterisk `*`. I know there's an option to turn this off but I just can't find it. Anyone know how to turn this feature off? | **Update: this setting was changed in VS 2015 update 2. See [this answer](https://stackoverflow.com/a/36319097/4294399).**
[This post](http://forums.msdn.microsoft.com/en-US/csharpide/thread/a41e3652-efe2-4f81-ad3e-94994974fcb2/) addresses your question. The gist of it is:
```
Text Editor > C# > Advanced > Generate XML documentation comments for ///
``` |
51,185 | <p>Does javascript use immutable or mutable strings? Do I need a "string builder"?</p>
| [
{
"answer_id": 51188,
"author": "JC Grubbs",
"author_id": 4541,
"author_profile": "https://Stackoverflow.com/users/4541",
"pm_score": 0,
"selected": false,
"text": "<p>JavaScript strings are indeed immutable.</p>\n"
},
{
"answer_id": 51191,
"author": "Glenn Slaven",
"auth... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220/"
] | Does javascript use immutable or mutable strings? Do I need a "string builder"? | They are immutable. You cannot change a character within a string with something like `var myString = "abbdef"; myString[2] = 'c'`. The string manipulation methods such as [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim), [`slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) return new strings.
In the same way, if you have two references to the same string, modifying one doesn't affect the other
```
let a = b = "hello";
a = a + " world";
// b is not affected
```
However, I've always heard what Ash mentioned in his answer (that using Array.join is faster for concatenation) so I wanted to test out the different methods of concatenating strings and abstracting the fastest way into a StringBuilder. I wrote some tests to see if this is true (it isn't!).
This was what I believed would be the fastest way, though I kept thinking that adding a method call may make it slower...
```
function StringBuilder() {
this._array = [];
this._index = 0;
}
StringBuilder.prototype.append = function (str) {
this._array[this._index] = str;
this._index++;
}
StringBuilder.prototype.toString = function () {
return this._array.join('');
}
```
Here are performance speed tests. All three of them create a gigantic string made up of concatenating `"Hello diggity dog"` one hundred thousand times into an empty string.
I've created three types of tests
* Using `Array.push` and `Array.join`
* Using Array indexing to avoid `Array.push`, then using `Array.join`
* Straight string concatenation
Then I created the same three tests by abstracting them into `StringBuilderConcat`, `StringBuilderArrayPush` and `StringBuilderArrayIndex` <http://jsperf.com/string-concat-without-sringbuilder/5> Please go there and run tests so we can get a nice sample. Note that I fixed a small bug, so the data for the tests got wiped, I will update the table once there's enough performance data. Go to <http://jsperf.com/string-concat-without-sringbuilder/5> for the old data table.
Here are some numbers (Latest update in Ma5rch 2018), if you don't want to follow the link. The number on each test is in 1000 operations/second (**higher is better**)
| Browser | Index | Push | Concat | SBIndex | SBPush | SBConcat |
| --- | --- | --- | --- | --- | --- | --- |
| Chrome 71.0.3578 | 988 | 1006 | 2902 | 963 | 1008 | 2902 |
| Firefox 65 | 1979 | 1902 | 2197 | 1917 | 1873 | 1953 |
| Edge | 593 | 373 | 952 | 361 | 415 | 444 |
| Exploder 11 | 655 | 532 | 761 | 537 | 567 | 387 |
| Opera 58.0.3135 | 1135 | 1200 | 4357 | 1137 | 1188 | 4294 |
**Findings**
* Nowadays, all evergreen browsers handle string concatenation well. `Array.join` only helps IE 11
* Overall, Opera is fastest, 4 times as fast as Array.join
* Firefox is second and `Array.join` is only slightly slower in FF but considerably slower (3x) in Chrome.
* Chrome is third but string concat is 3 times faster than Array.join
* Creating a StringBuilder seems to not affect perfomance too much.
Hope somebody else finds this useful
**Different Test Case**
Since @RoyTinker thought that my test was flawed, I created a new case that doesn't create a big string by concatenating the same string, it uses a different character for each iteration. String concatenation still seemed faster or just as fast. Let's get those tests running.
I suggest everybody should keep thinking of other ways to test this, and feel free to add new links to different test cases below.
<http://jsperf.com/string-concat-without-sringbuilder/7> |
51,195 | <p>I want to write a little "DBQuery" function in perl so I can have one-liners which send an SQL statement and receive back and an array of hashes, i.e. a recordset. However, I'm running into an issue with Perl syntax (and probably some odd pointer/reference issue) which is preventing me from packing out the information from the hash that I'm getting from the database. The sample code below demonstrates the issue.</p>
<p>I can get the data "Jim" out of a hash inside an array with this syntax:</p>
<pre><code>print $records[$index]{'firstName'}
</code></pre>
<p>returns "Jim"</p>
<p>but if I copy the hash record in the array to its own hash variable first, then I strangely can't access the data anymore in that hash:</p>
<pre><code>
%row = $records[$index];
$row{'firstName'};
</code></pre>
<p>returns "" (blank)</p>
<p>Here is the full sample code showing the problem. Any help is appreciated:</p>
<pre><code>
my @records = (
{'id' => 1, 'firstName' => 'Jim'},
{'id' => 2, 'firstName' => 'Joe'}
);
my @records2 = ();
$numberOfRecords = scalar(@records);
print "number of records: " . $numberOfRecords . "\n";
for(my $index=0; $index < $numberOfRecords; $index++) {
#works
print 'you can print the records like this: ' . $records[$index]{'firstName'} . "\n";
#does NOT work
%row = $records[$index];
print 'but not like this: ' . $row{'firstName'} . "\n";
}
</code></pre>
| [
{
"answer_id": 51205,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 6,
"selected": true,
"text": "<p>The nested data structure contains a hash <em>reference</em>, not a hash.</p>\n\n<pre><code># Will work (the ->... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] | I want to write a little "DBQuery" function in perl so I can have one-liners which send an SQL statement and receive back and an array of hashes, i.e. a recordset. However, I'm running into an issue with Perl syntax (and probably some odd pointer/reference issue) which is preventing me from packing out the information from the hash that I'm getting from the database. The sample code below demonstrates the issue.
I can get the data "Jim" out of a hash inside an array with this syntax:
```
print $records[$index]{'firstName'}
```
returns "Jim"
but if I copy the hash record in the array to its own hash variable first, then I strangely can't access the data anymore in that hash:
```
%row = $records[$index];
$row{'firstName'};
```
returns "" (blank)
Here is the full sample code showing the problem. Any help is appreciated:
```
my @records = (
{'id' => 1, 'firstName' => 'Jim'},
{'id' => 2, 'firstName' => 'Joe'}
);
my @records2 = ();
$numberOfRecords = scalar(@records);
print "number of records: " . $numberOfRecords . "\n";
for(my $index=0; $index < $numberOfRecords; $index++) {
#works
print 'you can print the records like this: ' . $records[$index]{'firstName'} . "\n";
#does NOT work
%row = $records[$index];
print 'but not like this: ' . $row{'firstName'} . "\n";
}
``` | The nested data structure contains a hash *reference*, not a hash.
```
# Will work (the -> dereferences the reference)
$row = $records[$index];
print "This will work: ", $row->{firstName}, "\n";
# This will also work, by promoting the hash reference into a hash
%row = %{ $records[$index] };
print "This will work: ", $row{firstName}, "\n";
```
If you're ever presented with a deep Perl data structure, you may profit from printing it using [Data::Dumper](http://search.cpan.org/perldoc?Data::Dumper) to print it into human-readable (and Perl-parsable) form. |
51,210 | <p>I'm playing with the routing.rb code in Rails 2.1, and trying to to get it to the point where I can do something useful with the RoutingError exception that is thrown when it can't find the appropriate path.</p>
<p>This is a somewhat tricky problem, because there are some class of URLs which are just plain BAD: the /azenv.php bot attacks, the people typing /bar/foo/baz into the URL, etc... we don't want that.</p>
<p>Then there's subtle routing problems, where we do want to be notified: /artists/ for example, or ///. In these situations, we may want an error being thrown, or not... or we get Google sending us URLs which used to be valid but are no longer because people deleted them.</p>
<p>In each of these situations, I want a way to contain, analyze and filter the path that we get back, or at least some Railsy way to manage routing past the normal 'fallback catchall' url. Does this exist?</p>
<p>EDIT:</p>
<p>So the code here is: </p>
<pre><code># File vendor/rails/actionpack/lib/action_controller/rescue.rb, line 141
def rescue_action_without_handler(exception)
log_error(exception) if logger
erase_results if performed?
# Let the exception alter the response if it wants.
# For example, MethodNotAllowed sets the Allow header.
if exception.respond_to?(:handle_response!)
exception.handle_response!(response)
end
if consider_all_requests_local || local_request?
rescue_action_locally(exception)
else
rescue_action_in_public(exception)
end
end
</code></pre>
<p>So our best option is to override log_error(exception) so that we can filter down the exceptions according to the exception. So in ApplicationController</p>
<pre><code>def log_error(exception)
message = '...'
if should_log_exception_as_debug?(exception)
logger.debug(message)
else
logger.error(message)
end
end
def should_log_exception_as_debug?(exception)
return (ActionController::RoutingError === exception)
end
</code></pre>
<p>Salt for additional logic where we want different controller logic, routes, etc.</p>
| [
{
"answer_id": 51378,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 1,
"selected": false,
"text": "<p>There's the method_missing method. You could implement that in your Application Controller and catch all missi... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5266/"
] | I'm playing with the routing.rb code in Rails 2.1, and trying to to get it to the point where I can do something useful with the RoutingError exception that is thrown when it can't find the appropriate path.
This is a somewhat tricky problem, because there are some class of URLs which are just plain BAD: the /azenv.php bot attacks, the people typing /bar/foo/baz into the URL, etc... we don't want that.
Then there's subtle routing problems, where we do want to be notified: /artists/ for example, or ///. In these situations, we may want an error being thrown, or not... or we get Google sending us URLs which used to be valid but are no longer because people deleted them.
In each of these situations, I want a way to contain, analyze and filter the path that we get back, or at least some Railsy way to manage routing past the normal 'fallback catchall' url. Does this exist?
EDIT:
So the code here is:
```
# File vendor/rails/actionpack/lib/action_controller/rescue.rb, line 141
def rescue_action_without_handler(exception)
log_error(exception) if logger
erase_results if performed?
# Let the exception alter the response if it wants.
# For example, MethodNotAllowed sets the Allow header.
if exception.respond_to?(:handle_response!)
exception.handle_response!(response)
end
if consider_all_requests_local || local_request?
rescue_action_locally(exception)
else
rescue_action_in_public(exception)
end
end
```
So our best option is to override log\_error(exception) so that we can filter down the exceptions according to the exception. So in ApplicationController
```
def log_error(exception)
message = '...'
if should_log_exception_as_debug?(exception)
logger.debug(message)
else
logger.error(message)
end
end
def should_log_exception_as_debug?(exception)
return (ActionController::RoutingError === exception)
end
```
Salt for additional logic where we want different controller logic, routes, etc. | Nooooo!!! Don't implement method\_missing on your controller! And please try to avoid action\_missing as well.
The frequently touted pattern is to add a route:
```
map.connect '*', :controller => 'error', :action => 'not_found'
```
Where you can show an appropriate error.
Rails also has a mechanism called rescue\_action\_in\_public where you can write your own error handling logic -- we really should clean it up and encourage people to use it. PDI! :-) |
51,212 | <p>I am writing a little application to download files over http (as, for example, described <a href="https://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776">here</a>).</p>
<p>I also want to include a little download progress indicator showing the percentage of the download progress.</p>
<p>Here is what I came up with:</p>
<pre>
sys.stdout.write(rem_file + "...")
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("%2d%%" % percent)
sys.stdout.write("\b\b\b")
sys.stdout.flush()
</pre>
<p>Output: MyFileName... 9%</p>
<p>Any other ideas or recommendations to do this? </p>
<p>One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?</p>
<p><strong>EDIT:</strong></p>
<p>Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:</p>
<pre>
global rem_file # global variable to be used in dlProgress
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("\r" + rem_file + "...%d%%" % percent)
sys.stdout.flush()
</pre>
<p>Output: MyFileName...9% </p>
<p>And the cursor shows up at the END of the line. Much better.</p>
| [
{
"answer_id": 51214,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 2,
"selected": false,
"text": "<p>If you use the <code>curses</code> package, you have much greater control of the console. It also comes at a higher cost i... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2386/"
] | I am writing a little application to download files over http (as, for example, described [here](https://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776)).
I also want to include a little download progress indicator showing the percentage of the download progress.
Here is what I came up with:
```
sys.stdout.write(rem_file + "...")
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("%2d%%" % percent)
sys.stdout.write("\b\b\b")
sys.stdout.flush()
```
Output: MyFileName... 9%
Any other ideas or recommendations to do this?
One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?
**EDIT:**
Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:
```
global rem_file # global variable to be used in dlProgress
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("\r" + rem_file + "...%d%%" % percent)
sys.stdout.flush()
```
Output: MyFileName...9%
And the cursor shows up at the END of the line. Much better. | There's a text progress bar library for python at <http://pypi.python.org/pypi/progressbar/2.2> that you might find useful:
>
> This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway.
>
>
> The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line.
>
>
> The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when available.
>
>
> |
51,217 | <p>I work for a company whose primary business is not software related. Most documentation for using source control is written with a development team writing for commercial or open source projects in mind. As someone who writes in house software I can say that work is done differently then it would be in a commercial or open source setting. In addition there are stored procedures and database scripts that need to be kept in sync with the code.</p>
<p>In particular I am looking to get suggestions on how best to structure the repository with in house software in mind. Most documentation suggests trunk, branches, tags etc. And procedures for keeping production, test and development environments in sync with their respective sections in the repository etc. </p>
| [
{
"answer_id": 51220,
"author": "Eric",
"author_id": 5277,
"author_profile": "https://Stackoverflow.com/users/5277",
"pm_score": 2,
"selected": false,
"text": "<p>You could use a service like www.unfuddle.com to set up a free SVN or GIT repository.</p>\n\n<p>We use Unfuddle and it's real... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] | I work for a company whose primary business is not software related. Most documentation for using source control is written with a development team writing for commercial or open source projects in mind. As someone who writes in house software I can say that work is done differently then it would be in a commercial or open source setting. In addition there are stored procedures and database scripts that need to be kept in sync with the code.
In particular I am looking to get suggestions on how best to structure the repository with in house software in mind. Most documentation suggests trunk, branches, tags etc. And procedures for keeping production, test and development environments in sync with their respective sections in the repository etc. | Setting up SVN repositories can be tricky only in the sense of how you organize them. Before we setup SVN, I actually RTFM'd the online [Subversion manual](http://svnbook.red-bean.com/) which discusses organizational techniques for repositories and some of the gotchas you should think about in advance, namely what you cannot do after you have created your repositories if you decide to change your mind. I suggest a pass through this manual before setup.
For us, as consultants, we do custom and in-house software development as well as some document management through SVN. It was in our interest to create one repository for each client and one for ourselves. Within each repository, we created folders for each project (software or otherwise). This allowed us to segment security access by repository and by client and even by project within a repository. Going deeper, for each software project we created 'working', 'tags' and 'branches' folders. We generally put releases in 'tags' using 'release\_w.x.y.z' as the tag for a standard.
In your case, to keep sprocs, scripts, and other related documents in synch, you can create a project folder, then under that a 'working' folder, then under that 'code' and next to it 'scripts', etc. Then when you tag the working version for release, you end up tagging it all together.
```
\Repository
\ProjectX
\Working
\Code
\Scripts
\Notes
\Tags
\Branches
```
As for non-code, I would suggest a straight folder layout by project or document type (manuals, policies, etc.). Generally with documents and depending on how your company operates, just having the version history/logs is enough.
We run SVN on Windows along with [WebSVN](http://websvn.tigris.org/) which is a great open source repository viewer. We use it to give clients web access to their code and it's all driven by the underlying Subversion security. Internally, we use [TortoiseSVN](http://tortoisesvn.tigris.org/) to manage the repositories, commit, update, import, etc.
Another thing is that training should be considered an integral part of your deployment. Users new to version control may have a hard time understanding what is going on. We found that giving them functional instructions (do this when creating a project, do this when updating, etc.) was very helpful while they learned the concepts. We created a 'sandbox' repository where users can play all they want with documents and folders to practice, you may find this useful as well to experiment on what policies to establish.
Good luck! |
51,224 | <p>I'm trying to write a regular expression that validates a date. The regex needs to match the following</p>
<ul>
<li>M/D/YYYY</li>
<li>MM/DD/YYYY</li>
<li>Single digit months can start with a leading zero (eg: 03/12/2008)</li>
<li>Single digit days can start with a leading zero (eg: 3/02/2008)</li>
<li>CANNOT include February 30 or February 31 (eg: 2/31/2008)</li>
</ul>
<p>So far I have </p>
<pre><code>^(([1-9]|1[012])[-/.]([1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d)|((1[012]|0[1-9])(3[01]|2\d|1\d|0[1-9])(19|20)\d\d)|((1[012]|0[1-9])[-/.](3[01]|2\d|1\d|0[1-9])[-/.](19|20)\d\d)$
</code></pre>
<p>This matches properly EXCEPT it still includes 2/30/2008 & 2/31/2008.</p>
<p>Does anyone have a better suggestion?</p>
<p><strong>Edit:</strong> I found <a href="http://regexlib.com/REDetails.aspx?regexp_id=112" rel="noreferrer">the answer</a> on RegExLib</p>
<pre><code>^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$
</code></pre>
<p>It matches all valid months that follow the MM/DD/YYYY format.</p>
<p>Thanks everyone for the help.</p>
| [
{
"answer_id": 51227,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 2,
"selected": false,
"text": "<p>Sounds like you're overextending regex for this purpose. What I would do is use a regex to match a few date formats and then u... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3742/"
] | I'm trying to write a regular expression that validates a date. The regex needs to match the following
* M/D/YYYY
* MM/DD/YYYY
* Single digit months can start with a leading zero (eg: 03/12/2008)
* Single digit days can start with a leading zero (eg: 3/02/2008)
* CANNOT include February 30 or February 31 (eg: 2/31/2008)
So far I have
```
^(([1-9]|1[012])[-/.]([1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d)|((1[012]|0[1-9])(3[01]|2\d|1\d|0[1-9])(19|20)\d\d)|((1[012]|0[1-9])[-/.](3[01]|2\d|1\d|0[1-9])[-/.](19|20)\d\d)$
```
This matches properly EXCEPT it still includes 2/30/2008 & 2/31/2008.
Does anyone have a better suggestion?
**Edit:** I found [the answer](http://regexlib.com/REDetails.aspx?regexp_id=112) on RegExLib
```
^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$
```
It matches all valid months that follow the MM/DD/YYYY format.
Thanks everyone for the help. | This is not an appropriate use of regular expressions. You'd be better off using
```
[0-9]{2}/[0-9]{2}/[0-9]{4}
```
and then checking ranges in a higher-level language. |
51,233 | <p>How can I retrieve the page title of a webpage (title html tag) using Python?</p>
| [
{
"answer_id": 51240,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 7,
"selected": true,
"text": "<p>I'll always use <a href=\"http://lxml.de/\" rel=\"nofollow noreferrer\">lxml</a> for such tasks. You could use <a href... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2386/"
] | How can I retrieve the page title of a webpage (title html tag) using Python? | I'll always use [lxml](http://lxml.de/) for such tasks. You could use [beautifulsoup](http://www.crummy.com/software/BeautifulSoup/) as well.
```
import lxml.html
t = lxml.html.parse(url)
print(t.find(".//title").text)
```
EDIT based on comment:
```
from urllib2 import urlopen
from lxml.html import parse
url = "https://www.google.com"
page = urlopen(url)
p = parse(page)
print(p.find(".//title").text)
``` |
51,238 | <p>I have a table in a MySql database that stores user accounts. One of the columns, expires, stores an expiration date but defaults to NULL. I need to be able to remove an expiration date and set it back to the default value.</p>
<p>Currently, all of my CRUD routines are written using MySqlCommand with parameters. Can this be done directly with a MySqlParameter, or do I have to create an alternate command object to handle this eventuality?</p>
| [
{
"answer_id": 51257,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>It's not clear what conditions you're talking about. If you want to set column to default value, you can use <a href=\"http://... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1249/"
] | I have a table in a MySql database that stores user accounts. One of the columns, expires, stores an expiration date but defaults to NULL. I need to be able to remove an expiration date and set it back to the default value.
Currently, all of my CRUD routines are written using MySqlCommand with parameters. Can this be done directly with a MySqlParameter, or do I have to create an alternate command object to handle this eventuality? | The problem was DBNull, doing:
```
command.Parameters.AddWithValue("@parameter", null);
```
compiles OK. |
51,262 | <p>How can you find out what are the long running queries are on Informix database server? I have a query that is using up the CPU and want to find out what the query is.</p>
| [
{
"answer_id": 52121,
"author": "Jason Navarrete",
"author_id": 3920,
"author_profile": "https://Stackoverflow.com/users/3920",
"pm_score": -1,
"selected": false,
"text": "<pre><code>SELECT ELAPSED_TIME_MIN,SUBSTR(AUTHID,1,10) AS AUTH_ID, \nAGENT_ID, APPL_STATUS,SUBSTR(STMT_TEXT,1,20) AS... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486/"
] | How can you find out what are the long running queries are on Informix database server? I have a query that is using up the CPU and want to find out what the query is. | If the query is currently running watch the **onstat -g act -r 1** output and look for items with an ***rstcb*** that is not 0
```
Running threads:
tid tcb rstcb prty status vp-class name
106 c0000000d4860950 0 2 running 107soc soctcppoll
107 c0000000d4881950 0 2 running 108soc soctcppoll
564457 c0000000d7f28250 c0000000d7afcf20 2 running 1cpu CDRD_10
```
In this example the third row is what is currently running. If you have multiple rows with non-zero rstcb values then watch for a bit looking for the one that is always or almost always there. That is most likely the session that your looking for.
**c0000000d7afcf20** is the address that we're interested in for this example.
Use **onstat -u | grep c0000000d7afcf20** to find the session
```
c0000000d7afcf20 Y--P--- 22887 informix - c0000000d5b0abd0 0 5 14060 3811
```
This gives you the session id which in our example is **22887**. Use **onstat -g ses 22887**
to list info about that session. In my example it's a system session so there's nothing to see in the onstat -g ses output. |
51,264 | <p>What object do you query against to select all the table names in a schema in Oracle?</p>
| [
{
"answer_id": 51265,
"author": "jatanp",
"author_id": 959,
"author_profile": "https://Stackoverflow.com/users/959",
"pm_score": -1,
"selected": false,
"text": "<p>You may use:</p>\n\n<pre><code>select tabname from tabs \n</code></pre>\n\n<p>to get the name of tables present in schema.</... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] | What object do you query against to select all the table names in a schema in Oracle? | To see all the tables you have access to
```
select table_name from all_tables where owner='<SCHEMA>';
```
To select all tables for the current logged in schema (eg, your tables)
```
select table_name from user_tables;
``` |
51,269 | <p>I am not sure whether is it possible to change attribute's parameter during runtime? For example, inside an assembly I have the following class</p>
<pre><code>public class UserInfo
{
[Category("change me!")]
public int Age
{
get;
set;
}
[Category("change me!")]
public string Name
{
get;
set;
}
}
</code></pre>
<p>This is a class that is provided by a third party vendor and <strong>I can't change the code</strong>. But now I found that the above descriptions are not accurate, and I want to change the "change me" category name to something else when i bind an instance of the above class to a property grid.</p>
<p>May I know how to do this?</p>
| [
{
"answer_id": 51278,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 0,
"selected": false,
"text": "<p>I really don't think so, unless there's some funky reflection that can pull it off. The property decorations are set... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] | I am not sure whether is it possible to change attribute's parameter during runtime? For example, inside an assembly I have the following class
```
public class UserInfo
{
[Category("change me!")]
public int Age
{
get;
set;
}
[Category("change me!")]
public string Name
{
get;
set;
}
}
```
This is a class that is provided by a third party vendor and **I can't change the code**. But now I found that the above descriptions are not accurate, and I want to change the "change me" category name to something else when i bind an instance of the above class to a property grid.
May I know how to do this? | Well you learn something new every day, apparently I lied:
>
> What isn’t generally realised is that
> you can change attribute **instance** values fairly
> easily at runtime. The reason is, of
> course, that the instances of the
> attribute classes that are created are
> perfectly normal objects and can be
> used without restriction. For example,
> we can get the object:
>
>
>
> ```
> ASCII[] attrs1=(ASCII[])
> typeof(MyClass).GetCustomAttributes(typeof(ASCII), false);
>
> ```
>
> …change the value of its public variable and show that it has changed:
>
>
>
> ```
> attrs1[0].MyData="A New String";
> MessageBox.Show(attrs1[0].MyData);
>
> ```
>
> …and finally create another instance
> and show that its value is unchanged:
>
>
>
> ```
> ASCII[] attrs3=(ASCII[])
> typeof(MyClass).GetCustomAttributes(typeof(ASCII), false);
> MessageBox.Show(attrs3[0].MyData);
>
> ```
>
>
<http://www.vsj.co.uk/articles/display.asp?id=713> |
51,320 | <p>For a project I'm working on. I need to look for an executable on the filesystem. For UNIX derivatives, I assume the user has the file in the mighty $PATH variable, but there is no such thing on Windows.</p>
<p>I can safely assume the file is at most 2 levels deep into the filesystem, but I don't know on what drive it will be. I have to try all drives, but I can't figure out how to list all available drives (which have a letter assigned to it).</p>
<p>Any help?</p>
<p><strong>EDIT:</strong> I know there is a %PATH% variable, but it is not as integrated as in UNIX systems. For instance, the application I'm looking for is OpenOffice. Such software would not be in %PATH%, typically.</p>
| [
{
"answer_id": 51327,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": -1,
"selected": false,
"text": "<p>Of course there is a <code>PATH</code> environment variable <a href=\"http://en.wikipedia.org/wiki/Environment_variab... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018/"
] | For a project I'm working on. I need to look for an executable on the filesystem. For UNIX derivatives, I assume the user has the file in the mighty $PATH variable, but there is no such thing on Windows.
I can safely assume the file is at most 2 levels deep into the filesystem, but I don't know on what drive it will be. I have to try all drives, but I can't figure out how to list all available drives (which have a letter assigned to it).
Any help?
**EDIT:** I know there is a %PATH% variable, but it is not as integrated as in UNIX systems. For instance, the application I'm looking for is OpenOffice. Such software would not be in %PATH%, typically. | <http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listRoots()>
```
File[] roots = File.listRoots();
for(int i = 0; i < roots.length ; i++)
System.out.println("Root["+i+"]:" + roots[i]);
```
google: list drives java, first hit:-) |
51,339 | <p>I'm a bit stuck on this. Basically I want to do something like the following SQL query in LINQ to SQL:</p>
<pre><code>SELECT f.*
FROM Foo f
WHERE f.FooId IN (
SELECT fb.FooId
FROM FooBar fb
WHERE fb.BarId = 1000
)
</code></pre>
<p>Any help would be gratefully received.</p>
| [
{
"answer_id": 51345,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 2,
"selected": false,
"text": "<p>Try using two separate steps:</p>\n\n<pre><code>// create a Dictionary / Set / Collection fids first\nvar fids = (fro... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1904/"
] | I'm a bit stuck on this. Basically I want to do something like the following SQL query in LINQ to SQL:
```
SELECT f.*
FROM Foo f
WHERE f.FooId IN (
SELECT fb.FooId
FROM FooBar fb
WHERE fb.BarId = 1000
)
```
Any help would be gratefully received. | Have a look at [this article](http://blog.wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql). Basically, if you want to get the equivalent of IN, you need to construct an inner query first, and then use the Contains() method. Here's my attempt at translating:
```
var innerQuery = from fb in FoorBar where fb.BarId = 1000 select fb.FooId;
var result = from f in Foo where innerQuery.Contains(f.FooId) select f;
``` |
51,352 | <p>I'm currently working on a web application which has a page which displays a single chart (a .png image). On another part of this page there are a set of links which, when clicked, the entire page reloads and looks exactly the same as before except for the chart in the middle of the page.</p>
<p>What I want to do is when a link is clicked on a page just the chart on the page is changed. This will speed things up tremendously as the page is roughly 100kb large, and don't really want to reload the entire page just to display this. </p>
<p>I've been doing this via JavaScript, which works so far, using the following code</p>
<pre><code>document.getElementById('chart').src = '/charts/10.png';
</code></pre>
<p>The problem is that when the user clicks on the link, it may take a couple of seconds before the chart changes. This makes the user think that their click hasn't done anything, or that the system is slow to respond.</p>
<p>What I want to happen is display a spinner / throbber / status indicator, in place of where the image is while it is loading, so when the user clicks the link they know at least the system has taken their input and is doing something about it. </p>
<p>I've tried a few suggestions, even using a psudo time out to show a spinner, and then flick back to the image. </p>
<p>A good suggestion I've had is to use the following</p>
<pre><code><img src="/charts/10.png" lowsrc="/spinner.gif"/>
</code></pre>
<p>Which would be ideal, except the spinner is significantly smaller than the chart which is being displayed.</p>
<p>Any other ideas?</p>
| [
{
"answer_id": 51360,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 1,
"selected": false,
"text": "<p>put the spinner in a div the same size as the chart, you know the height and width so you can use relative positioning to ce... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3847/"
] | I'm currently working on a web application which has a page which displays a single chart (a .png image). On another part of this page there are a set of links which, when clicked, the entire page reloads and looks exactly the same as before except for the chart in the middle of the page.
What I want to do is when a link is clicked on a page just the chart on the page is changed. This will speed things up tremendously as the page is roughly 100kb large, and don't really want to reload the entire page just to display this.
I've been doing this via JavaScript, which works so far, using the following code
```
document.getElementById('chart').src = '/charts/10.png';
```
The problem is that when the user clicks on the link, it may take a couple of seconds before the chart changes. This makes the user think that their click hasn't done anything, or that the system is slow to respond.
What I want to happen is display a spinner / throbber / status indicator, in place of where the image is while it is loading, so when the user clicks the link they know at least the system has taken their input and is doing something about it.
I've tried a few suggestions, even using a psudo time out to show a spinner, and then flick back to the image.
A good suggestion I've had is to use the following
```
<img src="/charts/10.png" lowsrc="/spinner.gif"/>
```
Which would be ideal, except the spinner is significantly smaller than the chart which is being displayed.
Any other ideas? | I've used something like this to preload an image and then automatically call back to my javascript when the image is finished loading. You want to check complete before you setup the callback because the image may already be cached and it may not call your callback.
```
function PreloadImage(imgSrc, callback){
var objImagePreloader = new Image();
objImagePreloader.src = imgSrc;
if(objImagePreloader.complete){
callback();
objImagePreloader.onload=function(){};
}
else{
objImagePreloader.onload = function() {
callback();
// clear onLoad, IE behaves irratically with animated gifs otherwise
objImagePreloader.onload=function(){};
}
}
}
``` |
51,407 | <p>I want to load a desktop application, via reflection, as a Control inside another application.</p>
<p>The application I'm reflecting is a legacy one - I can't make changes to it.</p>
<p>I can dynamically access the Form, but can't load it as a Control.</p>
<p>In .Net Form expands on Control, and I can assign the reflected Form as a Control, but it throws a run-time exception.</p>
<p>Forms cannot be loaded as controls.</p>
<p>Is there any way to convert the form to a control? </p>
| [
{
"answer_id": 51428,
"author": "Rob Stevenson-Leggett",
"author_id": 4950,
"author_profile": "https://Stackoverflow.com/users/4950",
"pm_score": 1,
"selected": false,
"text": "<p>You should be able to add the form to the controls collection of your parent form...</p>\n\n<p>See here: \n<... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | I want to load a desktop application, via reflection, as a Control inside another application.
The application I'm reflecting is a legacy one - I can't make changes to it.
I can dynamically access the Form, but can't load it as a Control.
In .Net Form expands on Control, and I can assign the reflected Form as a Control, but it throws a run-time exception.
Forms cannot be loaded as controls.
Is there any way to convert the form to a control? | Yes, this works just fine. I'm working on a .NET app right now that loads forms into a panel on a host form.
The relevant snippet:
```
// setup the new form
form.TopLevel = false;
form.FormBorderStyle = FormBorderStyle.None;
form.Dock = DockStyle.Fill;
form.Show ( );
// add to the panel's list of child controls
panelFormHost.Controls.Add ( form );
``` |
51,412 | <p>Say I have the following methods:</p>
<pre><code>def methodA(arg, **kwargs):
pass
def methodB(arg, *args, **kwargs):
pass
</code></pre>
<p>In methodA I wish to call methodB, passing on the kwargs. However, it seems that if I define <code>methodA</code> as follows, the second argument will be passed on as positional rather than named variable arguments.</p>
<pre><code>def methodA(arg, **kwargs):
methodB("argvalue", kwargs)
</code></pre>
<p>How do I make sure that the **kwargs in methodA gets passed as **kwargs to methodB?</p>
| [
{
"answer_id": 51414,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 1,
"selected": false,
"text": "<p>Some experimentation and I figured this one out:</p>\n\n<p>def methodA(arg, **kwargs):\n methodB(\"argvalue\", **kwargs)... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355/"
] | Say I have the following methods:
```
def methodA(arg, **kwargs):
pass
def methodB(arg, *args, **kwargs):
pass
```
In methodA I wish to call methodB, passing on the kwargs. However, it seems that if I define `methodA` as follows, the second argument will be passed on as positional rather than named variable arguments.
```
def methodA(arg, **kwargs):
methodB("argvalue", kwargs)
```
How do I make sure that the \*\*kwargs in methodA gets passed as \*\*kwargs to methodB? | Put the asterisks before the kwargs variable. This makes Python pass the variable (which is assumed to be a dictionary) as keyword arguments.
```
methodB("argvalue", **kwargs)
``` |
51,420 | <p>I want to get the base 10 logarithm of a Fixnum using Ruby, but found that n.log or n.log10 are not defined. Math::log is defined but uses a different base than 10.</p>
<p>What is the easiest way to get the base 10 logarithm of a Fixnum?</p>
| [
{
"answer_id": 51423,
"author": "Wes Oldenbeuving",
"author_id": 4187,
"author_profile": "https://Stackoverflow.com/users/4187",
"pm_score": 2,
"selected": false,
"text": "<p>Reading the documentation for module Math the answer is really obvious:</p>\n\n<pre><code>Math::log10(n) \n</code... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4187/"
] | I want to get the base 10 logarithm of a Fixnum using Ruby, but found that n.log or n.log10 are not defined. Math::log is defined but uses a different base than 10.
What is the easiest way to get the base 10 logarithm of a Fixnum? | There is
```
Math::log10 (n)
```
And there is also a property of logarithms that `logx(y) = log(y)/log(x)` |
51,429 | <p>Can anyone give me some pointers on how to display the results of an XPath query in a textbox using code (C#)? My datascource <i>seems</i> to (re)bind correctly once the XPath query has been applied, but I cannot find how to get at the resulting data.<br /><br />
Any help would be greatly appreciated.</p>
| [
{
"answer_id": 51490,
"author": "d91-jal",
"author_id": 5085,
"author_profile": "https://Stackoverflow.com/users/5085",
"pm_score": 0,
"selected": false,
"text": "<p>Some more information would be nice to have to be able to give you a decent answer. Do you have any existing code snippets... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Can anyone give me some pointers on how to display the results of an XPath query in a textbox using code (C#)? My datascource *seems* to (re)bind correctly once the XPath query has been applied, but I cannot find how to get at the resulting data.
Any help would be greatly appreciated. | XMLDataSource is designed to be used with data-bound controls. ASP.NET's TextBox is not a data-bound control. So to accomplish what you want you either have to find a textbox control with data binding or display the result in some other way.
For example, you could use a [Repeater control](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.aspx) and create your own rendering template for it.
```
<asp:Repeater id="Repeater1" runat="server" datasource="XMLds">
<ItemTemplate>
<input type="text" value="<%# XPath("<path to display field>")%>" />
</ItemTemplate>
</asp:Repeater>
``` |
51,470 | <p>In <a href="http://en.wikipedia.org/wiki/PostgreSQL" rel="noreferrer">PostgreSQL</a>, I can do something like this:</p>
<pre><code>ALTER SEQUENCE serial RESTART WITH 0;
</code></pre>
<p>Is there an Oracle equivalent?</p>
| [
{
"answer_id": 51482,
"author": "Mo.",
"author_id": 1870,
"author_profile": "https://Stackoverflow.com/users/1870",
"pm_score": 7,
"selected": false,
"text": "<p>A true restart is not possible <a href=\"http://en.wiktionary.org/wiki/AFAIK\" rel=\"noreferrer\">AFAIK</a>. (Please correct m... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/917/"
] | In [PostgreSQL](http://en.wikipedia.org/wiki/PostgreSQL), I can do something like this:
```
ALTER SEQUENCE serial RESTART WITH 0;
```
Is there an Oracle equivalent? | Here is a good procedure for resetting any sequence to 0 from Oracle guru [Tom Kyte](http://asktom.oracle.com). Great discussion on the pros and cons in the links below too.
```
tkyte@TKYTE901.US.ORACLE.COM>
create or replace
procedure reset_seq( p_seq_name in varchar2 )
is
l_val number;
begin
execute immediate
'select ' || p_seq_name || '.nextval from dual' INTO l_val;
execute immediate
'alter sequence ' || p_seq_name || ' increment by -' || l_val ||
' minvalue 0';
execute immediate
'select ' || p_seq_name || '.nextval from dual' INTO l_val;
execute immediate
'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0';
end;
/
```
From this page: [Dynamic SQL to reset sequence value](http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:951269671592)
Another good discussion is also here: [How to reset sequences?](http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1119633817597) |
51,492 | <p>For me <strong>usable</strong> means that:</p>
<ul>
<li>it's being used in real-wold</li>
<li>it has tools support. (at least some simple editor)</li>
<li>it has human readable syntax (no angle brackets please) </li>
</ul>
<p>Also I want it to be as close to XML as possible, i.e. there must be support for attributes as well as for properties. So, no <a href="http://en.wikipedia.org/wiki/YAML" rel="noreferrer">YAML</a> please. Currently, only one matching language comes to my mind - <a href="http://en.wikipedia.org/wiki/JSON" rel="noreferrer">JSON</a>. Do you know any other alternatives?</p>
| [
{
"answer_id": 51494,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.json.org/\" rel=\"nofollow noreferrer\">JSON</a> is a very good alternative, and there are tools for i... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196/"
] | For me **usable** means that:
* it's being used in real-wold
* it has tools support. (at least some simple editor)
* it has human readable syntax (no angle brackets please)
Also I want it to be as close to XML as possible, i.e. there must be support for attributes as well as for properties. So, no [YAML](http://en.wikipedia.org/wiki/YAML) please. Currently, only one matching language comes to my mind - [JSON](http://en.wikipedia.org/wiki/JSON). Do you know any other alternatives? | YAML is a 100% superset of JSON, so it doesn't make sense to reject YAML and then consider JSON instead. YAML does everything JSON does, but YAML gives so much more too (like references).
I can't think of anything XML can do that YAML can't, except to validate a document with a DTD, which in my experience has never been worth the overhead. But YAML is so much faster and easier to type and read than XML.
As for attributes or properties, if you think about it, they don't truly "add" anything... it's just a notational shortcut to write something as an attribute of the node instead of putting it in its own child node. But if you like that convenience, you can often emulate it with YAML's inline lists/hashes. Eg:
```
<!-- XML -->
<Director name="Spielberg">
<Movies>
<Movie title="Jaws" year="1975"/>
<Movie title="E.T." year="1982"/>
</Movies>
</Director>
# YAML
Director:
name: Spielberg
Movies:
- Movie: {title: E.T., year: 1975}
- Movie: {title: Jaws, year: 1982}
```
For me, the luxury of not having to write each node tag twice, combined with the freedom from all the angle-bracket litter makes YAML a preferred choice. I also actually like the lack of formal tag attributes, as that always seemed to me like a gray area of XML that needlessly introduced two sets of syntax (both when writing and traversing) for essentially the same concept. YAML does away with that confusion altogether. |
51,502 | <p>I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.</p>
<p>However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.</p>
<p>For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
#-- while --
#-- if --
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me.</p>
| [
{
"answer_id": 51505,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 3,
"selected": false,
"text": "<p>You could try increasing the indent size, but in general I would just say, relax, it will come with time. I don't t... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5342/"
] | I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.
However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.
For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):
```
if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
```
The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:
```
if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
#-- while --
#-- if --
did_i_not_warn_you_biz()
my_father_is_avenged()
```
And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me. | Part of learning a new programming language is learning to read code in that language. A crutch like this may make it easier to read your own code, but it's going to impede the process of learning how to read anyone else's Python code. I really think you'd be better off getting rid of the end of block comments and getting used to normal Python. |
51,520 | <p>Given a path such as <code>"mydir/myfile.txt"</code>, how do I find the file's absolute path in Python? E.g. on Windows, I might end up with:</p>
<pre><code>"C:/example/cwd/mydir/myfile.txt"
</code></pre>
| [
{
"answer_id": 51523,
"author": "sherbang",
"author_id": 5026,
"author_profile": "https://Stackoverflow.com/users/5026",
"pm_score": 11,
"selected": true,
"text": "<pre><code>>>> import os\n>>> os.path.abspath(\"mydir/myfile.txt\")\n'C:/example/cwd/mydir/myfile.txt'\n</... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974/"
] | Given a path such as `"mydir/myfile.txt"`, how do I find the file's absolute path in Python? E.g. on Windows, I might end up with:
```
"C:/example/cwd/mydir/myfile.txt"
``` | ```
>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
```
Also works if it is already an absolute path:
```
>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
``` |
51,526 | <p>I have a list of structs and I want to change one element. For example :</p>
<pre><code>MyList.Add(new MyStruct("john");
MyList.Add(new MyStruct("peter");
</code></pre>
<p>Now I want to change one element:</p>
<pre><code>MyList[1].Name = "bob"
</code></pre>
<p>However, whenever I try and do this I get the following error:</p>
<blockquote>
<p>Cannot modify the return value of
System.Collections.Generic.List.this[int]‘ because it is not
a variable</p>
</blockquote>
<p>If I use a list of classes, the problem doesn't occur.</p>
<p>I guess the answer has to do with structs being a value type.</p>
<p>So, if I have a list of structs should I treat them as <em>read-only</em>? If I need to change elements in a list then I should use classes and not structs?</p>
| [
{
"answer_id": 51537,
"author": "Andrew",
"author_id": 1948,
"author_profile": "https://Stackoverflow.com/users/1948",
"pm_score": 6,
"selected": true,
"text": "<pre><code>MyList[1] = new MyStruct(\"bob\");\n</code></pre>\n\n<p>structs in C# should almost always be designed to be immutab... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989/"
] | I have a list of structs and I want to change one element. For example :
```
MyList.Add(new MyStruct("john");
MyList.Add(new MyStruct("peter");
```
Now I want to change one element:
```
MyList[1].Name = "bob"
```
However, whenever I try and do this I get the following error:
>
> Cannot modify the return value of
> System.Collections.Generic.List.this[int]‘ because it is not
> a variable
>
>
>
If I use a list of classes, the problem doesn't occur.
I guess the answer has to do with structs being a value type.
So, if I have a list of structs should I treat them as *read-only*? If I need to change elements in a list then I should use classes and not structs? | ```
MyList[1] = new MyStruct("bob");
```
structs in C# should almost always be designed to be immutable (that is, have no way to change their internal state once they have been created).
In your case, what you want to do is to replace the entire struct in specified array index, not to try to change just a single property or field. |
51,553 | <p>I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):</p>
<pre><code>SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples;
</code></pre>
<p>Is this normal behaviour when using a SQL database?</p>
<p>The schema (the table holds responses to a survey):</p>
<pre><code>CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);
\copy tuples from '350,000 responses.csv' delimiter as ','
</code></pre>
<p>I wrote some tests in Java and Python for context and they crush SQL (except for pure python):</p>
<pre><code>java 1.5 threads ~ 7 ms
java 1.5 ~ 10 ms
python 2.5 numpy ~ 18 ms
python 2.5 ~ 370 ms
</code></pre>
<p>Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)</p>
<p>Tunings i've tried without success include (blindly following some web advice):</p>
<pre><code>increased the shared memory available to Postgres to 256MB
increased the working memory to 2MB
disabled connection and statement logging
used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL
</code></pre>
<p>So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous. </p>
<p>Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.</p>
<hr>
<p>No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.</p>
<p>The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)</p>
<p>I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.</p>
<p>The Postgres query doesn't change timing on subsequent runs.</p>
<p>I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!)</p>
| [
{
"answer_id": 51668,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think that your results are all that surprising -- if anything it is that Postgres is so fast.</p>\n\n<p>Does t... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5357/"
] | I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):
```
SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples;
```
Is this normal behaviour when using a SQL database?
The schema (the table holds responses to a survey):
```
CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);
\copy tuples from '350,000 responses.csv' delimiter as ','
```
I wrote some tests in Java and Python for context and they crush SQL (except for pure python):
```
java 1.5 threads ~ 7 ms
java 1.5 ~ 10 ms
python 2.5 numpy ~ 18 ms
python 2.5 ~ 370 ms
```
Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)
Tunings i've tried without success include (blindly following some web advice):
```
increased the shared memory available to Postgres to 256MB
increased the working memory to 2MB
disabled connection and statement logging
used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL
```
So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous.
Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.
---
No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.
The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)
I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.
The Postgres query doesn't change timing on subsequent runs.
I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!) | Postgres is doing a lot more than it looks like (maintaining data consistency for a start!)
If the values don't have to be 100% spot on, or if the table is updated rarely, but you are running this calculation often, you might want to look into Materialized Views to speed it up.
(Note, I have not used materialized views in Postgres, they look at little hacky, but might suite your situation).
[Materialized Views](http://jonathangardner.net/tech/w/PostgreSQL/Materialized_Views)
Also consider the overhead of actually connecting to the server and the round trip required to send the request to the server and back.
I'd consider 200ms for something like this to be pretty good, A quick test on my oracle server, the same table structure with about 500k rows and no indexes, takes about 1 - 1.5 seconds, which is almost all just oracle sucking the data off disk.
The real question is, is 200ms fast enough?
-------------- More --------------------
I was interested in solving this using materialized views, since I've never really played with them. This is in oracle.
First I created a MV which refreshes every minute.
```
create materialized view mv_so_x
build immediate
refresh complete
START WITH SYSDATE NEXT SYSDATE + 1/24/60
as select count(*),avg(a),avg(b),avg(c),avg(d) from so_x;
```
While its refreshing, there is no rows returned
```
SQL> select * from mv_so_x;
no rows selected
Elapsed: 00:00:00.00
```
Once it refreshes, its MUCH faster than doing the raw query
```
SQL> select count(*),avg(a),avg(b),avg(c),avg(d) from so_x;
COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)
---------- ---------- ---------- ---------- ----------
1899459 7495.38839 22.2905454 5.00276131 2.13432836
Elapsed: 00:00:05.74
SQL> select * from mv_so_x;
COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)
---------- ---------- ---------- ---------- ----------
1899459 7495.38839 22.2905454 5.00276131 2.13432836
Elapsed: 00:00:00.00
SQL>
```
If we insert into the base table, the result is not immediately viewable view the MV.
```
SQL> insert into so_x values (1,2,3,4,5);
1 row created.
Elapsed: 00:00:00.00
SQL> commit;
Commit complete.
Elapsed: 00:00:00.00
SQL> select * from mv_so_x;
COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)
---------- ---------- ---------- ---------- ----------
1899459 7495.38839 22.2905454 5.00276131 2.13432836
Elapsed: 00:00:00.00
SQL>
```
But wait a minute or so, and the MV will update behind the scenes, and the result is returned fast as you could want.
```
SQL> /
COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)
---------- ---------- ---------- ---------- ----------
1899460 7495.35823 22.2905352 5.00276078 2.17647059
Elapsed: 00:00:00.00
SQL>
```
This isn't ideal. for a start, its not realtime, inserts/updates will not be immediately visible. Also, you've got a query running to update the MV whether you need it or not (this can be tune to whatever time frame, or on demand). But, this does show how much faster an MV can make it seem to the end user, if you can live with values which aren't quite upto the second accurate. |
51,572 | <p>How does one <strong>reliably</strong> determine a file's type? File extension analysis is not acceptable. There must be a rubyesque tool similar to the UNIX file(1) command?</p>
<p>This is regarding MIME or content type, not file system classifications, such as directory, file, or socket.</p>
| [
{
"answer_id": 51616,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": -1,
"selected": false,
"text": "<p>You could give a go with <a href=\"http://mime-types.rubyforge.org/\" rel=\"nofollow noreferrer\">MIME::Types for Ruby... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How does one **reliably** determine a file's type? File extension analysis is not acceptable. There must be a rubyesque tool similar to the UNIX file(1) command?
This is regarding MIME or content type, not file system classifications, such as directory, file, or socket. | There is a ruby binding to `libmagic` that does what you need. It is available as a gem named [ruby-filemagic](https://rubygems.org/gems/ruby-filemagic/versions/0.7.1):
```
gem install ruby-filemagic
```
Require `libmagic-dev`.
The documentation seems a little thin, but this should get you started:
```
$ irb
irb(main):001:0> require 'filemagic'
=> true
irb(main):002:0> fm = FileMagic.new
=> #<FileMagic:0x7fd4afb0>
irb(main):003:0> fm.file('foo.zip')
=> "Zip archive data, at least v2.0 to extract"
irb(main):004:0>
``` |
51,582 | <p>Let's say I have the following class:</p>
<pre><code>public class Test<E> {
public boolean sameClassAs(Object o) {
// TODO help!
}
}
</code></pre>
<p>How would I check that <code>o</code> is the same class as <code>E</code>?</p>
<pre><code>Test<String> test = new Test<String>();
test.sameClassAs("a string"); // returns true;
test.sameClassAs(4); // returns false;
</code></pre>
<p>I can't change the method signature from <code>(Object o)</code> as I'm overridding a superclass and so don't get to choose my method signature.</p>
<p>I would also rather not go down the road of attempting a cast and then catching the resulting exception if it fails.</p>
| [
{
"answer_id": 51603,
"author": "Slartibartfast",
"author_id": 4433,
"author_profile": "https://Stackoverflow.com/users/4433",
"pm_score": 2,
"selected": false,
"text": "<p>I could only make it working like this:</p>\n\n<pre><code>public class Test<E> { \n\n private E e; \n\n ... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] | Let's say I have the following class:
```
public class Test<E> {
public boolean sameClassAs(Object o) {
// TODO help!
}
}
```
How would I check that `o` is the same class as `E`?
```
Test<String> test = new Test<String>();
test.sameClassAs("a string"); // returns true;
test.sameClassAs(4); // returns false;
```
I can't change the method signature from `(Object o)` as I'm overridding a superclass and so don't get to choose my method signature.
I would also rather not go down the road of attempting a cast and then catching the resulting exception if it fails. | An instance of `Test` has no information as to what `E` is at runtime. So, you need to pass a `Class<E>` to the constructor of Test.
```
public class Test<E> {
private final Class<E> clazz;
public Test(Class<E> clazz) {
if (clazz == null) {
throw new NullPointerException();
}
this.clazz = clazz;
}
// To make things easier on clients:
public static <T> Test<T> create(Class<T> clazz) {
return new Test<T>(clazz);
}
public boolean sameClassAs(Object o) {
return o != null && o.getClass() == clazz;
}
}
```
If you want an "instanceof" relationship, use `Class.isAssignableFrom` instead of the `Class` comparison. Note, `E` will need to be a non-generic type, for the same reason `Test` needs the `Class` object.
For examples in the Java API, see `java.util.Collections.checkedSet` and similar. |
51,586 | <p>Is there a way to collect (e.g. in a List) multiple 'generic' objects that don't share a common super class? If so, how can I access their common properties?</p>
<p>For example:</p>
<pre><code>class MyObject<T>
{
public T Value { get; set; }
public string Name { get; set; }
public MyObject(string name, T value)
{
Name = name;
Value = value;
}
}
var fst = new MyObject<int>("fst", 42);
var snd = new MyObject<bool>("snd", true);
List<MyObject<?>> list = new List<MyObject<?>>(){fst, snd};
foreach (MyObject<?> o in list)
Console.WriteLine(o.Name);
</code></pre>
<p>Obviously, this is pseudo code, this doesn't work.</p>
<p>Also I don't need to access the .Value property (since that wouldn't be type-safe).</p>
<p><strong>EDIT:</strong> Now that I've been thinking about this, It would be possible to use sub-classes for this. However, I think that would mean I'd have to write a new subclass for every new type.</p>
<hr>
<p>@<a href="https://stackoverflow.com/questions/51586/accessing-non-generic-members-of-a-generic-object#51621">Grzenio</a>
Yes, that exactly answered my question. Of course, now I need to duplicate the entire shared interface, but that's not a big problem. I should have thought of that...</p>
<p>@<a href="https://stackoverflow.com/questions/51586/accessing-non-generic-members-of-a-generic-object#51611">aku</a>
You are right about the duck typing. I wouldn't expect two completely random types of objects to be accessible.</p>
<p>But I thought generic objects would share some kind of common interface, since they are exactly the same, apart from the type they are parametrized by. Apparently, this is not the case automatically.</p>
| [
{
"answer_id": 51611,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>C# doesn't support duck typing. You have 2 choices: interfaces and inheritance, otherwise you can't access similar properties ... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2597/"
] | Is there a way to collect (e.g. in a List) multiple 'generic' objects that don't share a common super class? If so, how can I access their common properties?
For example:
```
class MyObject<T>
{
public T Value { get; set; }
public string Name { get; set; }
public MyObject(string name, T value)
{
Name = name;
Value = value;
}
}
var fst = new MyObject<int>("fst", 42);
var snd = new MyObject<bool>("snd", true);
List<MyObject<?>> list = new List<MyObject<?>>(){fst, snd};
foreach (MyObject<?> o in list)
Console.WriteLine(o.Name);
```
Obviously, this is pseudo code, this doesn't work.
Also I don't need to access the .Value property (since that wouldn't be type-safe).
**EDIT:** Now that I've been thinking about this, It would be possible to use sub-classes for this. However, I think that would mean I'd have to write a new subclass for every new type.
---
@[Grzenio](https://stackoverflow.com/questions/51586/accessing-non-generic-members-of-a-generic-object#51621)
Yes, that exactly answered my question. Of course, now I need to duplicate the entire shared interface, but that's not a big problem. I should have thought of that...
@[aku](https://stackoverflow.com/questions/51586/accessing-non-generic-members-of-a-generic-object#51611)
You are right about the duck typing. I wouldn't expect two completely random types of objects to be accessible.
But I thought generic objects would share some kind of common interface, since they are exactly the same, apart from the type they are parametrized by. Apparently, this is not the case automatically. | I don't think it is possible in C#, because MyObject is not a baseclass of MyObject. What I usually do is to define an interface (a 'normal' one, not generic) and make MyObject implement that interface, e.g.
```
interface INamedObject
{
string Name {get;}
}
```
and then you can use the interface:
```
List<INamedObject> list = new List<INamedObject>(){fst, snd};
foreach (INamedObject o in list)
Console.WriteLine(o.Name);
```
Did it answer your question? |
51,593 | <p>What is the easiest way to extract the original exception from an exception returned via Apache's implementation of XML-RPC?</p>
| [
{
"answer_id": 52995,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 1,
"selected": false,
"text": "<p>According to the <a href=\"http://www.xmlrpc.com/spec\" rel=\"nofollow noreferrer\">XML-RPC Spec</a> it returns the \"fa... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/279/"
] | What is the easiest way to extract the original exception from an exception returned via Apache's implementation of XML-RPC? | It turns out that getting the cause exception from the Apache exception is the right one.
```
} catch (XmlRpcException rpce) {
Throwable cause = rpce.getCause();
if(cause != null) {
if(cause instanceof ExceptionYouCanHandleException) {
handler(cause);
}
else { throw(cause); }
}
else { throw(rpce); }
}
``` |
51,645 | <p>How can I discover any USB storage devices and/or CD/DVD writers available at a given time (using C# .Net2.0).</p>
<p>I would like to present users with a choice of devices onto which a file can be stored for physically removal - i.e. not the hard drive.</p>
| [
{
"answer_id": 51656,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 1,
"selected": false,
"text": "<p>this is VB.NET code to check for any removable drives or CDRom drives attached to the computer:</p>\n\n<pre><code>Me.lstDrives.It... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5019/"
] | How can I discover any USB storage devices and/or CD/DVD writers available at a given time (using C# .Net2.0).
I would like to present users with a choice of devices onto which a file can be stored for physically removal - i.e. not the hard drive. | ```
using System.IO;
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
if (d.IsReady && d.DriveType == DriveType.Removable)
{
// This is the drive you want...
}
}
```
The DriveInfo class documentation is here:
<http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx> |
51,654 | <p>I have the situation where i use GIS software which stores the information about GIS objects into separate database table for each type/class of GIS object (road, river, building, sea, ...) and keeps the metadata table in which it stores info about the class name and its DB table.</p>
<p>Those GIS objects of different classes share some parameters, i.e. Description and ID. I'd like to represent all of these different GIS classes with one common C# class (let's call it GisObject), which is enough for what i need to do from the non-GIS part of the application which lists GIS objects of the given GIS class.</p>
<p>The problem for me is how to map those objects using NHibernate to explain to the NHibernate when creating a C# GisObject to receive and <strong>use the table name as a parameter</strong> which will be read from the meta table (it can be in two steps, i can manually fetch the table name in first step and then pass it down to the NHibernate when pulling GisObject data).</p>
<p>Has anybody dealt with this kind of situation, and can it be done at all?</p>
| [
{
"answer_id": 51683,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 0,
"selected": false,
"text": "<p>one way you could do it is to declare an interface say IGisObject that has the common properties declared on the interface. T... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4723/"
] | I have the situation where i use GIS software which stores the information about GIS objects into separate database table for each type/class of GIS object (road, river, building, sea, ...) and keeps the metadata table in which it stores info about the class name and its DB table.
Those GIS objects of different classes share some parameters, i.e. Description and ID. I'd like to represent all of these different GIS classes with one common C# class (let's call it GisObject), which is enough for what i need to do from the non-GIS part of the application which lists GIS objects of the given GIS class.
The problem for me is how to map those objects using NHibernate to explain to the NHibernate when creating a C# GisObject to receive and **use the table name as a parameter** which will be read from the meta table (it can be in two steps, i can manually fetch the table name in first step and then pass it down to the NHibernate when pulling GisObject data).
Has anybody dealt with this kind of situation, and can it be done at all? | @Brian Chiasson
Unfortunately, it's not an option to create all classes of GIS data because classes are created dynamically in the application. Every GIS data of the same type should be a class, but my user has the possibility to get new set of data and put it in the database. I can't know in front which classes my user will have in the application. Therefore, the in-front per-class mapping model doesn't work because tomorrow there will be another new database table, and a need to create new class with new mapping.
@all
There might be a possibility to write my own custom query in the XML config file of my GisObject class, then in the data access class fetching that query using the
```
string qs = getSession().getNamedQuery(queryName);
```
and use the string replace to inject database name (by replacing some placeholder string) which i will pass as a parameter.
```
qs = qs.replace(":tablename:", tableName);
```
How do you feel about that solution? I know it might be a security risk in an uncontrolled environment where the table name would be fetched as the user input, but in this case, i have a meta table containing right and valid table names for the GIS data classes which i will read before calling the query for fetching data for the specific class of GIS objects. |
51,658 | <p>I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?</p>
| [
{
"answer_id": 51663,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "<p>The <a href=\"https://docs.python.org/2.7/library/os.html\" rel=\"nofollow noreferrer\">os.statvfs()</a> function is a ... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way? | ```
import ctypes
import os
import platform
import sys
def get_free_space_mb(dirname):
"""Return folder/drive free space (in megabytes)."""
if platform.system() == 'Windows':
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))
return free_bytes.value / 1024 / 1024
else:
st = os.statvfs(dirname)
return st.f_bavail * st.f_frsize / 1024 / 1024
```
Note that you *must* pass a directory name for `GetDiskFreeSpaceEx()` to work
(`statvfs()` works on both files and directories). You can get a directory name
from a file with `os.path.dirname()`.
Also see the documentation for [`os.statvfs()`](https://docs.python.org/3/library/os.html#os.fstatvfs) and [`GetDiskFreeSpaceEx`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx). |
51,684 | <p>I have a <a href="http://www.samurize.com/modules/news/" rel="noreferrer">Samurize</a> config that shows a CPU usage graph similar to Task manager. </p>
<p>How do I also display the name of the process with the current highest CPU usage percentage? </p>
<p>I would like this to be updated, at most, once per second. Samurize can call a command line tool and display it's output on screen, so this could also be an option.</p>
<hr>
<p>Further clarification: </p>
<p>I have investigated writing my own command line c# .NET application to enumerate the array returned from System.Diagnostics.Process.GetProcesses(), but the Process instance class does not seem to include a CPU percentage property. </p>
<p>Can I calculate this in some way?</p>
| [
{
"answer_id": 51705,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 1,
"selected": false,
"text": "<p>You might be able to use <a href=\"http://commandwindows.com/server2003tools.htm\" rel=\"nofollow noreferrer\">Pmon.exe</a>... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5023/"
] | I have a [Samurize](http://www.samurize.com/modules/news/) config that shows a CPU usage graph similar to Task manager.
How do I also display the name of the process with the current highest CPU usage percentage?
I would like this to be updated, at most, once per second. Samurize can call a command line tool and display it's output on screen, so this could also be an option.
---
Further clarification:
I have investigated writing my own command line c# .NET application to enumerate the array returned from System.Diagnostics.Process.GetProcesses(), but the Process instance class does not seem to include a CPU percentage property.
Can I calculate this in some way? | With PowerShell:
```
Get-Process | Sort-Object CPU -desc | Select-Object -first 3 | Format-Table CPU,ProcessName -hidetableheader
```
returns somewhat like:
```
16.8641632 System
12.548072 csrss
11.9892168 powershell
``` |
51,686 | <p>Is it possible to deploy a native Delphi application with ClickOnce without a stub C# exe that would be used to launch the Delphi application?</p>
<p>The same question applies to VB6, C++ and other native Windows applications.</p>
| [
{
"answer_id": 51691,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not 100% sure if this can be accomplished without the stub, but this article may provide some insight:</p>\n\n<p><a href... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5362/"
] | Is it possible to deploy a native Delphi application with ClickOnce without a stub C# exe that would be used to launch the Delphi application?
The same question applies to VB6, C++ and other native Windows applications. | Personally, I build my own mechanism to kick off self update process when my application timestamp is out of sync with the server. Not too difficult, but it's not a simple task.
By the way, for Delphi you can use some thirdparty help:
<http://www.tmssoftware.com/site/wupdate.asp>
UPDATED:
For my implementation:
MyApp.EXE will run in 3 different modes
1. MyApp.EXE without any argument. This will start the application typically.
1.1 The very first thing it does is to validate its own file-time with the server.
1.2 If update is required then it will download the updated file to the file named "MyApp-YYYY-MM-DD-HH-MM-SS.exe"
1.3 Then it invoke "MyApp-YYYY-MM-DD-HH-MM-SS.exe" with command argument
```
MyApp-YYYY-MM-DD-HH-MM-SS.exe --update MyApp.EXE
```
1.4 Terminate this application.
1.5 If there is no update required then the application will start normally from 1.1
2. MyApp.EXE --update "FILENAME".
2.1 Try copying itself to "FILENAME" every 100ms until success.
2.2 Invoke "FILENAME" when it success
2.3 Invoke "FILNAME --delete MyApp-YYYY-MM-DD-HH-MM-SS.exe" to delete itself.
2.4 Terminate
3. MyApp.EXE --delete "FILENAME"
3.1 Try deleting the file "FILENAME" every 500ms until success.
3.2 Terminate
I've already been using this scheme for my application for 7 years and it works well. It could be quite painful to debug when things goes wrong since the steps involve many processes. I suggest you make a lot of trace logging to allow simpler trouble-shooting.
Good Luck |
51,687 | <p>Has anyone implemented Lightbox style background dimming on a modal dialog box in a MFC/non .net app.<br>
I think the procedure would have to be something like:</p>
<p>steps:</p>
<ol>
<li><p>Get dialog parent HWND or CWnd* </p></li>
<li><p>Get the rect of the parent window and draw an overlay with a translucency over that window </p></li>
<li>allow the dialog to do it's modal draw routine, e.g DoModal()</li>
</ol>
<p>Are there any existing libraries/frameworks to do this, or what's the best way to drop a translucent overlay in MFC?<br>
<strong>edit</strong> Here's a mockup of what i'm trying to achieve if you don't know what 'lightbox style' means<br>
<strong>Some App</strong>:<br>
<img src="https://farm4.static.flickr.com/3065/2843243996_8a4536f516_o.png" alt="alt text"> </p>
<p>with a lightbox dialog box<br>
<img src="https://farm4.static.flickr.com/3280/2842409249_4a1c7f5810_o.png" alt="alt text"></p>
| [
{
"answer_id": 51979,
"author": "Brian Lyttle",
"author_id": 636,
"author_profile": "https://Stackoverflow.com/users/636",
"pm_score": 2,
"selected": false,
"text": "<p>I think you just need to create a window and set the transparency. There is an MFC <a href=\"http://www.codeproject.com... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/379/"
] | Has anyone implemented Lightbox style background dimming on a modal dialog box in a MFC/non .net app.
I think the procedure would have to be something like:
steps:
1. Get dialog parent HWND or CWnd\*
2. Get the rect of the parent window and draw an overlay with a translucency over that window
3. allow the dialog to do it's modal draw routine, e.g DoModal()
Are there any existing libraries/frameworks to do this, or what's the best way to drop a translucent overlay in MFC?
**edit** Here's a mockup of what i'm trying to achieve if you don't know what 'lightbox style' means
**Some App**:

with a lightbox dialog box
 | Here's what I did\* based on Brian's links
First create a dialog resource with the properties:
* border **FALSE**
* 3D look **FALSE**
* client edge **FALSE**
* Popup style
* static edge **FALSE**
* Transparent **TRUE**
* Title bar **FALSE**
and you should end up with a dialog window with no frame or anything, just a grey box.
override the Create function to look like this:
```
BOOL LightBoxDlg::Create(UINT nIDTemplate, CWnd* pParentWnd)
{
if(!CDialog::Create(nIDTemplate, pParentWnd))
return false;
RECT rect;
RECT size;
GetParent()->GetWindowRect(&rect);
size.top = 0;
size.left = 0;
size.right = rect.right - rect.left;
size.bottom = rect.bottom - rect.top;
SetWindowPos(m_pParentWnd,rect.left,rect.top,size.right,size.bottom,NULL);
HWND hWnd=m_hWnd;
SetWindowLong (hWnd , GWL_EXSTYLE ,GetWindowLong (hWnd , GWL_EXSTYLE ) | WS_EX_LAYERED ) ;
typedef DWORD (WINAPI *PSLWA)(HWND, DWORD, BYTE, DWORD);
PSLWA pSetLayeredWindowAttributes;
HMODULE hDLL = LoadLibrary (_T("user32"));
pSetLayeredWindowAttributes =
(PSLWA) GetProcAddress(hDLL,"SetLayeredWindowAttributes");
if (pSetLayeredWindowAttributes != NULL)
{
/*
* Second parameter RGB(255,255,255) sets the colorkey
* to white LWA_COLORKEY flag indicates that color key
* is valid LWA_ALPHA indicates that ALphablend parameter
* is valid - here 100 is used
*/
pSetLayeredWindowAttributes (hWnd,
RGB(255,255,255), 100, LWA_COLORKEY|LWA_ALPHA);
}
return true;
}
```
then create a small black bitmap in an image editor (say 48x48) and import it as a bitmap resource (in this example IDB\_BITMAP1)
override the WM\_ERASEBKGND message with:
```
BOOL LightBoxDlg::OnEraseBkgnd(CDC* pDC)
{
BOOL bRet = CDialog::OnEraseBkgnd(pDC);
RECT rect;
RECT size;
m_pParentWnd->GetWindowRect(&rect);
size.top = 0;
size.left = 0;
size.right = rect.right - rect.left;
size.bottom = rect.bottom - rect.top;
CBitmap cbmp;
cbmp.LoadBitmapW(IDB_BITMAP1);
BITMAP bmp;
cbmp.GetBitmap(&bmp);
CDC memDc;
memDc.CreateCompatibleDC(pDC);
memDc.SelectObject(&cbmp);
pDC->StretchBlt(0,0,size.right,size.bottom,&memDc,0,0,bmp.bmWidth,bmp.bmHeight,SRCCOPY);
return bRet;
}
```
Instantiate it in the DoModal of the desired dialog, Create it like a Modal Dialog i.e. on the stack(or heap if desired), call it's Create manually, show it then create your actual modal dialog over the top of it:
```
INT_PTR CAboutDlg::DoModal()
{
LightBoxDlg Dlg(m_pParentWnd);//make sure to pass in the parent of the new dialog
Dlg.Create(LightBoxDlg::IDD);
Dlg.ShowWindow(SW_SHOW);
BOOL ret = CDialog::DoModal();
Dlg.ShowWindow(SW_HIDE);
return ret;
}
```
and this results in something **exactly** like my mock up above
\*there are still places for improvment, like doing it without making a dialog box to begin with and some other general tidyups. |
51,690 | <p>Recently I got IE7 crashed on Vista on jar loading (presumably) with the following error:</p>
<pre><code>Problem signature:
Problem Event Name: BEX
Application Name: iexplore.exe
Application Version: 7.0.6001.18000
Application Timestamp: 47918f11
Fault Module Name: ntdll.dll
Fault Module Version: 6.0.6001.18000
Fault Module Timestamp: 4791a7a6
Exception Offset: 00087ba6
Exception Code: c000000d
Exception Data: 00000000
OS Version: 6.0.6001.2.1.0.768.3
Locale ID: 1037
Additional Information 1: fd00
Additional Information 2: ea6f5fe8924aaa756324d57f87834160
Additional Information 3: fd00
Additional Information 4: ea6f5fe8924aaa756324d57f87834160
</code></pre>
<p>Googling revealed this sort of problems <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1194672&SiteID=1" rel="noreferrer">is</a> <a href="http://support.mozilla.com/tiki-view_forum_thread.php?locale=eu&comments_parentId=101420&forumId=1" rel="noreferrer">common</a> <a href="http://www.eggheadcafe.com/software/aspnet/29930817/bex-problem.aspx" rel="noreferrer">for</a> <a href="http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.vc.mfc&tid=d511c635-3c99-431d-8118-526d3e3fff00&cat=&lang=&cr=&sloc=&p=1" rel="noreferrer">Vista</a> and relates to <a href="http://www.gomanuals.com/java_not_working_on_windows_vista.shtml" rel="noreferrer">Java</a> (although SUN <a href="http://weblogs.java.net/blog/chet/archive/2006/10/java_on_vista_y.html" rel="noreferrer">negates</a>). Also I think it has something to do with DEP. I failed to find official Microsoft Kb.</p>
<p>So, the questions are:</p>
<ul>
<li>What BEX stands for?</li>
<li>What is it about?</li>
<li>How to deal with such kind of errors?</li>
</ul>
| [
{
"answer_id": 166316,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 3,
"selected": true,
"text": "<p>BEX=Buffer overflow exception. See <a href=\"http://technet.microsoft.com/en-us/library/cc738483.aspx\" rel=\"nofollow ... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5383/"
] | Recently I got IE7 crashed on Vista on jar loading (presumably) with the following error:
```
Problem signature:
Problem Event Name: BEX
Application Name: iexplore.exe
Application Version: 7.0.6001.18000
Application Timestamp: 47918f11
Fault Module Name: ntdll.dll
Fault Module Version: 6.0.6001.18000
Fault Module Timestamp: 4791a7a6
Exception Offset: 00087ba6
Exception Code: c000000d
Exception Data: 00000000
OS Version: 6.0.6001.2.1.0.768.3
Locale ID: 1037
Additional Information 1: fd00
Additional Information 2: ea6f5fe8924aaa756324d57f87834160
Additional Information 3: fd00
Additional Information 4: ea6f5fe8924aaa756324d57f87834160
```
Googling revealed this sort of problems [is](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1194672&SiteID=1) [common](http://support.mozilla.com/tiki-view_forum_thread.php?locale=eu&comments_parentId=101420&forumId=1) [for](http://www.eggheadcafe.com/software/aspnet/29930817/bex-problem.aspx) [Vista](http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.vc.mfc&tid=d511c635-3c99-431d-8118-526d3e3fff00&cat=&lang=&cr=&sloc=&p=1) and relates to [Java](http://www.gomanuals.com/java_not_working_on_windows_vista.shtml) (although SUN [negates](http://weblogs.java.net/blog/chet/archive/2006/10/java_on_vista_y.html)). Also I think it has something to do with DEP. I failed to find official Microsoft Kb.
So, the questions are:
* What BEX stands for?
* What is it about?
* How to deal with such kind of errors? | BEX=Buffer overflow exception. See <http://technet.microsoft.com/en-us/library/cc738483.aspx> for details. However, c000000d is STATUS\_INVALID\_PARAMETER; the technet article talks primarily about status c0000005 or c0000409 (access violation/DEP) |
51,700 | <p>I am using .Net 2 and the normal way to store my settings. I store my custom object serialized to xml. I am trying to retrieve the default value of the property (but without reseting other properties). I use:</p>
<pre><code>ValuationInput valuationInput = (ValuationInput) Settings.Default.Properties["ValuationInput"].DefaultValue;
</code></pre>
<p>But it seems to return a string instead of ValuationInput and it throws an exception. </p>
<p>I made a quick hack, which works fine:</p>
<pre><code>string valuationInputStr = (string)
Settings.Default.Properties["ValuationInput"].DefaultValue;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(ValuationInput));
ValuationInput valuationInput = (ValuationInput) xmlSerializer.Deserialize(new StringReader(valuationInputStr));
</code></pre>
<p>But this is really ugly - when I use all the tool to define a strongly typed setting, I don't want to serialize the default value myself, I would like to read it the same way as I read the current value: <code>ValuationInput valuationInput = Settings.Default.ValuationInput;</code></p>
| [
{
"answer_id": 166316,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 3,
"selected": true,
"text": "<p>BEX=Buffer overflow exception. See <a href=\"http://technet.microsoft.com/en-us/library/cc738483.aspx\" rel=\"nofollow ... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5363/"
] | I am using .Net 2 and the normal way to store my settings. I store my custom object serialized to xml. I am trying to retrieve the default value of the property (but without reseting other properties). I use:
```
ValuationInput valuationInput = (ValuationInput) Settings.Default.Properties["ValuationInput"].DefaultValue;
```
But it seems to return a string instead of ValuationInput and it throws an exception.
I made a quick hack, which works fine:
```
string valuationInputStr = (string)
Settings.Default.Properties["ValuationInput"].DefaultValue;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(ValuationInput));
ValuationInput valuationInput = (ValuationInput) xmlSerializer.Deserialize(new StringReader(valuationInputStr));
```
But this is really ugly - when I use all the tool to define a strongly typed setting, I don't want to serialize the default value myself, I would like to read it the same way as I read the current value: `ValuationInput valuationInput = Settings.Default.ValuationInput;` | BEX=Buffer overflow exception. See <http://technet.microsoft.com/en-us/library/cc738483.aspx> for details. However, c000000d is STATUS\_INVALID\_PARAMETER; the technet article talks primarily about status c0000005 or c0000409 (access violation/DEP) |
51,741 | <p>I was given an .xml file that I needed to read into my code as a DataSet (as background, the file was created by creating a <code>DataSet</code> in C# and calling <code>dataSet.WriteXml(file, XmlWriteMode.IgnoreSchema)</code>, but this was done by someone else). </p>
<p>The .xml file was shaped like this:</p>
<pre><code> <?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Foo>
<Bar>abcd</Bar>
<Foo>efg</Foo>
</Foo>
<Foo>
<Bar>hijk</Bar>
<Foo>lmn</Foo>
</Foo>
</NewDataSet>
</code></pre>
<p>Using C# and .NET 2.0, I read the file in using the code below:</p>
<pre><code> DataSet ds = new DataSet();
ds.ReadXml(file);
</code></pre>
<p>Using a breakpoint, after this <code>line ds.Tables[0]</code> looked like this (using dashes in place of underscores that I couldn't get to format properly):</p>
<pre><code>Bar Foo-Id Foo-Id-0
abcd 0 null
null 1 0
hijk 2 null
null 3 2
</code></pre>
<p>I have found a workaround (I know there are many) and have been able to successfully read in the .xml, but what I would like to understand why <code>ds.ReadXml(file)</code> performed in this manner, so I will be able to avoid the issue in the future. Thanks.</p>
| [
{
"answer_id": 51777,
"author": "rohancragg",
"author_id": 5351,
"author_profile": "https://Stackoverflow.com/users/5351",
"pm_score": 0,
"selected": false,
"text": "<p>These are my observations rather than a full answer:</p>\n\n<p>My guess (without trying to re-produce it myself) is tha... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4660/"
] | I was given an .xml file that I needed to read into my code as a DataSet (as background, the file was created by creating a `DataSet` in C# and calling `dataSet.WriteXml(file, XmlWriteMode.IgnoreSchema)`, but this was done by someone else).
The .xml file was shaped like this:
```
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Foo>
<Bar>abcd</Bar>
<Foo>efg</Foo>
</Foo>
<Foo>
<Bar>hijk</Bar>
<Foo>lmn</Foo>
</Foo>
</NewDataSet>
```
Using C# and .NET 2.0, I read the file in using the code below:
```
DataSet ds = new DataSet();
ds.ReadXml(file);
```
Using a breakpoint, after this `line ds.Tables[0]` looked like this (using dashes in place of underscores that I couldn't get to format properly):
```
Bar Foo-Id Foo-Id-0
abcd 0 null
null 1 0
hijk 2 null
null 3 2
```
I have found a workaround (I know there are many) and have been able to successfully read in the .xml, but what I would like to understand why `ds.ReadXml(file)` performed in this manner, so I will be able to avoid the issue in the future. Thanks. | This appears to be correct for your *nested* Foo tags:
```
<NewDataSet>
<Foo> <!-- Foo-Id: 0 -->
<Bar>abcd</Bar>
<Foo>efg</Foo> <!-- Foo-Id: 1, Parent-Id: 0 -->
</Foo>
<Foo> <!-- Foo-Id: 2 -->
<Bar>hijk</Bar>
<Foo>lmn</Foo> <!-- Foo-Id: 3, Parent-Id: 2 -->
</Foo>
</NewDataSet>
```
So this correctly becomes 4 records in your result, with a parent-child key of "Foo-Id-0"
Try:
```
<NewDataSet>
<Rec> <!-- Rec-Id: 0 -->
<Bar>abcd</Bar>
<Foo>efg</Foo>
</Rec>
<Rec> <!-- Rec-Id: 1 -->
<Bar>hijk</Bar>
<Foo>lmn</Foo>
</Rec>
</NewDataSet>
```
Which should result in:
```
Bar Foo Rec-Id
abcd efg 0
hijk lmn 1
``` |
51,751 | <p>I have a ASP.Net website that is failing on AJAX postbacks (both with ASP.Net AJAX and a 3rd part control) in IE. FireFox works fine. If I install the website on another machine without .Net 3.5 SP1, it works as expected.</p>
<p>When it fails, Fiddler shows that I'm getting a 405 "Method Not Allowed". The form seems to be posting to pages other than page I'm viewing.</p>
<p>The form's action is "#" for the page on the broken website (with SP1). The form's action is "Default.aspx" for the same page on a website without SP1.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 51777,
"author": "rohancragg",
"author_id": 5351,
"author_profile": "https://Stackoverflow.com/users/5351",
"pm_score": 0,
"selected": false,
"text": "<p>These are my observations rather than a full answer:</p>\n\n<p>My guess (without trying to re-produce it myself) is tha... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5389/"
] | I have a ASP.Net website that is failing on AJAX postbacks (both with ASP.Net AJAX and a 3rd part control) in IE. FireFox works fine. If I install the website on another machine without .Net 3.5 SP1, it works as expected.
When it fails, Fiddler shows that I'm getting a 405 "Method Not Allowed". The form seems to be posting to pages other than page I'm viewing.
The form's action is "#" for the page on the broken website (with SP1). The form's action is "Default.aspx" for the same page on a website without SP1.
Any ideas? | This appears to be correct for your *nested* Foo tags:
```
<NewDataSet>
<Foo> <!-- Foo-Id: 0 -->
<Bar>abcd</Bar>
<Foo>efg</Foo> <!-- Foo-Id: 1, Parent-Id: 0 -->
</Foo>
<Foo> <!-- Foo-Id: 2 -->
<Bar>hijk</Bar>
<Foo>lmn</Foo> <!-- Foo-Id: 3, Parent-Id: 2 -->
</Foo>
</NewDataSet>
```
So this correctly becomes 4 records in your result, with a parent-child key of "Foo-Id-0"
Try:
```
<NewDataSet>
<Rec> <!-- Rec-Id: 0 -->
<Bar>abcd</Bar>
<Foo>efg</Foo>
</Rec>
<Rec> <!-- Rec-Id: 1 -->
<Bar>hijk</Bar>
<Foo>lmn</Foo>
</Rec>
</NewDataSet>
```
Which should result in:
```
Bar Foo Rec-Id
abcd efg 0
hijk lmn 1
``` |
51,768 | <p>As part of some error handling in our product, we'd like to dump some stack trace information. However, we experience that many users will simply take a screenshot of the error message dialog instead of sending us a copy of the full report available from the program, and thus I'd like to make some minimal stack trace information available in this dialog.</p>
<p>A .NET stack trace on my machine looks like this:</p>
<pre><code>at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
at System.IO.StreamReader..ctor(String path)
at LVKWinFormsSandbox.MainForm.button1_Click(Object sender, EventArgs e) in C:\Dev\VS.NET\Gatsoft\LVKWinFormsSandbox\MainForm.cs:line 36
</code></pre>
<p>I have this question:</p>
<p>The format looks to be this:</p>
<pre><code>at <class/method> [in file:line ##]
</code></pre>
<p>However, the <em>at</em> and <em>in</em> keywords, I assume these will be localized if they run, say, a norwegian .NET runtime instead of the english one I have installed.</p>
<p>Is there any way for me to pick apart this stack trace in a language-neutral manner, so that I can display only the file and line number for those entries that have this?</p>
<p>In other words, I'd like this information from the above text:</p>
<pre><code>C:\Dev\VS.NET\Gatsoft\LVKWinFormsSandbox\MainForm.cs:line 36
</code></pre>
<p>Any advice you can give will be helpful.</p>
| [
{
"answer_id": 51803,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 7,
"selected": true,
"text": "<p>You should be able to get a StackTrace object instead of a string by saying</p>\n\n<pre><code>var trace = new System... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
] | As part of some error handling in our product, we'd like to dump some stack trace information. However, we experience that many users will simply take a screenshot of the error message dialog instead of sending us a copy of the full report available from the program, and thus I'd like to make some minimal stack trace information available in this dialog.
A .NET stack trace on my machine looks like this:
```
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
at System.IO.StreamReader..ctor(String path)
at LVKWinFormsSandbox.MainForm.button1_Click(Object sender, EventArgs e) in C:\Dev\VS.NET\Gatsoft\LVKWinFormsSandbox\MainForm.cs:line 36
```
I have this question:
The format looks to be this:
```
at <class/method> [in file:line ##]
```
However, the *at* and *in* keywords, I assume these will be localized if they run, say, a norwegian .NET runtime instead of the english one I have installed.
Is there any way for me to pick apart this stack trace in a language-neutral manner, so that I can display only the file and line number for those entries that have this?
In other words, I'd like this information from the above text:
```
C:\Dev\VS.NET\Gatsoft\LVKWinFormsSandbox\MainForm.cs:line 36
```
Any advice you can give will be helpful. | You should be able to get a StackTrace object instead of a string by saying
```
var trace = new System.Diagnostics.StackTrace(exception);
```
You can then look at the frames yourself without relying on the framework's formatting.
See also: [StackTrace reference](http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx) |
51,781 | <p>I have a variable of type <code>Dynamic</code> and I know for sure one of its fields, lets call it <code>a</code>, actually is an array. But when I'm writing </p>
<pre><code>var d : Dynamic = getDynamic();
for (t in d.a) {
}
</code></pre>
<p>I get a compilation error on line two:</p>
<blockquote>
<p>You can't iterate on a Dynamic value, please specify Iterator or Iterable</p>
</blockquote>
<p>How can I make this compilable?</p>
| [
{
"answer_id": 51802,
"author": "Danny Wilson",
"author_id": 5364,
"author_profile": "https://Stackoverflow.com/users/5364",
"pm_score": 4,
"selected": true,
"text": "<p>Haxe can't iterate over <code>Dynamic</code> variables (as the compiler says).</p>\n\n<p>You can make it work in sever... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a variable of type `Dynamic` and I know for sure one of its fields, lets call it `a`, actually is an array. But when I'm writing
```
var d : Dynamic = getDynamic();
for (t in d.a) {
}
```
I get a compilation error on line two:
>
> You can't iterate on a Dynamic value, please specify Iterator or Iterable
>
>
>
How can I make this compilable? | Haxe can't iterate over `Dynamic` variables (as the compiler says).
You can make it work in several ways, where this one is probably easiest (depending on your situation):
```
var d : {a:Array<Dynamic>} = getDynamic();
for (t in d.a) { ... }
```
You could also change `Dynamic` to the type of the contents of the array. |
51,783 | <p>Flat files and relational databases give us a mechanism to serialize structured data. XML is superb for serializing un-structured tree-like data.</p>
<p>But many problems are best represented by graphs. A thermal simulation program will, for instance, work with temperature nodes connected to each others through resistive edges.</p>
<p>So what is the best way to serialize a graph structure? I know XML can, to some extent, do it---in the same way that a relational database can serialize a complex web of objects: it usually works but can easily get ugly.</p>
<p>I know about the dot language used by the graphviz program, but I'm not sure this is the best way to do it. This question is probably the sort of thing academia might be working on and I'd love to have references to any papers discussing this.</p>
| [
{
"answer_id": 51794,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 3,
"selected": false,
"text": "<p>XML is very verbose. Whenever I do it, I roll my own. Here's an example of a 3 node directed acyclic graph. It's pret... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1428/"
] | Flat files and relational databases give us a mechanism to serialize structured data. XML is superb for serializing un-structured tree-like data.
But many problems are best represented by graphs. A thermal simulation program will, for instance, work with temperature nodes connected to each others through resistive edges.
So what is the best way to serialize a graph structure? I know XML can, to some extent, do it---in the same way that a relational database can serialize a complex web of objects: it usually works but can easily get ugly.
I know about the dot language used by the graphviz program, but I'm not sure this is the best way to do it. This question is probably the sort of thing academia might be working on and I'd love to have references to any papers discussing this. | How do you represent your graph in memory?
Basically you have two (good) options:
* [an adjacency list representation](http://en.wikipedia.org/wiki/Adjacency_list)
* [an adjacency matrix representation](http://en.wikipedia.org/wiki/Adjacency_matrix)
in which the adjacency list representation is best used for a sparse graph, and a matrix representation for the dense graphs.
If you used suchs representations then you could serialize those representations instead.
If it has to be *human readable* you could still opt for creating your own serialization algorithm. For example you could write down the matrix representation like you would do with any "normal" matrix: just print out the columns and rows, and all the data in it like so:
```
1 2 3
1 #t #f #f
2 #f #f #t
3 #f #t #f
```
(this is a non-optimized, non weighted representation, but can be used for directed graphs) |
51,786 | <p>How can I generate UML diagrams (especially sequence diagrams) from existing Java code?</p>
| [
{
"answer_id": 51864,
"author": "prakash",
"author_id": 123,
"author_profile": "https://Stackoverflow.com/users/123",
"pm_score": 5,
"selected": false,
"text": "<p>What is your codebase? Java or C++?</p>\n\n<p><a href=\"http://marketplace.eclipse.org/content/euml2-free-edition\" rel=\"no... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772/"
] | How can I generate UML diagrams (especially sequence diagrams) from existing Java code? | [ObjectAid UML Explorer](http://www.objectaid.com/home)
=======================================================
Is what I used. It is easily **[installed](https://www.objectaid.com/install-objectaid)** from the repository:
```
Name: ObjectAid UML Explorer
Location: http://www.objectaid.com/update/current
```
And produces quite nice UML diagrams:

Description from the website:
-----------------------------
>
> The ObjectAid UML Explorer is different from other UML tools. It uses
> the UML notation to show a graphical representation of existing code
> that is as accurate and up-to-date as your text editor, while being
> very easy to use. Several unique features make this possible:
>
>
> * Your source code and libraries are the model that is displayed, they are not reverse engineered into a different format.
> * If you update your code in Eclipse, your diagram is updated as well; there is no need to reverse engineer source code.
> * Refactoring updates your diagram as well as your source code. When you rename a field or move a class, your diagram simply reflects the
> changes without going out of sync.
> * All diagrams in your Eclipse workspace are updated with refactoring changes as appropriate. If necessary, they are checked out of your
> version control system.
> * Diagrams are fully integrated into the Eclipse IDE. You can drag Java classes from any other view onto the diagram, and diagram-related
> information is shown in other views wherever applicable.
>
>
> |
51,827 | <p>I want to ask how other programmers are producing Dynamic SQL strings for execution as the CommandText of a SQLCommand object.</p>
<p>I am producing parameterized queries containing user-generated WHERE clauses and SELECT fields. Sometimes the queries are complex and I need a lot of control over how the different parts are built. </p>
<p>Currently, I am using many loops and switch statements to produce the necessary SQL code fragments and to create the SQL parameters objects needed. This method is difficult to follow and it makes maintenance a real chore. </p>
<p>Is there a cleaner, more stable way of doing this?</p>
<p>Any Suggestions?</p>
<p>EDIT:
To add detail to my previous post:</p>
<ol>
<li>I cannot really template my query due to the requirements. It just changes too much.</li>
<li>I have to allow for aggregate functions, like Count(). This has consequences for the Group By/Having clause. It also causes nested SELECT statements. This, in turn, effects the column name used by </li>
<li>Some Contact data is stored in an XML column. Users can query this data AS WELL AS and the other relational columns together. Consequences are that xmlcolumns cannot appear in Group By clauses[sql syntax].</li>
<li>I am using an efficient paging technique that uses Row_Number() SQL Function. Consequences are that I have to use a Temp table and then get the @@rowcount, before selecting my subset, to avoid a second query.</li>
</ol>
<p>I will show some code (the horror!) so that you guys have an idea of what I'm dealing with.</p>
<pre><code>sqlCmd.CommandText = "DECLARE @t Table(ContactId int, ROWRANK int" + declare
+ ")INSERT INTO @t(ContactId, ROWRANK" + insertFields + ")"//Insert as few cols a possible
+ "Select ContactID, ROW_NUMBER() OVER (ORDER BY " + sortExpression + " "
+ sortDirection + ") as ROWRANK" // generates a rowrank for each row
+ outerFields
+ " FROM ( SELECT c.id AS ContactID"
+ coreFields
+ from // sometimes different tables are required
+ where + ") T " // user input goes here.
+ groupBy+ " "
+ havingClause //can be empty
+ ";"
+ "select @@rowcount as rCount;" // return 2 recordsets, avoids second query
+ " SELECT " + fields + ",field1,field2" // join onto the other cols n the table
+" FROM @t t INNER JOIN contacts c on t.ContactID = c.id"
+" WHERE ROWRANK BETWEEN " + ((pageIndex * pageSize) + 1) + " AND "
+ ( (pageIndex + 1) * pageSize); // here I select the pages I want
</code></pre>
<p>In this example, I am querying XML data. For purely relational data, the query is much more simple. Each of the section variables are StringBuilders. Where clauses are built like so:</p>
<pre><code>// Add Parameter to SQL Command
AddParamToSQLCmd(sqlCmd, "@p" + z.ToString(), SqlDbType.VarChar, 50, ParameterDirection.Input, qc.FieldValue);
// Create SQL code Fragment
where.AppendFormat(" {0} {1} {2} @p{3}", qc.BooleanOperator, qc.FieldName, qc.ComparisonOperator, z);
</code></pre>
| [
{
"answer_id": 51839,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 0,
"selected": false,
"text": "<p>Out of curiousity, have you considered using an ORM for managing your data access. A lot of the functionality ... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5197/"
] | I want to ask how other programmers are producing Dynamic SQL strings for execution as the CommandText of a SQLCommand object.
I am producing parameterized queries containing user-generated WHERE clauses and SELECT fields. Sometimes the queries are complex and I need a lot of control over how the different parts are built.
Currently, I am using many loops and switch statements to produce the necessary SQL code fragments and to create the SQL parameters objects needed. This method is difficult to follow and it makes maintenance a real chore.
Is there a cleaner, more stable way of doing this?
Any Suggestions?
EDIT:
To add detail to my previous post:
1. I cannot really template my query due to the requirements. It just changes too much.
2. I have to allow for aggregate functions, like Count(). This has consequences for the Group By/Having clause. It also causes nested SELECT statements. This, in turn, effects the column name used by
3. Some Contact data is stored in an XML column. Users can query this data AS WELL AS and the other relational columns together. Consequences are that xmlcolumns cannot appear in Group By clauses[sql syntax].
4. I am using an efficient paging technique that uses Row\_Number() SQL Function. Consequences are that I have to use a Temp table and then get the @@rowcount, before selecting my subset, to avoid a second query.
I will show some code (the horror!) so that you guys have an idea of what I'm dealing with.
```
sqlCmd.CommandText = "DECLARE @t Table(ContactId int, ROWRANK int" + declare
+ ")INSERT INTO @t(ContactId, ROWRANK" + insertFields + ")"//Insert as few cols a possible
+ "Select ContactID, ROW_NUMBER() OVER (ORDER BY " + sortExpression + " "
+ sortDirection + ") as ROWRANK" // generates a rowrank for each row
+ outerFields
+ " FROM ( SELECT c.id AS ContactID"
+ coreFields
+ from // sometimes different tables are required
+ where + ") T " // user input goes here.
+ groupBy+ " "
+ havingClause //can be empty
+ ";"
+ "select @@rowcount as rCount;" // return 2 recordsets, avoids second query
+ " SELECT " + fields + ",field1,field2" // join onto the other cols n the table
+" FROM @t t INNER JOIN contacts c on t.ContactID = c.id"
+" WHERE ROWRANK BETWEEN " + ((pageIndex * pageSize) + 1) + " AND "
+ ( (pageIndex + 1) * pageSize); // here I select the pages I want
```
In this example, I am querying XML data. For purely relational data, the query is much more simple. Each of the section variables are StringBuilders. Where clauses are built like so:
```
// Add Parameter to SQL Command
AddParamToSQLCmd(sqlCmd, "@p" + z.ToString(), SqlDbType.VarChar, 50, ParameterDirection.Input, qc.FieldValue);
// Create SQL code Fragment
where.AppendFormat(" {0} {1} {2} @p{3}", qc.BooleanOperator, qc.FieldName, qc.ComparisonOperator, z);
``` | I had the need to do this on one of my recent projects. Here is the scheme that I am using for generating the SQL:
* Each component of the query is represented by an Object (which in my case is a Linq-to-Sql entity that maps to a table in the DB). So I have the following classes: Query, SelectColumn, Join, WhereCondition, Sort, GroupBy. Each of these classes contains all details relating to that component of the query.
* The last five classes are all related to a Query object. So the Query object itself has collections of each class.
* Each class has a method that can generate the SQL for the part of the query that it represents. So creating the overall query ends up calling Query.GenerateQuery() which in turn enumerates through all of the sub-collections and calls their respective GenerateQuery() methods
It is still a bit complicated, but in the end you know where the SQL generation for each individual part of the query originates (and I don't think that there are any big switch statements). And don't forget to use StringBuilder. |
51,837 | <p>I have up to 4 files based on this structure (note the prefixes are dates)</p>
<ul>
<li>0830filename.txt</li>
<li>0907filename.txt</li>
<li>0914filename.txt</li>
<li>0921filename.txt</li>
</ul>
<p>I want to open the the most recent one (0921filename.txt). how can i do this in a batch file?</p>
<p>Thanks.</p>
| [
{
"answer_id": 51861,
"author": "Graviton",
"author_id": 3834,
"author_profile": "https://Stackoverflow.com/users/3834",
"pm_score": -1,
"selected": false,
"text": "<p>Use regular expression to parse the relevant integer out and compare them.</p>\n"
},
{
"answer_id": 51868,
"... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] | I have up to 4 files based on this structure (note the prefixes are dates)
* 0830filename.txt
* 0907filename.txt
* 0914filename.txt
* 0921filename.txt
I want to open the the most recent one (0921filename.txt). how can i do this in a batch file?
Thanks. | This method uses the actual file modification date, to figure out which one is the latest file:
```
@echo off
for /F %%i in ('dir /B /O:-D *.txt') do (
call :open "%%i"
exit /B 0
)
:open
start "dummy" "%~1"
exit /B 0
```
This method, however, chooses the last file in alphabetic order (or the first one, in reverse-alphabetic order), so if the filenames are consistent - it will work:
```
@echo off
for /F %%i in ('dir /B *.txt^|sort /R') do (
call :open "%%i"
exit /B 0
)
:open
start "dummy" "%~1"
exit /B 0
```
You actually have to choose which method is better for you. |
51,927 | <p>How do I figure out if an array contains an element?
I thought there might be something like <code>[1, 2, 3].includes(1)</code> which would evaluate as <code>true</code>.</p>
| [
{
"answer_id": 51951,
"author": "banderson623",
"author_id": 5419,
"author_profile": "https://Stackoverflow.com/users/5419",
"pm_score": 6,
"selected": false,
"text": "<p>For lists, use <code>contains</code>:</p>\n\n<pre><code>[1,2,3].contains(1) == true\n</code></pre>\n"
},
{
"a... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5419/"
] | How do I figure out if an array contains an element?
I thought there might be something like `[1, 2, 3].includes(1)` which would evaluate as `true`. | .contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue()
```
[a:1,b:2,c:3].containsValue(3)
[a:1,b:2,c:3].containsKey('a')
``` |
51,931 | <p>I'm having a problem running a T4 template using TextTransform.exe on my build server. On my dev machine the template works perfectly. The error message is as follows.</p>
<blockquote>
<p>error : Running transformation: System.TypeLoadException: Could not instantiate type System.Xml.Linq.XDocument</p>
</blockquote>
<p>The build server has the windows 2008 SDK on it, my machine has VS 2008. I thought mayve it couldn't find System.Data.Xml so I ensure the dll was present in the same directory, but no luck. Any ideas?</p>
| [
{
"answer_id": 51951,
"author": "banderson623",
"author_id": 5419,
"author_profile": "https://Stackoverflow.com/users/5419",
"pm_score": 6,
"selected": false,
"text": "<p>For lists, use <code>contains</code>:</p>\n\n<pre><code>[1,2,3].contains(1) == true\n</code></pre>\n"
},
{
"a... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2086/"
] | I'm having a problem running a T4 template using TextTransform.exe on my build server. On my dev machine the template works perfectly. The error message is as follows.
>
> error : Running transformation: System.TypeLoadException: Could not instantiate type System.Xml.Linq.XDocument
>
>
>
The build server has the windows 2008 SDK on it, my machine has VS 2008. I thought mayve it couldn't find System.Data.Xml so I ensure the dll was present in the same directory, but no luck. Any ideas? | .contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue()
```
[a:1,b:2,c:3].containsValue(3)
[a:1,b:2,c:3].containsKey('a')
``` |
51,941 | <p>I have created a database report generator in Excel. I am trying to create a dialog box that displays status information as the program runs.</p>
<p>When I generate the report, although the dialog box appears, I cannot refresh/update the information it displays. Most of the time, the dialog box only partially appears. I have tried using the .repaint method, but I still get the same results. I only see the complete dialog box, after the report is generated.</p>
| [
{
"answer_id": 51946,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 0,
"selected": false,
"text": "<p>The dialog box is also running on the same UI thread. So, it is too busy to repaint itself. Not sure if VBA has good ... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2665/"
] | I have created a database report generator in Excel. I am trying to create a dialog box that displays status information as the program runs.
When I generate the report, although the dialog box appears, I cannot refresh/update the information it displays. Most of the time, the dialog box only partially appears. I have tried using the .repaint method, but I still get the same results. I only see the complete dialog box, after the report is generated. | The code below works well when performing actions within Excel (XP or later).
For actions that take place outside Excel, for example connecting to a database and retrieving data the best this offers is the opportunity to show dialogs before and after the action (e.g. *"Getting data"*, *"Got data"*)
Create a form called **"frmStatus"**, put a label on the form called **"Label1"**.
Set the form property **'ShowModal' = false**, this allows the code to run while the form is displayed.
```
Sub ShowForm_DoSomething()
Load frmStatus
frmStatus.Label1.Caption = "Starting"
frmStatus.Show
frmStatus.Repaint
'Load the form and set text
frmStatus.Label1.Caption = "Doing something"
frmStatus.Repaint
'code here to perform an action
frmStatus.Label1.Caption = "Doing something else"
frmStatus.Repaint
'code here to perform an action
frmStatus.Label1.Caption = "Finished"
frmStatus.Repaint
Application.Wait (Now + TimeValue("0:00:01"))
frmStatus.Hide
Unload frmStatus
'hide and unload the form
End Sub
``` |
51,950 | <p>I would like my Core assembly to not expose a certain class and I would still like to be able to test it. How can I do that ?</p>
| [
{
"answer_id": 51958,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 8,
"selected": true,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(VS.80).aspx\" rel... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4694/"
] | I would like my Core assembly to not expose a certain class and I would still like to be able to test it. How can I do that ? | [InternalsVisibleTo](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(VS.80).aspx) attribute to the rescue!
Just add:
```
[assembly:InternalsVisibleToAttribute("UnitTestAssemblyName")]
```
to your Core classes AssemblyInfo.cs file
See [Friend Assemblies (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/assemblies-gac/friend-assemblies) for best practices. |
51,964 | <p>In my base page I need to remove an item from the query string and redirect. I can't use<br/></p>
<pre><code>Request.QueryString.Remove("foo")
</code></pre>
<p>because the collection is read-only. Is there any way to get the query string (except for that one item) without iterating through the collection and re-building it?</p>
| [
{
"answer_id": 51981,
"author": "hollystyles",
"author_id": 2083160,
"author_profile": "https://Stackoverflow.com/users/2083160",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Response.Redirect(String.Format(\"nextpage.aspx?{0}\", Request.QueryString.ToString().Replace(\"foo\", \... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757/"
] | In my base page I need to remove an item from the query string and redirect. I can't use
```
Request.QueryString.Remove("foo")
```
because the collection is read-only. Is there any way to get the query string (except for that one item) without iterating through the collection and re-building it? | You'd have to reconstruct the url and then redirect. Something like this:
```
string url = Request.RawUrl;
NameValueCollection params = Request.QueryString;
for (int i=0; i<params.Count; i++)
{
if (params[i].GetKey(i).ToLower() == "foo")
{
url += string.Concat((i==0 ? "?" : "&"), params[i].GetKey(i), "=", params.Get(i));
}
}
Response.Redirect(url);
```
Anyway, I didn't test that or anything, but it should work (or at least get you in thye right direction) |
51,969 | <p>In Microsoft SQL Server, is there a way to detect whether a database has had its isolation level set via the T-SQL command <code>ALTER DATABASE <database> SET READ_COMMITTED_SNAPSHOT ON;</code>?</p>
<p>I cannot find a simple way to detect this in either T-SQL or via the Management Studio's GUI.</p>
| [
{
"answer_id": 51977,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 9,
"selected": true,
"text": "<pre><code>SELECT is_read_committed_snapshot_on FROM sys.databases \nWHERE name= 'YourDatabase'\n</code></pre>\n<p>Return va... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5217/"
] | In Microsoft SQL Server, is there a way to detect whether a database has had its isolation level set via the T-SQL command `ALTER DATABASE <database> SET READ_COMMITTED_SNAPSHOT ON;`?
I cannot find a simple way to detect this in either T-SQL or via the Management Studio's GUI. | ```
SELECT is_read_committed_snapshot_on FROM sys.databases
WHERE name= 'YourDatabase'
```
Return value:
* **1**: `READ_COMMITTED_SNAPSHOT` option is **ON**. Read operations under the `READ COMMITTED` isolation level are based on snapshot scans and do not acquire locks.
* **0** (default): `READ_COMMITTED_SNAPSHOT` option is **OFF**. Read operations under the `READ COMMITTED` isolation level use [Shared (S) locks](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms175519(v=sql.105)). |
52,002 | <p><strong>Definition:</strong></p>
<p><em>A palindrome is a word, phrase, number or other sequence of units that has the property of reading the same in either direction</em></p>
<p>How to check if the given string is a palindrome?</p>
<p>This was one of the FAIQ [Frequently Asked Interview Question] a while ago but that mostly using C.</p>
<p>Looking for solutions in any and all languages possible.</p>
| [
{
"answer_id": 52013,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 2,
"selected": false,
"text": "<pre><code>boolean isPalindrome(String str1) {\n //first strip out punctuation and spaces\n String stripped = str1.replaceA... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123/"
] | **Definition:**
*A palindrome is a word, phrase, number or other sequence of units that has the property of reading the same in either direction*
How to check if the given string is a palindrome?
This was one of the FAIQ [Frequently Asked Interview Question] a while ago but that mostly using C.
Looking for solutions in any and all languages possible. | **PHP sample**:
```
$string = "A man, a plan, a canal, Panama";
function is_palindrome($string)
{
$a = strtolower(preg_replace("/[^A-Za-z0-9]/","",$string));
return $a==strrev($a);
}
```
Removes any non-alphanumeric characters (spaces, commas, exclamation points, etc.) to allow for full sentences as above, as well as simple words. |
52,008 | <p>I need to design a small project for generating excel reports in .NET, which will be sent to users to use.</p>
<p>The excel reports will contain PivotTables.</p>
<p>I don't have much experience with them, but I can think of three implementation alternatives:</p>
<ol>
<li>Set a query for it, populate it, send it disconnected. This way the user will be able to group values and play a little, but he will not be able to refresh the data.</li>
<li>Generate a small access database and send it along with the excel file, connect to it.</li>
<li>Copy the data to the excel (perhaps in some other sheet) and connect to the data there. This will make the excel file very large I think.</li>
</ol>
<p>What would be the best alternative in regards to performance vs usability? Is there another alternative I don't know about?</p>
| [
{
"answer_id": 52013,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 2,
"selected": false,
"text": "<pre><code>boolean isPalindrome(String str1) {\n //first strip out punctuation and spaces\n String stripped = str1.replaceA... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | I need to design a small project for generating excel reports in .NET, which will be sent to users to use.
The excel reports will contain PivotTables.
I don't have much experience with them, but I can think of three implementation alternatives:
1. Set a query for it, populate it, send it disconnected. This way the user will be able to group values and play a little, but he will not be able to refresh the data.
2. Generate a small access database and send it along with the excel file, connect to it.
3. Copy the data to the excel (perhaps in some other sheet) and connect to the data there. This will make the excel file very large I think.
What would be the best alternative in regards to performance vs usability? Is there another alternative I don't know about? | **PHP sample**:
```
$string = "A man, a plan, a canal, Panama";
function is_palindrome($string)
{
$a = strtolower(preg_replace("/[^A-Za-z0-9]/","",$string));
return $a==strrev($a);
}
```
Removes any non-alphanumeric characters (spaces, commas, exclamation points, etc.) to allow for full sentences as above, as well as simple words. |
52,080 | <p>How can I build a loop in JavaScript?</p>
| [
{
"answer_id": 52083,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": -1,
"selected": false,
"text": "<p>A loop in JavaScript looks like this:</p>\n\n<pre><code>for (var = startvalue; var <= endvalue; var = var + increment)... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] | How can I build a loop in JavaScript? | **For loops**
```
for (i = startValue; i <= endValue; i++) {
// Before the loop: i is set to startValue
// After each iteration of the loop: i++ is executed
// The loop continues as long as i <= endValue is true
}
```
**For...in loops**
```
for (i in things) {
// If things is an array, i will usually contain the array keys *not advised*
// If things is an object, i will contain the member names
// Either way, access values using: things[i]
}
```
It is bad practice to use `for...in` loops to itterate over arrays. It goes against the [ECMA 262](http://www.ecma-international.org/publications/standards/Ecma-262.htm) standard and can cause problems when non-standard attributes or methods are added to the Array object, e.g. by [Prototype](http://www.prototypejs.org/api/array).
*(Thanks to [Chase Seibert](https://stackoverflow.com/users/7679/chase-seibert) for pointing this out in the comments)*
**While loops**
```
while (myCondition) {
// The loop will continue until myCondition is false
}
``` |
52,084 | <p>There is a field in my company's "Contacts" table. In that table, there is an XML type column. The column holds misc data about a particular contact. EG. </p>
<pre><code><contact>
<refno>123456</refno>
<special>a piece of custom data</special>
</contact>
</code></pre>
<p>The tags below <code>contact</code> can be different for each contact, and I must query these fragments
alongside the relational data columns in the same table.</p>
<p>I have used constructions like:</p>
<pre><code>SELECT c.id AS ContactID,c.ContactName as ForeName,
c.xmlvaluesn.value('(contact/Ref)[1]', 'VARCHAR(40)') as ref,
INNER JOIN ParticipantContactMap pcm ON c.id=pcm.contactid
AND pcm.participantid=2140
WHERE xmlvaluesn.exist('/contact[Ref = "118985"]') = 1
</code></pre>
<p>This method works ok but, it takes a while for the Server to respond.
I have also investigated using the nodes() function to parse the XML nodes and exist() to test if a nodes holds the value I'm searching for.</p>
<p>Does anyone know a better way to query XML columns??</p>
| [
{
"answer_id": 52097,
"author": "Paulj",
"author_id": 5433,
"author_profile": "https://Stackoverflow.com/users/5433",
"pm_score": 2,
"selected": true,
"text": "<p>I've found the msdn xml best practices helpful for working with xml blob columns, might provide some inspiration...\n<a href=... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5197/"
] | There is a field in my company's "Contacts" table. In that table, there is an XML type column. The column holds misc data about a particular contact. EG.
```
<contact>
<refno>123456</refno>
<special>a piece of custom data</special>
</contact>
```
The tags below `contact` can be different for each contact, and I must query these fragments
alongside the relational data columns in the same table.
I have used constructions like:
```
SELECT c.id AS ContactID,c.ContactName as ForeName,
c.xmlvaluesn.value('(contact/Ref)[1]', 'VARCHAR(40)') as ref,
INNER JOIN ParticipantContactMap pcm ON c.id=pcm.contactid
AND pcm.participantid=2140
WHERE xmlvaluesn.exist('/contact[Ref = "118985"]') = 1
```
This method works ok but, it takes a while for the Server to respond.
I have also investigated using the nodes() function to parse the XML nodes and exist() to test if a nodes holds the value I'm searching for.
Does anyone know a better way to query XML columns?? | I've found the msdn xml best practices helpful for working with xml blob columns, might provide some inspiration...
<http://msdn.microsoft.com/en-us/library/ms345115.aspx#sql25xmlbp_topic4> |
52,160 | <p>How can you obtain the Type (the name as a string is sufficient) of an Object in VB6 at runtime?</p>
<p>i.e. something like:</p>
<pre><code>If Typeof(foobar) = "CommandButton" Then ...
</code></pre>
<p><strong>/EDIT:</strong> to clarify, I need to check on Dynamically Typed objects. An example:</p>
<pre><code>Dim y As Object
Set y = CreateObject("SomeType")
Debug.Print( <The type name of> y)
</code></pre>
<p>Where the output would be "CommandButton"</p>
| [
{
"answer_id": 52181,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 0,
"selected": false,
"text": "<p>This should prove difficult, since in VB6 all objects are COM (<code>IDispatch</code>) things. Thus they are only an ... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111/"
] | How can you obtain the Type (the name as a string is sufficient) of an Object in VB6 at runtime?
i.e. something like:
```
If Typeof(foobar) = "CommandButton" Then ...
```
**/EDIT:** to clarify, I need to check on Dynamically Typed objects. An example:
```
Dim y As Object
Set y = CreateObject("SomeType")
Debug.Print( <The type name of> y)
```
Where the output would be "CommandButton" | I think what you are looking for is TypeName rather than TypeOf.
```
If TypeName(foobar) = "CommandButton" Then
DoSomething
End If
```
Edit: What do you mean Dynamic Objects? Do you mean objects created with
CreateObject(""), cause that should still work.
Edit:
```
Private Sub Command1_Click()
Dim oObject As Object
Set oObject = CreateObject("Scripting.FileSystemObject")
Debug.Print "Object Type: " & TypeName(oObject)
End Sub
```
Outputs
`Object Type: FileSystemObject` |
52,213 | <p>When a user hits Refresh on their browser, it reloads the page but keeps the contents of form fields. While I can see this being a useful default, it can be annoying on some dynamic pages, leading to a broken user experience.</p>
<p>Is there a way, in HTTP headers or equivalents, to change this behaviour?</p>
| [
{
"answer_id": 52221,
"author": "Edward Wilde",
"author_id": 5182,
"author_profile": "https://Stackoverflow.com/users/5182",
"pm_score": 2,
"selected": false,
"text": "<p>You could call the reset() method of the forms object from the body load event of your html document to clear the for... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1000/"
] | When a user hits Refresh on their browser, it reloads the page but keeps the contents of form fields. While I can see this being a useful default, it can be annoying on some dynamic pages, leading to a broken user experience.
Is there a way, in HTTP headers or equivalents, to change this behaviour? | ```
<input autocomplete="off">
``` |
52,234 | <p>Creating a patch is very easy in SubVersion, With Tortoise, you right-click and select Create Patch. But for the life of me, I can't find this functionality in TFS. Is this possible?</p>
<p>If not, what's the standard way to submit patches in open source TFS hosted projects (a la CodePlex)?</p>
| [
{
"answer_id": 52242,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 7,
"selected": true,
"text": "<pre><code>tf diff /shelveset:shelveset /format:unified\n</code></pre>\n\n<p><strong>Edit:</strong> This writes to stan... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
] | Creating a patch is very easy in SubVersion, With Tortoise, you right-click and select Create Patch. But for the life of me, I can't find this functionality in TFS. Is this possible?
If not, what's the standard way to submit patches in open source TFS hosted projects (a la CodePlex)? | ```
tf diff /shelveset:shelveset /format:unified
```
**Edit:** This writes to standard output. You can pipe the output to a file.
For more options, see [Difference Command](http://msdn.microsoft.com/en-us/library/6fd7dc73%28v=vs.100%29.aspx). |
52,238 | <p>How can I use the Prototype library and create unobtrusive javascript to inject the onmouseover and onmouseout events to each row, rather than putting the javascript in each table row tag?</p>
<p>An answer utilizing the Prototype library (instead of mootools, jQuery, etc) would be most helpful.</p>
| [
{
"answer_id": 52250,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 3,
"selected": false,
"text": "<p>You can use Prototype's <code>addClassName</code> and <code>removeClassName</code> methods.</p>\n\n<p>Create a CSS class \"hilig... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3920/"
] | How can I use the Prototype library and create unobtrusive javascript to inject the onmouseover and onmouseout events to each row, rather than putting the javascript in each table row tag?
An answer utilizing the Prototype library (instead of mootools, jQuery, etc) would be most helpful. | ```
<table id="mytable">
<tbody>
<tr><td>Foo</td><td>Bar</td></tr>
<tr><td>Bork</td><td>Bork</td></tr>
</tbody>
</table>
<script type="text/javascript">
$$('#mytable tr').each(function(item) {
item.observe('mouseover', function() {
item.setStyle({ backgroundColor: '#ddd' });
});
item.observe('mouseout', function() {
item.setStyle({backgroundColor: '#fff' });
});
});
</script>
``` |
52,239 | <p>We are working with an oracle database in which the person that set it up is "long gone" and thus do not know the sysdba password, but need it. We have root access to the box (its on linux). Is there any way to recover or change the sys passwords?</p>
| [
{
"answer_id": 52244,
"author": "Paul Hargreaves",
"author_id": 5330,
"author_profile": "https://Stackoverflow.com/users/5330",
"pm_score": 6,
"selected": true,
"text": "<p>Have you tried logging into Linux as your installed Oracle user then</p>\n\n<pre><code>sqlplus \"/ as sysdba\"\n</c... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/673/"
] | We are working with an oracle database in which the person that set it up is "long gone" and thus do not know the sysdba password, but need it. We have root access to the box (its on linux). Is there any way to recover or change the sys passwords? | Have you tried logging into Linux as your installed Oracle user then
```
sqlplus "/ as sysdba"
```
When you log in you'll be able to change your password.
```
alter user sys identified by <new password>;
```
Good luck :) |
52,286 | <p>Wrote the following in PowersHell as a quick iTunes demonstration:</p>
<pre><code>$iTunes = New-Object -ComObject iTunes.Application
$LibrarySource = $iTunes.LibrarySource
foreach ($PList in $LibrarySource.Playlists)
{
write-host $PList.name
}
</code></pre>
<p>This works well and pulls back a list of playlist names.
However on trying to close iTunes a warning appears</p>
<blockquote>
<p>One or more applications are using the iTunes scripting interface. Are you sure you want to quit?</p>
</blockquote>
<p>Obviously I can just ignore the message and press [Quit] or just wait the 20 seconds or so, but is there a clean way to tell iTunes that I've finished working with it?</p>
<pre><code>Itunes 7.7.1, Windows XP
</code></pre>
| [
{
"answer_id": 52309,
"author": "bruceatk",
"author_id": 791,
"author_profile": "https://Stackoverflow.com/users/791",
"pm_score": 3,
"selected": true,
"text": "<p>Here is one thing that I did on my a Powershell script that adds podcasts to iTunes. I use Juice on a server to download all... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5330/"
] | Wrote the following in PowersHell as a quick iTunes demonstration:
```
$iTunes = New-Object -ComObject iTunes.Application
$LibrarySource = $iTunes.LibrarySource
foreach ($PList in $LibrarySource.Playlists)
{
write-host $PList.name
}
```
This works well and pulls back a list of playlist names.
However on trying to close iTunes a warning appears
>
> One or more applications are using the iTunes scripting interface. Are you sure you want to quit?
>
>
>
Obviously I can just ignore the message and press [Quit] or just wait the 20 seconds or so, but is there a clean way to tell iTunes that I've finished working with it?
```
Itunes 7.7.1, Windows XP
``` | Here is one thing that I did on my a Powershell script that adds podcasts to iTunes. I use Juice on a server to download all the podcasts that I listen to. The script uses .Net methods to release the COM objects. When I wrote my iTunes script I had read a couple of articles that stated you should release your COM objects using .NET.
```
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$LibrarySource)
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$iTunes)
```
I also run my scripts the majority of time from a shortcut, not from the powershell prompt.
Based on your comments, I did some testing and I determined that I would get the message when running against iTunes, if I ran my script in a way that leaves powershell running. iTunes seems to keep track of that. Running the script in a manner that exits it's process after running, eliminated the message.
One method of running your script from powershell, is to prefix your script with powershell.
```
powershell .\scriptname.ps1
```
The above command will launch your script and then exit the process that was used to run it, but still leaving you at the powershell prompt. |
52,313 | <p>This question is kind of an add-on to this <a href="https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why">question</a></p>
<p>In C#, a switch case cannot fall through to other cases, this causes a compilation error. In this case I am just adding some number to the month total for the selected month and each subsequent month thereafter. (simple example, not meant to be real) </p>
<pre><code>switch (month)
{
case 0:
add something to month totals
case 1:
add something to month totals
case 2:
add something to month totals
default:
break;
}
</code></pre>
<p>Is there a logical alternative to this in C# without having to write out a ton of if statements?</p>
<pre><code>if (month <= 0)
add something to month
if (month <= 1)
add something to month
if (month <= 2)
add something to month
.... etc
</code></pre>
| [
{
"answer_id": 52314,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 1,
"selected": false,
"text": "<p>There is already a question addressing this topic:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/44905/c-s... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4144/"
] | This question is kind of an add-on to this [question](https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why)
In C#, a switch case cannot fall through to other cases, this causes a compilation error. In this case I am just adding some number to the month total for the selected month and each subsequent month thereafter. (simple example, not meant to be real)
```
switch (month)
{
case 0:
add something to month totals
case 1:
add something to month totals
case 2:
add something to month totals
default:
break;
}
```
Is there a logical alternative to this in C# without having to write out a ton of if statements?
```
if (month <= 0)
add something to month
if (month <= 1)
add something to month
if (month <= 2)
add something to month
.... etc
``` | Often times when you see the noise from a huge switch statement or many if statements that might fall into more than one block, you're trying to suppress a bad design.
Instead, what if you implemented the Specification pattern to see if something matched, and then act on it?
```
foreach(MonthSpecification spec in this.MonthSpecifications)
{
if(spec.IsSatisfiedBy(month))
spec.Perform(month);
}
```
then you can just add up different specs that match what you're trying to do.
It's hard to tell what your domain is, so my example might be a little contrived. |
52,315 | <p>We have some input data that sometimes appears with &nbsp characters on the end.</p>
<p>The data comes in from the source system as varchar() and our attempts to cast as decimal fail b/c of these characters.</p>
<p>Ltrim and Rtrim don't remove the characters, so we're forced to do something like:</p>
<pre><code>UPDATE myTable
SET myColumn = replace(myColumn,char(160),'')
WHERE charindex(char(160),myColumn) > 0
</code></pre>
<p>This works for the &nbsp, but is there a good way to do this for any non-alphanumeric (or in this case numeric) characters?</p>
| [
{
"answer_id": 52327,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://www.lazydba.com/sql/1__4390.html\" rel=\"noreferrer\">This page</a> has a sample of how you can remove non-al... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5202/"
] | We have some input data that sometimes appears with   characters on the end.
The data comes in from the source system as varchar() and our attempts to cast as decimal fail b/c of these characters.
Ltrim and Rtrim don't remove the characters, so we're forced to do something like:
```
UPDATE myTable
SET myColumn = replace(myColumn,char(160),'')
WHERE charindex(char(160),myColumn) > 0
```
This works for the  , but is there a good way to do this for any non-alphanumeric (or in this case numeric) characters? | [This page](http://www.lazydba.com/sql/1__4390.html) has a sample of how you can remove non-alphanumeric chars:
```
-- Put something like this into a user function:
DECLARE @cString VARCHAR(32)
DECLARE @nPos INTEGER
SELECT @cString = '90$%45623 *6%}~:@'
SELECT @nPos = PATINDEX('%[^0-9]%', @cString)
WHILE @nPos > 0
BEGIN
SELECT @cString = STUFF(@cString, @nPos, 1, '')
SELECT @nPos = PATINDEX('%[^0-9]%', @cString)
END
SELECT @cString
``` |
52,321 | <p>Using the obsolete System.Web.Mail sending email works fine, here's the code snippet:</p>
<pre><code> Public Shared Sub send(ByVal recipent As String, ByVal from As String, ByVal subject As String, ByVal body As String)
Try
Dim Message As System.Web.Mail.MailMessage = New System.Web.Mail.MailMessage
Message.To = recipent
Message.From = from
Message.Subject = subject
Message.Body = body
Message.BodyFormat = MailFormat.Html
Try
SmtpMail.SmtpServer = MAIL_SERVER
SmtpMail.Send(Message)
Catch ehttp As System.Web.HttpException
critical_error("Email sending failed, reason: " + ehttp.ToString)
End Try
Catch e As System.Exception
critical_error(e, "send() in Util_Email")
End Try
End Sub
</code></pre>
<p>and here's the updated version:</p>
<pre><code>Dim mailMessage As New System.Net.Mail.MailMessage()
mailMessage.From = New System.Net.Mail.MailAddress(from)
mailMessage.To.Add(New System.Net.Mail.MailAddress(recipent))
mailMessage.Subject = subject
mailMessage.Body = body
mailMessage.IsBodyHtml = True
mailMessage.Priority = System.Net.Mail.MailPriority.Normal
Try
Dim smtp As New Net.Mail.SmtpClient(MAIL_SERVER)
smtp.Send(mailMessage)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
</code></pre>
<p>I have tried many different variations and nothing seems to work, I have a feeling it may have to do with the SmtpClient, is there something that changed in the underlying code between these versions?</p>
<p>There are no exceptions that are thrown back.</p>
| [
{
"answer_id": 52361,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried adding </p>\n\n<pre><code>smtp.UseDefaultCredentials = True \n</code></pre>\n\n<p>before the send?<... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4827/"
] | Using the obsolete System.Web.Mail sending email works fine, here's the code snippet:
```
Public Shared Sub send(ByVal recipent As String, ByVal from As String, ByVal subject As String, ByVal body As String)
Try
Dim Message As System.Web.Mail.MailMessage = New System.Web.Mail.MailMessage
Message.To = recipent
Message.From = from
Message.Subject = subject
Message.Body = body
Message.BodyFormat = MailFormat.Html
Try
SmtpMail.SmtpServer = MAIL_SERVER
SmtpMail.Send(Message)
Catch ehttp As System.Web.HttpException
critical_error("Email sending failed, reason: " + ehttp.ToString)
End Try
Catch e As System.Exception
critical_error(e, "send() in Util_Email")
End Try
End Sub
```
and here's the updated version:
```
Dim mailMessage As New System.Net.Mail.MailMessage()
mailMessage.From = New System.Net.Mail.MailAddress(from)
mailMessage.To.Add(New System.Net.Mail.MailAddress(recipent))
mailMessage.Subject = subject
mailMessage.Body = body
mailMessage.IsBodyHtml = True
mailMessage.Priority = System.Net.Mail.MailPriority.Normal
Try
Dim smtp As New Net.Mail.SmtpClient(MAIL_SERVER)
smtp.Send(mailMessage)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
```
I have tried many different variations and nothing seems to work, I have a feeling it may have to do with the SmtpClient, is there something that changed in the underlying code between these versions?
There are no exceptions that are thrown back. | I've tested your code and my mail is sent successfully. Assuming that you're using the same parameters for the old code, I would suggest that your mail server (MAIL\_SERVER) is accepting the message and there's a delay in processing or it considers it spam and discards it.
I would suggest sending a message using a third way (telnet if you're feeling brave) and see if that is successful.
EDIT: I note (from your subsequent answer) that specifying the port has helped somewhat. You've not said if you're using port 25 (SMTP) or port 587 (Submission) or something else. If you're not doing it already, using the sumission port may also help solve your problem.
[Wikipedia](http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol) and [rfc4409](https://www.rfc-editor.org/rfc/rfc4409) have more details. |
52,353 | <p>I have an application that reads a CSV file with piles of data rows. I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause <code>OutOfMemoryError</code>s. Each row translates into an object. Is there an easy way to find out the size of that object programmatically? Is there a reference that defines how large primitive types and object references are for a <code>VM</code>?</p>
<p>Right now, I have code that says read up to <strong>32,000 rows</strong>, but I'd also like to have code that says read as many rows as possible until I've used <strong>32MB</strong> of memory. Maybe that is a different question, but I'd still like to know. </p>
| [
{
"answer_id": 52362,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": -1,
"selected": false,
"text": "<p>I doubt you want to do it programmatically unless you just want to do it once and store it for future use. It's a cost... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5074/"
] | I have an application that reads a CSV file with piles of data rows. I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause `OutOfMemoryError`s. Each row translates into an object. Is there an easy way to find out the size of that object programmatically? Is there a reference that defines how large primitive types and object references are for a `VM`?
Right now, I have code that says read up to **32,000 rows**, but I'd also like to have code that says read as many rows as possible until I've used **32MB** of memory. Maybe that is a different question, but I'd still like to know. | You can use the [`java.lang.instrument` package](http://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html).
Compile and put this class in a JAR:
```
import java.lang.instrument.Instrumentation;
public class ObjectSizeFetcher {
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long getObjectSize(Object o) {
return instrumentation.getObjectSize(o);
}
}
```
Add the following to your `MANIFEST.MF`:
```
Premain-Class: ObjectSizeFetcher
```
Use the `getObjectSize()` method:
```
public class C {
private int x;
private int y;
public static void main(String [] args) {
System.out.println(ObjectSizeFetcher.getObjectSize(new C()));
}
}
```
Invoke with:
```
java -javaagent:ObjectSizeFetcherAgent.jar C
``` |
52,356 | <p>I'm still fairly new to T-SQL and SQL 2005. I need to import a column of integers from a table in database1 to a identical table (only missing the column I need) in database2. Both are sql 2005 databases. I've tried the built in import command in Server Management Studio but it's forcing me to copy the entire table. This causes errors due to constraints and 'read-only' columns (whatever 'read-only' means in sql2005). I just want to grab a single column and copy it to a table.</p>
<p>There must be a simple way of doing this. Something like:</p>
<pre><code>INSERT INTO database1.myTable columnINeed
SELECT columnINeed from database2.myTable
</code></pre>
| [
{
"answer_id": 52368,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 0,
"selected": false,
"text": "<p>insert into Test2.dbo.MyTable (MyValue) select MyValue from Test1.dbo.MyTable</p>\n\n<p>This is assuming a great deal. Firs... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5433/"
] | I'm still fairly new to T-SQL and SQL 2005. I need to import a column of integers from a table in database1 to a identical table (only missing the column I need) in database2. Both are sql 2005 databases. I've tried the built in import command in Server Management Studio but it's forcing me to copy the entire table. This causes errors due to constraints and 'read-only' columns (whatever 'read-only' means in sql2005). I just want to grab a single column and copy it to a table.
There must be a simple way of doing this. Something like:
```
INSERT INTO database1.myTable columnINeed
SELECT columnINeed from database2.myTable
``` | Inserting won't do it since it'll attempt to insert new rows at the end of the table. What it sounds like your trying to do is add a column to the end of existing rows.
I'm not sure if the syntax is exactly right but, if I understood you then this will do what you're after.
1. Create the column allowing nulls in database2.
2. Perform an update:
UPDATE database2.dbo.tablename
SET database2.dbo.tablename.colname = database1.dbo.tablename.colname
FROM database2.dbo.tablename INNER JOIN database1.dbo.tablename ON database2.dbo.tablename.keycol = database1.dbo.tablename.keycol |
52,357 | <p>I've been wondering, what is the point of clog? As near as I can tell, clog is the same as cerr but with buffering so it is more efficient. Usually stderr is the same as stdout, so clog is the same as cout. This seems pretty lame to me, so I figure I must be misunderstanding it. If I have log messages going out to the same place I have error messages going out to (perhaps something in /var/log/messages), then I probably am not writing too much out (so there isn't much lost by using non-buffered cerr). In my experience, I want my log messages up to date (not buffered) so I can help find a crash (so I don't want to be using the buffered clog). Apparently I should always be using cerr.</p>
<p>I'd like to be able to redirect clog inside my program. It would be useful to redirect cerr so that when I call a library routine I can control where cerr and clog go to. Can some compilers support this? I just checked DJGPP and stdout is defined as the address of a FILE struct, so it is illegal to do something like "stdout = freopen(...)".</p>
<ul>
<li>Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr?</li>
<li>Is the only difference between clog and cerr the buffering?</li>
<li>How should I implement (or find) a more robust logging facility (links please)?</li>
</ul>
| [
{
"answer_id": 52365,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "<blockquote>\n <p>Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr?</p>\n</blockquote>\n\n<p>... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4662/"
] | I've been wondering, what is the point of clog? As near as I can tell, clog is the same as cerr but with buffering so it is more efficient. Usually stderr is the same as stdout, so clog is the same as cout. This seems pretty lame to me, so I figure I must be misunderstanding it. If I have log messages going out to the same place I have error messages going out to (perhaps something in /var/log/messages), then I probably am not writing too much out (so there isn't much lost by using non-buffered cerr). In my experience, I want my log messages up to date (not buffered) so I can help find a crash (so I don't want to be using the buffered clog). Apparently I should always be using cerr.
I'd like to be able to redirect clog inside my program. It would be useful to redirect cerr so that when I call a library routine I can control where cerr and clog go to. Can some compilers support this? I just checked DJGPP and stdout is defined as the address of a FILE struct, so it is illegal to do something like "stdout = freopen(...)".
* Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr?
* Is the only difference between clog and cerr the buffering?
* How should I implement (or find) a more robust logging facility (links please)? | >
> Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr?
>
>
>
Yes. You want the [`rdbuf`](http://www.cplusplus.com/reference/iostream/ios/rdbuf.html) function.
```
ofstream ofs("logfile");
cout.rdbuf(ofs.rdbuf());
cout << "Goes to file." << endl;
```
>
> Is the only difference between clog and cerr the buffering?
>
>
>
As far as I know, yes. |
52,400 | <p>I'm sure this has already been asked and answered so I apologize in advance for that but I'm not figuring out the correct keywords to search for. Searching for "Pattern" hits way too many Q & A's to be useful.</p>
<p>I'm working on a regression testing app. I'm displaying a form on the screen and according to which user is logged in to the app some of the fields should be read-only. So I can abstract a field object and I can abstract a user object but what pattern should I be looking at to describe the intersection of these two concepts? In other words how should I describe that for Field 1 and User A, the field should be read-only? It seems like read-only (or not) should be a property of the Field class but as I said, it depends on which user is looking at the form. I've considered a simple two-dimensional array (e. g. ReadOnly[Field,User] = True) but I want to make sure I've picked the most effective structure to represent this. </p>
<p>Are there any software design patterns regarding this kind of data structure? Am I overcomplicating things--would a two-dimensional array be the best way to go here? As I said if this has been asked and answered, I do apologize. I did search here and didn't find anything and a Google search failed to turn up anything either. </p>
| [
{
"answer_id": 52413,
"author": "Dan Blair",
"author_id": 1327,
"author_profile": "https://Stackoverflow.com/users/1327",
"pm_score": 1,
"selected": false,
"text": "<p>At first blush it sounds more like you have two different types of users and they have different access levels. This co... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820/"
] | I'm sure this has already been asked and answered so I apologize in advance for that but I'm not figuring out the correct keywords to search for. Searching for "Pattern" hits way too many Q & A's to be useful.
I'm working on a regression testing app. I'm displaying a form on the screen and according to which user is logged in to the app some of the fields should be read-only. So I can abstract a field object and I can abstract a user object but what pattern should I be looking at to describe the intersection of these two concepts? In other words how should I describe that for Field 1 and User A, the field should be read-only? It seems like read-only (or not) should be a property of the Field class but as I said, it depends on which user is looking at the form. I've considered a simple two-dimensional array (e. g. ReadOnly[Field,User] = True) but I want to make sure I've picked the most effective structure to represent this.
Are there any software design patterns regarding this kind of data structure? Am I overcomplicating things--would a two-dimensional array be the best way to go here? As I said if this has been asked and answered, I do apologize. I did search here and didn't find anything and a Google search failed to turn up anything either. | Table driven designs can be effective.
Steve Maguire had few nice examples in *Writing* *Solid* *Code* .
They are also a great way to capture tests, see [fit](http://fit.c2.com/) .
In your case something like:
```
Field1ReadonlyRules = {
'user class 1' : True,
'user class 2' : False
}
field1.readOnly = Field1ReadonlyRules[ someUser.userClass ]
```
As an aside you probably want to model *both* users and user classes/roles/groups instead of combining them.
A user typically captures *who* (authentication) while groups/roles capture *what* (permissions, capabilities) |
52,430 | <p>I've got the following rough structure:</p>
<pre><code>Object -> Object Revisions -> Data
</code></pre>
<p>The Data can be shared between several Objects.</p>
<p>What I'm trying to do is clean out old Object Revisions. I want to keep the first, active, and a spread of revisions so that the last change for a time period is kept. The Data might be changed a lot over the course of 2 days then left alone for months, so I want to keep the last revision before the changes started and the end change of the new set.</p>
<p>I'm currently using a cursor and temp table to hold the IDs and date between changes so I can select out the low hanging fruit to get rid of. This means using @LastID, @LastDate, updates and inserts to the temp table, etc... </p>
<p>Is there an easier/better way to calculate the date difference between the current row and the next row in my initial result set without using a cursor and temp table? </p>
<p>I'm on sql server 2000, but would be interested in any new features of 2005, 2008 that could help with this as well.</p>
| [
{
"answer_id": 52455,
"author": "Peter",
"author_id": 5189,
"author_profile": "https://Stackoverflow.com/users/5189",
"pm_score": 2,
"selected": false,
"text": "<p>Here is example SQL. If you have an Identity column, you can use this instead of \"ActivityDate\".</p>\n\n<pre><code>SELECT... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5201/"
] | I've got the following rough structure:
```
Object -> Object Revisions -> Data
```
The Data can be shared between several Objects.
What I'm trying to do is clean out old Object Revisions. I want to keep the first, active, and a spread of revisions so that the last change for a time period is kept. The Data might be changed a lot over the course of 2 days then left alone for months, so I want to keep the last revision before the changes started and the end change of the new set.
I'm currently using a cursor and temp table to hold the IDs and date between changes so I can select out the low hanging fruit to get rid of. This means using @LastID, @LastDate, updates and inserts to the temp table, etc...
Is there an easier/better way to calculate the date difference between the current row and the next row in my initial result set without using a cursor and temp table?
I'm on sql server 2000, but would be interested in any new features of 2005, 2008 that could help with this as well. | If the identity column is sequential you can use this approach:
`SELECT curr.*, DATEDIFF(MINUTE, prev.EventDateTime,curr.EventDateTime) Duration FROM DWLog curr join DWLog prev on prev.EventID = curr.EventID - 1` |
52,438 | <p>I've been doing c# for a long time, and have never come across an easy way to just new up a hash.</p>
<p>I've recently become acquainted with the ruby syntax of hashes and wonder, does anyone know of a simple way to declare a hash as a literal, without doing all the add calls.</p>
<pre><code>{ "whatever" => {i => 1}; "and then something else" => {j => 2}};
</code></pre>
| [
{
"answer_id": 52443,
"author": "Wheelie",
"author_id": 1131,
"author_profile": "https://Stackoverflow.com/users/1131",
"pm_score": 6,
"selected": true,
"text": "<p>If you're using C# 3.0 (.NET 3.5) then you can use collection initializers. They're not quite as terse as in Ruby but still... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220/"
] | I've been doing c# for a long time, and have never come across an easy way to just new up a hash.
I've recently become acquainted with the ruby syntax of hashes and wonder, does anyone know of a simple way to declare a hash as a literal, without doing all the add calls.
```
{ "whatever" => {i => 1}; "and then something else" => {j => 2}};
``` | If you're using C# 3.0 (.NET 3.5) then you can use collection initializers. They're not quite as terse as in Ruby but still an improvement.
This example is based on the [MSDN Example](http://msdn.microsoft.com/en-us/library/bb531208.aspx)
```
var students = new Dictionary<int, StudentName>()
{
{ 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
{ 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317, }},
{ 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198, }}
};
``` |
52,449 | <p>Can I return it as an object if I am doing a </p>
<pre><code>Select OneItem from Table Where OtherItem = "blah"?
</code></pre>
<p>Is there a better way to do this?</p>
<p>I am building a constructor to return an object based on its name rather than its ID.</p>
| [
{
"answer_id": 52470,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 4,
"selected": true,
"text": "<p><code>query.UniqueResult<T>()</code> returns just one <strong>T</strong></p>\n"
},
{
"answer_id": 21431... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
] | Can I return it as an object if I am doing a
```
Select OneItem from Table Where OtherItem = "blah"?
```
Is there a better way to do this?
I am building a constructor to return an object based on its name rather than its ID. | `query.UniqueResult<T>()` returns just one **T** |
52,485 | <p>I have a Question class:</p>
<pre><code>class Question {
public int QuestionNumber { get; set; }
public string Question { get; set; }
public string Answer { get; set; }
}
</code></pre>
<p>Now I make an ICollection of these available through an ObjectDataSource, and display them using a Repeater bound to the DataSource. I use <strong><%#Eval("Question")%></strong> to display the Question, and I use a TextBox and <strong><%#Bind("Answer")%></strong> to accept an answer.</p>
<p>If my ObjectDataSource returns three Question objects, then my Repeater displays the three questions with a TextBox following each question for the user to provide an answer.</p>
<p>So far it works great.</p>
<p>Now I want to take the user's response and put it back into the relevant Question classes, which I will then persist.</p>
<p>Surely the framework should take care of all of this for me? I've used the Bind method, I've specified a DataSourceID, I've specified an Update method in my ObjectDataSource class, but there seems no way to actually kickstart the whole thing.</p>
<p>I tried adding a Command button and in the code behind calling MyDataSource.Update(), but it attempts to call my Update method with no parameters, rather than the Question parameter it expects.</p>
<p>Surely there's an easy way to achieve all of this with little or no codebehind?</p>
<p>It seems like all the bits are there, but there's some glue missing to stick them all together.</p>
<p>Help!</p>
<p>Anthony</p>
| [
{
"answer_id": 52513,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 2,
"selected": true,
"text": "<p>You have to handle the postback event (button click or whatever) then enumerate the repeater items like this:</p>\n\n... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366/"
] | I have a Question class:
```
class Question {
public int QuestionNumber { get; set; }
public string Question { get; set; }
public string Answer { get; set; }
}
```
Now I make an ICollection of these available through an ObjectDataSource, and display them using a Repeater bound to the DataSource. I use **<%#Eval("Question")%>** to display the Question, and I use a TextBox and **<%#Bind("Answer")%>** to accept an answer.
If my ObjectDataSource returns three Question objects, then my Repeater displays the three questions with a TextBox following each question for the user to provide an answer.
So far it works great.
Now I want to take the user's response and put it back into the relevant Question classes, which I will then persist.
Surely the framework should take care of all of this for me? I've used the Bind method, I've specified a DataSourceID, I've specified an Update method in my ObjectDataSource class, but there seems no way to actually kickstart the whole thing.
I tried adding a Command button and in the code behind calling MyDataSource.Update(), but it attempts to call my Update method with no parameters, rather than the Question parameter it expects.
Surely there's an easy way to achieve all of this with little or no codebehind?
It seems like all the bits are there, but there's some glue missing to stick them all together.
Help!
Anthony | You have to handle the postback event (button click or whatever) then enumerate the repeater items like this:
```
foreach(RepeaterItem item in rptQuestions.Items)
{
//pull out question
var question = (Question)item.DataItem;
question.Answer = ((TextBox)item.FindControl("txtAnswer")).Text;
question.Save() ? <--- not sure what you want to do with it
}
``` |
52,506 | <p>A friend and I were discussing C++ templates. He asked me what this should do:</p>
<pre><code>#include <iostream>
template <bool>
struct A {
A(bool) { std::cout << "bool\n"; }
A(void*) { std::cout << "void*\n"; }
};
int main() {
A<true> *d = 0;
const int b = 2;
const int c = 1;
new A< b > (c) > (d);
}
</code></pre>
<p>The last line in main has two reasonable parses. Is 'b' the template argument or is <code>b > (c)</code> the template argument? </p>
<p>Although, it is trivial to compile this, and see what we get, we were wondering what resolves the ambiguity?</p>
| [
{
"answer_id": 52515,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 0,
"selected": false,
"text": "<p>The greediness of the lexer is probably the determining factor in the absence of parentheses to make it explicit. I'd... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4798/"
] | A friend and I were discussing C++ templates. He asked me what this should do:
```
#include <iostream>
template <bool>
struct A {
A(bool) { std::cout << "bool\n"; }
A(void*) { std::cout << "void*\n"; }
};
int main() {
A<true> *d = 0;
const int b = 2;
const int c = 1;
new A< b > (c) > (d);
}
```
The last line in main has two reasonable parses. Is 'b' the template argument or is `b > (c)` the template argument?
Although, it is trivial to compile this, and see what we get, we were wondering what resolves the ambiguity? | AFAIK it would be compiled as `new A<b>(c) > d`. This is the only reasonable way to parse it IMHO. If the parser can't assume under normal circumstances a > end a template argument, that would result it much more ambiguity. If you want it the other way, you should have written:
```
new A<(b > c)>(d);
``` |
52,550 | <p>What does the <code>,</code> operator do in C?</p>
| [
{
"answer_id": 52558,
"author": "lillq",
"author_id": 2064,
"author_profile": "https://Stackoverflow.com/users/2064",
"pm_score": 8,
"selected": true,
"text": "<p>The expression:</p>\n<pre><code>(expression1, expression2)\n</code></pre>\n<p>First <code>expression1</code> is evaluated, t... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064/"
] | What does the `,` operator do in C? | The expression:
```
(expression1, expression2)
```
First `expression1` is evaluated, then `expression2` is evaluated, and the value of `expression2` is returned for the whole expression. |
52,561 | <p>What is iPhone's browser tag and how iPhone optimized web site is different from a usual mobile web site?</p>
<p>Thanks!</p>
| [
{
"answer_id": 52570,
"author": "Espen Herseth Halvorsen",
"author_id": 1542,
"author_profile": "https://Stackoverflow.com/users/1542",
"pm_score": 2,
"selected": true,
"text": "<p>Nettuts has a great introduction to web-developement for iPhone. You find it <a href=\"http://nettuts.com/m... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4808/"
] | What is iPhone's browser tag and how iPhone optimized web site is different from a usual mobile web site?
Thanks! | Nettuts has a great introduction to web-developement for iPhone. You find it [here](http://nettuts.com/misc/learn-how-to-develop-for-the-iphone/)
This is the specific code you asked for (taken from that article):
```
<!--#if expr="(${HTTP_USER_AGENT} = /iPhone/)"-->
<!--
place iPhone code in here
-->
<!--#else -->
<!--
place standard code to be used by non iphone browser.
-->
<!--#endif -->
``` |
52,563 | <p>I'm trying to let an <code><input type="text"></code> (henceforth referred to as “textbox”) fill a parent container by settings its <code>width</code> to <code>100%</code>. This works until I give the textbox a padding. This is then added to the content width and the input field overflows. Notice that in Firefox this only happens when rendering the content as standards compliant. In quirks mode, another box model seems to apply.</p>
<p>Here's a minimal code to reproduce the behaviour in all modern browsers.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#x {
background: salmon;
padding: 1em;
}
#y, input {
background: red;
padding: 0 20px;
width: 100%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="x">
<div id="y">x</div>
<input type="text"/>
</div></code></pre>
</div>
</div>
</p>
<p>My question: <strong>How do I get the textbox to fit the container?</strong></p>
<p><em>Notice</em>: for the <code><div id="y"></code>, this is straightforward: simply set <code>width: auto</code>. However, if I try to do this for the textbox, the effect is different and the textbox takes its default row count as width (even if I set <code>display: block</code> for the textbox).</p>
<p>EDIT: David's solution would of course work. However, I do not want to modify the HTML – I do especially not want to add dummy elements with no semantic functionality. This is a typical case of <a href="http://en.wiktionary.org/wiki/Citations:divitis" rel="nofollow noreferrer">divitis</a> that I want to avoid at all cost. This can only be a last-resort hack.</p>
| [
{
"answer_id": 52575,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>i believe you can counter the overflow with a negative margin. ie</p>\n\n<pre><code>margin: -1em;\n</code></pre>\n"
},
... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1968/"
] | I'm trying to let an `<input type="text">` (henceforth referred to as “textbox”) fill a parent container by settings its `width` to `100%`. This works until I give the textbox a padding. This is then added to the content width and the input field overflows. Notice that in Firefox this only happens when rendering the content as standards compliant. In quirks mode, another box model seems to apply.
Here's a minimal code to reproduce the behaviour in all modern browsers.
```css
#x {
background: salmon;
padding: 1em;
}
#y, input {
background: red;
padding: 0 20px;
width: 100%;
}
```
```html
<div id="x">
<div id="y">x</div>
<input type="text"/>
</div>
```
My question: **How do I get the textbox to fit the container?**
*Notice*: for the `<div id="y">`, this is straightforward: simply set `width: auto`. However, if I try to do this for the textbox, the effect is different and the textbox takes its default row count as width (even if I set `display: block` for the textbox).
EDIT: David's solution would of course work. However, I do not want to modify the HTML – I do especially not want to add dummy elements with no semantic functionality. This is a typical case of [divitis](http://en.wiktionary.org/wiki/Citations:divitis) that I want to avoid at all cost. This can only be a last-resort hack. | With CSS3 you can use the box-sizing property on your inputs to standardise their box models.
Something like this would enable you to add padding and have 100% width:
```css
input[type="text"] {
-webkit-box-sizing: border-box; // Safari/Chrome, other WebKit
-moz-box-sizing: border-box; // Firefox, other Gecko
box-sizing: border-box; // Opera/IE 8+
}
```
Unfortunately this won't work for IE6/7 but the rest are fine ([Compatibility List](http://www.quirksmode.org/css/user-interface/)), so if you need to support these browsers your best bet would be Davids solution.
If you'd like to read more check out [this brilliant article by Chris Coyier](http://css-tricks.com/box-sizing/).
Hope this helps! |
52,591 | <p>A requirement for an ASP.Net 2.0 project I'm working on limits a certain field to a max of 10 words (not characters). I'm currently using a CustomValidator control with the following ServerValidate method:</p>
<pre><code>Protected Sub TenWordsTextBoxValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles TenWordsTextBoxValidator.ServerValidate
'' 10 words
args.IsValid = args.Value.Split(" ").Length <= 10
End Sub
</code></pre>
<p>Does anyone have a more thorough/accurate method of getting a word count?</p>
| [
{
"answer_id": 52610,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 3,
"selected": false,
"text": "<p>You can use one of the builtin validators with a regex that counts the words.</p>\n\n<p>I'm a little rusty with regex so... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] | A requirement for an ASP.Net 2.0 project I'm working on limits a certain field to a max of 10 words (not characters). I'm currently using a CustomValidator control with the following ServerValidate method:
```
Protected Sub TenWordsTextBoxValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles TenWordsTextBoxValidator.ServerValidate
'' 10 words
args.IsValid = args.Value.Split(" ").Length <= 10
End Sub
```
Does anyone have a more thorough/accurate method of getting a word count? | This regex seems to be working great:
```
"^(\b\S+\b\s*){0,10}$"
```
**Update**: the above had a few flaws so I ended up using this RegEx:
```
[\s\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\xBF]+
```
I `split()` the string on that regex and use the `length` of the resulting array to get the correct word count. |
52,600 | <p>I have to use a third-party component without source code. I have the release DLL and release PDB file. Let's call it 'CorporateComponent.dll'. My own code creates objects from this DLL and calls methods on these objects.</p>
<pre><code>CorpObject o = new CorpObject();
Int32 result = o.DoSomethingLousy();
</code></pre>
<p>While debugging, the method 'DoSomethingLousy' throws an exception. What does the PDB file do for me? If it does something nice, how can I be sure I'm making use of it?</p>
| [
{
"answer_id": 52609,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>The PDB is a database file that maps the instructions to their line numbers in the original code so when you get a sta... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3619/"
] | I have to use a third-party component without source code. I have the release DLL and release PDB file. Let's call it 'CorporateComponent.dll'. My own code creates objects from this DLL and calls methods on these objects.
```
CorpObject o = new CorpObject();
Int32 result = o.DoSomethingLousy();
```
While debugging, the method 'DoSomethingLousy' throws an exception. What does the PDB file do for me? If it does something nice, how can I be sure I'm making use of it? | To confirm if you're using the provided PDB, CorporateComponent.pdb, during debugging within the Visual Studio IDE review the output window and locate the line indicating that the CorporateComponent.dll is loaded and followed by the string `Symbols loaded`.
To illustrate from a project of mine:
```
The thread 0x6a0 has exited with code 0 (0x0).
The thread 0x1f78 has exited with code 0 (0x0).
'AvayaConfigurationService.vshost.exe' (Managed): Loaded 'C:\Development\Src\trunk\ntity\AvayaConfigurationService\AvayaConfigurationService\bin\Debug \AvayaConfigurationService.exe', Symbols loaded.
'AvayaConfigurationService.vshost.exe' (Managed): Loaded 'C:\Development\Src\trunk\ntity\AvayaConfigurationService\AvayaConfigurationService\bin\Debug\IPOConfigService.dll', No symbols loaded.
```
>
> `Loaded 'C:\Development\src...\bin\Debug\AvayaConfigurationService.exe', Symbols loaded.`
>
>
>
This indicates that the PDB was found and loaded by the IDE debugger.
As indicated by others When examining stack frames within your application you should be able to see the symbols from the CorporateComponent.pdb. If you don't then perhaps the third-party did not include symbol information in the release PDB build. |
52,634 | <p>So I'm been pounding on this problem all day. I've got a LinqDataSource that points to my model and a GridView that consumes it. When I attempt to do an update on the GridView, it does not update the underlying data source. I thought it might have to do with the LinqDataSource, so I added a SqlDataSource and the same thing happens. The aspx is as follows (the code-behind page is empty):</p>
<pre><code> <asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=devsql32;Initial Catalog=Steam;Persist Security Info=True;"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [LangID], [Code], [Name] FROM [Languages]" UpdateCommand="UPDATE [Languages] SET [Code]=@Code WHERE [LangID]=@LangId">
</asp:SqlDataSource>
<asp:GridView ID="_languageGridView" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="LangId"
DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="LangId" HeaderText="Id" ReadOnly="True" />
<asp:BoundField DataField="Code" HeaderText="Code" />
<asp:BoundField DataField="Name" HeaderText="Name" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="_languageDataSource" ContextTypeName="GeneseeSurvey.SteamDatabaseDataContext" runat="server" TableName="Languages" EnableInsert="True" EnableUpdate="true" EnableDelete="true">
</asp:LinqDataSource>
</code></pre>
<p>What in the world am I missing here? This problem is driving me insane.</p>
| [
{
"answer_id": 52644,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 0,
"selected": false,
"text": "<p>This is a total shot in the dark since I haven't used ASP at all.</p>\n\n<p>I've been just learning XAML and WPF, which a... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1194/"
] | So I'm been pounding on this problem all day. I've got a LinqDataSource that points to my model and a GridView that consumes it. When I attempt to do an update on the GridView, it does not update the underlying data source. I thought it might have to do with the LinqDataSource, so I added a SqlDataSource and the same thing happens. The aspx is as follows (the code-behind page is empty):
```
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=devsql32;Initial Catalog=Steam;Persist Security Info=True;"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [LangID], [Code], [Name] FROM [Languages]" UpdateCommand="UPDATE [Languages] SET [Code]=@Code WHERE [LangID]=@LangId">
</asp:SqlDataSource>
<asp:GridView ID="_languageGridView" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="LangId"
DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="LangId" HeaderText="Id" ReadOnly="True" />
<asp:BoundField DataField="Code" HeaderText="Code" />
<asp:BoundField DataField="Name" HeaderText="Name" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="_languageDataSource" ContextTypeName="GeneseeSurvey.SteamDatabaseDataContext" runat="server" TableName="Languages" EnableInsert="True" EnableUpdate="true" EnableDelete="true">
</asp:LinqDataSource>
```
What in the world am I missing here? This problem is driving me insane. | It turns out that we had a DataBind() call in the Page\_Load of the master page of the aspx file that was probably causing the state of the GridView to get tossed out on every page load.
As a note - update parameters for a LINQ query are not required unless you want to set them some non-null default. |
52,674 | <p>Let's say you have a variable in a makefile fragment like the following:</p>
<pre><code>MY_LIST=a b c d
</code></pre>
<p>How do I then reverse the order of that list? I need:</p>
<pre><code>$(warning MY_LIST=${MY_LIST})
</code></pre>
<p>to show</p>
<pre><code>MY_LIST=d c b a
</code></pre>
<p>Edit: the real problem is that </p>
<pre><code>ld -r some_object.o ${MY_LIST}
</code></pre>
<p>produces an <code>a.out</code> with undefined symbols because the items in <code>MY_LIST</code> are actually archives, but in the wrong order. If the order of <code>MY_LIST</code> is reversed, it will link correctly (I think). If you know a smarter way to get the link order right, clue me in.</p>
| [
{
"answer_id": 52722,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 3,
"selected": false,
"text": "<p>Doh! I could have just used a shell script-let:</p>\n\n<p><code>(for d in ${MY_LIST}; do echo $$d; done) | tac</code>... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3279/"
] | Let's say you have a variable in a makefile fragment like the following:
```
MY_LIST=a b c d
```
How do I then reverse the order of that list? I need:
```
$(warning MY_LIST=${MY_LIST})
```
to show
```
MY_LIST=d c b a
```
Edit: the real problem is that
```
ld -r some_object.o ${MY_LIST}
```
produces an `a.out` with undefined symbols because the items in `MY_LIST` are actually archives, but in the wrong order. If the order of `MY_LIST` is reversed, it will link correctly (I think). If you know a smarter way to get the link order right, clue me in. | A solution in pure GNU make:
>
> default: all
>
>
> foo = please reverse me
>
>
> reverse = $(if $(1),$(call
> reverse,$(wordlist 2,$(words
> $(1)),$(1)))) $(firstword $(1))
>
>
> all : @echo $(call reverse,$(foo))
>
>
>
Gives:
>
> $ make
>
>
> me reverse please
>
>
> |
52,702 | <p>I am looking to stream a file housed in a SharePoint 2003 document library down to the browser. Basically the idea is to open the file as a stream and then to "write" the file stream to the reponse, specifying the content type and content disposition headers. Content disposition is used to preserve the file name, content type of course to clue the browser about what app to open to view the file. </p>
<p>This works all good and fine in a development environment and UAT environment. However, in the production environment, things do not always work as expected,however only with IE6/IE7. FF works great in all environments. </p>
<p>Note that in the production environment SSL is enabled and generally used. (When SSL is not used in the production environment, file streams, is named as expected, and properly dislays.)</p>
<p>Here is a code snippet:</p>
<pre><code>System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(".") + "\\" + "test.doc", System.IO.FileMode.Open);
long byteNum = fs.Length;
byte[] pdfBytes = new byte[byteNum];
fs.Read(pdfBytes, 0, (int)byteNum);
Response.AppendHeader("Content-disposition", "filename=Testme.doc");
Response.CacheControl = "no-cache";
Response.ContentType = "application/msword; charset=utf-8";
Response.Expires = -1;
Response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length);
Response.Flush();
Response.Close();
fs.Close();
</code></pre>
<p>Like I said, this code snippet works fine on the dev machine and in the UAT environment. A dialog box opens and asks to save, view or cancel Testme.doc. But in production onnly when using SSL, IE 6 & IE7 don't use the name of the attachment. Instead it uses the name of the page that is sending the stream, testheader.apx and then an error is thrown. </p>
<p>IE does provide an advanced setting "Do not save encrypted pages to disk". </p>
<p>I suspect this is part of the problem, the server tells the browser not to cache the file, while IE has the "Do not save encrypted pages to disk" enabled.</p>
<p>Yes I am aware that for larger files, the code snippet above will be a major drag on memory and this implimentation will be problematic. So the real final solution will not open the entire file into a single byte array, but rather will open the file as a stream, and then send the file down to the client in bite size chunks (e.g. perhaps roughly 10K in size).</p>
<p>Anyone else have similar experience "streaming" binary files over ssl? Any suggestions or recommendations?</p>
| [
{
"answer_id": 53078,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 2,
"selected": false,
"text": "<p>It might be something really simple, believe it or not I coded exactly the same thing today, i think the issue might be that... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4764/"
] | I am looking to stream a file housed in a SharePoint 2003 document library down to the browser. Basically the idea is to open the file as a stream and then to "write" the file stream to the reponse, specifying the content type and content disposition headers. Content disposition is used to preserve the file name, content type of course to clue the browser about what app to open to view the file.
This works all good and fine in a development environment and UAT environment. However, in the production environment, things do not always work as expected,however only with IE6/IE7. FF works great in all environments.
Note that in the production environment SSL is enabled and generally used. (When SSL is not used in the production environment, file streams, is named as expected, and properly dislays.)
Here is a code snippet:
```
System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(".") + "\\" + "test.doc", System.IO.FileMode.Open);
long byteNum = fs.Length;
byte[] pdfBytes = new byte[byteNum];
fs.Read(pdfBytes, 0, (int)byteNum);
Response.AppendHeader("Content-disposition", "filename=Testme.doc");
Response.CacheControl = "no-cache";
Response.ContentType = "application/msword; charset=utf-8";
Response.Expires = -1;
Response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length);
Response.Flush();
Response.Close();
fs.Close();
```
Like I said, this code snippet works fine on the dev machine and in the UAT environment. A dialog box opens and asks to save, view or cancel Testme.doc. But in production onnly when using SSL, IE 6 & IE7 don't use the name of the attachment. Instead it uses the name of the page that is sending the stream, testheader.apx and then an error is thrown.
IE does provide an advanced setting "Do not save encrypted pages to disk".
I suspect this is part of the problem, the server tells the browser not to cache the file, while IE has the "Do not save encrypted pages to disk" enabled.
Yes I am aware that for larger files, the code snippet above will be a major drag on memory and this implimentation will be problematic. So the real final solution will not open the entire file into a single byte array, but rather will open the file as a stream, and then send the file down to the client in bite size chunks (e.g. perhaps roughly 10K in size).
Anyone else have similar experience "streaming" binary files over ssl? Any suggestions or recommendations? | It might be something really simple, believe it or not I coded exactly the same thing today, i think the issue might be that the content disposition doesnt tell the browser its an attachment and therefore able to be saved.
```
Response.AddHeader("Content-Disposition", "attachment;filename=myfile.doc");
```
failing that i've included my code below as I know that works over https://
```
private void ReadFile(string URL)
{
try
{
string uristring = URL;
WebRequest myReq = WebRequest.Create(uristring);
NetworkCredential netCredential = new NetworkCredential(ConfigurationManager.AppSettings["Username"].ToString(),
ConfigurationManager.AppSettings["Password"].ToString(),
ConfigurationManager.AppSettings["Domain"].ToString());
myReq.Credentials = netCredential;
StringBuilder strSource = new StringBuilder("");
//get the stream of data
string contentType = "";
MemoryStream ms;
// Send a request to download the pdf document and then get the response
using (HttpWebResponse response = (HttpWebResponse)myReq.GetResponse())
{
contentType = response.ContentType;
// Get the stream from the server
using (Stream stream = response.GetResponseStream())
{
// Use the ReadFully method from the link above:
byte[] data = ReadFully(stream, response.ContentLength);
// Return the memory stream.
ms = new MemoryStream(data);
}
}
Response.Clear();
Response.ContentType = contentType;
Response.AddHeader("Content-Disposition", "attachment;");
// Write the memory stream containing the pdf file directly to the Response object that gets sent to the client
ms.WriteTo(Response.OutputStream);
}
catch (Exception ex)
{
throw new Exception("Error in ReadFile", ex);
}
}
``` |
52,703 | <p>Has anyone encountered this oddity?</p>
<p>I'm checking for the existence of a number of directories in one of my unit tests. <code>is_dir</code> is reporting true (1) in spite of the folder not existing at the time it is called. The code looks like this (with a few extraneous intermediate vars to ease debugging):</p>
<pre><code>foreach($userfolders as $uf) {
$uf = sprintf($uf, $user_id);
$uf = ltrim($uf,'/');
$path = trim($base . '/' . $uf);
$res = is_dir($path); //returns false except last time returns 1
$this->assertFalse($res, $path);
}
</code></pre>
<p>The machine running Ubuntu Linux 8.04 with PHP Version 5.2.4-2ubuntu5.3</p>
<p>Things I have checked:</p>
<pre><code> - Paths are full paths
- The same thing happens on two separate machines (both running Ubuntu)
- I have stepped through line by line in a debugger
- Paths genuinely don't exist at the point where is_dir is called
- While the code is paused on this line, I can actually drop to a shell and run
</code></pre>
<p>the interactive PHP interpreter and get the correct result
- The paths are all WELL under 256 chars
- I can't imagine a permissions problem as the folder doesn't exist! The parent folder can't be causing permissions problems as the other folders in the loop are correctly reported as missing.</p>
<p>Comments on the PHP docs point to the odd issue with <code>is_dir</code> but not this particular one.</p>
<p>I'm not posting this as a "please help me fix" but in the hope that somebody encountering the same thing can search here and <em>hopefully</em> an answer from somebody else who has seen this!</p>
| [
{
"answer_id": 52712,
"author": "reefnet_alex",
"author_id": 2745,
"author_profile": "https://Stackoverflow.com/users/2745",
"pm_score": 1,
"selected": false,
"text": "<p>For what its worth, <code>is_readable</code> can be used as a work around.</p>\n"
},
{
"answer_id": 52716,
... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2745/"
] | Has anyone encountered this oddity?
I'm checking for the existence of a number of directories in one of my unit tests. `is_dir` is reporting true (1) in spite of the folder not existing at the time it is called. The code looks like this (with a few extraneous intermediate vars to ease debugging):
```
foreach($userfolders as $uf) {
$uf = sprintf($uf, $user_id);
$uf = ltrim($uf,'/');
$path = trim($base . '/' . $uf);
$res = is_dir($path); //returns false except last time returns 1
$this->assertFalse($res, $path);
}
```
The machine running Ubuntu Linux 8.04 with PHP Version 5.2.4-2ubuntu5.3
Things I have checked:
```
- Paths are full paths
- The same thing happens on two separate machines (both running Ubuntu)
- I have stepped through line by line in a debugger
- Paths genuinely don't exist at the point where is_dir is called
- While the code is paused on this line, I can actually drop to a shell and run
```
the interactive PHP interpreter and get the correct result
- The paths are all WELL under 256 chars
- I can't imagine a permissions problem as the folder doesn't exist! The parent folder can't be causing permissions problems as the other folders in the loop are correctly reported as missing.
Comments on the PHP docs point to the odd issue with `is_dir` but not this particular one.
I'm not posting this as a "please help me fix" but in the hope that somebody encountering the same thing can search here and *hopefully* an answer from somebody else who has seen this! | I don't think this would cause your problem, but $path does have the trailing slash, correct? |
52,704 | <p>How do I discard changes in my working copy that are not in the index?</p>
| [
{
"answer_id": 52713,
"author": "Tobi",
"author_id": 5422,
"author_profile": "https://Stackoverflow.com/users/5422",
"pm_score": 13,
"selected": false,
"text": "<p>For all <em>unstaged</em> files in current working directory use:</p>\n<pre><code>git restore .\n</code></pre>\n<p>For a spe... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | How do I discard changes in my working copy that are not in the index? | Another quicker way is:
```
git stash save --keep-index --include-untracked
```
You don't need to include `--include-untracked` if you don't want to be thorough about it.
After that, you can drop that stash with a `git stash drop` command if you like. |
52,723 | <p>I am trying to paginate the results of an SQL query for use on a web page. The language and the database backend are PHP and SQLite.</p>
<p>The code I'm using works something like this (page numbering starts at 0)</p>
<p><a href="http://example.com/table?page=0" rel="nofollow noreferrer">http://example.com/table?page=0</a></p>
<pre><code>page = request(page)
per = 10 // results per page
offset = page * per
// take one extra record so we know if a next link is needed
resultset = query(select columns from table where conditions limit offset, per + 1)
if(page > 0) show a previous link
if(count(resultset) > per) show a next link
unset(resultset[per])
display results
</code></pre>
<p>Are there more efficient ways to do pagination than this?</p>
<p>One problem that I can see with my current method is that I must store all 10 (or however many) results in memory before I start displaying them. I do this because PDO does not guarantee that the row count will be available.</p>
<p>Is it more efficient to issue a <code>COUNT(*)</code> query to learn how many rows exist, then stream the results to the browser?</p>
<p>Is this one of those "it depends on the size of your table, and whether the <code>count(*)</code> query requires a full table scan in the database backend", "do some profiling yourself" kind of questions?</p>
| [
{
"answer_id": 52742,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": true,
"text": "<p>i'd suggest just doing the count first. a count(primary key) is a very efficient query.</p>\n"
},
{
"answer_id": 52747... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581/"
] | I am trying to paginate the results of an SQL query for use on a web page. The language and the database backend are PHP and SQLite.
The code I'm using works something like this (page numbering starts at 0)
<http://example.com/table?page=0>
```
page = request(page)
per = 10 // results per page
offset = page * per
// take one extra record so we know if a next link is needed
resultset = query(select columns from table where conditions limit offset, per + 1)
if(page > 0) show a previous link
if(count(resultset) > per) show a next link
unset(resultset[per])
display results
```
Are there more efficient ways to do pagination than this?
One problem that I can see with my current method is that I must store all 10 (or however many) results in memory before I start displaying them. I do this because PDO does not guarantee that the row count will be available.
Is it more efficient to issue a `COUNT(*)` query to learn how many rows exist, then stream the results to the browser?
Is this one of those "it depends on the size of your table, and whether the `count(*)` query requires a full table scan in the database backend", "do some profiling yourself" kind of questions? | i'd suggest just doing the count first. a count(primary key) is a very efficient query. |
52,732 | <p>I need to dynamically create a Video object in ActionScript 2 and add it to a movie clip. In AS3 I just do this:</p>
<pre><code>var videoViewComp:UIComponent; // created elsewhere
videoView = new Video();
videoView.width = 400;
videoView.height = 400;
this.videoViewComp.addChild(videoView);
</code></pre>
<p>Unfortunately, I can't figure out how to accomplish this in AS2. Video isn't a child of MovieClip, so attachMovie() doesn't seem to be getting me anything. I don't see any equivalent to AS3's UIComponent.addChild() method either.</p>
<p>Is there any way to dynamically create a Video object in AS2 that actually shows up on the stage?</p>
<hr>
<p>I potentially need multiple videos at a time though. Is it possible to duplicate that video object?</p>
<p>I think I have another solution working. It's not optimal, but it fits with some of the things I have to do for other components so it's not too out of place in the project. Once I get it figured out I'll post what I did here.</p>
| [
{
"answer_id": 53254,
"author": "Pedro",
"author_id": 5488,
"author_profile": "https://Stackoverflow.com/users/5488",
"pm_score": 0,
"selected": false,
"text": "<p>I recommend you create a single instance of the Video object, leave it invisible (i.e., <code>videoview.visible = false</cod... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1409/"
] | I need to dynamically create a Video object in ActionScript 2 and add it to a movie clip. In AS3 I just do this:
```
var videoViewComp:UIComponent; // created elsewhere
videoView = new Video();
videoView.width = 400;
videoView.height = 400;
this.videoViewComp.addChild(videoView);
```
Unfortunately, I can't figure out how to accomplish this in AS2. Video isn't a child of MovieClip, so attachMovie() doesn't seem to be getting me anything. I don't see any equivalent to AS3's UIComponent.addChild() method either.
Is there any way to dynamically create a Video object in AS2 that actually shows up on the stage?
---
I potentially need multiple videos at a time though. Is it possible to duplicate that video object?
I think I have another solution working. It's not optimal, but it fits with some of the things I have to do for other components so it's not too out of place in the project. Once I get it figured out I'll post what I did here. | Ok, I've got something working.
First, I created a new Library symbol and called it "VideoWrapper". I then added a single Video object to that with an ID of "video".
Now, any time I need to dynamically add a Video to my state I can use MovieClip.attachMovie() to add a new copy of the Video object.
To make things easier I wrote a VideoWrapper class that exposes basic UI element handling (setPosition(), setSize(), etc). So when dealing with the Video in regular UI layout code I just use those methods so it looks just like all my other UI elements. When dealing with the video I just access the "video" member of the class.
My actual implementation is a bit more complicated, but that's the basics of how I got things working. I have a test app that's playing 2 videos, one from the local camera and one streaming from FMS, and it's working great. |
52,755 | <p>I am using Windows, and I have two monitors.</p>
<p>Some applications will <em>always</em> start on my primary monitor, no matter where they were when I closed them.</p>
<p>Others will always start on the <em>secondary</em> monitor, no matter where they were when I closed them.</p>
<p>Is there a registry setting buried somewhere, which I can manipulate to control which monitor applications launch into by default?</p>
<p>@rp: I have Ultramon, and I agree that it is indispensable, to the point that Microsoft should buy it and incorporate it into their OS. But as you said, it doesn't let you control the default monitor a program launches into.</p>
| [
{
"answer_id": 52775,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 2,
"selected": false,
"text": "<p>I'm fairly sure the primary monitor is the default. If the app was coded decently, when it's closed, it'll rememb... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] | I am using Windows, and I have two monitors.
Some applications will *always* start on my primary monitor, no matter where they were when I closed them.
Others will always start on the *secondary* monitor, no matter where they were when I closed them.
Is there a registry setting buried somewhere, which I can manipulate to control which monitor applications launch into by default?
@rp: I have Ultramon, and I agree that it is indispensable, to the point that Microsoft should buy it and incorporate it into their OS. But as you said, it doesn't let you control the default monitor a program launches into. | Correctly written Windows apps that want to save their location from run to run will save the results of [`GetWindowPlacement()`](http://msdn.microsoft.com/ru-ru/library/windows/desktop/ms633518%28v=vs.85%29.aspx) before shutting down, then use `SetWindowPlacement()` on startup to restore their position.
Frequently, apps will store the results of `GetWindowPlacement()` in the registry as a `REG_BINARY` for easy use.
The `WINDOWPLACEMENT`route has many advantages over other methods:
* Handles the case where the screen resolution changed since the last run: `SetWindowPlacement()` will automatically ensure that the window is not entirely offscreen
* Saves the state (minimized/maximized) but also saves the restored (normal) size and position
* Handles desktop metrics correctly, compensating for the taskbar position, etc. (i.e. uses "workspace coordinates" instead of "screen coordinates" -- techniques that rely on saving screen coordinates may suffer from the "walking windows" problem where a window will always appear a little lower each time if the user has a toolbar at the top of the screen).
Finally, programs that handle window restoration properly will take into account the `nCmdShow` parameter passed in from the shell. This parameter is set in the shortcut that launches the application (Normal, Minimized, Maximize):
```
if(nCmdShow != SW_SHOWNORMAL)
placement.showCmd = nCmdShow; //allow shortcut to override
```
For non-Win32 applications, it's important to be sure that the method you're using to save/restore window position eventually uses the same underlying call, otherwise (like Java Swing's `setBounds()`/`getBounds()` problem) you'll end up writing a lot of extra code to re-implement functionality that's already there in the `WINDOWPLACEMENT` functions. |
52,785 | <p>I think this is specific to IE 6.0 but...</p>
<p>In JavaScript I add a <code>div</code> to the DOM. I assign an <code>id</code> attribute. When I later try to pick up the <code>div</code> by the <code>id</code> all I get is <code>null</code>.</p>
<p>Any suggestions?</p>
<p>Example:</p>
<pre><code>var newDiv = document.createElement("DIV");
newDiv.setAttribute("ID", "obj_1000");
document.appendChild(newDiv);
alert("Added:" + newDiv.getAttribute("ID") + ":" + newDiv.id + ":" + document.getElementById("obj_1000") );
</code></pre>
<p>Alert prints <code>"::null"</code></p>
<p>Seems to work fine in Firefox 2.0+</p>
| [
{
"answer_id": 52791,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 1,
"selected": false,
"text": "<p>You have to add the div to the dom.</p>\n\n<pre><code>// Create the Div\nvar oDiv = document.createElement('div');\n... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2490/"
] | I think this is specific to IE 6.0 but...
In JavaScript I add a `div` to the DOM. I assign an `id` attribute. When I later try to pick up the `div` by the `id` all I get is `null`.
Any suggestions?
Example:
```
var newDiv = document.createElement("DIV");
newDiv.setAttribute("ID", "obj_1000");
document.appendChild(newDiv);
alert("Added:" + newDiv.getAttribute("ID") + ":" + newDiv.id + ":" + document.getElementById("obj_1000") );
```
Alert prints `"::null"`
Seems to work fine in Firefox 2.0+ | In addition to what the other answers suggest (that you need to actually insert the element into the DOM for it to be found via `getElementById()`), you also need to use a lower-case attribute name in order for IE6 to recognize it as the `id`:
```
var newDiv = document.createElement("DIV");
newDiv.setAttribute("id", "obj_1000");
document.body.appendChild(newDiv);
alert("Added:"
+ newDiv.getAttribute("id")
+ ":" + newDiv.id + ":"
+ document.getElementById("obj_1000") );
```
...responds as expected:
```
Added:obj_1000:obj_1000:[object]
```
---
According to the [MSDN documentation](http://msdn.microsoft.com/en-us/library/ms536739(VS.85).aspx) for `setAttribute()`, up to IE8 there is an optional *third parameter* that controls whether or not it is case sensitive with regard to the attribute name. Guess what the default is... |