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 |
|---|---|---|---|---|---|---|
11,200 | <p>I'm guessing it needs to be something like:</p>
<pre><code>CONVERT(CHAR(24), lastModified, 101)
</code></pre>
<p>However I'm not sure of the right value for the third parameter.</p>
<p>Thanks!</p>
<hr>
<p>Well I'm trying to write a script to copy my sql server db to a sqlite file, which gets downloaded to an air app, which then syncs the data to another sqlite file. I'm having a ton of trouble with dates. If I select a date in air and try to insert it, it fails because it's not in the right format... even if it was a valid date to begin with. I figured I'd try to experiment with the unix time since that's the only thing thats worked so far. I am considering just leaving them as varchar because I don't sort by them anyway.</p>
| [
{
"answer_id": 11213,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 0,
"selected": false,
"text": "<p>Define \"last epoch\". Does this come close?</p>\n\n<p>Select Cast(lastModified As Integer)</p>\n"
},
{
"answer_id": 112... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] | I'm guessing it needs to be something like:
```
CONVERT(CHAR(24), lastModified, 101)
```
However I'm not sure of the right value for the third parameter.
Thanks!
---
Well I'm trying to write a script to copy my sql server db to a sqlite file, which gets downloaded to an air app, which then syncs the data to another sqlite file. I'm having a ton of trouble with dates. If I select a date in air and try to insert it, it fails because it's not in the right format... even if it was a valid date to begin with. I figured I'd try to experiment with the unix time since that's the only thing thats worked so far. I am considering just leaving them as varchar because I don't sort by them anyway. | I wound up using format 120 in MS SQL:
```
convert(char(24), lastModified, 120)
```
Each time I needed to a select a date in SQLite for non-display purposes I used:
```
strftime(\"%Y-%m-%d %H:%M:%S\", dateModified) as dateModified
```
Now I just need a readable/friendly way to display the date to the user!
edit: accept answer goes to whoever shows me how to display the date nicely from sqlite ;p |
11,219 | <p>I'd like to start moving our application business layers into a collection of REST web services. However, most of our Intranet has been built using Classic ASP and most of the developers where I work keep programming in Classic ASP. Ideally, then, for them to benefit from the advantages of a unique set of web APIs, it would have to be called from Classic ASP pages.</p>
<p>I haven't the slightest idea how to do that. </p>
| [
{
"answer_id": 11237,
"author": "SitWalkStand",
"author_id": 509,
"author_profile": "https://Stackoverflow.com/users/509",
"pm_score": 3,
"selected": false,
"text": "<p>Here are a few articles describing how to call a web service from a class ASP page:</p>\n\n<ul>\n<li><a href=\"https://... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/160/"
] | I'd like to start moving our application business layers into a collection of REST web services. However, most of our Intranet has been built using Classic ASP and most of the developers where I work keep programming in Classic ASP. Ideally, then, for them to benefit from the advantages of a unique set of web APIs, it would have to be called from Classic ASP pages.
I haven't the slightest idea how to do that. | You could use a combination of JQuery with JSON calls to consume REST services from the client
or
if you need to interact with the REST services from the ASP layer you can use
MSXML2.ServerXMLHTTP
like:
```
Set HttpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")
HttpReq.open "GET", "Rest_URI", False
HttpReq.send
``` |
11,267 | <h1>Outline</h1>
<p>OK, I have Google'd this and already expecting a big fat <strong>NO!!</strong> But I thought I should ask since I know sometimes there can be the odd little gem of knowledge lurking around in peoples heads ^_^</p>
<p>I am working my way through some excercises in a book for study, and this particular exercise is User Controls. I have cobbled together a control and would like to set the DefaultEvent for it (having done this for previous controls) so when I double-click it, the default event created is whatever I specify it to be. </p>
<p><strong>NOTE:</strong> This is a standard User Control (.ascx), <em>NOT</em> a custom rendered control.</p>
<h2>Current Code</h2>
<p>Here is the class & event definition:</p>
<pre><code>[System.ComponentModel.DefaultEvent("OKClicked")]
public partial class AddressBox : System.Web.UI.UserControl
{
public event EventHandler OKClicked;
</code></pre>
<h2>Current Result</h2>
<p>Now, when I double click the the control when it is on a ASPX page, the following is created:</p>
<pre><code> protected void AddressBox1_Load(object sender, EventArgs e)
{
}
</code></pre>
<p>Not quite what I was expecting! So, my question:</p>
<h2>Is it possible to define a DefaultEvent for a UserControl? Is it a hack? If it's [not] supported, is there a reason?</h2>
<hr>
<p><strong>Side Note</strong>: How do we put underscores in code? I cant seem to put and escape char in?</p>
| [
{
"answer_id": 11271,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 4,
"selected": true,
"text": "<p>I think to be honest you a better just boning up on your standard design patterns and applying them to the individual prob... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | Outline
=======
OK, I have Google'd this and already expecting a big fat **NO!!** But I thought I should ask since I know sometimes there can be the odd little gem of knowledge lurking around in peoples heads ^\_^
I am working my way through some excercises in a book for study, and this particular exercise is User Controls. I have cobbled together a control and would like to set the DefaultEvent for it (having done this for previous controls) so when I double-click it, the default event created is whatever I specify it to be.
**NOTE:** This is a standard User Control (.ascx), *NOT* a custom rendered control.
Current Code
------------
Here is the class & event definition:
```
[System.ComponentModel.DefaultEvent("OKClicked")]
public partial class AddressBox : System.Web.UI.UserControl
{
public event EventHandler OKClicked;
```
Current Result
--------------
Now, when I double click the the control when it is on a ASPX page, the following is created:
```
protected void AddressBox1_Load(object sender, EventArgs e)
{
}
```
Not quite what I was expecting! So, my question:
Is it possible to define a DefaultEvent for a UserControl? Is it a hack? If it's [not] supported, is there a reason?
--------------------------------------------------------------------------------------------------------------------
---
**Side Note**: How do we put underscores in code? I cant seem to put and escape char in? | I think to be honest you a better just boning up on your standard design patterns and applying them to the individual problems that you face in developing your UI.
While there are common UI "themes" (such as dealing with modifier keys) the actual implementation may vary widely.
I have O'Reilly's [Head First Design Patterns](http://www.amazon.co.uk/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.co.uk%2FHead-First-Design-Patterns%2Fdp%2F0596007124%2Fref%3Dpd_bbs_sr_1%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1218730650%26sr%3D1-1&tag=robcthegeek-21&linkCode=ur2&camp=1634&creative=6738) and [The Poster](http://www.amazon.co.uk/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.co.uk%2FHead-First-Design-Patterns-Poster%2Fdp%2F0596102143%2Fref%3Dpd_bbs_sr_3%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1218730650%26sr%3D1-3&tag=robcthegeek-21&linkCode=ur2&camp=1634&creative=6738), which I have found invaluable!
### Shameless Plug : These links are using my associates ID. |
11,279 | <p>I have a small VB.NET application that I'm working on using the full version of Visual Studio 2005. In the <strong>Publish</strong> properties of the project, I have it set to <em>Automatically increment revision with each publish</em>.</p>
<p>The issue is that it's only incrementing the revision in the Setup files. It doesn't seem to be updating the version number in the About Box (which is the generic, built-in, About Box template). That version number seems to be coming from <em>My.Application.Info.Version</em>.</p>
<p>What should I be using instead so that my automatically incrementing revision number shows up in the about box?</p>
| [
{
"answer_id": 11284,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 0,
"selected": false,
"text": "<p>I'm no VB.NET expert, but have you tried to set the value to for example 1.0.0.*?\nThis should increase the revision... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | I have a small VB.NET application that I'm working on using the full version of Visual Studio 2005. In the **Publish** properties of the project, I have it set to *Automatically increment revision with each publish*.
The issue is that it's only incrementing the revision in the Setup files. It doesn't seem to be updating the version number in the About Box (which is the generic, built-in, About Box template). That version number seems to be coming from *My.Application.Info.Version*.
What should I be using instead so that my automatically incrementing revision number shows up in the about box? | Change the code for the About box to
```
Me.LabelVersion.Text = String.Format("Version {0}", My.Application.Deployment.CurrentVersion.ToString)
```
Please note that all the other answers are correct for "how do I get my assembly version", not the stated question "how do I show my publish version". |
11,288 | <p>So WPF doesn't support standard sorting or filtering behavior for views of CompositeCollections, so what would be a best practice for solving this problem. </p>
<p>There are two or more object collections of different types. You want to combine them into a single sortable and filterable collection (withing having to manually implement sort or filter).</p>
<p>One of the approaches I've considered is to create a new object collection with only a few core properties, including the ones that I would want the collection sorted on, and an object instance of each type. </p>
<pre><code>class MyCompositeObject
{
enum ObjectType;
DateTime CreatedDate;
string SomeAttribute;
myObjectType1 Obj1;
myObjectType2 Obj2;
{
class MyCompositeObjects : List<MyCompositeObject> { }
</code></pre>
<p>And then loop through my two object collections to build the new composite collection. Obviously this is a bit of a brute force method, but it would work. I'd get all the default view sorting and filtering behavior on my new composite object collection, and I'd be able to put a data template on it to display my list items properly depending on which type is actually stored in that composite item.</p>
<p>What suggestions are there for doing this in a more elegant way?</p>
| [
{
"answer_id": 11284,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 0,
"selected": false,
"text": "<p>I'm no VB.NET expert, but have you tried to set the value to for example 1.0.0.*?\nThis should increase the revision... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1346/"
] | So WPF doesn't support standard sorting or filtering behavior for views of CompositeCollections, so what would be a best practice for solving this problem.
There are two or more object collections of different types. You want to combine them into a single sortable and filterable collection (withing having to manually implement sort or filter).
One of the approaches I've considered is to create a new object collection with only a few core properties, including the ones that I would want the collection sorted on, and an object instance of each type.
```
class MyCompositeObject
{
enum ObjectType;
DateTime CreatedDate;
string SomeAttribute;
myObjectType1 Obj1;
myObjectType2 Obj2;
{
class MyCompositeObjects : List<MyCompositeObject> { }
```
And then loop through my two object collections to build the new composite collection. Obviously this is a bit of a brute force method, but it would work. I'd get all the default view sorting and filtering behavior on my new composite object collection, and I'd be able to put a data template on it to display my list items properly depending on which type is actually stored in that composite item.
What suggestions are there for doing this in a more elegant way? | Change the code for the About box to
```
Me.LabelVersion.Text = String.Format("Version {0}", My.Application.Deployment.CurrentVersion.ToString)
```
Please note that all the other answers are correct for "how do I get my assembly version", not the stated question "how do I show my publish version". |
11,291 | <p>I'm slowly learning Objective-C and Cocoa, and the only way I see so far to capture key events in Text Views is to use delegation, but I'm having trouble finding useful documentation and examples on how to implement such a solution. Can anyone point me in the right direction or supply some first-hand help? </p>
| [
{
"answer_id": 11312,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 5,
"selected": true,
"text": "<p>Generally, the way you implement it is simply to add the required function to your view's controller, and set its de... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344/"
] | I'm slowly learning Objective-C and Cocoa, and the only way I see so far to capture key events in Text Views is to use delegation, but I'm having trouble finding useful documentation and examples on how to implement such a solution. Can anyone point me in the right direction or supply some first-hand help? | Generally, the way you implement it is simply to add the required function to your view's controller, and set its delegate. For example, if you want code to run when the view loads, you just delegate your view to the controller, and implement the awakeFromNib function.
So, to detect a key press in a text view, make sure your controller is the text view's delegate, and then implement this:
```
- (void)keyUp:(NSEvent *)theEvent
```
Note that this is an inherited NSResponder method, not a NSTextView method. |
11,305 | <p>I work in VBA, and want to parse a string eg</p>
<pre><code><PointN xsi:type='typens:PointN'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<X>24.365</X>
<Y>78.63</Y>
</PointN>
</code></pre>
<p>and get the X & Y values into two separate integer variables.</p>
<p>I'm a newbie when it comes to XML, since I'm stuck in VB6 and VBA, because of the field I work in.</p>
<p>How do I do this?</p>
| [
{
"answer_id": 11325,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 7,
"selected": true,
"text": "<p>This is a bit of a complicated question, but it seems like the most direct route would be to load the XML document or XML str... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/895/"
] | I work in VBA, and want to parse a string eg
```
<PointN xsi:type='typens:PointN'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<X>24.365</X>
<Y>78.63</Y>
</PointN>
```
and get the X & Y values into two separate integer variables.
I'm a newbie when it comes to XML, since I'm stuck in VB6 and VBA, because of the field I work in.
How do I do this? | This is a bit of a complicated question, but it seems like the most direct route would be to load the XML document or XML string via MSXML2.DOMDocument which will then allow you to access the XML nodes.
You can find more on MSXML2.DOMDocument at the following sites:
* [Manipulating XML files with Excel VBA & Xpath](https://web.archive.org/web/20161217090033/http://en.allexperts.com/q/XML-1469/Manipulating-XML-files-Excel.htm)
* MSXML - <http://msdn.microsoft.com/en-us/library/ms763742(VS.85).aspx>
* [An Overview of MSXML 4.0](https://web.archive.org/web/20161030020427/http://www.xml.com:80/lpt/a/979) |
11,311 | <p>Is it possible to format certain text in a WinForm Label instead of breaking the text into multiple labels? Please disregard the HTML tags within the label's text; it's only used to get my point out.</p>
<p>For example:</p>
<pre><code>Dim myLabel As New Label
myLabel.Text = "This is <b>bold</b> text. This is <i>italicized</i> text."
</code></pre>
<p>Which would produce the text in the label as:</p>
<blockquote>
<p>This is <strong>bold</strong> text. This is
<em>italicized</em> text.</p>
</blockquote>
| [
{
"answer_id": 11320,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 1,
"selected": false,
"text": "<p>I Would also be interested in finding out if it is possible.</p>\n\n<p>When we couldn't find a solution we resorted to Compon... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299/"
] | Is it possible to format certain text in a WinForm Label instead of breaking the text into multiple labels? Please disregard the HTML tags within the label's text; it's only used to get my point out.
For example:
```
Dim myLabel As New Label
myLabel.Text = "This is <b>bold</b> text. This is <i>italicized</i> text."
```
Which would produce the text in the label as:
>
> This is **bold** text. This is
> *italicized* text.
>
>
> | That's not possible with a WinForms label as it is. The label has to have exactly one font, with exactly one size and one face. You have a couple of options:
1. Use separate labels
2. Create a new Control-derived class that does its own drawing via GDI+ and use that instead of Label; this is probably your best option, as it gives you complete control over how to instruct the control to format its text
3. Use a third-party label control that will let you insert HTML snippets (there are a bunch - check CodeProject); this would be someone else's implementation of #2. |
11,318 | <p>Imagine you want to animate some object on a WinForm. You setup a timer to update the state or model, and override the paint event of the Form. But from there, what's the best way to continually repaint the Form for the animation?</p>
<ul>
<li>Invalidate the Form as soon as you are done drawing?</li>
<li>Setup a second timer and invalidate the form on a regular interval?</li>
<li>Perhaps there is a common pattern for this thing?</li>
<li>Are there any useful .NET classes to help out?</li>
</ul>
<p>Each time I need to do this I discover a new method with a new drawback. What are the experiences and recommendations from the SO community?</p>
| [
{
"answer_id": 11329,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 2,
"selected": false,
"text": "<p>What you're doing is the only solution I've ever used in WinForms (a timer with constant redrawings). There are a b... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322/"
] | Imagine you want to animate some object on a WinForm. You setup a timer to update the state or model, and override the paint event of the Form. But from there, what's the best way to continually repaint the Form for the animation?
* Invalidate the Form as soon as you are done drawing?
* Setup a second timer and invalidate the form on a regular interval?
* Perhaps there is a common pattern for this thing?
* Are there any useful .NET classes to help out?
Each time I need to do this I discover a new method with a new drawback. What are the experiences and recommendations from the SO community? | In some situations, it's faster and more convenient to not draw using the paint event, but getting the Graphics object from the control/form and painting "on" that. This may give some troubles with opacity/anti aliasing/text etc, but could be worth the trouble in terms of not having to repaint the whole shabang. Something along the lines of:
```
private void AnimationTimer_Tick(object sender, EventArgs args)
{
// First paint background, like Clear(Control.Background), or by
// painting an image you have previously buffered that was the background.
animationControl.CreateGraphics().DrawImage(0, 0, animationImages[animationTick++]));
}
```
I use this in some Controls myself, and have buffered images to "clear" the background with, when the object of interest moves or need to be removed. |
11,330 | <p>Let's say I'm creating a chess program. I have a function</p>
<pre><code>void foreachMove( void (*action)(chess_move*), chess_game* game);
</code></pre>
<p>which will call the function pointer action on each valid move. This is all well and good, but what if I need to pass more parameters to the action function? For example:</p>
<pre><code>chess_move getNextMove(chess_game* game, int depth){
//for each valid move, determine how good the move is
foreachMove(moveHandler, game);
}
void moveHandler(chess_move* move){
//uh oh, now I need the variables "game" and "depth" from the above function
}
</code></pre>
<p>Redefining the function pointer is not the optimal solution. The foreachMove function is versatile and many different places in the code reference it. It doesn't make sense for each one of those references to have to update their function to include parameters that they don't need.</p>
<p>How can I pass extra parameters to a function that I'm calling through a pointer?</p>
| [
{
"answer_id": 11335,
"author": "Antonio Haley",
"author_id": 390,
"author_profile": "https://Stackoverflow.com/users/390",
"pm_score": 3,
"selected": false,
"text": "<p>You'd probably need to redefine the function pointer to take additional arguments.</p>\n\n<pre><code>void foreachMove(... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | Let's say I'm creating a chess program. I have a function
```
void foreachMove( void (*action)(chess_move*), chess_game* game);
```
which will call the function pointer action on each valid move. This is all well and good, but what if I need to pass more parameters to the action function? For example:
```
chess_move getNextMove(chess_game* game, int depth){
//for each valid move, determine how good the move is
foreachMove(moveHandler, game);
}
void moveHandler(chess_move* move){
//uh oh, now I need the variables "game" and "depth" from the above function
}
```
Redefining the function pointer is not the optimal solution. The foreachMove function is versatile and many different places in the code reference it. It doesn't make sense for each one of those references to have to update their function to include parameters that they don't need.
How can I pass extra parameters to a function that I'm calling through a pointer? | Ah, if only C supported closures...
Antonio is right; if you need to pass extra parameters, you'll need to redefine your function pointer to accept the additional arguments. If you don't know exactly what parameters you'll need, then you have at least three choices:
1. Have the last argument in your prototype be a void\*. This gives you flexibility of passing in anything else that you need, but it definitely isn't type-safe.
2. Use variadic parameters (...). Given my lack of experience with variadic parameters in C, I'm not sure if you can use this with a function pointer, but this gives even more flexibility than the first solution, albeit still with the lack of type safety.
3. Upgrade to C++ and use [function objects](http://en.wikipedia.org/wiki/Function_object). |
11,345 | <p>What is the story behind XPath and support for namespaces? Did XPath as a specification precede namespaces? If I have a document where elements have been given a default namespace: </p>
<pre><code><foo xmlns="uri" />
</code></pre>
<p>It appears as though some of the XPath processor libraries won't recognize <code>//foo</code> because of the namespace whereas others will. The option my team has thought about is to add a namespace prefix using regular expressions to the XPath (you can add a namespace prefix via XmlNameTable) but this seems brittle since XPath is such a flexible language when it comes to node tests.</p>
<p>Is there a standard that applies to this?</p>
<p>My approach is a bit hackish but it seems to work fine; I remove the <code>xmlns</code> declaration with a search/replace and then apply XPath.</p>
<pre><code>string readyForXpath = Regex.Replace(xmldocument, "xmlns=\".+\"", String.Empty );
</code></pre>
<p>Is that a fair approach or has anyone solved this differently?</p>
| [
{
"answer_id": 11351,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 4,
"selected": false,
"text": "<p>You need local-name():</p>\n<p><a href=\"http://www.w3.org/TR/xpath#function-local-name\" rel=\"nofollow noreferrer\">http://www... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64/"
] | What is the story behind XPath and support for namespaces? Did XPath as a specification precede namespaces? If I have a document where elements have been given a default namespace:
```
<foo xmlns="uri" />
```
It appears as though some of the XPath processor libraries won't recognize `//foo` because of the namespace whereas others will. The option my team has thought about is to add a namespace prefix using regular expressions to the XPath (you can add a namespace prefix via XmlNameTable) but this seems brittle since XPath is such a flexible language when it comes to node tests.
Is there a standard that applies to this?
My approach is a bit hackish but it seems to work fine; I remove the `xmlns` declaration with a search/replace and then apply XPath.
```
string readyForXpath = Regex.Replace(xmldocument, "xmlns=\".+\"", String.Empty );
```
Is that a fair approach or has anyone solved this differently? | I tried something similar to what palehorse proposed and could not get it to work. Since I was getting data from a published service I couldn't change the xml. I ended up using XmlDocument and XmlNamespaceManager like so:
```
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlWithBogusNamespace);
XmlNamespaceManager nSpace = new XmlNamespaceManager(doc.NameTable);
nSpace.AddNamespace("myNs", "http://theirUri");
XmlNodeList nodes = doc.SelectNodes("//myNs:NodesIWant",nSpace);
//etc
``` |
11,405 | <p>The following code doesn't compile with gcc, but does with Visual Studio:</p>
<pre><code>template <typename T> class A {
public:
T foo;
};
template <typename T> class B: public A <T> {
public:
void bar() { cout << foo << endl; }
};
</code></pre>
<p>I get the error:</p>
<blockquote>
<p>test.cpp: In member function ‘void B::bar()’:</p>
<p>test.cpp:11: error: ‘foo’ was not declared in this scope</p>
</blockquote>
<p>But it should be! If I change <code>bar</code> to</p>
<pre><code>void bar() { cout << this->foo << endl; }
</code></pre>
<p>then it <em>does</em> compile, but I don't think I have to do this. Is there something in the official specs of C++ that GCC is following here, or is it just a quirk?</p>
| [
{
"answer_id": 11414,
"author": "David Joyner",
"author_id": 1146,
"author_profile": "https://Stackoverflow.com/users/1146",
"pm_score": 5,
"selected": true,
"text": "<p>This changed in <a href=\"http://gcc.gnu.org/gcc-3.4/changes.html#cplusplus\" rel=\"noreferrer\">gcc-3.4</a>. The C++... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/112/"
] | The following code doesn't compile with gcc, but does with Visual Studio:
```
template <typename T> class A {
public:
T foo;
};
template <typename T> class B: public A <T> {
public:
void bar() { cout << foo << endl; }
};
```
I get the error:
>
> test.cpp: In member function ‘void B::bar()’:
>
>
> test.cpp:11: error: ‘foo’ was not declared in this scope
>
>
>
But it should be! If I change `bar` to
```
void bar() { cout << this->foo << endl; }
```
then it *does* compile, but I don't think I have to do this. Is there something in the official specs of C++ that GCC is following here, or is it just a quirk? | This changed in [gcc-3.4](http://gcc.gnu.org/gcc-3.4/changes.html#cplusplus). The C++ parser got much more strict in that release -- per the spec but still kinda annoying for people with legacy or multi-platform code bases. |
11,491 | <p>What is the best way people have found to do String to Lower case / Upper case in C++?</p>
<p>The issue is complicated by the fact that C++ isn't an English only programming language. Is there a good multilingual method?</p>
| [
{
"answer_id": 11502,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 6,
"selected": true,
"text": "<pre><code>#include <algorithm>\nstd::string data = \"Abc\";\nstd::transform(data.begin(), data.end(), data.begin(), ::t... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366/"
] | What is the best way people have found to do String to Lower case / Upper case in C++?
The issue is complicated by the fact that C++ isn't an English only programming language. Is there a good multilingual method? | ```
#include <algorithm>
std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(), ::toupper);
```
<http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/>
Also, CodeProject article for common string methods: <http://www.codeproject.com/KB/stl/STL_string_util.aspx> |
11,532 | <p>How can I find any unused functions in a PHP project?</p>
<p>Are there features or APIs built into PHP that will allow me to analyse my codebase - for example <a href="http://ie.php.net/manual/en/language.oop5.reflection.php" rel="noreferrer">Reflection</a>, <a href="http://php.net/manual/en/function.token-get-all.php" rel="noreferrer"><code>token_get_all()</code></a>?</p>
<p>Are these APIs feature rich enough for me not to have to rely on a third party tool to perform this type of analysis?</p>
| [
{
"answer_id": 14625,
"author": "Stacey Richards",
"author_id": 1142,
"author_profile": "https://Stackoverflow.com/users/1142",
"pm_score": 6,
"selected": true,
"text": "<p>Thanks Greg and Dave for the feedback. Wasn't quite what I was looking for, but I decided to put a bit of time into... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1142/"
] | How can I find any unused functions in a PHP project?
Are there features or APIs built into PHP that will allow me to analyse my codebase - for example [Reflection](http://ie.php.net/manual/en/language.oop5.reflection.php), [`token_get_all()`](http://php.net/manual/en/function.token-get-all.php)?
Are these APIs feature rich enough for me not to have to rely on a third party tool to perform this type of analysis? | Thanks Greg and Dave for the feedback. Wasn't quite what I was looking for, but I decided to put a bit of time into researching it and came up with this quick and dirty solution:
```
<?php
$functions = array();
$path = "/path/to/my/php/project";
define_dir($path, $functions);
reference_dir($path, $functions);
echo
"<table>" .
"<tr>" .
"<th>Name</th>" .
"<th>Defined</th>" .
"<th>Referenced</th>" .
"</tr>";
foreach ($functions as $name => $value) {
echo
"<tr>" .
"<td>" . htmlentities($name) . "</td>" .
"<td>" . (isset($value[0]) ? count($value[0]) : "-") . "</td>" .
"<td>" . (isset($value[1]) ? count($value[1]) : "-") . "</td>" .
"</tr>";
}
echo "</table>";
function define_dir($path, &$functions) {
if ($dir = opendir($path)) {
while (($file = readdir($dir)) !== false) {
if (substr($file, 0, 1) == ".") continue;
if (is_dir($path . "/" . $file)) {
define_dir($path . "/" . $file, $functions);
} else {
if (substr($file, - 4, 4) != ".php") continue;
define_file($path . "/" . $file, $functions);
}
}
}
}
function define_file($path, &$functions) {
$tokens = token_get_all(file_get_contents($path));
for ($i = 0; $i < count($tokens); $i++) {
$token = $tokens[$i];
if (is_array($token)) {
if ($token[0] != T_FUNCTION) continue;
$i++;
$token = $tokens[$i];
if ($token[0] != T_WHITESPACE) die("T_WHITESPACE");
$i++;
$token = $tokens[$i];
if ($token[0] != T_STRING) die("T_STRING");
$functions[$token[1]][0][] = array($path, $token[2]);
}
}
}
function reference_dir($path, &$functions) {
if ($dir = opendir($path)) {
while (($file = readdir($dir)) !== false) {
if (substr($file, 0, 1) == ".") continue;
if (is_dir($path . "/" . $file)) {
reference_dir($path . "/" . $file, $functions);
} else {
if (substr($file, - 4, 4) != ".php") continue;
reference_file($path . "/" . $file, $functions);
}
}
}
}
function reference_file($path, &$functions) {
$tokens = token_get_all(file_get_contents($path));
for ($i = 0; $i < count($tokens); $i++) {
$token = $tokens[$i];
if (is_array($token)) {
if ($token[0] != T_STRING) continue;
if ($tokens[$i + 1] != "(") continue;
$functions[$token[1]][1][] = array($path, $token[2]);
}
}
}
?>
```
I'll probably spend some more time on it so I can quickly find the files and line numbers of the function definitions and references; this information is being gathered, just not displayed. |
11,561 | <p>I've used Apache CXF to expose about ten java classes as web services.</p>
<p>I've generated clients using CXF, Axis, and .NET.</p>
<p>In Axis and CXF a "Service" or "Locator" is generated.
From this service you can get a "Port".
The "Port" is used to make individual calls to the methods exposed by the web service.</p>
<p>In .NET the "Service" directly exposes the calls to the web service.</p>
<p>Can someone explain the difference between a port, a service, a locator, and an endpoint when it comes to web services?</p>
<p>Axis:</p>
<pre><code>PatientServiceImplServiceLocator locator =
new PatientServiceImplServiceLocator();
PatientService service = locator.getPatientServiceImplPort();
</code></pre>
<p>CXF:</p>
<pre><code>PatientServiceImplService locator = new PatientServiceImplService();
PatientService service = locator.getPatientServiceImplPort();
</code></pre>
<p>.net:</p>
<pre><code>PatientServiceImplService service = new PatientServiceImplService();
</code></pre>
| [
{
"answer_id": 11567,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 1,
"selected": false,
"text": "<p>As you already mentioned, those terms mean different things in different stacks - there is no one right generic answer fo... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
] | I've used Apache CXF to expose about ten java classes as web services.
I've generated clients using CXF, Axis, and .NET.
In Axis and CXF a "Service" or "Locator" is generated.
From this service you can get a "Port".
The "Port" is used to make individual calls to the methods exposed by the web service.
In .NET the "Service" directly exposes the calls to the web service.
Can someone explain the difference between a port, a service, a locator, and an endpoint when it comes to web services?
Axis:
```
PatientServiceImplServiceLocator locator =
new PatientServiceImplServiceLocator();
PatientService service = locator.getPatientServiceImplPort();
```
CXF:
```
PatientServiceImplService locator = new PatientServiceImplService();
PatientService service = locator.getPatientServiceImplPort();
```
.net:
```
PatientServiceImplService service = new PatientServiceImplService();
``` | I'd hop over to <http://www.w3.org/TR/wsdl.html> which I think explains Port, Service and Endpoint reasonably well. A locator is an implementation specific mechanism that some WS stacks use to provide access to service endpoints. |
11,562 | <p><code>std::swap()</code> is used by many std containers (such as <code>std::list</code> and <code>std::vector</code>) during sorting and even assignment.</p>
<p>But the std implementation of <code>swap()</code> is very generalized and rather inefficient for custom types.</p>
<p>Thus efficiency can be gained by overloading <code>std::swap()</code> with a custom type specific implementation. But how can you implement it so it will be used by the std containers?</p>
| [
{
"answer_id": 11599,
"author": "Wilka",
"author_id": 1367,
"author_profile": "https://Stackoverflow.com/users/1367",
"pm_score": 6,
"selected": false,
"text": "<p>You're not allowed (by the C++ standard) to overload std::swap, however you are specifically allowed to add template special... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366/"
] | `std::swap()` is used by many std containers (such as `std::list` and `std::vector`) during sorting and even assignment.
But the std implementation of `swap()` is very generalized and rather inefficient for custom types.
Thus efficiency can be gained by overloading `std::swap()` with a custom type specific implementation. But how can you implement it so it will be used by the std containers? | The right way to overload `std::swap`'s implemention (aka specializing it), is to write it in the same namespace as what you're swapping, so that it can be found via [argument-dependent lookup (ADL)](https://en.cppreference.com/w/cpp/language/adl). One particularly easy thing to do is:
```
class X
{
// ...
friend void swap(X& a, X& b)
{
using std::swap; // bring in swap for built-in types
swap(a.base1, b.base1);
swap(a.base2, b.base2);
// ...
swap(a.member1, b.member1);
swap(a.member2, b.member2);
// ...
}
};
``` |
11,574 | <p>I have an AppleScript program which creates XML tags and elements within an Adobe InDesign document. The data is in tables, and tagging each cell takes .5 seconds. The entire script takes several hours to complete.</p>
<p>I can post the inner loop code, but I'm not sure if SO is supposed to be generic or specific. I'll let the mob decide.</p>
<p>[edit]
The code builds a list (prior to this loop) which contains one item per row in the table. There is also a list containing one string for each column in the table. For each cell, the program creates an XML element and an XML tag by concatenating the items in the [row]/[column] positions of the two lists. It also associates the text in that cell to the newly-created element.</p>
<p>I'm completely new to AppleScript so some of this code is crudely modified from Adobe's samples. If the code is atrocious I won't be offended.</p>
<p>Here's the code:</p>
<pre><code>repeat with columnNumber from COL_START to COL_END
select text of cell ((columnNumber as string) & ":" & (rowNumber as string)) of ThisTable
tell activeDocument
set thisXmlTag to make XML tag with properties {name:item rowNumber of symbolList & "_" & item columnNumber of my histLabelList}
tell rootXmlElement
set thisXmlElement to make XML element with properties {markup tag:thisXmlTag}
end tell
set contents of thisXmlElement to (selection as string)
end tell
end repeat
</code></pre>
<p>EDIT: I've rephrased the question to better reflect the correct answer.</p>
| [
{
"answer_id": 11580,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>I can post the inner loop code, but I'm not sure if SO is supposed to be generic or specific. I'll let th... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1019/"
] | I have an AppleScript program which creates XML tags and elements within an Adobe InDesign document. The data is in tables, and tagging each cell takes .5 seconds. The entire script takes several hours to complete.
I can post the inner loop code, but I'm not sure if SO is supposed to be generic or specific. I'll let the mob decide.
[edit]
The code builds a list (prior to this loop) which contains one item per row in the table. There is also a list containing one string for each column in the table. For each cell, the program creates an XML element and an XML tag by concatenating the items in the [row]/[column] positions of the two lists. It also associates the text in that cell to the newly-created element.
I'm completely new to AppleScript so some of this code is crudely modified from Adobe's samples. If the code is atrocious I won't be offended.
Here's the code:
```
repeat with columnNumber from COL_START to COL_END
select text of cell ((columnNumber as string) & ":" & (rowNumber as string)) of ThisTable
tell activeDocument
set thisXmlTag to make XML tag with properties {name:item rowNumber of symbolList & "_" & item columnNumber of my histLabelList}
tell rootXmlElement
set thisXmlElement to make XML element with properties {markup tag:thisXmlTag}
end tell
set contents of thisXmlElement to (selection as string)
end tell
end repeat
```
EDIT: I've rephrased the question to better reflect the correct answer. | I figured this one out.
The document contains a bunch of data tables. In all, there are about 7,000 data points that need to be exported. I was creating one root element with 7,000 children.
Don't do that. Adding each child to the root element got slower and slower until at about 5,000 children AppleScript timed out and the program aborted.
The solution was to make my code more brittle by creating ~480 children off the root, with each child having about 16 grandchildren. Same number of nodes, but the code now runs fast enough. (It still takes about 40 minutes to process the document, but that's infinitely less time than infinity.)
Incidentally, the original 7,000 children plan wasn't as stupid or as lazy as it appears. The new solution is forcing me to link the two tables together using data in the tables that I don't control. The program will now break if there's so much as a space where there shouldn't be one. (But it works.) |
11,585 | <p>For my blog I am wanting to use the Output Cache to save a cached version of a perticular post for around 10 minutes, and thats fine...</p>
<pre><code><%@OutputCache Duration="600" VaryByParam="*" %>
</code></pre>
<p>However, if someone posts a comment, I want to clear the cache so that the page is refreshed and the comment can be seen.</p>
<p>How do I do this in ASP.Net C#?</p>
| [
{
"answer_id": 11611,
"author": "John Christensen",
"author_id": 1194,
"author_profile": "https://Stackoverflow.com/users/1194",
"pm_score": 1,
"selected": false,
"text": "<p>Hmm. You can specify a VaryByCustom attribute on the OutputCache item. The value of this is passed as a parameter... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | For my blog I am wanting to use the Output Cache to save a cached version of a perticular post for around 10 minutes, and thats fine...
```
<%@OutputCache Duration="600" VaryByParam="*" %>
```
However, if someone posts a comment, I want to clear the cache so that the page is refreshed and the comment can be seen.
How do I do this in ASP.Net C#? | I've found the answer I was looking for:
```
HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx");
``` |
11,620 | <p>I want to rename a database, but keep getting the error that 'couldn't get exclusive lock' on the database, which implies there is some connection(s) still active.</p>
<p>How can I kill all the connections to the database so that I can rename it?</p>
| [
{
"answer_id": 11623,
"author": "John Christensen",
"author_id": 1194,
"author_profile": "https://Stackoverflow.com/users/1194",
"pm_score": 2,
"selected": false,
"text": "<p>In MS SQL Server Management Studio on the object explorer, right click on the database. In the context menu that ... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341/"
] | I want to rename a database, but keep getting the error that 'couldn't get exclusive lock' on the database, which implies there is some connection(s) still active.
How can I kill all the connections to the database so that I can rename it? | The reason that the approach that [Adam suggested](https://stackoverflow.com/questions/11620/how-do-you-kill-all-current-connections-to-a-sql-server-2005-database/11627#11627) won't work is that during the time that you are looping over the active connections new one can be established, and you'll miss those. You could instead use the following approach which does not have this drawback:
```
-- set your current connection to use master otherwise you might get an error
use master
ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE
--do you stuff here
ALTER DATABASE YourDatabase SET MULTI_USER
``` |
11,635 | <p>What is the best way of doing case-insensitive string comparison in C++ without transforming a string to all uppercase or all lowercase?</p>
<p>Please indicate whether the methods are Unicode-friendly and how portable they are.</p>
| [
{
"answer_id": 11653,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming you are looking for a method and not a magic function that already exists, there is frankly no better way. W... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366/"
] | What is the best way of doing case-insensitive string comparison in C++ without transforming a string to all uppercase or all lowercase?
Please indicate whether the methods are Unicode-friendly and how portable they are. | Boost includes a handy algorithm for this:
```
#include <boost/algorithm/string.hpp>
// Or, for fewer header dependencies:
//#include <boost/algorithm/string/predicate.hpp>
std::string str1 = "hello, world!";
std::string str2 = "HELLO, WORLD!";
if (boost::iequals(str1, str2))
{
// Strings are identical
}
``` |
11,665 | <p>Here is the sample code for my accordion:</p>
<pre><code><mx:Accordion x="15" y="15" width="230" height="599" styleName="myAccordion">
<mx:Canvas id="pnlSpotlight" label="SPOTLIGHT" height="100%" width="100%" horizontalScrollPolicy="off">
<mx:VBox width="100%" height="80%" paddingTop="2" paddingBottom="1" verticalGap="1">
<mx:Repeater id="rptrSpotlight" dataProvider="{aSpotlight}">
<sm:SmallCourseListItem
viewClick="PlayFile(event.currentTarget.getRepeaterItem().fileID);"
Description="{rptrSpotlight.currentItem.fileDescription}"
FileID = "{rptrSpotlight.currentItem.fileID}"
detailsClick="{detailsView.SetFile(event.currentTarget.getRepeaterItem().fileID,this)}"
Title="{rptrSpotlight.currentItem.fileTitle}"
FileIcon="{iconLibrary.getIcon(rptrSpotlight.currentItem.fileExtension)}" />
</mx:Repeater>
</mx:VBox>
</mx:Canvas>
</mx:Accordion>
</code></pre>
<p>I would like to include a button in each header like so:</p>
<p><img src="https://i.stack.imgur.com/EN3kP.jpg" alt="wishful" onclick="alert('xss')"></p>
| [
{
"answer_id": 12266,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 1,
"selected": false,
"text": "<p>You will have to create a custom header renderer, add a button to it and position it manually. Try something like this:</p>\n... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] | Here is the sample code for my accordion:
```
<mx:Accordion x="15" y="15" width="230" height="599" styleName="myAccordion">
<mx:Canvas id="pnlSpotlight" label="SPOTLIGHT" height="100%" width="100%" horizontalScrollPolicy="off">
<mx:VBox width="100%" height="80%" paddingTop="2" paddingBottom="1" verticalGap="1">
<mx:Repeater id="rptrSpotlight" dataProvider="{aSpotlight}">
<sm:SmallCourseListItem
viewClick="PlayFile(event.currentTarget.getRepeaterItem().fileID);"
Description="{rptrSpotlight.currentItem.fileDescription}"
FileID = "{rptrSpotlight.currentItem.fileID}"
detailsClick="{detailsView.SetFile(event.currentTarget.getRepeaterItem().fileID,this)}"
Title="{rptrSpotlight.currentItem.fileTitle}"
FileIcon="{iconLibrary.getIcon(rptrSpotlight.currentItem.fileExtension)}" />
</mx:Repeater>
</mx:VBox>
</mx:Canvas>
</mx:Accordion>
```
I would like to include a button in each header like so:
 | Thanks, I got it working using [FlexLib](http://code.google.com/p/flexlib/)'s CanvasButtonAccordionHeader. |
11,689 | <p>I am intentionally leaving this quite vague at first. I'm looking for discussion and what issues are important more than I'm looking for hard answers.</p>
<p>I'm in the middle of designing an app that does something like portfolio management. The design I have so far is</p>
<ul>
<li>Problem: a problem that needs to be solved</li>
<li>Solution: a proposed solution to one or more problems</li>
<li>Relationship: a relationship among two problems, two solutions, or a problem and a solution. Further broken down into:
<ul>
<li>Parent-child - some sort of categorization / tree hierarchy</li>
<li>Overlap - the degree to which two solutions or two problems really address the same concept</li>
<li>Addresses - the degree to which a problem addresses a solution</li>
</ul></li>
</ul>
<p>My question is about the temporal nature of these things. Problems crop up, then fade. Solutions have an expected resolution date, but that might be modified as they are developed. The degree of a relationship might change over time as problems and solutions evolve.</p>
<p>So, the question: what is the best design for versioning of these things so I can get both a current and an historical perspective of my portfolio?</p>
<p><em>Later: perhaps I should make this a more specific question, though @Eric Beard's answer is worth an up.</em></p>
<p>I've considered three database designs. I'll enough of each to show their drawbacks. My question is: which to pick, or can you think of something better?</p>
<h2>1: Problems (and separately, Solutions) are self-referential in versioning.</h2>
<pre><code>table problems
int id | string name | text description | datetime created_at | int previous_version_id
foreign key previous_version_id -> problems.id
</code></pre>
<p>This is problematic because every time I want a new version, I have to duplicate the entire row, including that long <code>description</code> column.</p>
<h2>2: Create a new Relationship type: Version.</h2>
<pre><code>table problems
int id | string name | text description | datetime created_at
</code></pre>
<p>This simply moves the relationship from the Problems and Solutions tables into the Relationships table. Same duplication problem, but perhaps a little "cleaner" since I already have an abstract Relationship concept.</p>
<h2>3: Use a more Subversion-like structure; move all Problem and Solution attributes into a separate table and version them.</h2>
<pre><code>table problems
int id
table attributes
int id | int thing_id | string thing_type | string name | string value | datetime created_at | int previous_version_id
foreign key (thing_id, thing_type) -> problems.id or solutions.id
foreign key previous_version_id -> attributes.id
</code></pre>
<p>This means that to load the current version of a Problem or Solution I have to fetch all versions of the attribute, sort them by date and then use the most current. That might not be terrible. What seems really bad to me is that I can't type-check these attributes in the database. That <code>value</code> column has to be free-text. I can make the <code>name</code> column a reference into a separate <code>attribute_names</code> table that has a <code>type</code> column, but that doesn't <em>force</em> the correct type in the <code>attributes</code> table.</p>
<p><em>later still: response to @Eric Beard's comments about multi-table foreign keys:</em></p>
<p>Alas, what I've described is simplistic: there are only two types of Things (Problems and Solutions). I actually have about 9 or 10 different types of Things, so I'd have 9 or 10 columns of foreign keys under your strategy. I wanted to use single-table inheritance, but the Things have so little in common that it would be <em>extremely</em> wasteful to do combine them into one table.</p>
| [
{
"answer_id": 11694,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 2,
"selected": true,
"text": "<p>Hmm, sounds kind of like this site...</p>\n\n<p>As far as a database design would go, a versioning system kind of like... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] | I am intentionally leaving this quite vague at first. I'm looking for discussion and what issues are important more than I'm looking for hard answers.
I'm in the middle of designing an app that does something like portfolio management. The design I have so far is
* Problem: a problem that needs to be solved
* Solution: a proposed solution to one or more problems
* Relationship: a relationship among two problems, two solutions, or a problem and a solution. Further broken down into:
+ Parent-child - some sort of categorization / tree hierarchy
+ Overlap - the degree to which two solutions or two problems really address the same concept
+ Addresses - the degree to which a problem addresses a solution
My question is about the temporal nature of these things. Problems crop up, then fade. Solutions have an expected resolution date, but that might be modified as they are developed. The degree of a relationship might change over time as problems and solutions evolve.
So, the question: what is the best design for versioning of these things so I can get both a current and an historical perspective of my portfolio?
*Later: perhaps I should make this a more specific question, though @Eric Beard's answer is worth an up.*
I've considered three database designs. I'll enough of each to show their drawbacks. My question is: which to pick, or can you think of something better?
1: Problems (and separately, Solutions) are self-referential in versioning.
---------------------------------------------------------------------------
```
table problems
int id | string name | text description | datetime created_at | int previous_version_id
foreign key previous_version_id -> problems.id
```
This is problematic because every time I want a new version, I have to duplicate the entire row, including that long `description` column.
2: Create a new Relationship type: Version.
-------------------------------------------
```
table problems
int id | string name | text description | datetime created_at
```
This simply moves the relationship from the Problems and Solutions tables into the Relationships table. Same duplication problem, but perhaps a little "cleaner" since I already have an abstract Relationship concept.
3: Use a more Subversion-like structure; move all Problem and Solution attributes into a separate table and version them.
-------------------------------------------------------------------------------------------------------------------------
```
table problems
int id
table attributes
int id | int thing_id | string thing_type | string name | string value | datetime created_at | int previous_version_id
foreign key (thing_id, thing_type) -> problems.id or solutions.id
foreign key previous_version_id -> attributes.id
```
This means that to load the current version of a Problem or Solution I have to fetch all versions of the attribute, sort them by date and then use the most current. That might not be terrible. What seems really bad to me is that I can't type-check these attributes in the database. That `value` column has to be free-text. I can make the `name` column a reference into a separate `attribute_names` table that has a `type` column, but that doesn't *force* the correct type in the `attributes` table.
*later still: response to @Eric Beard's comments about multi-table foreign keys:*
Alas, what I've described is simplistic: there are only two types of Things (Problems and Solutions). I actually have about 9 or 10 different types of Things, so I'd have 9 or 10 columns of foreign keys under your strategy. I wanted to use single-table inheritance, but the Things have so little in common that it would be *extremely* wasteful to do combine them into one table. | Hmm, sounds kind of like this site...
As far as a database design would go, a versioning system kind of like SVN, where you never actually do any updates, just inserts (with a version number) when things change, might be what you need. This is called MVCC, Multi-Value Concurrency Control. A wiki is another good example of this. |
11,699 | <p>I'm getting notifications to back up my encryption key for EFS in Vista, however i haven't enabled bit locker or drive encryption.</p>
<p>Anyone know how to find out what files may be encrypted or have an explanation for why it would notify me?</p>
| [
{
"answer_id": 11709,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "<p>Clippy noticed that you have sensitive information in your files and automatically encrypted them.</p>\n\n<p>Are you sure ... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] | I'm getting notifications to back up my encryption key for EFS in Vista, however i haven't enabled bit locker or drive encryption.
Anyone know how to find out what files may be encrypted or have an explanation for why it would notify me? | To find out which files on your system have been encrypted with EFS, you can simply run this command:
```
CIPHER.EXE /U /N
``` |
11,720 | <p>What I would like to do is create a clean virtual machine image as the output of a build of an application.</p>
<p>So a new virtual machine would be created (from a template is fine, with the OS installed, and some base software installed) --- a new web site would be created in IIS, and the web app build output copied to a location on the virtual machine hard disk, and IIS configured correctly, the VM would start up and run.</p>
<p>I know there are MSBuild tasks to script all the administrative actions in IIS, but how do you script all the actions with Virtual machines? Specifically, creating a new virtual machine from a template, naming it uniquely, starting it, configuring it, etc...</p>
<p>Specifically I was wondering if anyone has successfully implemented any VM scripting as part of a build process.</p>
<p>Update: I assume with Hyper-V, there is a different set of libraries/APIs to script virtual machines, anyone played around with this? And anyone with real practical experience of doing something like this?</p>
| [
{
"answer_id": 11709,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "<p>Clippy noticed that you have sensitive information in your files and automatically encrypted them.</p>\n\n<p>Are you sure ... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341/"
] | What I would like to do is create a clean virtual machine image as the output of a build of an application.
So a new virtual machine would be created (from a template is fine, with the OS installed, and some base software installed) --- a new web site would be created in IIS, and the web app build output copied to a location on the virtual machine hard disk, and IIS configured correctly, the VM would start up and run.
I know there are MSBuild tasks to script all the administrative actions in IIS, but how do you script all the actions with Virtual machines? Specifically, creating a new virtual machine from a template, naming it uniquely, starting it, configuring it, etc...
Specifically I was wondering if anyone has successfully implemented any VM scripting as part of a build process.
Update: I assume with Hyper-V, there is a different set of libraries/APIs to script virtual machines, anyone played around with this? And anyone with real practical experience of doing something like this? | To find out which files on your system have been encrypted with EFS, you can simply run this command:
```
CIPHER.EXE /U /N
``` |
11,761 | <p>I have a web service that queries data from this json file, but I don't want the web service to have to access the file every time. I'm thinking that maybe I can store the data somewhere else (maybe in memory) so the web service can just get the data from there the next time it's trying to query the same data. I kinda understand what needs to be done but I'm just not sure how to actually do it. How do we persist data in a web service? </p>
<p><strong>Update:</strong>
Both suggestions, caching and using static variables, look good. Maybe I should just use both so I can look at one first, and if it's not in there, use the second one, if it's not in there either, then I'll look at the json file.</p>
| [
{
"answer_id": 11779,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>ASP.NET caching works just as well with Web services so you can implement regular caching as explained here: <a href=\"http:... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1381/"
] | I have a web service that queries data from this json file, but I don't want the web service to have to access the file every time. I'm thinking that maybe I can store the data somewhere else (maybe in memory) so the web service can just get the data from there the next time it's trying to query the same data. I kinda understand what needs to be done but I'm just not sure how to actually do it. How do we persist data in a web service?
**Update:**
Both suggestions, caching and using static variables, look good. Maybe I should just use both so I can look at one first, and if it's not in there, use the second one, if it's not in there either, then I'll look at the json file. | Extending on [Ice^^Heat](https://stackoverflow.com/questions/11761/persisting-data-in-net-web-service-memory#11779)'s idea, you might want to think about where you would cache - either cache the contents of the json file in the Application cache like so:
```
Context.Cache.Insert("foo", _
Foo, _
Nothing, _
DateAdd(DateInterval.Minute, 30, Now()), _
System.Web.Caching.Cache.NoSlidingExpiration)
```
And then generate the results you need from that on every hit. Alternatively you can cache the webservice output on the function definition:
```
<WebMethod(CacheDuration:=60)> _
Public Function HelloWorld() As String
Return "Hello World"
End Function
```
Info gathered from [XML Web Service Caching Strategies](http://msdn.microsoft.com/en-us/library/aa480499.aspx). |
11,762 | <p>I needed some simple string encryption, so I wrote the following code (with a great deal of "inspiration" from <a href="http://www.codeproject.com/KB/security/DotNetCrypto.aspx" rel="noreferrer">here</a>):</p>
<pre><code> // create and initialize a crypto algorithm
private static SymmetricAlgorithm getAlgorithm(string password) {
SymmetricAlgorithm algorithm = Rijndael.Create();
Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(
password, new byte[] {
0x53,0x6f,0x64,0x69,0x75,0x6d,0x20, // salty goodness
0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65
}
);
algorithm.Padding = PaddingMode.ISO10126;
algorithm.Key = rdb.GetBytes(32);
algorithm.IV = rdb.GetBytes(16);
return algorithm;
}
/*
* encryptString
* provides simple encryption of a string, with a given password
*/
public static string encryptString(string clearText, string password) {
SymmetricAlgorithm algorithm = getAlgorithm(password);
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
/*
* decryptString
* provides simple decryption of a string, with a given password
*/
public static string decryptString(string cipherText, string password) {
SymmetricAlgorithm algorithm = getAlgorithm(password);
byte[] cipherBytes = Convert.FromBase64String(cipherText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
return System.Text.Encoding.Unicode.GetString(ms.ToArray());
}
</code></pre>
<p>The code appears to work fine, except that when decrypting data with an incorrect key, I get a CryptographicException - "Padding is invalid and cannot be removed" - on the cs.Close() line in decryptString. </p>
<p>example code:</p>
<pre><code> string password1 = "password";
string password2 = "letmein";
string startClearText = "The quick brown fox jumps over the lazy dog";
string cipherText = encryptString(startClearText, password1);
string endClearText = decryptString(cipherText, password2); // exception thrown
</code></pre>
<p>My question is, is this to be expected? I would have thought that decrypting with the wrong password would just result in nonsense output, rather than an exception.</p>
| [
{
"answer_id": 11776,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, this is to be expected, or at least, its exactly what happens when our crypto routines get non-decryptable data</... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
] | I needed some simple string encryption, so I wrote the following code (with a great deal of "inspiration" from [here](http://www.codeproject.com/KB/security/DotNetCrypto.aspx)):
```
// create and initialize a crypto algorithm
private static SymmetricAlgorithm getAlgorithm(string password) {
SymmetricAlgorithm algorithm = Rijndael.Create();
Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(
password, new byte[] {
0x53,0x6f,0x64,0x69,0x75,0x6d,0x20, // salty goodness
0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65
}
);
algorithm.Padding = PaddingMode.ISO10126;
algorithm.Key = rdb.GetBytes(32);
algorithm.IV = rdb.GetBytes(16);
return algorithm;
}
/*
* encryptString
* provides simple encryption of a string, with a given password
*/
public static string encryptString(string clearText, string password) {
SymmetricAlgorithm algorithm = getAlgorithm(password);
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
/*
* decryptString
* provides simple decryption of a string, with a given password
*/
public static string decryptString(string cipherText, string password) {
SymmetricAlgorithm algorithm = getAlgorithm(password);
byte[] cipherBytes = Convert.FromBase64String(cipherText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
return System.Text.Encoding.Unicode.GetString(ms.ToArray());
}
```
The code appears to work fine, except that when decrypting data with an incorrect key, I get a CryptographicException - "Padding is invalid and cannot be removed" - on the cs.Close() line in decryptString.
example code:
```
string password1 = "password";
string password2 = "letmein";
string startClearText = "The quick brown fox jumps over the lazy dog";
string cipherText = encryptString(startClearText, password1);
string endClearText = decryptString(cipherText, password2); // exception thrown
```
My question is, is this to be expected? I would have thought that decrypting with the wrong password would just result in nonsense output, rather than an exception. | Although this have been already answered I think it would be a good idea to explain **why** it is to be expected.
A padding scheme is usually applied because most cryptographic filters are not semantically secure and to prevent some forms of cryptoatacks. For example, usually in RSA the [OAEP](http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding) padding scheme is used which prevents some sorts of attacks (such as a chosen plaintext attack or [blinding](http://en.wikipedia.org/wiki/Blinding_(cryptography))).
A padding scheme appends some (usually) random garbage to the message m before the message is sent. In the OAEP method, for example, two Oracles are used (this is a simplistic explanation):
1. Given the size of the modulus you padd k1 bits with 0 and k0 bits with a random number.
2. Then by applying some transformation to the message you obtain the padded message wich is encrypted and sent.
That provides you with a randomization for the messages and with a way to test if the message is garbage or not. As the padding scheme is reversible, when you decrypt the message whereas you can't say anything about the integrity of the message itself you can, in fact, make some assertion about the padding and thus you can know if the message has been correctly decrypted or you're doing something wrong (i.e someone has tampered with the message or you're using the wrong key) |
11,806 | <p>I'm trying to run powershell commands through a web interface (ASP.NET/C#) in order to create mailboxes/etc on Exchange 2007. When I run the page using Visual Studio (Cassini), the page loads up correctly. However, when I run it on IIS (v5.1), I get the error "unknown user name or bad password". The biggest problem that I noticed was that Powershell was logged in as ASPNET instead of my Active Directory Account. How do I force my Powershell session to be authenticated with another Active Directory Account?</p>
<p>Basically, the script that I have so far looks something like this:</p>
<pre><code>RunspaceConfiguration rc = RunspaceConfiguration.Create();
PSSnapInException snapEx = null;
rc.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapEx);
Runspace runspace = RunspaceFactory.CreateRunspace(rc);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
using (pipeline)
{
pipeline.Commands.AddScript("Get-Mailbox -identity 'user.name'");
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
if (pipeline.Error != null && pipeline.Error.Count > 0)
{
foreach (object item in pipeline.Error.ReadToEnd())
resultString += "Error: " + item.ToString() + "\n";
}
runspace.Close();
foreach (PSObject obj in results)
resultString += obj.ToString();
}
return resultString;
</code></pre>
| [
{
"answer_id": 11811,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 2,
"selected": false,
"text": "<p>In your ASP.NET app, you will need to impersonate a valid AD account with the correct permissions:</p>\n\n<p><a href=\"http://su... | 2008/08/15 | [
"https://Stackoverflow.com/questions/11806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] | I'm trying to run powershell commands through a web interface (ASP.NET/C#) in order to create mailboxes/etc on Exchange 2007. When I run the page using Visual Studio (Cassini), the page loads up correctly. However, when I run it on IIS (v5.1), I get the error "unknown user name or bad password". The biggest problem that I noticed was that Powershell was logged in as ASPNET instead of my Active Directory Account. How do I force my Powershell session to be authenticated with another Active Directory Account?
Basically, the script that I have so far looks something like this:
```
RunspaceConfiguration rc = RunspaceConfiguration.Create();
PSSnapInException snapEx = null;
rc.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapEx);
Runspace runspace = RunspaceFactory.CreateRunspace(rc);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
using (pipeline)
{
pipeline.Commands.AddScript("Get-Mailbox -identity 'user.name'");
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
if (pipeline.Error != null && pipeline.Error.Count > 0)
{
foreach (object item in pipeline.Error.ReadToEnd())
resultString += "Error: " + item.ToString() + "\n";
}
runspace.Close();
foreach (PSObject obj in results)
resultString += obj.ToString();
}
return resultString;
``` | Exchange 2007 doesn't allow you to impersonate a user for security reasons. This means that it is impossible (at the moment) to create mailboxes by impersonating a user. In order to get around this problem, I created a web service which runs under AD user which has permissions to create email acounts, etc. You can then access this webservice to get access to powershell. Please remember to add the necessary security because this could potentially be a huge security hole. |
11,809 | <p>The only thing I've found has been;</p>
<pre class="lang-css prettyprint-override"><code>.hang {
text-indent: -3em;
margin-left: 3em;
}
</code></pre>
<p>The only way for this to work is putting text in a paragraph, which causes those horribly unsightly extra lines. I'd much rather just have them in a <code><span class="hang"></span></code> type of thing.</p>
<p>I'm also looking for a way to further indent than just a single-level of hanging. Using paragraphs to stack the indentions doesn't work.</p>
| [
{
"answer_id": 11815,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": true,
"text": "<p><code><span></code> is an inline element. The term <em>hanging indent</em> is meaningless unless you're talking about a p... | 2008/08/15 | [
"https://Stackoverflow.com/questions/11809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/362/"
] | The only thing I've found has been;
```css
.hang {
text-indent: -3em;
margin-left: 3em;
}
```
The only way for this to work is putting text in a paragraph, which causes those horribly unsightly extra lines. I'd much rather just have them in a `<span class="hang"></span>` type of thing.
I'm also looking for a way to further indent than just a single-level of hanging. Using paragraphs to stack the indentions doesn't work. | `<span>` is an inline element. The term *hanging indent* is meaningless unless you're talking about a paragraph (which generally means a block element). You can, of course, change the margins on `<p>` or `<div>` or any other block element to get rid of extra vertical space between paragraphs.
You may want something like `display: run-in`, where the tag will become either block or inline depending on context... sadly, this is [not yet universally supported by browsers](http://quirksmode.org/css/css2/display.html). |
11,820 | <p>This <a href="https://stackoverflow.com/questions/11782/file-uploads-via-web-services">question and answer</a> shows how to send a file as a byte array through an XML web service. How much overhead is generated by using this method for file transfer? I assume the data looks something like this:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<bytes>
<byte>16</byte>
<byte>28</byte>
<byte>127</byte>
...
</bytes>
</code></pre>
<p>If this format is correct, the bytes must first be converted to UTF-8 characters. Each of these characters allocates 8 bytes. Are the bytes stored in base 10, hex, or binary characters? How much larger does the file appear as it is being sent due to the XML data and character encoding? Is compression built into web services?</p>
| [
{
"answer_id": 11830,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 0,
"selected": false,
"text": "<p>I use this method for some internal corporate webservices, and I haven't noticed any major slow-downs (but that doesn't ... | 2008/08/15 | [
"https://Stackoverflow.com/questions/11820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] | This [question and answer](https://stackoverflow.com/questions/11782/file-uploads-via-web-services) shows how to send a file as a byte array through an XML web service. How much overhead is generated by using this method for file transfer? I assume the data looks something like this:
```
<?xml version="1.0" encoding="UTF-8" ?>
<bytes>
<byte>16</byte>
<byte>28</byte>
<byte>127</byte>
...
</bytes>
```
If this format is correct, the bytes must first be converted to UTF-8 characters. Each of these characters allocates 8 bytes. Are the bytes stored in base 10, hex, or binary characters? How much larger does the file appear as it is being sent due to the XML data and character encoding? Is compression built into web services? | Typically a byte array is sent as a `base64` encoded string, not as individual bytes in tags.
<http://en.wikipedia.org/wiki/Base64>
The `base64` encoded version is about **137%** of the size of the original content. |
11,854 | <p>In a project our team is using object lists to perform mass operations on sets of data that should all be processed in a similar way. In particular, different objects would ideally act the same, which would be very easily achieved with polymorphism. The problem I have with it is that inheritance implies the <em>is a</em> relationship, rather than the <em>has a</em> relationship. For example, several objects <em>have a</em> damage counter, but to make this easy to use in an object list, polymorphism could be used - except that would imply an <em>is a</em> relationship which wouldn't be true. (A person <em>is not a</em> damage counter.)</p>
<p>The only solution I can think of is to have a member of the class return the proper object type when implicitly casted instead of relying on inheritance. Would it be better to forgo the <em>is a</em> / <em>has a</em> ideal in exchange for ease of programming?</p>
<p>Edit:
To be more specific, I am using C++, so using polymorphism would allow the different objects to "act the same" in the sense that the derived classes could reside within a single list and be operated upon by a virtual function of the base class. The use of an interface (or imitating them via inheritance) seems like a solution I would be willing to use.</p>
| [
{
"answer_id": 11859,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "<p>Sometimes it's worth giving up the ideal for the realistic. If it's going to cause a massive problem to \"do it right\" ... | 2008/08/15 | [
"https://Stackoverflow.com/questions/11854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256/"
] | In a project our team is using object lists to perform mass operations on sets of data that should all be processed in a similar way. In particular, different objects would ideally act the same, which would be very easily achieved with polymorphism. The problem I have with it is that inheritance implies the *is a* relationship, rather than the *has a* relationship. For example, several objects *have a* damage counter, but to make this easy to use in an object list, polymorphism could be used - except that would imply an *is a* relationship which wouldn't be true. (A person *is not a* damage counter.)
The only solution I can think of is to have a member of the class return the proper object type when implicitly casted instead of relying on inheritance. Would it be better to forgo the *is a* / *has a* ideal in exchange for ease of programming?
Edit:
To be more specific, I am using C++, so using polymorphism would allow the different objects to "act the same" in the sense that the derived classes could reside within a single list and be operated upon by a virtual function of the base class. The use of an interface (or imitating them via inheritance) seems like a solution I would be willing to use. | This can be accomplished using multiple inheritance. In your specific case (C++), you can use pure virtual classes as interfaces. This allows you to have multiple inheritance without creating scope/ambiguity problems. Example:
```
class Damage {
virtual void addDamage(int d) = 0;
virtual int getDamage() = 0;
};
class Person : public virtual Damage {
void addDamage(int d) {
// ...
damage += d * 2;
}
int getDamage() {
return damage;
}
};
class Car : public virtual Damage {
void addDamage(int d) {
// ...
damage += d;
}
int getDamage() {
return damage;
}
};
```
Now both Person and Car 'is-a' Damage, meaning, they implement the Damage interface. The use of pure virtual classes (so that they are like interfaces) is key and should be used frequently. It insulates future changes from altering the entire system. Read up on the Open-Closed Principle for more information. |
11,879 | <p>Instead of returning a common string, is there a way to return classic objects?
If not: what are the best practices? Do you transpose your object to xml and rebuild the object on the other side? What are the other possibilities? </p>
| [
{
"answer_id": 11883,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "<p>Yes: in .NET they call this serialization, where objects are serialized into XML and then reconstructed by the consuming ... | 2008/08/15 | [
"https://Stackoverflow.com/questions/11879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/391/"
] | Instead of returning a common string, is there a way to return classic objects?
If not: what are the best practices? Do you transpose your object to xml and rebuild the object on the other side? What are the other possibilities? | As mentioned, you can do this in .net via serialization. By default all native types are serializable so this happens automagically for you.
However if you have complex types, you need to mark the object with the [Serializable] attribute. The same goes with complex types as properties.
So for example you need to have:
```
[Serializable]
public class MyClass
{
public string MyString {get; set;}
[Serializable]
public MyOtherClass MyOtherClassProperty {get; set;}
}
``` |
11,887 | <p>I get an Access is Denied error message when I use the strong name tool to create a new key to sign a .NET assembly. This works just fine on a Windows XP machine but it does not work on my Vista machine.</p>
<pre><code>PS C:\users\brian\Dev\Projects\BELib\BELib> sn -k keypair.snk
Microsoft (R) .NET Framework Strong Name Utility Version 3.5.21022.8
Copyright (c) Microsoft Corporation. All rights reserved.
Failed to generate a strong name key pair -- Access is denied.
</code></pre>
<p>What causes this problem and how can I fix it?</p>
<hr>
<blockquote>
<p>Are you running your PowerShell or
Command Prompt as an Administrator? I
found this to be the first place to
look until you get used to User Access
Control or by turning User Access
Control off.</p>
</blockquote>
<p>Yes I have tried running PS and the regular command prompt as administrator. The same error message comes up.</p>
| [
{
"answer_id": 11891,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 2,
"selected": false,
"text": "<p>Are you running your PowerShell or Command Prompt as an Administrator? I found this to be the first place to look unti... | 2008/08/15 | [
"https://Stackoverflow.com/questions/11887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1254/"
] | I get an Access is Denied error message when I use the strong name tool to create a new key to sign a .NET assembly. This works just fine on a Windows XP machine but it does not work on my Vista machine.
```
PS C:\users\brian\Dev\Projects\BELib\BELib> sn -k keypair.snk
Microsoft (R) .NET Framework Strong Name Utility Version 3.5.21022.8
Copyright (c) Microsoft Corporation. All rights reserved.
Failed to generate a strong name key pair -- Access is denied.
```
What causes this problem and how can I fix it?
---
>
> Are you running your PowerShell or
> Command Prompt as an Administrator? I
> found this to be the first place to
> look until you get used to User Access
> Control or by turning User Access
> Control off.
>
>
>
Yes I have tried running PS and the regular command prompt as administrator. The same error message comes up. | >
> Yes I have tried running PS and the
> regular command prompt as
> administrator. The same error message
> comes up.
>
>
>
Another possible solution could be that you need to give your user account access to the key container located at C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys |
11,926 | <p>I'm new to MVC (and ASP.Net routing). I'm trying to map <code>*.aspx</code> to a controller called <code>PageController</code>. </p>
<pre><code>routes.MapRoute(
"Page",
"{name}.aspx",
new { controller = "Page", action = "Index", id = "" }
);
</code></pre>
<p>Wouldn't the code above map *.aspx to <code>PageController</code>? When I run this and type in any .aspx page I get the following error:</p>
<blockquote>
<p>The controller for path '/Page.aspx' could not be found or it does not implement the IController interface.
Parameter name: controllerType</p>
</blockquote>
<p>Is there something I'm not doing here?</p>
| [
{
"answer_id": 11937,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure how your controller looks, the error seems to be pointing to the fact that it can't find the controller. Did ... | 2008/08/15 | [
"https://Stackoverflow.com/questions/11926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105/"
] | I'm new to MVC (and ASP.Net routing). I'm trying to map `*.aspx` to a controller called `PageController`.
```
routes.MapRoute(
"Page",
"{name}.aspx",
new { controller = "Page", action = "Index", id = "" }
);
```
Wouldn't the code above map \*.aspx to `PageController`? When I run this and type in any .aspx page I get the following error:
>
> The controller for path '/Page.aspx' could not be found or it does not implement the IController interface.
> Parameter name: controllerType
>
>
>
Is there something I'm not doing here? | >
> I just answered my own question. I had
> the routes backwards (Default was
> above page).
>
>
>
Yeah, you have to put all custom routes above the Default route.
>
> So this brings up the next question...
> how does the "Default" route match (I
> assume they use regular expressions
> here) the "Page" route?
>
>
>
The Default route matches based on what we call Convention over Configuration. Scott Guthrie explains it well in his first blog post on ASP.NET MVC. I recommend that you read through it and also his other posts. Keep in mind that these were posted based on the first CTP and the framework has changed. You can also find web cast on ASP.NET MVC on the asp.net site by Scott Hanselman.
* <http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx>
* <http://www.asp.net/MVC/> |
11,930 | <p>How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP?</p>
<p>This is somewhat easy in .NET if you know your way around. But how do you do it in Java?</p>
| [
{
"answer_id": 11943,
"author": "Brian",
"author_id": 725,
"author_profile": "https://Stackoverflow.com/users/725",
"pm_score": 1,
"selected": false,
"text": "<p>That is not as easy as it sounds. Java is platform independent, so I am not sure how to do it in Java. I am <em>guessing</em... | 2008/08/15 | [
"https://Stackoverflow.com/questions/11930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] | How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP?
This is somewhat easy in .NET if you know your way around. But how do you do it in Java? | Java doesn't make this as pleasant as other languages, unfortunately. Here's what I did:
```
import java.io.*;
import java.util.*;
public class ExecTest {
public static void main(String[] args) throws IOException {
Process result = Runtime.getRuntime().exec("traceroute -m 1 www.amazon.com");
BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));
String thisLine = output.readLine();
StringTokenizer st = new StringTokenizer(thisLine);
st.nextToken();
String gateway = st.nextToken();
System.out.printf("The gateway is %s\n", gateway);
}
}
```
This presumes that the gateway is the second token and not the third. If it is, you need to add an extra `st.nextToken();` to advance the tokenizer one more spot. |
11,974 | <p>Basically, something better than this:</p>
<pre><code><input type="file" name="myfile" size="50">
</code></pre>
<p>First of all, the <code>browse</code> button looks different on every browser. Unlike the <code>submit</code> button on a form, you have to come up with some <a href="http://www.quirksmode.org/dom/inputfile.html" rel="nofollow noreferrer">hack-y</a> way to style it.</p>
<p>Secondly, there's no progress indicator showing you how much of the file has uploaded. You usually have to implement some kind of client-side way to disable multiple submits (e.g. change the submit button to a disabled button showing "Form submitting... please wait.") or flash a giant warning.</p>
<p>Are there any good solutions to this that don't use Flash or Java?</p>
<p><a href="https://stackoverflow.com/questions/11974/what-is-the-best-way-to-upload-a-file-via-an-http-post-with-a-web-form#12005">Yaakov</a>: That product looks to be exactly what I'm looking for, but the cost is $1000 and its specifically for <code>ASP.NET.</code> Are there any open source projects that cover the same or similar functionality?</p>
| [
{
"answer_id": 12005,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 0,
"selected": false,
"text": "<p>It is true, the file upload control is definitely behind the times. Hopefully this will be addressed in a future asp.net ... | 2008/08/15 | [
"https://Stackoverflow.com/questions/11974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1396/"
] | Basically, something better than this:
```
<input type="file" name="myfile" size="50">
```
First of all, the `browse` button looks different on every browser. Unlike the `submit` button on a form, you have to come up with some [hack-y](http://www.quirksmode.org/dom/inputfile.html) way to style it.
Secondly, there's no progress indicator showing you how much of the file has uploaded. You usually have to implement some kind of client-side way to disable multiple submits (e.g. change the submit button to a disabled button showing "Form submitting... please wait.") or flash a giant warning.
Are there any good solutions to this that don't use Flash or Java?
[Yaakov](https://stackoverflow.com/questions/11974/what-is-the-best-way-to-upload-a-file-via-an-http-post-with-a-web-form#12005): That product looks to be exactly what I'm looking for, but the cost is $1000 and its specifically for `ASP.NET.` Are there any open source projects that cover the same or similar functionality? | File upload boxes is where we're currently at if you don't want to involve other technologies like Flash, Java or ActiveX.
With plain HTML you are pretty much limited to the experience you've described (no progress bar, double submits, etc). If you are willing to use some javascript, you can solve some of the problems by giving feedback that the upload is in progress and even [showing the upload progress](http://www.raditha.com/php/progress.php) (it is a hack because you shouldn't have to do a full round-trip to the server and back, but at least it works).
If you are willing to use Flash (which is available pretty much anywhere and on many platforms), you can overcome pretty much all of these problems. A quick googling turned up [two](http://www.downloadsquad.com/2006/11/16/swfupload-open-source-flash-multi-file-upload/) [such](http://www.codeproject.com/KB/aspnet/FlashUpload.aspx) components, both of them free *and* open source. I never used any of them, but they look good. BTW, Flash isn't without its problems either, for example when using the multi-file uploader for slide share, the browser kept constantly crashing on me :-(
Probably the best solution currently is to detect dynamically if the user has Flash, and if it's the case, give her the flash version of the uploader, while still making it possible to choose the basic HTML one.
HTH |
12,009 | <p>How can I pipe the new password to smbpasswd so I can automate my installation process.</p>
| [
{
"answer_id": 12016,
"author": "icco",
"author_id": 1063,
"author_profile": "https://Stackoverflow.com/users/1063",
"pm_score": -1,
"selected": false,
"text": "<p>using either <a href=\"http://en.wikipedia.org/wiki/Pipeline_(Unix)\" rel=\"nofollow noreferrer\">pipelines</a> or <a href=\... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] | How can I pipe the new password to smbpasswd so I can automate my installation process. | Thanks to Mark I found the answer:
```
(echo newpassword; echo confirmNewPassword) | smbpasswd -s
```
BTW: (echo oldpasswd; echo newpasswd) | smbpasswd -s does not work. |
12,039 | <p>I have an application that sometimes causes a BSOD on a Win XP machine. Trying to find out more, I loaded up the resulting *.dmp file (from C:\Windows\Minidump), but get this message when in much of the readout when doing so:</p>
<pre><code>*********************************************************************
* Symbols can not be loaded because symbol path is not initialized. *
* *
* The Symbol Path can be set by: *
* using the _NT_SYMBOL_PATH environment variable. *
* using the -y <symbol_path> argument when starting the debugger. *
* using .sympath and .sympath+ *
*********************************************************************
</code></pre>
<p>What does this mean, and how do I "fix" it?</p>
| [
{
"answer_id": 12043,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 2,
"selected": false,
"text": "<p>you actually need to either download the symbols to your computer, or configure it to download as you go if you are online w... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have an application that sometimes causes a BSOD on a Win XP machine. Trying to find out more, I loaded up the resulting \*.dmp file (from C:\Windows\Minidump), but get this message when in much of the readout when doing so:
```
*********************************************************************
* Symbols can not be loaded because symbol path is not initialized. *
* *
* The Symbol Path can be set by: *
* using the _NT_SYMBOL_PATH environment variable. *
* using the -y <symbol_path> argument when starting the debugger. *
* using .sympath and .sympath+ *
*********************************************************************
```
What does this mean, and how do I "fix" it? | Quick answer is to
c:\> set \_NT\_SYMBOL\_PATH=SRV\*C:\WINDOWS\Symbols\*http://msdl.microsoft.com/download/symbols
before starting windbg. |
12,051 | <p>If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that?</p>
<p>For example, if I inherit from the Exception class I want to do something like this:</p>
<pre><code>class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extraInfo)
{
//This is where it's all falling apart
base(message);
}
}
</code></pre>
<p>Basically what I want is to be able to pass the string message to the base Exception class.</p>
| [
{
"answer_id": 12052,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 12,
"selected": true,
"text": "<p>Modify your constructor to the following so that it calls the base class constructor properly:</p>\n\n<pre><code>public c... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] | If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that?
For example, if I inherit from the Exception class I want to do something like this:
```
class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extraInfo)
{
//This is where it's all falling apart
base(message);
}
}
```
Basically what I want is to be able to pass the string message to the base Exception class. | Modify your constructor to the following so that it calls the base class constructor properly:
```
public class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extrainfo) : base(message)
{
//other stuff here
}
}
```
Note that a constructor is not something that you can call anytime within a method. That's the reason you're getting errors in your call in the constructor body. |
12,095 | <p>Our team is creating a new recruitment workflow system to replace an old one. I have been tasked with migrating the old data into the new schema. I have decided to do this by creating a small Windows Forms project as the schema are radically different and straight TSQL scripts are not an adequate solution.</p>
<p>The main sealed class 'ImportController' that does the work declares the following delegate event:</p>
<pre><code>public delegate void ImportProgressEventHandler(object sender, ImportProgressEventArgs e);
public static event ImportProgressEventHandler importProgressEvent;
</code></pre>
<p>The main window starts a static method in that class using a new thread:</p>
<pre><code>Thread dataProcessingThread = new Thread(new ParameterizedThreadStart(ImportController.ImportData));
dataProcessingThread.Name = "Data Importer: Data Processing Thread";
dataProcessingThread.Start(settings);
</code></pre>
<p>the ImportProgressEvent args carries a string message, a max int value for the progress bar and an current progress int value. The Windows form subcribes to the event:</p>
<pre><code>ImportController.importProgressEvent += new ImportController.ImportProgressEventHandler(ImportController_importProgressEvent);
</code></pre>
<p>And responds to the event in this manner using it's own delegate:</p>
<pre><code> private delegate void TaskCompletedUIDelegate(string completedTask, int currentProgress, int progressMax);
private void ImportController_importProgressEvent(object sender, ImportProgressEventArgs e)
{
this.Invoke(new TaskCompletedUIDelegate(this.DisplayCompletedTask), e.CompletedTask, e.CurrentProgress, e.ProgressMax);
}
</code></pre>
<p>Finally the progress bar and listbox are updated:</p>
<pre><code>private void DisplayCompletedTask(string completedTask, int currentProgress, int progressMax)
{
string[] items = completedTask.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in items)
{
this.lstTasks.Items.Add(item);
}
if (currentProgress >= 0 && progressMax > 0 && currentProgress <= progressMax)
{
this.ImportProgressBar.Maximum = progressMax;
this.ImportProgressBar.Value = currentProgress;
}
}
</code></pre>
<p>The thing is the ListBox seems to update very quickly, but the progress bar never moves until the batch is almost complete anyway ??? what gives ?</p>
| [
{
"answer_id": 12104,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe you can try the BackgroundWorker component. It makes threading easier. Examples here:</p>\n\n<ul>\n<li><a href=\"http://ww... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2083160/"
] | Our team is creating a new recruitment workflow system to replace an old one. I have been tasked with migrating the old data into the new schema. I have decided to do this by creating a small Windows Forms project as the schema are radically different and straight TSQL scripts are not an adequate solution.
The main sealed class 'ImportController' that does the work declares the following delegate event:
```
public delegate void ImportProgressEventHandler(object sender, ImportProgressEventArgs e);
public static event ImportProgressEventHandler importProgressEvent;
```
The main window starts a static method in that class using a new thread:
```
Thread dataProcessingThread = new Thread(new ParameterizedThreadStart(ImportController.ImportData));
dataProcessingThread.Name = "Data Importer: Data Processing Thread";
dataProcessingThread.Start(settings);
```
the ImportProgressEvent args carries a string message, a max int value for the progress bar and an current progress int value. The Windows form subcribes to the event:
```
ImportController.importProgressEvent += new ImportController.ImportProgressEventHandler(ImportController_importProgressEvent);
```
And responds to the event in this manner using it's own delegate:
```
private delegate void TaskCompletedUIDelegate(string completedTask, int currentProgress, int progressMax);
private void ImportController_importProgressEvent(object sender, ImportProgressEventArgs e)
{
this.Invoke(new TaskCompletedUIDelegate(this.DisplayCompletedTask), e.CompletedTask, e.CurrentProgress, e.ProgressMax);
}
```
Finally the progress bar and listbox are updated:
```
private void DisplayCompletedTask(string completedTask, int currentProgress, int progressMax)
{
string[] items = completedTask.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in items)
{
this.lstTasks.Items.Add(item);
}
if (currentProgress >= 0 && progressMax > 0 && currentProgress <= progressMax)
{
this.ImportProgressBar.Maximum = progressMax;
this.ImportProgressBar.Value = currentProgress;
}
}
```
The thing is the ListBox seems to update very quickly, but the progress bar never moves until the batch is almost complete anyway ??? what gives ? | @John
Thanks for the links.
@Will
There's no gain from threadpooling as I know it will only ever spawn one thread. The use of a thread is purely to have a responsive UI while SQL Server is being pounded with reads and writes. It's certainly not a short lived thread.
Regarding sledge-hammers you're right. But, as it turns out my problem was between screen and chair after all. I seem to have an unusal batch of data that has many many many more foreign key records than the other batches and just happens to get selected early in the process meaning the currentProgress doesn't get ++'d for a good 10 seconds.
@All
Thanks for all your input, it got me thinking, which got me looking elsewhere in the code, which led to my ahaa moment of humility where I prove yet again the error is usually human :) |
12,103 | <p>When I am running the following statement:</p>
<pre><code>@filtered = map {s/&nbsp;//g} @outdata;
</code></pre>
<p>it is returning an empty list instead of the filtered list that I expected. What I am trying to do is remove every occurrence of <code>&nbsp;</code> from an array of string (which is an XML file).</p>
<p>Obviously, I am not understanding something. Can anyone tell me the correct way to do this might be, and why this isn't working for me as is?</p>
| [
{
"answer_id": 12108,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code>@filtered = map {s/&nbsp;//g; $_} @outdata;\n</code></pre>\n\n<p>The problem is the s op... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/274/"
] | When I am running the following statement:
```
@filtered = map {s/ //g} @outdata;
```
it is returning an empty list instead of the filtered list that I expected. What I am trying to do is remove every occurrence of ` ` from an array of string (which is an XML file).
Obviously, I am not understanding something. Can anyone tell me the correct way to do this might be, and why this isn't working for me as is? | Try this:
```
@filtered = map {s/ //g; $_} @outdata;
```
The problem is the s operator in perl modifies $\_ but actually returns the number of changes it made. So, the extra $\_ at the end causes perl to return the modified string for each element of @outdata. |
12,135 | <p>I'm using an XmlSerializer to deserialize a particular type in mscorelib.dll</p>
<pre><code>XmlSerializer ser = new XmlSerializer( typeof( [.Net type in System] ) );
return ([.Net type in System]) ser.Deserialize( new StringReader( xmlValue ) );
</code></pre>
<p>This throws a caught <code>FileNotFoundException</code> when the assembly is loaded:</p>
<blockquote>
<p>"Could not load file or assembly
'mscorlib.XmlSerializers,
Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' or
one of its dependencies. The system
cannot find the file specified."</p>
</blockquote>
<p>FusionLog:</p>
<pre><code>=== Pre-bind state information ===
LOG: User = ###
LOG: DisplayName = mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86
(Fully-specified)
LOG: Appbase = file:///C:/localdir
LOG: Initial PrivatePath = NULL
Calling assembly : System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\localdir\bin\Debug\appname.vshost.exe.Config
LOG: Using machine configuration file from c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: Post-policy reference: mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.DLL.
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.DLL.
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.EXE.
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.EXE.
</code></pre>
<p>As far as I know there is no mscorlib.XmlSerializers.DLL, I think the DLL name has bee auto generated by .Net looking for the serializer. </p>
<p>You have the option of creating a myApplication.XmlSerializers.DLL when compiling to optimise serializations, so I assume this is part of the framework's checking for it.</p>
<p>The problem is that this appears to be causing a delay in loading the application - it seems to hang for a few seconds at this point.</p>
<p>Any ideas how to avoid this or speed it up?</p>
| [
{
"answer_id": 12136,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 2,
"selected": false,
"text": "<p>The delay is because, having been unable to find the custom serializer dll, the system is building the equivalent code (wh... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | I'm using an XmlSerializer to deserialize a particular type in mscorelib.dll
```
XmlSerializer ser = new XmlSerializer( typeof( [.Net type in System] ) );
return ([.Net type in System]) ser.Deserialize( new StringReader( xmlValue ) );
```
This throws a caught `FileNotFoundException` when the assembly is loaded:
>
> "Could not load file or assembly
> 'mscorlib.XmlSerializers,
> Version=2.0.0.0, Culture=neutral,
> PublicKeyToken=b77a5c561934e089' or
> one of its dependencies. The system
> cannot find the file specified."
>
>
>
FusionLog:
```
=== Pre-bind state information ===
LOG: User = ###
LOG: DisplayName = mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86
(Fully-specified)
LOG: Appbase = file:///C:/localdir
LOG: Initial PrivatePath = NULL
Calling assembly : System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\localdir\bin\Debug\appname.vshost.exe.Config
LOG: Using machine configuration file from c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: Post-policy reference: mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.DLL.
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.DLL.
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.EXE.
LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.EXE.
```
As far as I know there is no mscorlib.XmlSerializers.DLL, I think the DLL name has bee auto generated by .Net looking for the serializer.
You have the option of creating a myApplication.XmlSerializers.DLL when compiling to optimise serializations, so I assume this is part of the framework's checking for it.
The problem is that this appears to be causing a delay in loading the application - it seems to hang for a few seconds at this point.
Any ideas how to avoid this or speed it up? | I'm guessing now. but:
1. The system might be generating a serializer for the whole of mscorlib, which could be very slow.
2. You could probably avoid this by wrapping the system type in your own type and serialising that instead - then you'd get a serializer for your own assembly.
3. You might be able to build the serializer for mscorlib with sgen.exe, which was the old way of building serializer dlls before it got integrated into VS. |
12,140 | <p>A database application that I'm currently working on, stores all sorts of settings in the database. Most of those settings are there to customize certain business rules, but there's also some other stuff in there.</p>
<p>The app contains objects that specifically do a certain task, e.g., a certain complicated calculation. Those non-UI objects are unit-tested, but also need access to lots of those global settings. The way we've implemented this right now, is by giving the objects properties that are filled by the Application Controller at runtime. When testing, we create the objects in the test and fill in values for testing (not from the database).</p>
<p>This works better, in any case much better than having all those objects need some global <em>Settings</em> object --- that of course effectively makes unit testing impossible :) Disadvantage can be that you sometimes need to set a dozen of properties, or that you need to let those properties 'percolate' into sub-objects.</p>
<p><strong>So the general question is</strong>: how do you provide access to global application settings in your projects, without the need for global variables, while still being able to unit test your code? This must be a problem that's been solved 100's of times...</p>
<p>(Note: I'm not too much of an experienced programmer, as you'll have noticed; but I love to learn! And of course, I've already done research into this topic, but I'm really looking for some first-hand experiences)</p>
| [
{
"answer_id": 12161,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 0,
"selected": false,
"text": "<p>Usually this is handled by an ini file or XML configuration file. Then you just have a class that reads the setting wh... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037/"
] | A database application that I'm currently working on, stores all sorts of settings in the database. Most of those settings are there to customize certain business rules, but there's also some other stuff in there.
The app contains objects that specifically do a certain task, e.g., a certain complicated calculation. Those non-UI objects are unit-tested, but also need access to lots of those global settings. The way we've implemented this right now, is by giving the objects properties that are filled by the Application Controller at runtime. When testing, we create the objects in the test and fill in values for testing (not from the database).
This works better, in any case much better than having all those objects need some global *Settings* object --- that of course effectively makes unit testing impossible :) Disadvantage can be that you sometimes need to set a dozen of properties, or that you need to let those properties 'percolate' into sub-objects.
**So the general question is**: how do you provide access to global application settings in your projects, without the need for global variables, while still being able to unit test your code? This must be a problem that's been solved 100's of times...
(Note: I'm not too much of an experienced programmer, as you'll have noticed; but I love to learn! And of course, I've already done research into this topic, but I'm really looking for some first-hand experiences) | You could use Martin Fowlers ServiceLocator pattern. In php it could look like this:
```
class ServiceLocator {
private static $soleInstance;
private $globalSettings;
public static function load($locator) {
self::$soleInstance = $locator;
}
public static function globalSettings() {
if (!isset(self::$soleInstance->globalSettings)) {
self::$soleInstance->setGlobalSettings(new GlobalSettings());
}
return self::$soleInstance->globalSettings;
}
}
```
Your production code then initializes the service locator like this:
```
ServiceLocator::load(new ServiceLocator());
```
In your test-code, you insert your mock-settings like this:
```
ServiceLocator s = new ServiceLocator();
s->setGlobalSettings(new MockGlobalSettings());
ServiceLocator::load(s);
```
It's a repository for singletons that can be exchanged for testing purposes. |
12,141 | <p>For example: Updating all rows of the customer table because you forgot to add the where clause.</p>
<ol>
<li>What was it like, realizing it and reporting it to your coworkers or customers? </li>
<li>What were the lessons learned?</li>
</ol>
| [
{
"answer_id": 12143,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I dropped the live database and deleted it.</p>\n\n<p>Lesson learned: ensure you know your SQL - and make sure that you back... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/990/"
] | For example: Updating all rows of the customer table because you forgot to add the where clause.
1. What was it like, realizing it and reporting it to your coworkers or customers?
2. What were the lessons learned? | I think my worst mistake was
```
truncate table Customers
truncate table Transactions
```
I didnt see what MSSQL server I was logged into, I wanted to clear my local copy out...The familiar "OH s\*\*t" when it was taking significantly longer than about half a second to delete, my boss noticed I went visibily white, and asked what I just did. About half a mintue later, our site monitor went nuts and started emailing us saying the site was down.
Lesson learned? Never keep a connection open to live DB longer than absolutly needed.
Was only up till 4am restoring the data from the backups too! My boss felt sorry for me, and bought me dinner... |
12,176 | <p>Is there any way to include the SVN repository revision number in the version string of a .NET assembly? Something like Major.Minor.SVNRev</p>
<p>I've seen mention of doing this with something like CC.NET (although on ASP.NET actually), but is there any way to do it without any extra software? I've done similar things in C/C++ before using build batch scripts, but in was accomplished by reading the version number, then having the script write out a file called "ver.h" everytime with something to the effect of:</p>
<pre><code>#define MAJORVER 4
#define MINORVER 23
#define SOURCEVER 965
</code></pre>
<p>We would then use these defines to generate the version string.</p>
<p>Is something like this possible for .NET?</p>
| [
{
"answer_id": 12189,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 4,
"selected": true,
"text": "<p>Have a look at SubWCRev - <a href=\"http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-subwcrev.html\" rel=\"noreferre... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] | Is there any way to include the SVN repository revision number in the version string of a .NET assembly? Something like Major.Minor.SVNRev
I've seen mention of doing this with something like CC.NET (although on ASP.NET actually), but is there any way to do it without any extra software? I've done similar things in C/C++ before using build batch scripts, but in was accomplished by reading the version number, then having the script write out a file called "ver.h" everytime with something to the effect of:
```
#define MAJORVER 4
#define MINORVER 23
#define SOURCEVER 965
```
We would then use these defines to generate the version string.
Is something like this possible for .NET? | Have a look at SubWCRev - <http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-subwcrev.html>
The assembly version numbers are usually in assemblyinfo.cs |
12,225 | <p>I have a database that contains a date and we are using the MaskedEditExtender (MEE) and MaskedEditValidator to make sure the dates are appropriate. However, we want the Admins to be able to go in and change the data (specifically the date) if necessary. </p>
<p>How can I have the MEE field pre-populate with the database value when the data is shown on the page? I've tried to use 'bind' in the 'InitialValue' property but it doesn't populate the textbox.</p>
<p>Thanks.</p>
| [
{
"answer_id": 12257,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>Are you referring to the asp.Net Ajax toolkit extensions at:</p>\n\n<p><a href=\"http://www.asp.net/AJAX/AjaxControlToolkit/Sa... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] | I have a database that contains a date and we are using the MaskedEditExtender (MEE) and MaskedEditValidator to make sure the dates are appropriate. However, we want the Admins to be able to go in and change the data (specifically the date) if necessary.
How can I have the MEE field pre-populate with the database value when the data is shown on the page? I've tried to use 'bind' in the 'InitialValue' property but it doesn't populate the textbox.
Thanks. | We found out this morning why our code was mishandling the extender. Since the db was handling the date as a date/time it was returning the date in this format 99/99/9999 99:99:99 but we had the extender mask looking for this format 99/99/9999 99:99
```
Mask="99/99/9999 99:99:99"
```
the above code fixed the problem.
thanks to everyone for their help. |
12,271 | <p>I have created a template for Visual Studio 2008 and it currently shows up under File->New Project->Visual C#. However, it is only really specific to Visual C#/Windows but I can't work out how to get it to show up under the "Windows" category and not the more general "Visual C#".</p>
| [
{
"answer_id": 12292,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 0,
"selected": false,
"text": "<p>Categorization of templates depends on settings (for example, if you choose \"C#\" settings, all of a sudden all other languages... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214/"
] | I have created a template for Visual Studio 2008 and it currently shows up under File->New Project->Visual C#. However, it is only really specific to Visual C#/Windows but I can't work out how to get it to show up under the "Windows" category and not the more general "Visual C#". | Check out MSDN "[How to: Locate and Organize Project and Item Templates](http://msdn.microsoft.com/en-us/library/y3kkate1.aspx)"
Create a folder within one of these
```
<VisualStudioInstallDir>\Common7\IDE\ItemTemplates\CSharp\
My Documents\Visual Studio 2008\Templates\ProjectTemplates\CSharp\
``` |
12,297 | <p>I've got a Repeater that lists all the <code>web.sitemap</code> child pages on an ASP.NET page. Its <code>DataSource</code> is a <code>SiteMapNodeCollection</code>. But, I don't want my registration form page to show up there.</p>
<pre><code>Dim Children As SiteMapNodeCollection = SiteMap.CurrentNode.ChildNodes
'remove registration page from collection
For Each n As SiteMapNode In SiteMap.CurrentNode.ChildNodes
If n.Url = "/Registration.aspx" Then
Children.Remove(n)
End If
Next
RepeaterSubordinatePages.DataSource = Children
</code></pre>
<p>The <code>SiteMapNodeCollection.Remove()</code> method throws a </p>
<blockquote>
<p>NotSupportedException: "Collection is read-only".</p>
</blockquote>
<p>How can I remove the node from the collection before DataBinding the Repeater?</p>
| [
{
"answer_id": 12303,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 1,
"selected": false,
"text": "<p>Using Linq and .Net 3.5:</p>\n\n<pre><code>//this will now be an enumeration, rather than a read only collection\nDim children... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | I've got a Repeater that lists all the `web.sitemap` child pages on an ASP.NET page. Its `DataSource` is a `SiteMapNodeCollection`. But, I don't want my registration form page to show up there.
```
Dim Children As SiteMapNodeCollection = SiteMap.CurrentNode.ChildNodes
'remove registration page from collection
For Each n As SiteMapNode In SiteMap.CurrentNode.ChildNodes
If n.Url = "/Registration.aspx" Then
Children.Remove(n)
End If
Next
RepeaterSubordinatePages.DataSource = Children
```
The `SiteMapNodeCollection.Remove()` method throws a
>
> NotSupportedException: "Collection is read-only".
>
>
>
How can I remove the node from the collection before DataBinding the Repeater? | Your shouldn't need CType
```
Dim children = _
From n In SiteMap.CurrentNode.ChildNodes.Cast(Of SiteMapNode)() _
Where n.Url <> "/Registration.aspx" _
Select n
``` |
12,304 | <p>This is a problem I have seen other people besides myself having, and I haven't found a good explanation.</p>
<p>Let's say you have a maintenance plan with a task to check the database, something like this:</p>
<pre><code>USE [MyDb]
GO
DBCC CHECKDB with no_infomsgs, all_errormsgs
</code></pre>
<p>If you go look in your logs after the task executes, you might see something like this:</p>
<pre><code>08/15/2008 06:00:22,spid55,Unknown,DBCC CHECKDB (mssqlsystemresource) executed by NT AUTHORITY\SYSTEM found 0 errors and repaired 0 errors. Elapsed time: 0 hours 0 minutes 0 seconds.
08/15/2008 06:00:21,spid55,Unknown,DBCC CHECKDB (master) executed by NT AUTHORITY\SYSTEM found 0 errors and repaired 0 errors. Elapsed time: 0 hours 0 minutes 0 seconds.
</code></pre>
<p>Instead of checking MyDb, it checked master and msssqlsystemresource.</p>
<p>Why?</p>
<p>My workaround is to create a Sql Server Agent Job with this:</p>
<pre><code>dbcc checkdb ('MyDb') with no_infomsgs, all_errormsgs;
</code></pre>
<p>That always works fine.</p>
<pre><code>08/15/2008 04:26:04,spid54,Unknown,DBCC CHECKDB (MyDb) WITH all_errormsgs<c/> no_infomsgs executed by NT AUTHORITY\SYSTEM found 0 errors and repaired 0 errors. Elapsed time: 0 hours 26 minutes 3 seconds.
</code></pre>
| [
{
"answer_id": 12320,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 1,
"selected": false,
"text": "<p>For starters, always remember that <code>GO</code> is not a SQL keyword; it is merely a batch separator that is (generally) impl... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] | This is a problem I have seen other people besides myself having, and I haven't found a good explanation.
Let's say you have a maintenance plan with a task to check the database, something like this:
```
USE [MyDb]
GO
DBCC CHECKDB with no_infomsgs, all_errormsgs
```
If you go look in your logs after the task executes, you might see something like this:
```
08/15/2008 06:00:22,spid55,Unknown,DBCC CHECKDB (mssqlsystemresource) executed by NT AUTHORITY\SYSTEM found 0 errors and repaired 0 errors. Elapsed time: 0 hours 0 minutes 0 seconds.
08/15/2008 06:00:21,spid55,Unknown,DBCC CHECKDB (master) executed by NT AUTHORITY\SYSTEM found 0 errors and repaired 0 errors. Elapsed time: 0 hours 0 minutes 0 seconds.
```
Instead of checking MyDb, it checked master and msssqlsystemresource.
Why?
My workaround is to create a Sql Server Agent Job with this:
```
dbcc checkdb ('MyDb') with no_infomsgs, all_errormsgs;
```
That always works fine.
```
08/15/2008 04:26:04,spid54,Unknown,DBCC CHECKDB (MyDb) WITH all_errormsgs<c/> no_infomsgs executed by NT AUTHORITY\SYSTEM found 0 errors and repaired 0 errors. Elapsed time: 0 hours 26 minutes 3 seconds.
``` | For starters, always remember that `GO` is not a SQL keyword; it is merely a batch separator that is (generally) implemented/recognized by the client, not the server. So, depending on context and client, there really is no guarantee that the current database is preserved between batches. |
12,306 | <p>I'm trying to serialize a Type object in the following way:</p>
<pre><code>Type myType = typeof (StringBuilder);
var serializer = new XmlSerializer(typeof(Type));
TextWriter writer = new StringWriter();
serializer.Serialize(writer, myType);
</code></pre>
<p>When I do this, the call to Serialize throws the following exception: </p>
<blockquote>
<p>"The type System.Text.StringBuilder was not expected. Use the
XmlInclude or SoapInclude attribute to specify types that are not
known statically."</p>
</blockquote>
<p>Is there a way for me to serialize the <code>Type</code> object? Note that I am not trying to serialize the <code>StringBuilder</code> itself, but the <code>Type</code> object containing the metadata about the <code>StringBuilder</code> class.</p>
| [
{
"answer_id": 12314,
"author": "AdamSane",
"author_id": 805,
"author_profile": "https://Stackoverflow.com/users/805",
"pm_score": 1,
"selected": false,
"text": "<p>Just looked at its definition, it is not marked as Serializable. If you really need this data to be serialize, then you may... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767/"
] | I'm trying to serialize a Type object in the following way:
```
Type myType = typeof (StringBuilder);
var serializer = new XmlSerializer(typeof(Type));
TextWriter writer = new StringWriter();
serializer.Serialize(writer, myType);
```
When I do this, the call to Serialize throws the following exception:
>
> "The type System.Text.StringBuilder was not expected. Use the
> XmlInclude or SoapInclude attribute to specify types that are not
> known statically."
>
>
>
Is there a way for me to serialize the `Type` object? Note that I am not trying to serialize the `StringBuilder` itself, but the `Type` object containing the metadata about the `StringBuilder` class. | I wasn't aware that a Type object could be created with only a string containing the fully-qualified name. To get the fully qualified name, you can use the following:
```
string typeName = typeof (StringBuilder).FullName;
```
You can then persist this string however needed, then reconstruct the type like this:
```
Type t = Type.GetType(typeName);
```
If you need to create an instance of the type, you can do this:
```
object o = Activator.CreateInstance(t);
```
If you check the value of o.GetType(), it will be StringBuilder, just as you would expect. |
12,319 | <p>I'm looking to the equivalent of Windows <a href="http://msdn.microsoft.com/fr-fr/library/yeby3zcb.aspx" rel="noreferrer"><code>_wfopen()</code></a> under Mac OS X. Any idea?</p>
<p>I need this in order to port a Windows library that uses <code>wchar*</code> for its File interface. As this is intended to be a cross-platform library, I am unable to rely on how the client application will get the file path and give it to the library.</p>
| [
{
"answer_id": 12367,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using Cocoa it's fairly easy with NSString. Just load the UTF16 data in using -initWithBytes:length:encoding: (... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/268/"
] | I'm looking to the equivalent of Windows [`_wfopen()`](http://msdn.microsoft.com/fr-fr/library/yeby3zcb.aspx) under Mac OS X. Any idea?
I need this in order to port a Windows library that uses `wchar*` for its File interface. As this is intended to be a cross-platform library, I am unable to rely on how the client application will get the file path and give it to the library. | POSIX API in Mac OS X are usable with UTF-8 strings. In order to convert a wchar\_t string to UTF-8, it is possible to use the CoreFoundation framework from Mac OS X.
Here is a class that will wrap an UTF-8 generated string from a wchar\_t string.
```
class Utf8
{
public:
Utf8(const wchar_t* wsz): m_utf8(NULL)
{
// OS X uses 32-bit wchar
const int bytes = wcslen(wsz) * sizeof(wchar_t);
// comp_bLittleEndian is in the lib I use in order to detect PowerPC/Intel
CFStringEncoding encoding = comp_bLittleEndian ? kCFStringEncodingUTF32LE
: kCFStringEncodingUTF32BE;
CFStringRef str = CFStringCreateWithBytesNoCopy(NULL,
(const UInt8*)wsz, bytes,
encoding, false,
kCFAllocatorNull
);
const int bytesUtf8 = CFStringGetMaximumSizeOfFileSystemRepresentation(str);
m_utf8 = new char[bytesUtf8];
CFStringGetFileSystemRepresentation(str, m_utf8, bytesUtf8);
CFRelease(str);
}
~Utf8()
{
if( m_utf8 )
{
delete[] m_utf8;
}
}
public:
operator const char*() const { return m_utf8; }
private:
char* m_utf8;
};
```
Usage:
```
const wchar_t wsz = L"Here is some Unicode content: éà€œæ";
const Utf8 utf8 = wsz;
FILE* file = fopen(utf8, "r");
```
This will work for reading or writing files. |
12,368 | <p>The .NET garbage collector will eventually free up memory, but what if you want that memory back immediately? What code do you need to use in a class <code>MyClass</code> to call</p>
<pre><code>MyClass.Dispose()
</code></pre>
<p>and free up all the used space by variables and objects in <code>MyClass</code>?</p>
| [
{
"answer_id": 12376,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.codeguru.com/csharp/.net/net_general/tipstricks/article.php/c7047/\" rel=\"nofollow noreferrer\" tit... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1271/"
] | The .NET garbage collector will eventually free up memory, but what if you want that memory back immediately? What code do you need to use in a class `MyClass` to call
```
MyClass.Dispose()
```
and free up all the used space by variables and objects in `MyClass`? | IDisposable has nothing to do with freeing memory. IDisposable is a pattern for freeing *unmanaged* resources -- and memory is quite definitely a managed resource.
The links pointing to GC.Collect() are the correct answer, though use of this function is generally discouraged by the Microsoft .NET documentation.
**Edit:** Having earned a substantial amount of karma for this answer, I feel a certain responsibility to elaborate on it, lest a newcomer to .NET resource management get the wrong impression.
Inside a .NET process, there are two kinds of resource -- managed and unmanaged. "Managed" means that the runtime is in control of the resource, while "unmanaged" means that it's the programmer's responsibility. And there really is only one kind of managed resource that we care about in .NET today -- memory. The programmer tells the runtime to allocate memory and after that it's up to the runtime to figure out when the memory can freed. The mechanism that .NET uses for this purpose is called [garbage collection](http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)) and you can find plenty of information about GC on the internet simply by using Google.
For the other kinds of resources, .NET doesn't know anything about cleaning them up so it has to rely on the programmer to do the right thing. To this end, the platform gives the programmer three tools:
1. The IDisposable interface and the "using" statement in VB and C#
2. Finalizers
3. The IDisposable pattern as implemented by many BCL classes
The first of these allows the programmer to efficiently acquire a resource, use it and then release it all within the same method.
```
using (DisposableObject tmp = DisposableObject.AcquireResource()) {
// Do something with tmp
}
// At this point, tmp.Dispose() will automatically have been called
// BUT, tmp may still a perfectly valid object that still takes up memory
```
If "AcquireResource" is a factory method that (for instance) opens a file and "Dispose" automatically closes the file, then this code cannot leak a file resource. But the memory for the "tmp" object itself may well still be allocated. That's because the IDisposable interface has absolutely no connection to the garbage collector. If you *did* want to ensure that the memory was freed, your only option would be to call `GC.Collect()` to force a garbage collection.
However, it cannot be stressed enough that this is probably not a good idea. It's generally much better to let the garbage collector do what it was designed to do, which is to manage memory.
What happens if the resource is being used for a longer period of time, such that its lifespan crosses several methods? Clearly, the "using" statement is no longer applicable, so the programmer would have to manually call "Dispose" when he or she is done with the resource. And what happens if the programmer forgets? If there's no fallback, then the process or computer may eventually run out of whichever resource isn't being properly freed.
That's where finalizers come in. A finalizer is a method on your class that has a special relationship with the garbage collector. The GC promises that -- before freeing the memory for any object of that type -- it will first give the finalizer a chance to do some kind of cleanup.
So in the case of a file, we theoretically don't need to close the file manually at all. We can just wait until the garbage collector gets to it and then let the finalizer do the work. Unfortunately, this doesn't work well in practice because the garbage collector runs non-deterministically. The file may stay open considerably longer than the programmer expects. And if enough files are kept open, the system may fail when trying to open an additional file.
For most resources, we want both of these things. We want a convention to be able to say "we're done with this resource now" and we want to make sure that there's at least some chance for the cleanup to happen automatically if we forget to do it manually. That's where the "IDisposable" pattern comes into play. This is a convention that allows IDispose and a finalizer to play nicely together. You can see how the pattern works by looking at the [official documentation for IDisposable](http://msdn.microsoft.com/en-us/library/system.idisposable.aspx).
**Bottom line:** If what you really want to do is to just make sure that memory is freed, then IDisposable and finalizers will not help you. But the IDisposable interface is part of an extremely important pattern that all .NET programmers should understand. |
12,374 | <p>We’ve found that the unit tests we’ve written for our C#/C++ code have really paid off.
But we still have thousands of lines of business logic in stored procedures, which only really get tested in anger when our product is rolled out to a large number of users. </p>
<p>What makes this worse is that some of these stored procedures end up being very long, because of the performance hit when passing temporary tables between SPs. This has prevented us from refactoring to make the code simpler.</p>
<p>We have made several attempts at building unit tests around some of our key stored procedures (primarily testing the performance), but have found that setting up the test data for these tests is really hard. For example, we end up copying around test databases. In addition to this, the tests end up being really sensitive to change, and even the smallest change to a stored proc. or table requires a large amount of changes to the tests. So after many builds breaking due to these database tests failing intermittently, we’ve just had to pull them out of the build process.</p>
<p>So, the main part of my questions is: has anyone ever successfully written unit tests for their stored procedures?</p>
<p>The second part of my questions is whether unit testing would be/is easier with linq? </p>
<p>I was thinking that rather than having to set up tables of test data, you could simply create a collection of test objects, and test your linq code in a “linq to objects” situation? (I am a totally new to linq so don’t know if this would even work at all)</p>
| [
{
"answer_id": 12387,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "<p>Have you tried <a href=\"http://dbunit.sourceforge.net/\" rel=\"nofollow noreferrer\">DBUnit</a>? It's designed to unit t... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1078/"
] | We’ve found that the unit tests we’ve written for our C#/C++ code have really paid off.
But we still have thousands of lines of business logic in stored procedures, which only really get tested in anger when our product is rolled out to a large number of users.
What makes this worse is that some of these stored procedures end up being very long, because of the performance hit when passing temporary tables between SPs. This has prevented us from refactoring to make the code simpler.
We have made several attempts at building unit tests around some of our key stored procedures (primarily testing the performance), but have found that setting up the test data for these tests is really hard. For example, we end up copying around test databases. In addition to this, the tests end up being really sensitive to change, and even the smallest change to a stored proc. or table requires a large amount of changes to the tests. So after many builds breaking due to these database tests failing intermittently, we’ve just had to pull them out of the build process.
So, the main part of my questions is: has anyone ever successfully written unit tests for their stored procedures?
The second part of my questions is whether unit testing would be/is easier with linq?
I was thinking that rather than having to set up tables of test data, you could simply create a collection of test objects, and test your linq code in a “linq to objects” situation? (I am a totally new to linq so don’t know if this would even work at all) | I ran into this same issue a while back and found that if I created a simple abstract base class for data access that allowed me to inject a connection and transaction, I could unit test my sprocs to see if they did the work in SQL that I asked them to do and then rollback so none of the test data is left in the db.
This felt better than the usual "run a script to setup my test db, then after the tests run do a cleanup of the junk/test data". This also felt closer to unit testing because these tests could be run alone w/out having a great deal of "everything in the db needs to be 'just so' before I run these tests".
**Here is a snippet of the abstract base class used for data access**
```
Public MustInherit Class Repository(Of T As Class)
Implements IRepository(Of T)
Private mConnectionString As String = ConfigurationManager.ConnectionStrings("Northwind.ConnectionString").ConnectionString
Private mConnection As IDbConnection
Private mTransaction As IDbTransaction
Public Sub New()
mConnection = Nothing
mTransaction = Nothing
End Sub
Public Sub New(ByVal connection As IDbConnection, ByVal transaction As IDbTransaction)
mConnection = connection
mTransaction = transaction
End Sub
Public MustOverride Function BuildEntity(ByVal cmd As SqlCommand) As List(Of T)
Public Function ExecuteReader(ByVal Parameter As Parameter) As List(Of T) Implements IRepository(Of T).ExecuteReader
Dim entityList As List(Of T)
If Not mConnection Is Nothing Then
Using cmd As SqlCommand = mConnection.CreateCommand()
cmd.Transaction = mTransaction
cmd.CommandType = Parameter.Type
cmd.CommandText = Parameter.Text
If Not Parameter.Items Is Nothing Then
For Each param As SqlParameter In Parameter.Items
cmd.Parameters.Add(param)
Next
End If
entityList = BuildEntity(cmd)
If Not entityList Is Nothing Then
Return entityList
End If
End Using
Else
Using conn As SqlConnection = New SqlConnection(mConnectionString)
Using cmd As SqlCommand = conn.CreateCommand()
cmd.CommandType = Parameter.Type
cmd.CommandText = Parameter.Text
If Not Parameter.Items Is Nothing Then
For Each param As SqlParameter In Parameter.Items
cmd.Parameters.Add(param)
Next
End If
conn.Open()
entityList = BuildEntity(cmd)
If Not entityList Is Nothing Then
Return entityList
End If
End Using
End Using
End If
Return Nothing
End Function
End Class
```
**next you will see a sample data access class using the above base to get a list of products**
```
Public Class ProductRepository
Inherits Repository(Of Product)
Implements IProductRepository
Private mCache As IHttpCache
'This const is what you will use in your app
Public Sub New(ByVal cache As IHttpCache)
MyBase.New()
mCache = cache
End Sub
'This const is only used for testing so we can inject a connectin/transaction and have them roll'd back after the test
Public Sub New(ByVal cache As IHttpCache, ByVal connection As IDbConnection, ByVal transaction As IDbTransaction)
MyBase.New(connection, transaction)
mCache = cache
End Sub
Public Function GetProducts() As System.Collections.Generic.List(Of Product) Implements IProductRepository.GetProducts
Dim Parameter As New Parameter()
Parameter.Type = CommandType.StoredProcedure
Parameter.Text = "spGetProducts"
Dim productList As List(Of Product)
productList = MyBase.ExecuteReader(Parameter)
Return productList
End Function
'This function is used in each class that inherits from the base data access class so we can keep all the boring left-right mapping code in 1 place per object
Public Overrides Function BuildEntity(ByVal cmd As System.Data.SqlClient.SqlCommand) As System.Collections.Generic.List(Of Product)
Dim productList As New List(Of Product)
Using reader As SqlDataReader = cmd.ExecuteReader()
Dim product As Product
While reader.Read()
product = New Product()
product.ID = reader("ProductID")
product.SupplierID = reader("SupplierID")
product.CategoryID = reader("CategoryID")
product.ProductName = reader("ProductName")
product.QuantityPerUnit = reader("QuantityPerUnit")
product.UnitPrice = reader("UnitPrice")
product.UnitsInStock = reader("UnitsInStock")
product.UnitsOnOrder = reader("UnitsOnOrder")
product.ReorderLevel = reader("ReorderLevel")
productList.Add(product)
End While
If productList.Count > 0 Then
Return productList
End If
End Using
Return Nothing
End Function
End Class
```
**And now in your unit test you can also inherit from a very simple base class that does your setup / rollback work - or keep this on a per unit test basis**
**below is the simple testing base class I used**
```
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Public MustInherit Class TransactionFixture
Protected mConnection As IDbConnection
Protected mTransaction As IDbTransaction
Private mConnectionString As String = ConfigurationManager.ConnectionStrings("Northwind.ConnectionString").ConnectionString
<TestInitialize()> _
Public Sub CreateConnectionAndBeginTran()
mConnection = New SqlConnection(mConnectionString)
mConnection.Open()
mTransaction = mConnection.BeginTransaction()
End Sub
<TestCleanup()> _
Public Sub RollbackTranAndCloseConnection()
mTransaction.Rollback()
mTransaction.Dispose()
mConnection.Close()
mConnection.Dispose()
End Sub
End Class
```
**and finally - the below is a simple test using that test base class that shows how to test the entire CRUD cycle to make sure all the sprocs do their job and that your ado.net code does the left-right mapping correctly**
**I know this doesn't test the "spGetProducts" sproc used in the above data access sample, but you should see the power behind this approach to unit testing sprocs**
```
Imports SampleApplication.Library
Imports System.Collections.Generic
Imports Microsoft.VisualStudio.TestTools.UnitTesting
<TestClass()> _
Public Class ProductRepositoryUnitTest
Inherits TransactionFixture
Private mRepository As ProductRepository
<TestMethod()> _
Public Sub Should-Insert-Update-And-Delete-Product()
mRepository = New ProductRepository(New HttpCache(), mConnection, mTransaction)
'** Create a test product to manipulate throughout **'
Dim Product As New Product()
Product.ProductName = "TestProduct"
Product.SupplierID = 1
Product.CategoryID = 2
Product.QuantityPerUnit = "10 boxes of stuff"
Product.UnitPrice = 14.95
Product.UnitsInStock = 22
Product.UnitsOnOrder = 19
Product.ReorderLevel = 12
'** Insert the new product object into SQL using your insert sproc **'
mRepository.InsertProduct(Product)
'** Select the product object that was just inserted and verify it does exist **'
'** Using your GetProductById sproc **'
Dim Product2 As Product = mRepository.GetProduct(Product.ID)
Assert.AreEqual("TestProduct", Product2.ProductName)
Assert.AreEqual(1, Product2.SupplierID)
Assert.AreEqual(2, Product2.CategoryID)
Assert.AreEqual("10 boxes of stuff", Product2.QuantityPerUnit)
Assert.AreEqual(14.95, Product2.UnitPrice)
Assert.AreEqual(22, Product2.UnitsInStock)
Assert.AreEqual(19, Product2.UnitsOnOrder)
Assert.AreEqual(12, Product2.ReorderLevel)
'** Update the product object **'
Product2.ProductName = "UpdatedTestProduct"
Product2.SupplierID = 2
Product2.CategoryID = 1
Product2.QuantityPerUnit = "a box of stuff"
Product2.UnitPrice = 16.95
Product2.UnitsInStock = 10
Product2.UnitsOnOrder = 20
Product2.ReorderLevel = 8
mRepository.UpdateProduct(Product2) '**using your update sproc
'** Select the product object that was just updated to verify it completed **'
Dim Product3 As Product = mRepository.GetProduct(Product2.ID)
Assert.AreEqual("UpdatedTestProduct", Product2.ProductName)
Assert.AreEqual(2, Product2.SupplierID)
Assert.AreEqual(1, Product2.CategoryID)
Assert.AreEqual("a box of stuff", Product2.QuantityPerUnit)
Assert.AreEqual(16.95, Product2.UnitPrice)
Assert.AreEqual(10, Product2.UnitsInStock)
Assert.AreEqual(20, Product2.UnitsOnOrder)
Assert.AreEqual(8, Product2.ReorderLevel)
'** Delete the product and verify it does not exist **'
mRepository.DeleteProduct(Product3.ID)
'** The above will use your delete product by id sproc **'
Dim Product4 As Product = mRepository.GetProduct(Product3.ID)
Assert.AreEqual(Nothing, Product4)
End Sub
End Class
```
I know this is a long example, but it helped to have a reusable class for the data access work, and yet another reusable class for my testing so I didn't have to do the setup/teardown work over and over again ;) |
12,385 | <p>How would you attach a propertychanged callback to a property that is inherited? Like such:</p>
<pre><code>class A {
DependencyProperty prop;
}
class B : A {
//...
prop.AddListener(PropertyChangeCallback);
}
</code></pre>
| [
{
"answer_id": 12436,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 3,
"selected": true,
"text": "<p>(edited to remove recommendation to use DependencyPropertyDescriptor, which is not available in Silverlight)</p>\n\n<p><a hr... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93/"
] | How would you attach a propertychanged callback to a property that is inherited? Like such:
```
class A {
DependencyProperty prop;
}
class B : A {
//...
prop.AddListener(PropertyChangeCallback);
}
``` | (edited to remove recommendation to use DependencyPropertyDescriptor, which is not available in Silverlight)
[PropertyDescriptor AddValueChanged Alternative](http://agsmith.wordpress.com/2008/04/07/propertydescriptor-addvaluechanged-alternative/) |
12,428 | <p>Once I have my renamed files I need to add them to my project's wiki page. This is a fairly repetitive manual task, so I guess I could script it but I don't know where to start.</p>
<p>The process is:</p>
<pre><code>Got to appropriate page on the wiki
for each team member (DeveloperA, DeveloperB, DeveloperC)
{
for each of two files ('*_current.jpg', '*_lastweek.jpg')
{
Select 'Attach' link on page
Select the 'manage' link next to the file to be updated
Click 'Browse' button
Browse to the relevant file (which has the same name as the previous version)
Click 'Upload file' button
}
}
</code></pre>
<p>Not necessarily looking for the full solution as I'd like to give it a go myself.</p>
<p>Where to begin? What language could I use to do this and how difficult would it be?</p>
| [
{
"answer_id": 12439,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 1,
"selected": false,
"text": "<p>If you're writing in C#, the WebClient classes might be a good place to start. I bet people could give more specific advic... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/849/"
] | Once I have my renamed files I need to add them to my project's wiki page. This is a fairly repetitive manual task, so I guess I could script it but I don't know where to start.
The process is:
```
Got to appropriate page on the wiki
for each team member (DeveloperA, DeveloperB, DeveloperC)
{
for each of two files ('*_current.jpg', '*_lastweek.jpg')
{
Select 'Attach' link on page
Select the 'manage' link next to the file to be updated
Click 'Browse' button
Browse to the relevant file (which has the same name as the previous version)
Click 'Upload file' button
}
}
```
Not necessarily looking for the full solution as I'd like to give it a go myself.
Where to begin? What language could I use to do this and how difficult would it be? | Check if the wiki you mean to talk to supports [XMLRPC](http://www.jspwiki.org/wiki/WikiRPCInterface2), because if it does it should be a snap. I wrote a tool called [WikiUp](http://trac.gargoyle.ath.cx/trac/wiki/WikiUp) to solve a similar problem (updating a delineated section on a wiki page). |
12,482 | <p>I have CruiseControl.NET Version 1.4 set up on my development server. Whenever a developer checks in code, it makes a compile. </p>
<p>Now we're at a place where we can start giving our application to the testers. We'd like to use ClickOnce to distribute the application, with the idea being that when a tester goes to test the application, they have the latest build. </p>
<p>I can't find a way to make that happen with CruiseControl.NET. We're using MSBUILD to perform the builds.</p>
| [
{
"answer_id": 12497,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": -1,
"selected": false,
"text": "<p>You want to use the ClickOnce manifest generation tasks in msbuild. The process is a little long winded, so I am just... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/702/"
] | I have CruiseControl.NET Version 1.4 set up on my development server. Whenever a developer checks in code, it makes a compile.
Now we're at a place where we can start giving our application to the testers. We'd like to use ClickOnce to distribute the application, with the idea being that when a tester goes to test the application, they have the latest build.
I can't find a way to make that happen with CruiseControl.NET. We're using MSBUILD to perform the builds. | Thanks for all the help. The final solution we implemented took a bit from every answer.
We found it easier to handle working with multiple environments using simple batch files. I'm not suggesting this is the best way to do this, but for our given scenario and requirements, this worked well. Supplement "Project" with your project name and "Environment" with your environment name (dev, test, stage, production, whatever).
Here is the tasks area of our "ccnet.config" file.
```
<!-- override settings -->
<exec>
<executable>F:\Source\Project\Environment\CruiseControl\CopySettings.bat</executable>
</exec>
<!-- compile -->
<msbuild>
<executable>C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe</executable>
<workingDirectory>F:\Source\Project\Environment\</workingDirectory>
<projectFile>Project.sln</projectFile>
<buildArgs>/noconsolelogger /p:Configuration=Debug /v:diag</buildArgs>
<targets>Rebuild</targets>
<timeout>0</timeout>
<logger>ThoughtWorks.CruiseControl.MsBuild.XmlLogger,ThoughtWorks.CruiseControl.MsBuild.dll</logger>
</msbuild>
<!-- clickonce publish -->
<exec>
<executable>F:\Source\Project\Environment\CruiseControl\Publish.bat</executable>
</exec>
```
The first thing you will notice is that CopySettings.bat runs. This copies specific settings for the environment, such as database connections.
Next, the standard MSBUILD task runs. Any compile errors are caught here and handled as normal.
The last thing to execute is Publish.bat. This actually performs a MSBUILD "rebuild" again from command line, and parameters from CruiseControl are automatically passed in and built. Next, MSBUILD is called for the "publish" target. The exact same parameters are given to the publish as the rebuild was issued. This keeps the build numbers in sync. Also, our executables are named differently (i.e. - ProjectDev and ProjectTest). We end up with different version numbers and names, and this allows ClickOnce to do its thing.
The last part of Publish.bat copies the actual files to their new homes. We don't use the publish.htm as all our users are on the network, we just give them a shortcut to the manifest file on their desktop and they can click and always be running the correct executable with a version number that ties out in CruiseControl.
Here is CopySettings.bat
```
XCOPY "F:\Source\Project\Environment\CruiseControl\Project\app.config" "F:\Source\Project\Environment\Project" /Y /I /R
XCOPY "F:\Source\Project\Environment\CruiseControl\Project\My Project\Settings.Designer.vb" "F:\Source\Project\Environment\Project\My Project" /Y /I /R
XCOPY "F:\Source\Project\Environment\CruiseControl\Project\My Project\Settings.settings" "F:\Source\Project\Environment\Project\My Project" /Y /I /R
```
And lastly, here is Publish.bat
```
C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe /target:rebuild "F:\Source\Project\Environment\Project\Project.vbproj" /property:ApplicationRevision=%CCNetLabel% /property:AssemblyName="ProjectEnvironment" /property:PublishUrl="\\Server\bin\Project\Environment\\"
C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe /target:publish "F:\Source\Project\Environment\Project\Project.vbproj" /property:ApplicationVersion="1.0.0.%CCNetLabel%" /property:AssemblyVersion="1.0.0.%CCNetLabel%" /property:AssemblyName="ProjectEnvironment"
XCOPY "F:\Source\Project\Environment\Project\bin\Debug\app.publish" "F:\Binary\Project\Environment" /Y /I
XCOPY "F:\Source\Project\Environment\Project\bin\Debug\app.publish\Application Files" "F:\Binary\Project\Environment\Application Files" /Y /I /S
```
Like I said, it's probably not done the way that CruiseControl and MSBUILD developers had intended things to work, but it does work. If you need to get this working yesterday, it might be the solution you're looking for. Good luck! |
12,489 | <p>How do you scan a directory for folders and files in C? It needs to be cross-platform.</p>
| [
{
"answer_id": 12500,
"author": "PW.",
"author_id": 927,
"author_profile": "https://Stackoverflow.com/users/927",
"pm_score": 3,
"selected": false,
"text": "<p>opendir/readdir are POSIX. If POSIX is not enough for the portability you want to achieve, check <a href=\"http://apr.apache.org... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | How do you scan a directory for folders and files in C? It needs to be cross-platform. | The following POSIX program will print the names of the files in the current directory:
```
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("./");
if (dp != NULL)
{
while ((ep = readdir (dp)) != NULL)
puts (ep->d_name);
(void) closedir (dp);
return 0;
}
else
{
perror ("Couldn't open the directory");
return -1;
}
}
```
Credit: <http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html>
Tested in Ubuntu 16.04. |
12,516 | <p>This morning, I was reading <a href="http://steve.yegge.googlepages.com/when-polymorphism-fails" rel="noreferrer">Steve Yegge's: When Polymorphism Fails</a>, when I came across a question that a co-worker of his used to ask potential employees when they came for their interview at Amazon.</p>
<blockquote>
<p>As an example of polymorphism in
action, let's look at the classic
"eval" interview question, which (as
far as I know) was brought to Amazon
by Ron Braunstein. The question is
quite a rich one, as it manages to
probe a wide variety of important
skills: OOP design, recursion, binary
trees, polymorphism and runtime
typing, general coding skills, and (if
you want to make it extra hard)
parsing theory.</p>
<p>At some point, the candidate hopefully
realizes that you can represent an
arithmetic expression as a binary
tree, assuming you're only using
binary operators such as "+", "-",
"*", "/". The leaf nodes are all
numbers, and the internal nodes are
all operators. Evaluating the
expression means walking the tree. If
the candidate doesn't realize this,
you can gently lead them to it, or if
necessary, just tell them.</p>
<p>Even if you tell them, it's still an
interesting problem.</p>
<p>The first half of the question, which
some people (whose names I will
protect to my dying breath, but their
initials are Willie Lewis) feel is a
Job Requirement If You Want To Call
Yourself A Developer And Work At
Amazon, is actually kinda hard. The
question is: how do you go from an
arithmetic expression (e.g. in a
string) such as "2 + (2)" to an
expression tree. We may have an ADJ
challenge on this question at some
point.</p>
<p>The second half is: let's say this is
a 2-person project, and your partner,
who we'll call "Willie", is
responsible for transforming the
string expression into a tree. You get
the easy part: you need to decide what
classes Willie is to construct the
tree with. You can do it in any
language, but make sure you pick one,
or Willie will hand you assembly
language. If he's feeling ornery, it
will be for a processor that is no
longer manufactured in production.</p>
<p>You'd be amazed at how many candidates
boff this one.</p>
<p>I won't give away the answer, but a
Standard Bad Solution involves the use
of a switch or case statment (or just
good old-fashioned cascaded-ifs). A
Slightly Better Solution involves
using a table of function pointers,
and the Probably Best Solution
involves using polymorphism. I
encourage you to work through it
sometime. Fun stuff!</p>
</blockquote>
<p>So, let's try to tackle the problem all three ways. How do you go from an arithmetic expression (e.g. in a string) such as "2 + (2)" to an expression tree using cascaded-if's, a table of function pointers, and/or polymorphism? </p>
<p>Feel free to tackle one, two, or all three.</p>
<p>[update: title modified to better match what most of the answers have been.]</p>
| [
{
"answer_id": 12538,
"author": "eplawless",
"author_id": 1370,
"author_profile": "https://Stackoverflow.com/users/1370",
"pm_score": 2,
"selected": false,
"text": "<p>String Tokenizer + LL(1) Parser will give you an expression tree... the polymorphism way might involve an abstract Arith... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25/"
] | This morning, I was reading [Steve Yegge's: When Polymorphism Fails](http://steve.yegge.googlepages.com/when-polymorphism-fails), when I came across a question that a co-worker of his used to ask potential employees when they came for their interview at Amazon.
>
> As an example of polymorphism in
> action, let's look at the classic
> "eval" interview question, which (as
> far as I know) was brought to Amazon
> by Ron Braunstein. The question is
> quite a rich one, as it manages to
> probe a wide variety of important
> skills: OOP design, recursion, binary
> trees, polymorphism and runtime
> typing, general coding skills, and (if
> you want to make it extra hard)
> parsing theory.
>
>
> At some point, the candidate hopefully
> realizes that you can represent an
> arithmetic expression as a binary
> tree, assuming you're only using
> binary operators such as "+", "-",
> "\*", "/". The leaf nodes are all
> numbers, and the internal nodes are
> all operators. Evaluating the
> expression means walking the tree. If
> the candidate doesn't realize this,
> you can gently lead them to it, or if
> necessary, just tell them.
>
>
> Even if you tell them, it's still an
> interesting problem.
>
>
> The first half of the question, which
> some people (whose names I will
> protect to my dying breath, but their
> initials are Willie Lewis) feel is a
> Job Requirement If You Want To Call
> Yourself A Developer And Work At
> Amazon, is actually kinda hard. The
> question is: how do you go from an
> arithmetic expression (e.g. in a
> string) such as "2 + (2)" to an
> expression tree. We may have an ADJ
> challenge on this question at some
> point.
>
>
> The second half is: let's say this is
> a 2-person project, and your partner,
> who we'll call "Willie", is
> responsible for transforming the
> string expression into a tree. You get
> the easy part: you need to decide what
> classes Willie is to construct the
> tree with. You can do it in any
> language, but make sure you pick one,
> or Willie will hand you assembly
> language. If he's feeling ornery, it
> will be for a processor that is no
> longer manufactured in production.
>
>
> You'd be amazed at how many candidates
> boff this one.
>
>
> I won't give away the answer, but a
> Standard Bad Solution involves the use
> of a switch or case statment (or just
> good old-fashioned cascaded-ifs). A
> Slightly Better Solution involves
> using a table of function pointers,
> and the Probably Best Solution
> involves using polymorphism. I
> encourage you to work through it
> sometime. Fun stuff!
>
>
>
So, let's try to tackle the problem all three ways. How do you go from an arithmetic expression (e.g. in a string) such as "2 + (2)" to an expression tree using cascaded-if's, a table of function pointers, and/or polymorphism?
Feel free to tackle one, two, or all three.
[update: title modified to better match what most of the answers have been.] | **Polymorphic Tree Walking**, Python version
```
#!/usr/bin/python
class Node:
"""base class, you should not process one of these"""
def process(self):
raise('you should not be processing a node')
class BinaryNode(Node):
"""base class for binary nodes"""
def __init__(self, _left, _right):
self.left = _left
self.right = _right
def process(self):
raise('you should not be processing a binarynode')
class Plus(BinaryNode):
def process(self):
return self.left.process() + self.right.process()
class Minus(BinaryNode):
def process(self):
return self.left.process() - self.right.process()
class Mul(BinaryNode):
def process(self):
return self.left.process() * self.right.process()
class Div(BinaryNode):
def process(self):
return self.left.process() / self.right.process()
class Num(Node):
def __init__(self, _value):
self.value = _value
def process(self):
return self.value
def demo(n):
print n.process()
demo(Num(2)) # 2
demo(Plus(Num(2),Num(5))) # 2 + 3
demo(Plus(Mul(Num(2),Num(3)),Div(Num(10),Num(5)))) # (2 * 3) + (10 / 2)
```
The tests are just building up the binary trees by using constructors.
program structure:
abstract base class: Node
* all Nodes inherit from this class
abstract base class: BinaryNode
* all binary operators inherit from this class
* process method does the work of evaluting the expression and returning the result
binary operator classes: Plus,Minus,Mul,Div
* two child nodes, one each for left side and right side subexpressions
number class: Num
* holds a leaf-node numeric value, e.g. 17 or 42 |
12,533 | <p>Is there a quick one-liner to call datepart in Sql Server and get back the name of the day instead of just the number?</p>
<pre><code>select datepart(dw, getdate());
</code></pre>
<p>This will return 1-7, with Sunday being 1. I would like 'Sunday' instead of 1.</p>
| [
{
"answer_id": 12541,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 0,
"selected": false,
"text": "<p>This is not possible without using the result to select the day yourself. For one thing the textual representation of... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] | Is there a quick one-liner to call datepart in Sql Server and get back the name of the day instead of just the number?
```
select datepart(dw, getdate());
```
This will return 1-7, with Sunday being 1. I would like 'Sunday' instead of 1. | ```
select datename(weekday, getdate());
``` |
12,565 | <p>In Ruby, what's the difference between <code>{}</code> and <code>[]</code>?</p>
<p><code>{}</code> seems to be used for both code blocks and hashes.</p>
<p>Are <code>[]</code> only for arrays?</p>
<p>The documention isn't very clear.</p>
| [
{
"answer_id": 12575,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 3,
"selected": false,
"text": "<p>Broadly speaking, you're correct. As well as hashes, the general style is that curly braces <code>{}</code> are often ... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1470/"
] | In Ruby, what's the difference between `{}` and `[]`?
`{}` seems to be used for both code blocks and hashes.
Are `[]` only for arrays?
The documention isn't very clear. | It depends on the context:
1. When on their own, or assigning to a variable, `[]` creates arrays, and `{}` creates hashes. e.g.
```
a = [1,2,3] # an array
b = {1 => 2} # a hash
```
2. `[]` can be overridden as a custom method, and is generally used to fetch things from hashes (the standard library sets up `[]` as a method on hashes which is the same as `fetch`)
There is also a convention that it is used as a class method in the same way you might use a `static Create` method in C# or Java. e.g.
```
a = {1 => 2} # create a hash for example
puts a[1] # same as a.fetch(1), will print 2
Hash[1,2,3,4] # this is a custom class method which creates a new hash
```
See the Ruby [Hash docs](http://www.ruby-doc.org/core-2.0/Hash.html#method-c-5B-5D) for that last example.
3. This is probably the most tricky one -
`{}` is also syntax for blocks, but only when passed to a method OUTSIDE the arguments parens.
When you invoke methods without parens, Ruby looks at where you put the commas to figure out where the arguments end (where the parens would have been, had you typed them)
```
1.upto(2) { puts 'hello' } # it's a block
1.upto 2 { puts 'hello' } # syntax error, ruby can't figure out where the function args end
1.upto 2, { puts 'hello' } # the comma means "argument", so ruby sees it as a hash - this won't work because puts 'hello' isn't a valid hash
``` |
12,569 | <p>Let's say we have a simple function defined in a pseudo language.</p>
<pre><code>List<Numbers> SortNumbers(List<Numbers> unsorted, bool ascending);
</code></pre>
<p>We pass in an unsorted list of numbers and a boolean specifying ascending or descending sort order. In return, we get a sorted list of numbers.</p>
<p>In my experience, some people are better at capturing boundary conditions than others. The question is, "How do you know when you are 'done' capturing test cases"?</p>
<p>We can start listing cases now and some clever person will undoubtedly think of 'one more' case that isn't covered by any of the previous.</p>
| [
{
"answer_id": 12571,
"author": "Justin Standard",
"author_id": 92,
"author_profile": "https://Stackoverflow.com/users/92",
"pm_score": 4,
"selected": true,
"text": "<p>Don't waste too much time trying to think of <em>every</em> boundry condition. Your tests won't be able to catch <em>e... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12081/"
] | Let's say we have a simple function defined in a pseudo language.
```
List<Numbers> SortNumbers(List<Numbers> unsorted, bool ascending);
```
We pass in an unsorted list of numbers and a boolean specifying ascending or descending sort order. In return, we get a sorted list of numbers.
In my experience, some people are better at capturing boundary conditions than others. The question is, "How do you know when you are 'done' capturing test cases"?
We can start listing cases now and some clever person will undoubtedly think of 'one more' case that isn't covered by any of the previous. | Don't waste too much time trying to think of *every* boundry condition. Your tests won't be able to catch *every* bug first time around. The idea is to have tests that are *pretty good*, and then each time a bug *does* surface, write a new test specifically for that bug so that you never hear from it again.
Another note I want to make about code coverage tools. In a language like C# or Java where your have many get/set and similar methods, you should **not** be shooting for 100% coverage. That means you are wasting too much time writing tests for trivial code. You *only* want 100% coverage on your complex business logic. If your full codebase is closer to 70-80% coverage, you are doing a good job. If your code coverage tool allows multiple coverage metrics, the best one is 'block coverage' which measures coverage of 'basic blocks'. Other types are class and method coverage (which don't give you as much information) and line coverage (which is too fine grain). |
12,576 | <p>What can I do to increase the performance/speed of my PHP scripts without installing software on my servers?</p>
| [
{
"answer_id": 12579,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 2,
"selected": false,
"text": "<p>There is no magic solution, and attempting to provide generic solutions could well just be a waste of time.</p>\n\n<p... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] | What can I do to increase the performance/speed of my PHP scripts without installing software on my servers? | Profile. Profile. Profile. I'm not sure if there is anything out there for PHP, but it should be simple to write a little tool to insert profiling information in your code. You will want to profile function times and SQL query times.
So where you have a function:
```
function foo($stuff) {
...
return ...;
}
```
I would change it to:
```
function foo($stuff) {
trace_push_fn('foo');
...
trace_pop_fn('foo');
return ...;
}
```
(This is one of those cases where multiple returns in a function become a hinderance.)
And SQL:
```
function bar($stuff) {
trace_push_fn('bar');
$query = ...;
trace_push_sql($query);
mysql_query($query);
trace_pop_sql($query);
trace_pop_fn('bar');
return ...;
}
```
In the end, you can generate a full trace of the program execution and use all sorts of techniques to identify your bottlenecks. |
12,591 | <p>Is there a way, when I parse an XML document using lxml, to validate that document against its DTD using an external catalog file? I need to be able to work the fixed attributes defined in a document’s DTD.</p>
| [
{
"answer_id": 13040,
"author": "Michael Twomey",
"author_id": 995,
"author_profile": "https://Stackoverflow.com/users/995",
"pm_score": 1,
"selected": false,
"text": "<p>Can you give an example? According to the <a href=\"http://codespeak.net/lxml/validation.html\" rel=\"nofollow norefe... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207/"
] | Is there a way, when I parse an XML document using lxml, to validate that document against its DTD using an external catalog file? I need to be able to work the fixed attributes defined in a document’s DTD. | You can add the catalog to the `XML_CATALOG_FILES` environment variable:
```
os.environ['XML_CATALOG_FILES'] = 'file:///to/my/catalog.xml'
```
See [this thread](http://thread.gmane.org/gmane.comp.python.lxml.devel/5907). Note that entries in `XML_CATALOG_FILES` are space-separated URLs. You can use Python's `pathname2url` and `urljoin` (with `file:`) to generate the URL from a pathname. |
12,592 | <p>Is it possible to write a <code>doctest</code> unit test that will check that an exception is raised?<br />
For example, if I have a function <code>foo(x)</code> that is supposed to raise an exception if <code>x < 0</code>, how would I write the <code>doctest</code> for that?</p>
| [
{
"answer_id": 12609,
"author": "cnu",
"author_id": 1448,
"author_profile": "https://Stackoverflow.com/users/1448",
"pm_score": 8,
"selected": true,
"text": "<p>Yes. You can do it. The <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"noreferrer\">doctest module documentat... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] | Is it possible to write a `doctest` unit test that will check that an exception is raised?
For example, if I have a function `foo(x)` that is supposed to raise an exception if `x < 0`, how would I write the `doctest` for that? | Yes. You can do it. The [doctest module documentation](https://docs.python.org/3/library/doctest.html) and Wikipedia has an [example](http://en.wikipedia.org/wiki/Doctest#Example_2:_doctests_embedded_in_a_README.txt_file) of it.
```
>>> x
Traceback (most recent call last):
...
NameError: name 'x' is not defined
``` |
12,613 | <p>I've been using Emacs's sql interactive mode to talk to the MySQL db server and gotten to enjoy it. A developer has set up another db on a new non-default port number but I don't know how to access it using sql-mysql.</p>
<p>How do I specify a port number when I'm trying to connect to a database?</p>
<p>It would be even better if Emacs can prompt me for a port number and just use the default if I don't specify. Any chances of that?</p>
| [
{
"answer_id": 12628,
"author": "Marcel Levy",
"author_id": 676,
"author_profile": "https://Stackoverflow.com/users/676",
"pm_score": 3,
"selected": false,
"text": "<pre><code>(setq sql-mysql-options (list \"-P <port number>\"))\n</code></pre>\n"
},
{
"answer_id": 12658,
... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
] | I've been using Emacs's sql interactive mode to talk to the MySQL db server and gotten to enjoy it. A developer has set up another db on a new non-default port number but I don't know how to access it using sql-mysql.
How do I specify a port number when I'm trying to connect to a database?
It would be even better if Emacs can prompt me for a port number and just use the default if I don't specify. Any chances of that? | After digging through the sql.el file, I found a variable that allows me to specify a port when I try to create a connection.
This option was added GNU Emacs 24.1.
>
> **sql-mysql-login-params**
>
>
> List of login parameters needed to connect to MySQL.
>
>
>
I added this to my Emacs init file:
```
(setq sql-mysql-login-params (append sql-mysql-login-params '(port)))
```
The default port is 0. If you'd like to set that to the default MySQL port you can customize `sql-port`
```
(setq sql-port 3306) ;; default MySQL port
```
There is a `sql-*-login-params` variable for all the popular RDMS systems in GNU Emacs 24.1. `sql-port` is used for both MySQL and PostreSQL |
12,638 | <p>So basically I'm building an app for my company and it NEEDS to be built using MS Access and it needs to be built on SQL Server.</p>
<p>I've drawn up most of the plans but am having a hard time figuring out a way to handle the auditing system.</p>
<p>Since it is being used internally only and you won't even be able to touch the db from outside the building we are not using a login system as the program will only be used once a user has already logged in to our internal network via Active Directory. Knowing this, we're using <a href="https://stackoverflow.com/questions/9052/is-there-a-way-for-ms-access-to-grab-the-current-active-directory-user">a system to detect automatically the name of the Active Directory user</a> and with their permissions in one of the DB tables, deciding what they can or cannot do.</p>
<p>So the actual audit table will have 3 columns (this design may change but for this question it doesn't matter); who (Active Directory User), when (time of addition/deletion/edit), what (what was changed)</p>
<p>My question is how should I be handling this. Ideally I know I should be using a trigger so that it is impossible for the database to be updated without an audit being logged, however I don't know how I could grab the Active Directory User that way. An alternate would be to code it directly into the Access source so that whenever something changes I run an INSERT statement. Obviously that is flawed because if something happens to Access or the database is touched by something else then it will not log the audit.</p>
<p>Any advice, examples or articles that may help me would be greatly appreciated!</p>
| [
{
"answer_id": 12644,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 0,
"selected": false,
"text": "<p>How many users of the app will there be? Is there possibility of using windows integrated authentication for SQL authentication?... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
] | So basically I'm building an app for my company and it NEEDS to be built using MS Access and it needs to be built on SQL Server.
I've drawn up most of the plans but am having a hard time figuring out a way to handle the auditing system.
Since it is being used internally only and you won't even be able to touch the db from outside the building we are not using a login system as the program will only be used once a user has already logged in to our internal network via Active Directory. Knowing this, we're using [a system to detect automatically the name of the Active Directory user](https://stackoverflow.com/questions/9052/is-there-a-way-for-ms-access-to-grab-the-current-active-directory-user) and with their permissions in one of the DB tables, deciding what they can or cannot do.
So the actual audit table will have 3 columns (this design may change but for this question it doesn't matter); who (Active Directory User), when (time of addition/deletion/edit), what (what was changed)
My question is how should I be handling this. Ideally I know I should be using a trigger so that it is impossible for the database to be updated without an audit being logged, however I don't know how I could grab the Active Directory User that way. An alternate would be to code it directly into the Access source so that whenever something changes I run an INSERT statement. Obviously that is flawed because if something happens to Access or the database is touched by something else then it will not log the audit.
Any advice, examples or articles that may help me would be greatly appreciated! | Does this work for you?
```
select user_name(),suser_sname()
```
---
Doh! I forgot to escape my code. |
12,642 | <p>I am trying to upload a file or stream of data to our web server and I cant find a decent way of doing this. I have tried both <code>WebClient</code> and <code>WebRequest</code> both have their problems. </p>
<p><strong>WebClient</strong><br>
Nice and easy but you do not get any notification that the asynchronous upload has completed, and the <code>UploadProgressChanged</code> event doesnt get called back with anything useful. The alternative is to convert your binary data to a string and use <code>UploadStringASync</code> because then at least you get a <code>UploadStringCompleted</code>, problem is you need a lot of ram for big files as its encoding all the data and uploading it in one go.</p>
<p><strong>HttpWebRequest</strong><br>
Bit more complicated but still does what is needed, problem I am getting is that even though it is called on a background thread (supposedly), it still seems to be blocking my UI and the whole browser until the upload has completed which doesnt seem quite right.</p>
<p>Normal .net does have some appropriate <code>WebClient</code> methods for <a href="http://msdn.microsoft.com/en-us/library/system.net.webclient.onuploaddatacompleted.aspx" rel="nofollow noreferrer">OnUploadDataCompleted</a> and progress but these arent available in Silverlight .net ... big omission I think!</p>
<p>Does anyone have any solutions, I need to upload multiple binary files preferrably with a progress but I need to perform some actions when the files have completed their upload.</p>
<p>Look forward to some help with this.</p>
| [
{
"answer_id": 12649,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 0,
"selected": false,
"text": "<p>Matt Berseth had some thoughts in this, might help:</p>\n\n<p><a href=\"http://mattberseth.com/blog/2008/07/aspnet_file_upload_w... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1478/"
] | I am trying to upload a file or stream of data to our web server and I cant find a decent way of doing this. I have tried both `WebClient` and `WebRequest` both have their problems.
**WebClient**
Nice and easy but you do not get any notification that the asynchronous upload has completed, and the `UploadProgressChanged` event doesnt get called back with anything useful. The alternative is to convert your binary data to a string and use `UploadStringASync` because then at least you get a `UploadStringCompleted`, problem is you need a lot of ram for big files as its encoding all the data and uploading it in one go.
**HttpWebRequest**
Bit more complicated but still does what is needed, problem I am getting is that even though it is called on a background thread (supposedly), it still seems to be blocking my UI and the whole browser until the upload has completed which doesnt seem quite right.
Normal .net does have some appropriate `WebClient` methods for [OnUploadDataCompleted](http://msdn.microsoft.com/en-us/library/system.net.webclient.onuploaddatacompleted.aspx) and progress but these arent available in Silverlight .net ... big omission I think!
Does anyone have any solutions, I need to upload multiple binary files preferrably with a progress but I need to perform some actions when the files have completed their upload.
Look forward to some help with this. | The way i get around it is through INotifyPropertyChanged and event notification.
The essentials:
```
public void DoIt(){
this.IsUploading = True;
WebRequest postRequest = WebRequest.Create(new Uri(ServiceURL));
postRequest.BeginGetRequestStream(new AsyncCallback(RequestOpened), postRequest);
}
private void RequestOpened(IAsyncResult result){
WebRequest req = result.AsyncState as WebRequest;
req.BeginGetResponse(new AsyncCallback(GetResponse), req);
}
private void GetResponse(IAsyncResult result)
{
WebRequest req = result.AsyncState as WebRequest;
string serverresult = string.Empty;
WebResponse postResponse = req.EndGetResponse(result);
StreamReader responseReader = new StreamReader(postResponse.GetResponseStream());
this.IsUploading= False;
}
private Bool_IsUploading;
public Bool IsUploading
{
get { return _IsUploading; }
private set
{
_IsUploading = value;
OnPropertyChanged("IsUploading");
}
}
```
Right now silverlight is a PiTA because of the double and triple Async calls. |
12,647 | <p>Is there a simple way in Perl that will allow me to determine if a given variable is numeric? Something along the lines of:</p>
<pre><code>if (is_number($x))
{ ... }
</code></pre>
<p>would be ideal. A technique that won't throw warnings when the <code>-w</code> switch is being used is certainly preferred.</p>
| [
{
"answer_id": 12654,
"author": "farmerchris",
"author_id": 1317,
"author_profile": "https://Stackoverflow.com/users/1317",
"pm_score": 2,
"selected": false,
"text": "<p>Not perfect, but you can use a regex:</p>\n\n<pre><code>sub isnumber \n{\n shift =~ /^-?\\d+\\.?\\d*$/;\n}\n</code>... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/872/"
] | Is there a simple way in Perl that will allow me to determine if a given variable is numeric? Something along the lines of:
```
if (is_number($x))
{ ... }
```
would be ideal. A technique that won't throw warnings when the `-w` switch is being used is certainly preferred. | Use `Scalar::Util::looks_like_number()` which uses the internal Perl C API's looks\_like\_number() function, which is probably the most efficient way to do this.
Note that the strings "inf" and "infinity" are treated as numbers.
Example:
--------
```
#!/usr/bin/perl
use warnings;
use strict;
use Scalar::Util qw(looks_like_number);
my @exprs = qw(1 5.25 0.001 1.3e8 foo bar 1dd inf infinity);
foreach my $expr (@exprs) {
print "$expr is", looks_like_number($expr) ? '' : ' not', " a number\n";
}
```
Gives this output:
```
1 is a number
5.25 is a number
0.001 is a number
1.3e8 is a number
foo is not a number
bar is not a number
1dd is not a number
inf is a number
infinity is a number
```
See also:
---------
* [perldoc Scalar::Util](http://perldoc.perl.org/Scalar/Util.html)
* [perldoc perlapi](http://perldoc.perl.org/perlapi.html#SV-Body-Allocation) for `looks_like_number` |
12,656 | <p>In a project that I'm about to wrap up, I've written and implemented an object-relational mapping solution for PHP. Before the doubters and dreamers cry out "how on earth?", relax -- I haven't found a way to make late static binding work -- I'm just working around it in the best way that I possibly can.</p>
<p>Anyway, I'm not currently using prepared statements for querying, because I couldn't come up with a way to pass a variable number of arguments to the <code>bind_params()</code> or <code>bind_result()</code> methods. </p>
<p>Why do I need to support a variable number of arguments, you ask? Because the superclass of my models (think of my solution as a hacked-up PHP ActiveRecord wannabe) is where the querying is defined, and so the find() method, for example, doesn't know how many parameters it would need to bind.</p>
<p>Now, I've already thought of building an argument list and passing a string to eval(), but I don't like that solution very much -- I'd rather just implement my own security checks and pass on statements.</p>
<p>Does anyone have any suggestions (or success stories) about how to get this done? If you can help me solve this first problem, perhaps we can tackle binding the result set (something I suspect will be more difficult, or at least more resource-intensive if it involves an initial query to determine table structure).</p>
| [
{
"answer_id": 13092,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 5,
"selected": true,
"text": "<p>In PHP you can pass a variable number of arguments to a function or method by using <a href=\"http://www.php.net/call_use... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344/"
] | In a project that I'm about to wrap up, I've written and implemented an object-relational mapping solution for PHP. Before the doubters and dreamers cry out "how on earth?", relax -- I haven't found a way to make late static binding work -- I'm just working around it in the best way that I possibly can.
Anyway, I'm not currently using prepared statements for querying, because I couldn't come up with a way to pass a variable number of arguments to the `bind_params()` or `bind_result()` methods.
Why do I need to support a variable number of arguments, you ask? Because the superclass of my models (think of my solution as a hacked-up PHP ActiveRecord wannabe) is where the querying is defined, and so the find() method, for example, doesn't know how many parameters it would need to bind.
Now, I've already thought of building an argument list and passing a string to eval(), but I don't like that solution very much -- I'd rather just implement my own security checks and pass on statements.
Does anyone have any suggestions (or success stories) about how to get this done? If you can help me solve this first problem, perhaps we can tackle binding the result set (something I suspect will be more difficult, or at least more resource-intensive if it involves an initial query to determine table structure). | In PHP you can pass a variable number of arguments to a function or method by using [`call_user_func_array`](http://www.php.net/call_user_func_array). An example for a method would be:
```
call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);
```
The function will be called with each member in the array passed as its own argument. |
12,657 | <p>I'm using the new ASP.Net ListView control to list database items that will be grouped together in sections based on one of their columns like so:</p>
<pre><code>region1
store1
store2
store3
region2
store4
region3
store5
store6
</code></pre>
<p>Is this possible to do with the ListView's GroupItemTemplate? Every example I have seen uses a static number of items per group, which won't work for me. Am I misunderstanding the purpose of the GroupItem?</p>
| [
{
"answer_id": 12735,
"author": "Otto",
"author_id": 519,
"author_profile": "https://Stackoverflow.com/users/519",
"pm_score": 3,
"selected": true,
"text": "<p>I haven't used GroupItemCount, but I have taken this example written up by <a href=\"http://mattberseth.com/\" rel=\"nofollow no... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1249/"
] | I'm using the new ASP.Net ListView control to list database items that will be grouped together in sections based on one of their columns like so:
```
region1
store1
store2
store3
region2
store4
region3
store5
store6
```
Is this possible to do with the ListView's GroupItemTemplate? Every example I have seen uses a static number of items per group, which won't work for me. Am I misunderstanding the purpose of the GroupItem? | I haven't used GroupItemCount, but I have taken this example written up by [Matt Berseth](http://mattberseth.com/) titled [Building a Grouping Grid with the ASP.NET 3.5 LinqDataSource and ListView Controls](http://mattberseth.com/blog/2008/01/building_a_grouping_grid_with.html) and have grouped items by a key just like you want.
It involves using an outer and inner ListView control. Works great, give it a try. |
12,661 | <p>What's the most efficient way to resize large images in PHP?</p>
<p>I'm currently using the <a href="http://en.wikipedia.org/wiki/GD_Graphics_Library" rel="noreferrer">GD</a> function imagecopyresampled to take high resolution images, and cleanly resize them down to a size for web viewing (roughly 700 pixels wide by 700 pixels tall).</p>
<p>This works great on small (under 2 MB) photos and the entire resize operation takes less than a second on the server. However, the site will eventually service photographers who may be uploading images up to 10 MB in size (or images up to 5000x4000 pixels in size).</p>
<p>Doing this kind of resize operation with large images tends to increase the memory usage by a very large margin (larger images can spike the memory usage for the script past 80 MB). Is there any way to make this resize operation more efficient? Should I be using an alternate image library such as <a href="http://en.wikipedia.org/wiki/ImageMagick" rel="noreferrer">ImageMagick</a>?</p>
<p>Right now, the resize code looks something like this</p>
<pre><code>function makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality) {
// Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it
// and places it at endfile (path/to/thumb.jpg).
// Load image and get image size.
$img = imagecreatefromjpeg($sourcefile);
$width = imagesx( $img );
$height = imagesy( $img );
if ($width > $height) {
$newwidth = $thumbwidth;
$divisor = $width / $thumbwidth;
$newheight = floor( $height / $divisor);
} else {
$newheight = $thumbheight;
$divisor = $height / $thumbheight;
$newwidth = floor( $width / $divisor );
}
// Create a new temporary image.
$tmpimg = imagecreatetruecolor( $newwidth, $newheight );
// Copy and resize old image into new image.
imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
// Save thumbnail into a file.
imagejpeg( $tmpimg, $endfile, $quality);
// release the memory
imagedestroy($tmpimg);
imagedestroy($img);
</code></pre>
| [
{
"answer_id": 12732,
"author": "phenry",
"author_id": 1482,
"author_profile": "https://Stackoverflow.com/users/1482",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://phpthumb.sourceforge.net/\" rel=\"noreferrer\">phpThumb</a> uses ImageMagick whenever possible for speed (... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477/"
] | What's the most efficient way to resize large images in PHP?
I'm currently using the [GD](http://en.wikipedia.org/wiki/GD_Graphics_Library) function imagecopyresampled to take high resolution images, and cleanly resize them down to a size for web viewing (roughly 700 pixels wide by 700 pixels tall).
This works great on small (under 2 MB) photos and the entire resize operation takes less than a second on the server. However, the site will eventually service photographers who may be uploading images up to 10 MB in size (or images up to 5000x4000 pixels in size).
Doing this kind of resize operation with large images tends to increase the memory usage by a very large margin (larger images can spike the memory usage for the script past 80 MB). Is there any way to make this resize operation more efficient? Should I be using an alternate image library such as [ImageMagick](http://en.wikipedia.org/wiki/ImageMagick)?
Right now, the resize code looks something like this
```
function makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality) {
// Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it
// and places it at endfile (path/to/thumb.jpg).
// Load image and get image size.
$img = imagecreatefromjpeg($sourcefile);
$width = imagesx( $img );
$height = imagesy( $img );
if ($width > $height) {
$newwidth = $thumbwidth;
$divisor = $width / $thumbwidth;
$newheight = floor( $height / $divisor);
} else {
$newheight = $thumbheight;
$divisor = $height / $thumbheight;
$newwidth = floor( $width / $divisor );
}
// Create a new temporary image.
$tmpimg = imagecreatetruecolor( $newwidth, $newheight );
// Copy and resize old image into new image.
imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
// Save thumbnail into a file.
imagejpeg( $tmpimg, $endfile, $quality);
// release the memory
imagedestroy($tmpimg);
imagedestroy($img);
``` | People say that ImageMagick is much faster. At best just compare both libraries and measure that.
1. Prepare 1000 typical images.
2. Write two scripts -- one for GD, one
for ImageMagick.
3. Run both of them a few times.
4. Compare results (total execution
time, CPU and I/O usage, result
image quality).
Something which the best everyone else, could not be the best for you.
Also, in my opinion, ImageMagick has much better API interface. |
12,702 | <p>I have a WCF service from which I want to return a DataTable. I know that this is often a highly-debated topic, as far as whether or not returning DataTables is a good practice. Let's put that aside for a moment.</p>
<p>When I create a DataTable from scratch, as below, there are no problems whatsoever. The table is created, populated, and returned to the client, and all is well:</p>
<pre><code>[DataContract]
public DataTable GetTbl()
{
DataTable tbl = new DataTable("testTbl");
for(int i=0;i<100;i++)
{
tbl.Columns.Add(i);
tbl.Rows.Add(new string[]{"testValue"});
}
return tbl;
}
</code></pre>
<p>However, as soon as I go out and hit the database to create the table, as below, I get a CommunicationException "The underlying connection was closed: The connection was closed unexpectedly."</p>
<pre><code>[DataContract]
public DataTable GetTbl()
{
DataTable tbl = new DataTable("testTbl");
//Populate table with SQL query
return tbl;
}
</code></pre>
<p>The table is being populated correctly on the server side. It is significantly smaller than the test table that I looped through and returned, and the query is small and fast - there is no issue here with timeouts or large data transfer. The same exact functions and DataContracts/ServiceContracts/BehaviorContracts are being used.</p>
<p>Why would the way that the table is being populated have any bearing on the table returning successfully?</p>
| [
{
"answer_id": 12712,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>The attribute you want is OperationContract (on interface) / Operation Behavior (on method):</p>\n\n<pre><code>[ServiceCon... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940/"
] | I have a WCF service from which I want to return a DataTable. I know that this is often a highly-debated topic, as far as whether or not returning DataTables is a good practice. Let's put that aside for a moment.
When I create a DataTable from scratch, as below, there are no problems whatsoever. The table is created, populated, and returned to the client, and all is well:
```
[DataContract]
public DataTable GetTbl()
{
DataTable tbl = new DataTable("testTbl");
for(int i=0;i<100;i++)
{
tbl.Columns.Add(i);
tbl.Rows.Add(new string[]{"testValue"});
}
return tbl;
}
```
However, as soon as I go out and hit the database to create the table, as below, I get a CommunicationException "The underlying connection was closed: The connection was closed unexpectedly."
```
[DataContract]
public DataTable GetTbl()
{
DataTable tbl = new DataTable("testTbl");
//Populate table with SQL query
return tbl;
}
```
The table is being populated correctly on the server side. It is significantly smaller than the test table that I looped through and returned, and the query is small and fast - there is no issue here with timeouts or large data transfer. The same exact functions and DataContracts/ServiceContracts/BehaviorContracts are being used.
Why would the way that the table is being populated have any bearing on the table returning successfully? | For anyone having similar problems, I have solved my issue. It was several-fold.
* As Darren suggested and Paul backed up, the Max..Size properties in the configuration needed to be enlarged. The SvcTraceViewer utility helped in determining this, but it still does not always give the most helpful error messages.
* It also appears that when the Service Reference is updated on the client side, the configuration will sometimes not update properly (e.g. Changing config values on the server will not always properly update on the client. I had to go in and change the Max..Size properties multiple times on both the client and server sides in the course of my debugging)
* For a DataTable to be serializable, it needs to be given a name. The default constructor does not give the table a name, so:
```
return new DataTable();
```
will not be serializable, while:
```
return new DataTable("someName");
```
will name the table whatever is passed as the parameter.
Note that a table can be given a name at any time by assigning a string to the `TableName` property of the DataTable.
```
var table = new DataTable();
table.TableName = "someName";
```
Hopefully that will help someone. |
12,716 | <p>In C++ program, I am trying to #import TLB of .NET out-of-proc server.</p>
<p>I get errors like:</p>
<blockquote>
<p>z:\server.tlh(111) : error C2146: syntax error : missing ';' before identifier 'GetType'</p>
<p>z:\server.tlh(111) : error C2501: '_TypePtr' : missing storage-class or type specifiers</p>
<p>z:\server.tli(74) : error C2143: syntax error : missing ';' before 'tag::id'</p>
<p>z:\server.tli(74) : error C2433: '_TypePtr' : 'inline' not permitted on data declarations</p>
<p>z:\server.tli(74) : error C2501: '_TypePtr' : missing storage-class or type specifiers</p>
<p>z:\server.tli(74) : fatal error C1004: unexpected end of file found</p>
</blockquote>
<p>The TLH looks like:</p>
<pre><code>_bstr_t GetToString();
VARIANT_BOOL Equals (const _variant_t & obj);
long GetHashCode();
_TypePtr GetType();
long Open();
</code></pre>
<p>I am not really interested in the having the base object .NET object methods like GetType(), Equals(), etc. But GetType() seems to be causing problems.</p>
<p>Some google research indicates I could <code>#import mscorlib.tlb</code> (or put it in path), but I can't get that to compile either.</p>
<p>Any tips?</p>
| [
{
"answer_id": 12751,
"author": "jm.",
"author_id": 814,
"author_profile": "https://Stackoverflow.com/users/814",
"pm_score": 2,
"selected": true,
"text": "<p>Added no_namespace and raw_interfaces_only to my #import:</p>\n\n<pre><code>#import \"server.tlb\" no_namespace named_guids\n</co... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
] | In C++ program, I am trying to #import TLB of .NET out-of-proc server.
I get errors like:
>
> z:\server.tlh(111) : error C2146: syntax error : missing ';' before identifier 'GetType'
>
>
> z:\server.tlh(111) : error C2501: '\_TypePtr' : missing storage-class or type specifiers
>
>
> z:\server.tli(74) : error C2143: syntax error : missing ';' before 'tag::id'
>
>
> z:\server.tli(74) : error C2433: '\_TypePtr' : 'inline' not permitted on data declarations
>
>
> z:\server.tli(74) : error C2501: '\_TypePtr' : missing storage-class or type specifiers
>
>
> z:\server.tli(74) : fatal error C1004: unexpected end of file found
>
>
>
The TLH looks like:
```
_bstr_t GetToString();
VARIANT_BOOL Equals (const _variant_t & obj);
long GetHashCode();
_TypePtr GetType();
long Open();
```
I am not really interested in the having the base object .NET object methods like GetType(), Equals(), etc. But GetType() seems to be causing problems.
Some google research indicates I could `#import mscorlib.tlb` (or put it in path), but I can't get that to compile either.
Any tips? | Added no\_namespace and raw\_interfaces\_only to my #import:
```
#import "server.tlb" no_namespace named_guids
```
Also using TLBEXP.EXE instead of REGASM.EXE seems to help this issue. |
12,718 | <p>When installing subversion as a service, I used this command:</p>
<pre><code>c:\>svnservice -install --daemon --root "c:\documents and settings\my_repository"
</code></pre>
<p>And then I got this error:</p>
<pre><code>Could not create service in service control manager.
</code></pre>
<p>After looking at some MSDN docs on the service control manager, I tried granting full control to everyone in the permissions on the registry key at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services, but that hasn't had any effect.</p>
<p>Anybody know what I did wrong, or how to overcome this?</p>
<p><em>Note #1: I am running as an administrator on this box</em></p>
<p>*Note #2: I was following the instructions given <a href="http://blogs.vertigosoftware.com/teamsystem/archive/2006/01/16/Setting_up_a_Subversion_Server_under_Windows.aspx" rel="nofollow noreferrer">here</a>, so maybe my choice of directory is misguided. And my repository is not actually called "my_repository". I used the name of an actual project which is currently under source control in <em>gasp</em> VSS.*</p>
| [
{
"answer_id": 12727,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 0,
"selected": false,
"text": "<p>I've never used the command line installer for this. I assume you are downloading the latest from:</p>\n\n<p><a href... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] | When installing subversion as a service, I used this command:
```
c:\>svnservice -install --daemon --root "c:\documents and settings\my_repository"
```
And then I got this error:
```
Could not create service in service control manager.
```
After looking at some MSDN docs on the service control manager, I tried granting full control to everyone in the permissions on the registry key at HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Services, but that hasn't had any effect.
Anybody know what I did wrong, or how to overcome this?
*Note #1: I am running as an administrator on this box*
\*Note #2: I was following the instructions given [here](http://blogs.vertigosoftware.com/teamsystem/archive/2006/01/16/Setting_up_a_Subversion_Server_under_Windows.aspx), so maybe my choice of directory is misguided. And my repository is not actually called "my\_repository". I used the name of an actual project which is currently under source control in *gasp* VSS.\* | [VisualSVN Server](http://www.visualsvn.com/server) installs as a Windows service. It is free, includes Apache, OpenSSL, and a repository / permission management tool. It can also integrate with Active Directory for user authentication. I highly recommend it for hosting SVN on Windows. |
12,765 | <p>This is driving me crazy.</p>
<p>I have this one php file on a test server at work which does not work.. I kept deleting stuff from it till it became </p>
<pre>
<?
print 'Hello';
?>
</pre>
<p>it outputs </p>
<blockquote>
<p>Hello</p>
</blockquote>
<p>if I create a new file and copy / paste the same script to it it works!
Why does this one file give me the strange characters all the time?</p>
| [
{
"answer_id": 12769,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 5,
"selected": true,
"text": "<p>That's the <a href=\"http://en.wikipedia.org/wiki/Byte_Order_Mark\" rel=\"noreferrer\">BOM (Byte Order Mark)</a> you are seeing.<... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This is driving me crazy.
I have this one php file on a test server at work which does not work.. I kept deleting stuff from it till it became
```
<?
print 'Hello';
?>
```
it outputs
>
> Hello
>
>
>
if I create a new file and copy / paste the same script to it it works!
Why does this one file give me the strange characters all the time? | That's the [BOM (Byte Order Mark)](http://en.wikipedia.org/wiki/Byte_Order_Mark) you are seeing.
In your editor, there should be a way to force saving without BOM which will remove the problem. |
12,794 | <p>I'm trying to use <code>jQuery</code> to format code blocks, specifically to add a <code><pre></code> tag inside the <code><code></code> tag:</p>
<pre><code>$(document).ready(function() {
$("code").wrapInner("<pre></pre>");
});
</code></pre>
<p>Firefox applies the formatting correctly, but IE puts the entire code block on one line. If I add an alert </p>
<pre><code>alert($("code").html());
</code></pre>
<p>I see that IE has inserted some additional text into the pre tag:</p>
<pre><code><PRE jQuery1218834632572="null">
</code></pre>
<p>If I reload the page, the number following jQuery changes.</p>
<p>If I use <code>wrap()</code> instead of <code>wrapInner()</code>, to wrap the <code><pre></code> outside the <code><code></code> tag, both IE and Firefox handle it correctly. But shouldn't <code><pre></code> work <em>inside</em> <code><code></code> as well?</p>
<p>I'd prefer to use <code>wrapInner()</code> because I can then add a CSS class to the <code><pre></code> tag to handle all formatting, but if I use <code>wrap()</code>, I have to put page formatting CSS in the <code><pre></code> tag and text/font formatting in the <code><code></code> tag, or Firefox and IE both choke. Not a huge deal, but I'd like to keep it as simple as possible.</p>
<p>Has anyone else encountered this? Am I missing something?</p>
| [
{
"answer_id": 12804,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 1,
"selected": false,
"text": "<p>Are you using the latest jQuery ?\nWhat if you try </p>\n\n<pre><code>$(\"code\").wrapInner(document.createElement(\"pre\"));\n<... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311/"
] | I'm trying to use `jQuery` to format code blocks, specifically to add a `<pre>` tag inside the `<code>` tag:
```
$(document).ready(function() {
$("code").wrapInner("<pre></pre>");
});
```
Firefox applies the formatting correctly, but IE puts the entire code block on one line. If I add an alert
```
alert($("code").html());
```
I see that IE has inserted some additional text into the pre tag:
```
<PRE jQuery1218834632572="null">
```
If I reload the page, the number following jQuery changes.
If I use `wrap()` instead of `wrapInner()`, to wrap the `<pre>` outside the `<code>` tag, both IE and Firefox handle it correctly. But shouldn't `<pre>` work *inside* `<code>` as well?
I'd prefer to use `wrapInner()` because I can then add a CSS class to the `<pre>` tag to handle all formatting, but if I use `wrap()`, I have to put page formatting CSS in the `<pre>` tag and text/font formatting in the `<code>` tag, or Firefox and IE both choke. Not a huge deal, but I'd like to keep it as simple as possible.
Has anyone else encountered this? Am I missing something? | That's the difference between [block and inline](http://www.w3.org/TR/html4/struct/global.html#h-7.5.3) elements. [`pre` is a block level element](http://www.w3.org/TR/html4/sgml/dtd.html#block). It's not legal to put it inside a `code` tag, which [can only contain inline content](http://www.w3.org/TR/html4/struct/text.html#h-9.2.1).
Because browsers have to support whatever godawful tag soup they might find on the real web, Firefox tries to do what you mean. IE happens to handle it differently, which is fine by the spec; behavior in that case is unspecified, because it should never happen.
* Could you instead *replace* the `code` element with the `pre`? (Because of the block/inline issue, technically that should only work if the elements are inside [an element with "flow" content](http://www.w3.org/TR/html4/sgml/dtd.html#flow), but the browsers might do what you want anyway.)
* Why is it a `code` element in the first place, if you want `pre`'s behavior?
* You could also give the `code` element `pre`'s whitespace preserving power with the CSS [`white-space: pre`](http://www.blooberry.com/indexdot/css/properties/text/whitespace.htm), but apparently [IE 6 only honors that in Strict Mode](http://www.quirksmode.org/css/whitespace.html). |
12,855 | <p>I have a query where I am searching against a string:</p>
<pre><code>SELECT county FROM city WHERE UPPER(name) = 'SAN FRANCISCO';
</code></pre>
<p>Now, this works fine, but it doesn't scale well, and I need to optimize it. I have <a href="http://www.ibm.com/developerworks/db2/library/techarticle/0203adamache/0203adamache.html" rel="nofollow noreferrer">found an option</a> along the lines of creating a generated view, or something like that, but I was hoping for a simpler solution using an index.</p>
<p>We are using DB2, and I really want to use an <a href="http://ibmsystemsmag.blogs.com/db2utor/2007/11/db2-9-index-wit.html" rel="nofollow noreferrer">expression in an index</a>, but this option seems to only be available on z/OS, however we are running Linux. I tried the expression index anyways:</p>
<pre><code>CREATE INDEX city_upper_name_idx
ON city UPPER(name) ALLOW REVERSE SCANS;
</code></pre>
<p>But of course, it chokes on the UPPER(name).</p>
<p>Is there another way I can create an index or something similar in this manner such that I don't have to restructure my existing queries to use a new generated view, or alter my existing columns, or any other such intrusive change?</p>
<p>EDIT: I'm open to hearing solutions for other databases... it might carry over to DB2...</p>
| [
{
"answer_id": 12886,
"author": "nsanders",
"author_id": 1244,
"author_profile": "https://Stackoverflow.com/users/1244",
"pm_score": 3,
"selected": false,
"text": "<p>You could add an indexed column holding a numerical hash key of the city name. (With duplicates allowed).</p>\n\n<p>Then... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | I have a query where I am searching against a string:
```
SELECT county FROM city WHERE UPPER(name) = 'SAN FRANCISCO';
```
Now, this works fine, but it doesn't scale well, and I need to optimize it. I have [found an option](http://www.ibm.com/developerworks/db2/library/techarticle/0203adamache/0203adamache.html) along the lines of creating a generated view, or something like that, but I was hoping for a simpler solution using an index.
We are using DB2, and I really want to use an [expression in an index](http://ibmsystemsmag.blogs.com/db2utor/2007/11/db2-9-index-wit.html), but this option seems to only be available on z/OS, however we are running Linux. I tried the expression index anyways:
```
CREATE INDEX city_upper_name_idx
ON city UPPER(name) ALLOW REVERSE SCANS;
```
But of course, it chokes on the UPPER(name).
Is there another way I can create an index or something similar in this manner such that I don't have to restructure my existing queries to use a new generated view, or alter my existing columns, or any other such intrusive change?
EDIT: I'm open to hearing solutions for other databases... it might carry over to DB2... | You could add an indexed column holding a numerical hash key of the city name. (With duplicates allowed).
Then you could do a multi-clause where :
```
hash = [compute hash key for 'SAN FRANCISCO']
SELECT county
FROM city
WHERE cityHash = hash
AND UPPER(name) = 'SAN FRANCISCO' ;
```
Alternatively, go through your db manual and look at the options for creating table indexes. There might be something helpful. |
12,865 | <p>Got a bluescreen in windows while cloning a mercurial repository.</p>
<p>After reboot, I now get this message for almost all hg commands:</p>
<pre>
c:\src\>hg commit
waiting for lock on repository c:\src\McVrsServer held by '\x00\x00\x00\x00\x00\
x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
interrupted!
</pre>
<p>Google is no help.</p>
<p>Any tips?</p>
| [
{
"answer_id": 12879,
"author": "jm.",
"author_id": 814,
"author_profile": "https://Stackoverflow.com/users/814",
"pm_score": 10,
"selected": true,
"text": "<p>When \"waiting for lock on repository\", delete the repository file: <code>.hg/wlock</code> (or it may be in <code><code>.hg/sto... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
] | Got a bluescreen in windows while cloning a mercurial repository.
After reboot, I now get this message for almost all hg commands:
```
c:\src\>hg commit
waiting for lock on repository c:\src\McVrsServer held by '\x00\x00\x00\x00\x00\
x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
interrupted!
```
Google is no help.
Any tips? | When "waiting for lock on repository", delete the repository file: `.hg/wlock` (or it may be in ``.hg/store/lock``)
When deleting the lock file, you must make sure nothing else is accessing the repository. (If the lock is a string of zeros or blank, this is almost certainly true). |
12,870 | <p>This is a nasty one for me... I'm a PHP guy working in Java on a JSP project. I know how to do what I'm attempting through too much code and a complete lack of finesse. </p>
<p>I'd prefer to do it right. Here is the situation:</p>
<p>I'm writing a small display to show customers what days they can water their lawns based on their watering group (ABCDE) and what time of year it is. Our seasons look like this:
Summer (5-1 to 8-31)
Spring (3-1 to 4-30)
Fall (9-1 to 10-31)
Winter (11-1 to 2-28) </p>
<p>An example might be:</p>
<p>If I'm in group A, here would be my allowed times:
Winter: Mondays only
Spring: Tues, Thurs, Sat
Summer: Any Day
Fall: Tues, Thurs, Sat</p>
<p>If I was writing this in PHP I would use arrays like this:</p>
<pre><code>//M=Monday,t=Tuesday,T=Thursday.... etc
$schedule["A"]["Winter"]='M';
$schedule["A"]["Spring"]='tTS';
$schedule["A"]["Summer"]='Any';
$schedule["A"]["Fall"]='tTS';
$schedule["B"]["Winter"]='t';
</code></pre>
<p>I COULD make the days arrays (array("Tuesday","Thursday","Saturday")) etc, but it is not necessary for what I'm really trying to accomplish.</p>
<p>I will also need to setup arrays to determine what season I'm in:</p>
<pre><code>$seasons["Summer"]["start"]=0501;
$seasons["Summer"]["end"]=0801;
</code></pre>
<p>Can anyone suggest a really cool way to do this? I will have today's date and the group letter. I will need to get out of my function a day (M) or a series of days (tTS), (Any).</p>
| [
{
"answer_id": 12878,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 5,
"selected": true,
"text": "<p>You could do essentially the same code with Hashtables (or some other Map):</p>\n\n<pre><code>Hashtable<String, Hashtab... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172/"
] | This is a nasty one for me... I'm a PHP guy working in Java on a JSP project. I know how to do what I'm attempting through too much code and a complete lack of finesse.
I'd prefer to do it right. Here is the situation:
I'm writing a small display to show customers what days they can water their lawns based on their watering group (ABCDE) and what time of year it is. Our seasons look like this:
Summer (5-1 to 8-31)
Spring (3-1 to 4-30)
Fall (9-1 to 10-31)
Winter (11-1 to 2-28)
An example might be:
If I'm in group A, here would be my allowed times:
Winter: Mondays only
Spring: Tues, Thurs, Sat
Summer: Any Day
Fall: Tues, Thurs, Sat
If I was writing this in PHP I would use arrays like this:
```
//M=Monday,t=Tuesday,T=Thursday.... etc
$schedule["A"]["Winter"]='M';
$schedule["A"]["Spring"]='tTS';
$schedule["A"]["Summer"]='Any';
$schedule["A"]["Fall"]='tTS';
$schedule["B"]["Winter"]='t';
```
I COULD make the days arrays (array("Tuesday","Thursday","Saturday")) etc, but it is not necessary for what I'm really trying to accomplish.
I will also need to setup arrays to determine what season I'm in:
```
$seasons["Summer"]["start"]=0501;
$seasons["Summer"]["end"]=0801;
```
Can anyone suggest a really cool way to do this? I will have today's date and the group letter. I will need to get out of my function a day (M) or a series of days (tTS), (Any). | You could do essentially the same code with Hashtables (or some other Map):
```
Hashtable<String, Hashtable<String, String>> schedule
= new Hashtable<String, Hashtable<String, String>>();
schedule.put("A", new Hashtable<String, String>());
schedule.put("B", new Hashtable<String, String>());
schedule.put("C", new Hashtable<String, String>());
schedule.put("D", new Hashtable<String, String>());
schedule.put("E", new Hashtable<String, String>());
schedule.get("A").put("Winter", "M");
schedule.get("A").put("Spring", "tTS");
// Etc...
```
Not as elegant, but then again, Java isn't a dynamic language, and it doesn't have hashes on the language level.
Note: You might be able to do a better solution, this just popped in my head as I read your question. |
12,877 | <p>I just get the beach ball all day long (it's been doing nothing for hours). It's not taking CPU, not reading from disk, not using the network.</p>
<p>I'm using <strong>Java 1.6</strong> on <strong>Mac OS X 10.5.4</strong>. It worked once, now even restarts of the computer won't help. Activity Monitor says it's "(Not Responding)". Only thing that I can do is kill -9 that sucker.</p>
<p>When I sample the process I see this:</p>
<pre><code> mach_msg_trap 16620
read 831
semaphore_wait_trap 831
</code></pre>
<p>An acceptable answer that doesn't fix this would include a url for a decent free Oracle client for the Mac.</p>
<p>Edit:
@Mark Harrison sadly this happens every time I start it up, it's not an old connection. I'll like to avoid running Windows on my laptop. I'm giving some plugins for my IDE a whirl, but still no solution for me.
@Matthew Schinckel Navicat seems to only have a non-commercial Oracle product...I need a commercial friendly one (even if it costs money).</p>
| [
{
"answer_id": 12943,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 1,
"selected": false,
"text": "<p>The company <a href=\"http://www.navicat.com/\" rel=\"nofollow noreferrer\">Navicat</a> has released an Oracle cli... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/484/"
] | I just get the beach ball all day long (it's been doing nothing for hours). It's not taking CPU, not reading from disk, not using the network.
I'm using **Java 1.6** on **Mac OS X 10.5.4**. It worked once, now even restarts of the computer won't help. Activity Monitor says it's "(Not Responding)". Only thing that I can do is kill -9 that sucker.
When I sample the process I see this:
```
mach_msg_trap 16620
read 831
semaphore_wait_trap 831
```
An acceptable answer that doesn't fix this would include a url for a decent free Oracle client for the Mac.
Edit:
@Mark Harrison sadly this happens every time I start it up, it's not an old connection. I'll like to avoid running Windows on my laptop. I'm giving some plugins for my IDE a whirl, but still no solution for me.
@Matthew Schinckel Navicat seems to only have a non-commercial Oracle product...I need a commercial friendly one (even if it costs money). | I get the same problem after there's been an active connection sitting idle for a while. I solve it by restarting sql developer every once in a while.
I also have Toad for Oracle running on a vmware XP session, and it works great. If you don't mind the money, try that. |
12,890 | <p>I have a large database of normalized order data that is becoming very slow to query for reporting. Many of the queries that I use in reports join five or six tables and are having to examine tens or hundreds of thousands of lines.</p>
<p>There are lots of queries and most have been optimized as much as possible to reduce server load and increase speed. I think it's time to start keeping a copy of the data in a denormalized format.</p>
<p>Any ideas on an approach? Should I start with a couple of my worst queries and go from there?</p>
| [
{
"answer_id": 12900,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 1,
"selected": false,
"text": "<p>I know this is a bit tangential, but have you tried seeing if there are more indexes you can add?</p>\n\n<p>I don't have ... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1430/"
] | I have a large database of normalized order data that is becoming very slow to query for reporting. Many of the queries that I use in reports join five or six tables and are having to examine tens or hundreds of thousands of lines.
There are lots of queries and most have been optimized as much as possible to reduce server load and increase speed. I think it's time to start keeping a copy of the data in a denormalized format.
Any ideas on an approach? Should I start with a couple of my worst queries and go from there? | I know more about mssql that mysql, but I don't think the number of joins or number of rows you are talking about should cause you too many problems with the correct indexes in place. Have you analyzed the query plan to see if you are missing any?
<http://dev.mysql.com/doc/refman/5.0/en/explain.html>
That being said, once you are satisifed with your indexes and have exhausted all other avenues, de-normalization might be the right answer. If you just have one or two queries that are problems, a manual approach is probably appropriate, whereas some sort of data warehousing tool might be better for creating a platform to develop data cubes.
Here's a site I found that touches on the subject:
<http://www.meansandends.com/mysql-data-warehouse/?link_body%2Fbody=%7Bincl%3AAggregation%7D>
Here's a simple technique that you can use to keep denormalizing queries simple, if you're just doing a few at a time (and I'm not replacing your OLTP tables, just creating a new one for reporting purposes). Let's say you have this query in your application:
```
select a.name, b.address from tbla a
join tblb b on b.fk_a_id = a.id where a.id=1
```
You could create a denormalized table and populate with almost the same query:
```
create table tbl_ab (a_id, a_name, b_address);
-- (types elided)
```
Notice the underscores match the table aliases you use
```
insert tbl_ab select a.id, a.name, b.address from tbla a
join tblb b on b.fk_a_id = a.id
-- no where clause because you want everything
```
Then to fix your app to use the new denormalized table, switch the dots for underscores.
```
select a_name as name, b_address as address
from tbl_ab where a_id = 1;
```
For huge queries this can save a lot of time and makes it clear where the data came from, and you can re-use the queries you already have.
Remember, I'm only advocating this as the last resort. I bet there's a few indexes that would help you. And when you de-normalize, don't forget to account for the extra space on your disks, and figure out when you will run the query to populate the new tables. This should probably be at night, or whenever activity is low. And the data in that table, of course, will never exactly be up to date.
[Yet another edit] Don't forget that the new tables you create need to be indexed too! The good part is that you can index to your heart's content and not worry about update lock contention, since aside from your bulk insert the table will only see selects. |
12,896 | <p>I'm looking for good/working/simple to use PHP code for parsing raw email into parts.</p>
<p>I've written a couple of brute force solutions, but every time, one small change/header/space/something comes along and my whole parser fails and the project falls apart.</p>
<p>And before I get pointed at PEAR/PECL, I need actual code. My host has some screwy config or something, I can never seem to get the .so's to build right. If I do get the .so made, some difference in path/environment/php.ini doesn't always make it available (apache vs cron vs CLI).</p>
<p>Oh, and one last thing, I'm parsing the raw email text, NOT POP3, and NOT IMAP. It's being piped into the PHP script via a .qmail email redirect.</p>
<p>I'm not expecting SOF to write it for me, I'm looking for some tips/starting points on doing it "right". This is one of those "wheel" problems that I know has already been solved.</p>
| [
{
"answer_id": 12965,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 6,
"selected": true,
"text": "<p>What are you hoping to end up with at the end? The body, the subject, the sender, an attachment? You should spend some time wi... | 2008/08/15 | [
"https://Stackoverflow.com/questions/12896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314/"
] | I'm looking for good/working/simple to use PHP code for parsing raw email into parts.
I've written a couple of brute force solutions, but every time, one small change/header/space/something comes along and my whole parser fails and the project falls apart.
And before I get pointed at PEAR/PECL, I need actual code. My host has some screwy config or something, I can never seem to get the .so's to build right. If I do get the .so made, some difference in path/environment/php.ini doesn't always make it available (apache vs cron vs CLI).
Oh, and one last thing, I'm parsing the raw email text, NOT POP3, and NOT IMAP. It's being piped into the PHP script via a .qmail email redirect.
I'm not expecting SOF to write it for me, I'm looking for some tips/starting points on doing it "right". This is one of those "wheel" problems that I know has already been solved. | What are you hoping to end up with at the end? The body, the subject, the sender, an attachment? You should spend some time with [RFC2822](http://www.faqs.org/rfcs/rfc2822.html) to understand the format of the mail, but here's the simplest rules for well formed email:
```
HEADERS\n
\n
BODY
```
That is, the first blank line (double newline) is the separator between the HEADERS and the BODY. A HEADER looks like this:
```
HSTRING:HTEXT
```
HSTRING always starts at the beginning of a line and doesn't contain any white space or colons. HTEXT can contain a wide variety of text, including newlines as long as the newline char is followed by whitespace.
The "BODY" is really just any data that follows the first double newline. (There are different rules if you are transmitting mail via SMTP, but processing it over a pipe you don't have to worry about that).
So, in really simple, circa-1982 [RFC822](http://www.faqs.org/rfcs/rfc822.html) terms, an email looks like this:
```
HEADER: HEADER TEXT
HEADER: MORE HEADER TEXT
INCLUDING A LINE CONTINUATION
HEADER: LAST HEADER
THIS IS ANY
ARBITRARY DATA
(FOR THE MOST PART)
```
Most modern email is more complex than that though. Headers can be encoded for charsets or [RFC2047](http://www.faqs.org/rfcs/rfc2047.html) mime words, or a ton of other stuff I'm not thinking of right now. The bodies are really hard to roll your own code for these days to if you want them to be meaningful. Almost all email that's generated by an MUA will be [MIME](http://www.faqs.org/rfcs/rfc2045.html) encoded. That might be uuencoded text, it might be html, it might be a uuencoded excel spreadsheet.
I hope this helps provide a framework for understanding some of the very elemental buckets of email. If you provide more background on what you are trying to do with the data I (or someone else) might be able to provide better direction. |
12,905 | <p>I'm experimenting with creating an add-in for Infopath 2007. The documentation is very skimpy. What I'm trying to determine is what kind of actions an add-in can take while designing a form. Most of the discussion and samples are for when the user is filling out the form. Can I, for example, add a new field to the form in the designer? Add a new item to the schema? Move a form field on the design surface? It doesn't appear so, but I can't find anything definitive.</p>
| [
{
"answer_id": 12965,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 6,
"selected": true,
"text": "<p>What are you hoping to end up with at the end? The body, the subject, the sender, an attachment? You should spend some time wi... | 2008/08/16 | [
"https://Stackoverflow.com/questions/12905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9/"
] | I'm experimenting with creating an add-in for Infopath 2007. The documentation is very skimpy. What I'm trying to determine is what kind of actions an add-in can take while designing a form. Most of the discussion and samples are for when the user is filling out the form. Can I, for example, add a new field to the form in the designer? Add a new item to the schema? Move a form field on the design surface? It doesn't appear so, but I can't find anything definitive. | What are you hoping to end up with at the end? The body, the subject, the sender, an attachment? You should spend some time with [RFC2822](http://www.faqs.org/rfcs/rfc2822.html) to understand the format of the mail, but here's the simplest rules for well formed email:
```
HEADERS\n
\n
BODY
```
That is, the first blank line (double newline) is the separator between the HEADERS and the BODY. A HEADER looks like this:
```
HSTRING:HTEXT
```
HSTRING always starts at the beginning of a line and doesn't contain any white space or colons. HTEXT can contain a wide variety of text, including newlines as long as the newline char is followed by whitespace.
The "BODY" is really just any data that follows the first double newline. (There are different rules if you are transmitting mail via SMTP, but processing it over a pipe you don't have to worry about that).
So, in really simple, circa-1982 [RFC822](http://www.faqs.org/rfcs/rfc822.html) terms, an email looks like this:
```
HEADER: HEADER TEXT
HEADER: MORE HEADER TEXT
INCLUDING A LINE CONTINUATION
HEADER: LAST HEADER
THIS IS ANY
ARBITRARY DATA
(FOR THE MOST PART)
```
Most modern email is more complex than that though. Headers can be encoded for charsets or [RFC2047](http://www.faqs.org/rfcs/rfc2047.html) mime words, or a ton of other stuff I'm not thinking of right now. The bodies are really hard to roll your own code for these days to if you want them to be meaningful. Almost all email that's generated by an MUA will be [MIME](http://www.faqs.org/rfcs/rfc2045.html) encoded. That might be uuencoded text, it might be html, it might be a uuencoded excel spreadsheet.
I hope this helps provide a framework for understanding some of the very elemental buckets of email. If you provide more background on what you are trying to do with the data I (or someone else) might be able to provide better direction. |
12,906 | <p>I need to know how much space occupies all the databases inside an SQL Server 2000. I did some research but could not found any script to help me out.</p>
| [
{
"answer_id": 12911,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<p>I know this might sound a little arcanine but why not just stat the directory that contains the database.</p>\n"
},
{
... | 2008/08/16 | [
"https://Stackoverflow.com/questions/12906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296/"
] | I need to know how much space occupies all the databases inside an SQL Server 2000. I did some research but could not found any script to help me out. | Source: <http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1313431,00.html>
Works with SQL2000,2005,2008
```
USE master;
GO
IF OBJECT_ID('dbo.sp_SDS', 'P') IS NOT NULL
DROP PROCEDURE dbo.sp_SDS;
GO
CREATE PROCEDURE dbo.sp_SDS
@TargetDatabase sysname = NULL, -- NULL: all dbs
@Level varchar(10) = 'Database', -- or "File"
@UpdateUsage bit = 0, -- default no update
@Unit char(2) = 'MB' -- Megabytes, Kilobytes or Gigabytes
AS
/**************************************************************************************************
**
** author: Richard Ding
** date: 4/8/2008
** usage: list db size AND path w/o SUMmary
** test code: sp_SDS -- default behavior
** sp_SDS 'maAster'
** sp_SDS NULL, NULL, 0
** sp_SDS NULL, 'file', 1, 'GB'
** sp_SDS 'Test_snapshot', 'Database', 1
** sp_SDS 'Test', 'File', 0, 'kb'
** sp_SDS 'pfaids', 'Database', 0, 'gb'
** sp_SDS 'tempdb', NULL, 1, 'kb'
**
**************************************************************************************************/
SET NOCOUNT ON;
IF @TargetDatabase IS NOT NULL AND DB_ID(@TargetDatabase) IS NULL
BEGIN
RAISERROR(15010, -1, -1, @TargetDatabase);
RETURN (-1)
END
IF OBJECT_ID('tempdb.dbo.##Tbl_CombinedInfo', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_CombinedInfo;
IF OBJECT_ID('tempdb.dbo.##Tbl_DbFileStats', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_DbFileStats;
IF OBJECT_ID('tempdb.dbo.##Tbl_ValidDbs', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_ValidDbs;
IF OBJECT_ID('tempdb.dbo.##Tbl_Logs', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_Logs;
CREATE TABLE dbo.##Tbl_CombinedInfo (
DatabaseName sysname NULL,
[type] VARCHAR(10) NULL,
LogicalName sysname NULL,
T dec(10, 2) NULL,
U dec(10, 2) NULL,
[U(%)] dec(5, 2) NULL,
F dec(10, 2) NULL,
[F(%)] dec(5, 2) NULL,
PhysicalName sysname NULL );
CREATE TABLE dbo.##Tbl_DbFileStats (
Id int identity,
DatabaseName sysname NULL,
FileId int NULL,
FileGroup int NULL,
TotalExtents bigint NULL,
UsedExtents bigint NULL,
Name sysname NULL,
FileName varchar(255) NULL );
CREATE TABLE dbo.##Tbl_ValidDbs (
Id int identity,
Dbname sysname NULL );
CREATE TABLE dbo.##Tbl_Logs (
DatabaseName sysname NULL,
LogSize dec (10, 2) NULL,
LogSpaceUsedPercent dec (5, 2) NULL,
Status int NULL );
DECLARE @Ver varchar(10),
@DatabaseName sysname,
@Ident_last int,
@String varchar(2000),
@BaseString varchar(2000);
SELECT @DatabaseName = '',
@Ident_last = 0,
@String = '',
@Ver = CASE WHEN @@VERSION LIKE '%9.0%' THEN 'SQL 2005'
WHEN @@VERSION LIKE '%8.0%' THEN 'SQL 2000'
WHEN @@VERSION LIKE '%10.0%' THEN 'SQL 2008'
END;
SELECT @BaseString =
' SELECT DB_NAME(), ' +
CASE WHEN @Ver = 'SQL 2000' THEN 'CASE WHEN status & 0x40 = 0x40 THEN ''Log'' ELSE ''Data'' END'
ELSE ' CASE type WHEN 0 THEN ''Data'' WHEN 1 THEN ''Log'' WHEN 4 THEN ''Full-text'' ELSE ''reserved'' END' END +
', name, ' +
CASE WHEN @Ver = 'SQL 2000' THEN 'filename' ELSE 'physical_name' END +
', size*8.0/1024.0 FROM ' +
CASE WHEN @Ver = 'SQL 2000' THEN 'sysfiles' ELSE 'sys.database_files' END +
' WHERE '
+ CASE WHEN @Ver = 'SQL 2000' THEN ' HAS_DBACCESS(DB_NAME()) = 1' ELSE 'state_desc = ''ONLINE''' END + '';
SELECT @String = 'INSERT INTO dbo.##Tbl_ValidDbs SELECT name FROM ' +
CASE WHEN @Ver = 'SQL 2000' THEN 'master.dbo.sysdatabases'
WHEN @Ver IN ('SQL 2005', 'SQL 2008') THEN 'master.sys.databases'
END + ' WHERE HAS_DBACCESS(name) = 1 ORDER BY name ASC';
EXEC (@String);
INSERT INTO dbo.##Tbl_Logs EXEC ('DBCC SQLPERF (LOGSPACE) WITH NO_INFOMSGS');
-- For data part
IF @TargetDatabase IS NOT NULL
BEGIN
SELECT @DatabaseName = @TargetDatabase;
IF @UpdateUsage <> 0 AND DATABASEPROPERTYEX (@DatabaseName,'Status') = 'ONLINE'
AND DATABASEPROPERTYEX (@DatabaseName, 'Updateability') <> 'READ_ONLY'
BEGIN
SELECT @String = 'USE [' + @DatabaseName + '] DBCC UPDATEUSAGE (0)';
PRINT '*** ' + @String + ' *** ';
EXEC (@String);
PRINT '';
END
SELECT @String = 'INSERT INTO dbo.##Tbl_CombinedInfo (DatabaseName, type, LogicalName, PhysicalName, T) ' + @BaseString;
INSERT INTO dbo.##Tbl_DbFileStats (FileId, FileGroup, TotalExtents, UsedExtents, Name, FileName)
EXEC ('USE [' + @DatabaseName + '] DBCC SHOWFILESTATS WITH NO_INFOMSGS');
EXEC ('USE [' + @DatabaseName + '] ' + @String);
UPDATE dbo.##Tbl_DbFileStats SET DatabaseName = @DatabaseName;
END
ELSE
BEGIN
WHILE 1 = 1
BEGIN
SELECT TOP 1 @DatabaseName = Dbname FROM dbo.##Tbl_ValidDbs WHERE Dbname > @DatabaseName ORDER BY Dbname ASC;
IF @@ROWCOUNT = 0
BREAK;
IF @UpdateUsage <> 0 AND DATABASEPROPERTYEX (@DatabaseName, 'Status') = 'ONLINE'
AND DATABASEPROPERTYEX (@DatabaseName, 'Updateability') <> 'READ_ONLY'
BEGIN
SELECT @String = 'DBCC UPDATEUSAGE (''' + @DatabaseName + ''') ';
PRINT '*** ' + @String + '*** ';
EXEC (@String);
PRINT '';
END
SELECT @Ident_last = ISNULL(MAX(Id), 0) FROM dbo.##Tbl_DbFileStats;
SELECT @String = 'INSERT INTO dbo.##Tbl_CombinedInfo (DatabaseName, type, LogicalName, PhysicalName, T) ' + @BaseString;
EXEC ('USE [' + @DatabaseName + '] ' + @String);
INSERT INTO dbo.##Tbl_DbFileStats (FileId, FileGroup, TotalExtents, UsedExtents, Name, FileName)
EXEC ('USE [' + @DatabaseName + '] DBCC SHOWFILESTATS WITH NO_INFOMSGS');
UPDATE dbo.##Tbl_DbFileStats SET DatabaseName = @DatabaseName WHERE Id BETWEEN @Ident_last + 1 AND @@IDENTITY;
END
END
-- set used size for data files, do not change total obtained from sys.database_files as it has for log files
UPDATE dbo.##Tbl_CombinedInfo
SET U = s.UsedExtents*8*8/1024.0
FROM dbo.##Tbl_CombinedInfo t JOIN dbo.##Tbl_DbFileStats s
ON t.LogicalName = s.Name AND s.DatabaseName = t.DatabaseName;
-- set used size and % values for log files:
UPDATE dbo.##Tbl_CombinedInfo
SET [U(%)] = LogSpaceUsedPercent,
U = T * LogSpaceUsedPercent/100.0
FROM dbo.##Tbl_CombinedInfo t JOIN dbo.##Tbl_Logs l
ON l.DatabaseName = t.DatabaseName
WHERE t.type = 'Log';
UPDATE dbo.##Tbl_CombinedInfo SET F = T - U, [U(%)] = U*100.0/T;
UPDATE dbo.##Tbl_CombinedInfo SET [F(%)] = F*100.0/T;
IF UPPER(ISNULL(@Level, 'DATABASE')) = 'FILE'
BEGIN
IF @Unit = 'KB'
UPDATE dbo.##Tbl_CombinedInfo
SET T = T * 1024, U = U * 1024, F = F * 1024;
IF @Unit = 'GB'
UPDATE dbo.##Tbl_CombinedInfo
SET T = T / 1024, U = U / 1024, F = F / 1024;
SELECT DatabaseName AS 'Database',
type AS 'Type',
LogicalName,
T AS 'Total',
U AS 'Used',
[U(%)] AS 'Used (%)',
F AS 'Free',
[F(%)] AS 'Free (%)',
PhysicalName
FROM dbo.##Tbl_CombinedInfo
WHERE DatabaseName LIKE ISNULL(@TargetDatabase, '%')
ORDER BY DatabaseName ASC, type ASC;
SELECT CASE WHEN @Unit = 'GB' THEN 'GB' WHEN @Unit = 'KB' THEN 'KB' ELSE 'MB' END AS 'SUM',
SUM (T) AS 'TOTAL', SUM (U) AS 'USED', SUM (F) AS 'FREE' FROM dbo.##Tbl_CombinedInfo;
END
IF UPPER(ISNULL(@Level, 'DATABASE')) = 'DATABASE'
BEGIN
DECLARE @Tbl_Final TABLE (
DatabaseName sysname NULL,
TOTAL dec (10, 2),
[=] char(1),
used dec (10, 2),
[used (%)] dec (5, 2),
[+] char(1),
free dec (10, 2),
[free (%)] dec (5, 2),
[==] char(2),
Data dec (10, 2),
Data_Used dec (10, 2),
[Data_Used (%)] dec (5, 2),
Data_Free dec (10, 2),
[Data_Free (%)] dec (5, 2),
[++] char(2),
Log dec (10, 2),
Log_Used dec (10, 2),
[Log_Used (%)] dec (5, 2),
Log_Free dec (10, 2),
[Log_Free (%)] dec (5, 2) );
INSERT INTO @Tbl_Final
SELECT x.DatabaseName,
x.Data + y.Log AS 'TOTAL',
'=' AS '=',
x.Data_Used + y.Log_Used AS 'U',
(x.Data_Used + y.Log_Used)*100.0 / (x.Data + y.Log) AS 'U(%)',
'+' AS '+',
x.Data_Free + y.Log_Free AS 'F',
(x.Data_Free + y.Log_Free)*100.0 / (x.Data + y.Log) AS 'F(%)',
'==' AS '==',
x.Data,
x.Data_Used,
x.Data_Used*100/x.Data AS 'D_U(%)',
x.Data_Free,
x.Data_Free*100/x.Data AS 'D_F(%)',
'++' AS '++',
y.Log,
y.Log_Used,
y.Log_Used*100/y.Log AS 'L_U(%)',
y.Log_Free,
y.Log_Free*100/y.Log AS 'L_F(%)'
FROM
( SELECT d.DatabaseName,
SUM(d.T) AS 'Data',
SUM(d.U) AS 'Data_Used',
SUM(d.F) AS 'Data_Free'
FROM dbo.##Tbl_CombinedInfo d WHERE d.type = 'Data' GROUP BY d.DatabaseName ) AS x
JOIN
( SELECT l.DatabaseName,
SUM(l.T) AS 'Log',
SUM(l.U) AS 'Log_Used',
SUM(l.F) AS 'Log_Free'
FROM dbo.##Tbl_CombinedInfo l WHERE l.type = 'Log' GROUP BY l.DatabaseName ) AS y
ON x.DatabaseName = y.DatabaseName;
IF @Unit = 'KB'
UPDATE @Tbl_Final SET TOTAL = TOTAL * 1024,
used = used * 1024,
free = free * 1024,
Data = Data * 1024,
Data_Used = Data_Used * 1024,
Data_Free = Data_Free * 1024,
Log = Log * 1024,
Log_Used = Log_Used * 1024,
Log_Free = Log_Free * 1024;
IF @Unit = 'GB'
UPDATE @Tbl_Final SET TOTAL = TOTAL / 1024,
used = used / 1024,
free = free / 1024,
Data = Data / 1024,
Data_Used = Data_Used / 1024,
Data_Free = Data_Free / 1024,
Log = Log / 1024,
Log_Used = Log_Used / 1024,
Log_Free = Log_Free / 1024;
DECLARE @GrantTotal dec(11, 2);
SELECT @GrantTotal = SUM(TOTAL) FROM @Tbl_Final;
SELECT
CONVERT(dec(10, 2), TOTAL*100.0/@GrantTotal) AS 'WEIGHT (%)',
DatabaseName AS 'DATABASE',
CONVERT(VARCHAR(12), used) + ' (' + CONVERT(VARCHAR(12), [used (%)]) + ' %)' AS 'USED (%)',
[+],
CONVERT(VARCHAR(12), free) + ' (' + CONVERT(VARCHAR(12), [free (%)]) + ' %)' AS 'FREE (%)',
[=],
TOTAL,
[=],
CONVERT(VARCHAR(12), Data) + ' (' + CONVERT(VARCHAR(12), Data_Used) + ', ' +
CONVERT(VARCHAR(12), [Data_Used (%)]) + '%)' AS 'DATA (used, %)',
[+],
CONVERT(VARCHAR(12), Log) + ' (' + CONVERT(VARCHAR(12), Log_Used) + ', ' +
CONVERT(VARCHAR(12), [Log_Used (%)]) + '%)' AS 'LOG (used, %)'
FROM @Tbl_Final
WHERE DatabaseName LIKE ISNULL(@TargetDatabase, '%')
ORDER BY DatabaseName ASC;
IF @TargetDatabase IS NULL
SELECT CASE WHEN @Unit = 'GB' THEN 'GB' WHEN @Unit = 'KB' THEN 'KB' ELSE 'MB' END AS 'SUM',
SUM (used) AS 'USED',
SUM (free) AS 'FREE',
SUM (TOTAL) AS 'TOTAL',
SUM (Data) AS 'DATA',
SUM (Log) AS 'LOG'
FROM @Tbl_Final;
END
RETURN (0)
GO
``` |
13,000 | <p>I want to define something like this in <em>php</em>:</p>
<pre><code>$EL = "\n<br />\n";
</code></pre>
<p>and then use that variable as an "endline" marker all over my site, like this:</p>
<pre><code>echo "Blah blah blah{$EL}";
</code></pre>
<p>How do I define $EL once (in only 1 file), include it on every page on my site, and <em>not</em> have to reference it using the (strangely backwards) <code>global $EL;</code> statement in every page function?</p>
| [
{
"answer_id": 13003,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 4,
"selected": true,
"text": "<p>Most PHP sites should have a file (I call it a header) that you include on every single page of the site. If you put that... | 2008/08/16 | [
"https://Stackoverflow.com/questions/13000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103/"
] | I want to define something like this in *php*:
```
$EL = "\n<br />\n";
```
and then use that variable as an "endline" marker all over my site, like this:
```
echo "Blah blah blah{$EL}";
```
How do I define $EL once (in only 1 file), include it on every page on my site, and *not* have to reference it using the (strangely backwards) `global $EL;` statement in every page function? | Most PHP sites should have a file (I call it a header) that you include on every single page of the site. If you put that first line of code in the header file, then include it like this on every page:
```
include 'header.php';
```
you won't have to use the global keyword or anything, the second line of code you wrote should work.
Edit: Oh sorry, that won't work inside functions... now I see your problem.
Edit #2: Ok, take my original advice with the header, but use a [define()](http://php.net/define) rather than a variable. Those work inside functions after being included. |
13,021 | <p>I've frequently encountered sites that put all of their JavaScript inside a <code>namespace</code> structure along the lines of:</p>
<pre><code>namespaces = { com : { example: { example.com's data} }
</code></pre>
<p>However, setting this up safely with respect to other namespaced frameworks seems to require a relatively hefty amount of code (defined as > 2 lines). I was wondering whether anyone knows of a concise way to do this? Furthermore, whether there's a relatively standard/consistent way to structure it? For example, is the <code>com</code> namespace directly attached to the global object, or is it attached through a namespace object?</p>
<p>[Edit: whoops, obviously <code>{com = { ... } }</code> wouldn't accomplish anything close to what I intended, thanks to Shog9 for pointing that out.] </p>
| [
{
"answer_id": 13193,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": true,
"text": "<p>Javascript doesn't have stand-alone namespaces. It has functions, which can provide scope for resolving names, and objects, whi... | 2008/08/16 | [
"https://Stackoverflow.com/questions/13021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/784/"
] | I've frequently encountered sites that put all of their JavaScript inside a `namespace` structure along the lines of:
```
namespaces = { com : { example: { example.com's data} }
```
However, setting this up safely with respect to other namespaced frameworks seems to require a relatively hefty amount of code (defined as > 2 lines). I was wondering whether anyone knows of a concise way to do this? Furthermore, whether there's a relatively standard/consistent way to structure it? For example, is the `com` namespace directly attached to the global object, or is it attached through a namespace object?
[Edit: whoops, obviously `{com = { ... } }` wouldn't accomplish anything close to what I intended, thanks to Shog9 for pointing that out.] | Javascript doesn't have stand-alone namespaces. It has functions, which can provide scope for resolving names, and objects, which can contribute to the named data accessible in a given scope.
Here's your example, corrected:
```
var namespaces = { com: { example: { /* example.com's data */ } } }
```
This is a variable `namespaces` being assigned an object literal. The object contains one property: `com`, an object with one property: `example`, an object which presumably would contain something interesting.
So, you can type something like **namespaces.com.example.*somePropertyOrFunctionOnExample*** and it'll all work. Of course, it's also ridiculous. You don't have a hierarchical namespace, you have an object containing an object containing an object with the stuff you actually care about.
```
var com_example_data = { /* example.com's data */ };
```
That works just as well, without the pointless hierarchy.
**Now**, if you actually *want* to build a hierarchy, you can try something like this:
```
com_example = com_example || {};
com_example.flags = com_example.flags || { active: false, restricted: true};
com_example.ops = com_example.ops || (function()
{
var launchCodes = "38925491753824"; // hidden / private
return {
activate: function() { /* ... */ },
destroyTheWorld: function() { /* ... */ }
};
})();
```
...which is, IMHO, reasonably concise. |
13,060 | <p>I'm looking for a clear, concise and accurate answer. </p>
<p>Ideally as the actual answer, although links to good explanations welcome.</p>
<p>This also applies to VB.Net, but the keywords are different - <code>ByRef</code> and <code>ByVal</code>.</p>
| [
{
"answer_id": 13061,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "<p><code>out</code> means that the parameter will be initialised by the method:</p>\n\n<pre><code>int result; //not initialised\n... | 2008/08/16 | [
"https://Stackoverflow.com/questions/13060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | I'm looking for a clear, concise and accurate answer.
Ideally as the actual answer, although links to good explanations welcome.
This also applies to VB.Net, but the keywords are different - `ByRef` and `ByVal`. | By default (in C#), passing an object to a function actually passes a copy of the reference to that object. Changing the parameter itself only changes the value in the parameter, and not the variable that was specified.
```
void Test1(string param)
{
param = "new value";
}
string s1 = "initial value";
Test1(s1);
// s1 == "initial value"
```
Using `out` or `ref` passes a reference to the variable specified in the call to the function. Any changes to the value of an `out` or `ref` parameter will be passed back to the caller.
Both `out` and `ref` behave identically except for one slight difference: `ref` parameters are required to be initialised before calling, while `out` parameters can be uninitialised. By extension, `ref` parameters are guaranteed to be initialised at the start of the method, while `out` parameters are treated as uninitialised.
```
void Test2(ref string param)
{
param = "new value";
}
void Test3(out string param)
{
// Use of param here will not compile
param = "another value";
}
string s2 = "initial value";
string s3;
Test2(ref s2);
// s2 == "new value"
// Test2(ref s3); // Passing ref s3 will not compile
Test3(out s2);
// s2 == "another value"
Test3(out s3);
// s3 == "another value"
```
**Edit**: As [dp](https://stackoverflow.com/questions/13060/what-do-ref-val-and-out-mean-on-method-parameters#13105 "dp") points out, the difference between `out` and `ref` is only enforced by the C# compiler, not by the CLR. As far as I know, VB has no equivalent for `out` and implements `ref` (as `ByRef`) only, matching the support of the CLR. |
13,109 | <p>In php, I often need to map a variable using an array ... but I can not seem to be able to do this in a one liner. c.f. example:</p>
<pre><code>// the following results in an error:
echo array('a','b','c')[$key];
// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];
</code></pre>
<p>This is a minor problem, but it keeps bugging every once in a while ... I don't like the fact, that I use a variable for nothing ;)</p>
| [
{
"answer_id": 13113,
"author": "onnodb",
"author_id": 1037,
"author_profile": "https://Stackoverflow.com/users/1037",
"pm_score": 5,
"selected": true,
"text": "<p>I wouldn't bother about that extra variable, really. If you want, though, you could also remove it from memory after you've ... | 2008/08/16 | [
"https://Stackoverflow.com/questions/13109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1532/"
] | In php, I often need to map a variable using an array ... but I can not seem to be able to do this in a one liner. c.f. example:
```
// the following results in an error:
echo array('a','b','c')[$key];
// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];
```
This is a minor problem, but it keeps bugging every once in a while ... I don't like the fact, that I use a variable for nothing ;) | I wouldn't bother about that extra variable, really. If you want, though, you could also remove it from memory after you've used it:
```
$variable = array('a','b','c');
echo $variable[$key];
unset($variable);
```
Or, you could write a small function:
```
function indexonce(&$ar, $index) {
return $ar[$index];
}
```
and call this with:
```
$something = indexonce(array('a', 'b', 'c'), 2);
```
The array should be destroyed automatically now. |
13,160 | <p>I've created a webservice and when I want to use its methods I instantiate it in the a procedure, call the method, and I finally I dispose it, however I think also it could be okay to instantiate the webservice in the "private void Main_Load(object sender, EventArgs e)" event.</p>
<p>The thing is that if I do it the first way I have to instantiate the webservice every time I need one of its methods but in the other way I have to keep a webservice connected all the time when I use it in a form for example. </p>
<p>I would like to know which of these practices are better or if there's a much better way to do it</p>
<p><strong>Strategy 1</strong></p>
<pre><code>private void btnRead_Click(object sender, EventArgs e)
{
try
{
//Show clock
this.picResult.Image = new Bitmap(pathWait);
Application.DoEvents();
//Connect to webservice
svc = new ForPocketPC.ServiceForPocketPC();
svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password);
svc.AllowAutoRedirect = false;
svc.UserAgent = Settings.UserAgent;
svc.PreAuthenticate = true;
svc.Url = Settings.Url;
svc.Timeout = System.Threading.Timeout.Infinite;
svc.CallMethod();
...
}
catch (Exception ex)
{
ShowError(ex);
}
finally
{
if (svc != null)
svc.Dispose();
}
}
</code></pre>
<p><strong>Strategy 2</strong></p>
<pre><code>private myWebservice svc;
private void Main_Load(object sender, EventArgs e)
{
//Connect to webservice
svc = new ForPocketPC.ServiceForPocketPC();
svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password);
svc.AllowAutoRedirect = false;
svc.UserAgent = Settings.UserAgent;
svc.PreAuthenticate = true;
svc.Url = Settings.Url;
svc.Timeout = System.Threading.Timeout.Infinite;
}
private void btnRead_Click(object sender, EventArgs e)
{
try
{
//Show clock
this.picResult.Image = new Bitmap(pathWait);
Application.DoEvents();
svc.CallMethod();
...
}
catch (Exception ex)
{
ShowError(ex);
}
}
private void Main_Closing(object sender, CancelEventArgs e)
{
svc.Dispose();
}
</code></pre>
| [
{
"answer_id": 13164,
"author": "Brandon Wood",
"author_id": 423,
"author_profile": "https://Stackoverflow.com/users/423",
"pm_score": 3,
"selected": true,
"text": "<p>It depends on how often you are going to be calling the web service. If you're going to be calling it almost constantly... | 2008/08/16 | [
"https://Stackoverflow.com/questions/13160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1130097/"
] | I've created a webservice and when I want to use its methods I instantiate it in the a procedure, call the method, and I finally I dispose it, however I think also it could be okay to instantiate the webservice in the "private void Main\_Load(object sender, EventArgs e)" event.
The thing is that if I do it the first way I have to instantiate the webservice every time I need one of its methods but in the other way I have to keep a webservice connected all the time when I use it in a form for example.
I would like to know which of these practices are better or if there's a much better way to do it
**Strategy 1**
```
private void btnRead_Click(object sender, EventArgs e)
{
try
{
//Show clock
this.picResult.Image = new Bitmap(pathWait);
Application.DoEvents();
//Connect to webservice
svc = new ForPocketPC.ServiceForPocketPC();
svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password);
svc.AllowAutoRedirect = false;
svc.UserAgent = Settings.UserAgent;
svc.PreAuthenticate = true;
svc.Url = Settings.Url;
svc.Timeout = System.Threading.Timeout.Infinite;
svc.CallMethod();
...
}
catch (Exception ex)
{
ShowError(ex);
}
finally
{
if (svc != null)
svc.Dispose();
}
}
```
**Strategy 2**
```
private myWebservice svc;
private void Main_Load(object sender, EventArgs e)
{
//Connect to webservice
svc = new ForPocketPC.ServiceForPocketPC();
svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password);
svc.AllowAutoRedirect = false;
svc.UserAgent = Settings.UserAgent;
svc.PreAuthenticate = true;
svc.Url = Settings.Url;
svc.Timeout = System.Threading.Timeout.Infinite;
}
private void btnRead_Click(object sender, EventArgs e)
{
try
{
//Show clock
this.picResult.Image = new Bitmap(pathWait);
Application.DoEvents();
svc.CallMethod();
...
}
catch (Exception ex)
{
ShowError(ex);
}
}
private void Main_Closing(object sender, CancelEventArgs e)
{
svc.Dispose();
}
``` | It depends on how often you are going to be calling the web service. If you're going to be calling it almost constantly, it would probably be better to use method #2. However, if it's not going to be getting called quite so often, you are better off using method #1, and only instantiating it when you need it. |
13,170 | <p>From time to time I get a System.Threading.ThreadStateException when attempting to restart a thread. The code in question is as follows:</p>
<pre><code>// Make sure the thread is done stopping
while (this.mThread.ThreadState == ThreadState.Running)
{
Thread.Sleep(0);
}
// Respawn a thread if the current one is stopped or doesn't exist
if (this.mThread == null || this.mThread.ThreadState == ThreadState.Stopped)
{
this.mThread = new Thread(new ParameterizedThreadStart(Monitor)); }
// Start the thread
if (check)
{
this.mThread.Start(60000);
}
else
{
this.mThread.Start(0);
}
</code></pre>
<p>So two questions - is this the correct way of doing things, and it is, is there a way to prevent the error from occurring?</p>
| [
{
"answer_id": 13207,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 1,
"selected": false,
"text": "<p>A ThreadStateException is thrown because you're trying to start a thread that's not in a startable state. The most lik... | 2008/08/16 | [
"https://Stackoverflow.com/questions/13170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
] | From time to time I get a System.Threading.ThreadStateException when attempting to restart a thread. The code in question is as follows:
```
// Make sure the thread is done stopping
while (this.mThread.ThreadState == ThreadState.Running)
{
Thread.Sleep(0);
}
// Respawn a thread if the current one is stopped or doesn't exist
if (this.mThread == null || this.mThread.ThreadState == ThreadState.Stopped)
{
this.mThread = new Thread(new ParameterizedThreadStart(Monitor)); }
// Start the thread
if (check)
{
this.mThread.Start(60000);
}
else
{
this.mThread.Start(0);
}
```
So two questions - is this the correct way of doing things, and it is, is there a way to prevent the error from occurring? | The problem is that you have code that first checks if it should create a new thread object, and another piece of code that determines wether to start the thread object. Due to race conditions and similar things, your code might end up trying to call .Start on an existing thread object. Considering you don't post the details behind the *check* variable, it's impossible to know what might trigger this behavior.
You should reorganize your code so that .Start is guaranteed to only be called on new objects. In short, you should put the Start method into the same if-statement as the one that creates a new thread object.
Personally, I would try to reorganize the entire code so that I didn't need to create another thread, but wrap the code inside the thread object inside a loop so that the thread just keeps on going. |
13,204 | <p>I have a cron job on an Ubuntu Hardy VPS that only half works and I can't work out why. The job is a Ruby script that uses mysqldump to back up a MySQL database used by a Rails application, which is then gzipped and uploaded to a remote server using SFTP.</p>
<p>The gzip file is created and copied successfully but it's always zero bytes. Yet if I run the cron command directly from the command line it works perfectly.</p>
<p>This is the cron job:</p>
<pre><code>PATH=/usr/bin
10 3 * * * ruby /home/deploy/bin/datadump.rb
</code></pre>
<p>This is datadump.rb:</p>
<pre><code>#!/usr/bin/ruby
require 'yaml'
require 'logger'
require 'rubygems'
require 'net/ssh'
require 'net/sftp'
APP = '/home/deploy/apps/myapp/current'
LOGFILE = '/home/deploy/log/data.log'
TIMESTAMP = '%Y%m%d-%H%M'
TABLES = 'table1 table2'
log = Logger.new(LOGFILE, 5, 10 * 1024)
dump = "myapp-#{Time.now.strftime(TIMESTAMP)}.sql.gz"
ftpconfig = YAML::load(open('/home/deploy/apps/myapp/shared/config/sftp.yml'))
config = YAML::load(open(APP + '/config/database.yml'))['production']
cmd = "mysqldump -u #{config['username']} -p#{config['password']} -h #{config['host']} --add-drop-table --add-locks --extended-insert --lock-tables #{config['database']} #{TABLES} | gzip -cf9 > #{dump}"
log.info 'Getting ready to create a backup'
`#{cmd}`
# Strongspace
log.info 'Backup created, starting the transfer to Strongspace'
Net::SSH.start(ftpconfig['strongspace']['host'], ftpconfig['strongspace']['username'], ftpconfig['strongspace']['password']) do |ssh|
ssh.sftp.connect do |sftp|
sftp.open_handle("#{ftpconfig['strongspace']['dir']}/#{dump}", 'w') do |handle|
sftp.write(handle, open("#{dump}").read)
end
end
end
log.info 'Finished transferring backup to Strongspace'
log.info 'Removing local file'
cmd = "rm -f #{dump}"
log.debug "Executing: #{cmd}"
`#{cmd}`
log.info 'Local file removed'
</code></pre>
<p>I've checked and double-checked all the paths and they're correct. Both <strong>sftp.yml</strong> (SFTP credentials) and <strong>database.yml</strong> (MySQL credentials) are owned by the executing user (deploy) with read-only permissions for that user (chmod 400). I'm using the 1.1.x versions of net-ssh and net-sftp. I know they're not the latest, but they're what I'm familiar with at the moment.</p>
<p>What could be causing the cron job to fail?</p>
| [
{
"answer_id": 13220,
"author": "Judge Maygarden",
"author_id": 1491,
"author_profile": "https://Stackoverflow.com/users/1491",
"pm_score": 3,
"selected": true,
"text": "<p>Are you sure the temporary file is being created correctly when running as a cron job? The working directory for yo... | 2008/08/16 | [
"https://Stackoverflow.com/questions/13204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450/"
] | I have a cron job on an Ubuntu Hardy VPS that only half works and I can't work out why. The job is a Ruby script that uses mysqldump to back up a MySQL database used by a Rails application, which is then gzipped and uploaded to a remote server using SFTP.
The gzip file is created and copied successfully but it's always zero bytes. Yet if I run the cron command directly from the command line it works perfectly.
This is the cron job:
```
PATH=/usr/bin
10 3 * * * ruby /home/deploy/bin/datadump.rb
```
This is datadump.rb:
```
#!/usr/bin/ruby
require 'yaml'
require 'logger'
require 'rubygems'
require 'net/ssh'
require 'net/sftp'
APP = '/home/deploy/apps/myapp/current'
LOGFILE = '/home/deploy/log/data.log'
TIMESTAMP = '%Y%m%d-%H%M'
TABLES = 'table1 table2'
log = Logger.new(LOGFILE, 5, 10 * 1024)
dump = "myapp-#{Time.now.strftime(TIMESTAMP)}.sql.gz"
ftpconfig = YAML::load(open('/home/deploy/apps/myapp/shared/config/sftp.yml'))
config = YAML::load(open(APP + '/config/database.yml'))['production']
cmd = "mysqldump -u #{config['username']} -p#{config['password']} -h #{config['host']} --add-drop-table --add-locks --extended-insert --lock-tables #{config['database']} #{TABLES} | gzip -cf9 > #{dump}"
log.info 'Getting ready to create a backup'
`#{cmd}`
# Strongspace
log.info 'Backup created, starting the transfer to Strongspace'
Net::SSH.start(ftpconfig['strongspace']['host'], ftpconfig['strongspace']['username'], ftpconfig['strongspace']['password']) do |ssh|
ssh.sftp.connect do |sftp|
sftp.open_handle("#{ftpconfig['strongspace']['dir']}/#{dump}", 'w') do |handle|
sftp.write(handle, open("#{dump}").read)
end
end
end
log.info 'Finished transferring backup to Strongspace'
log.info 'Removing local file'
cmd = "rm -f #{dump}"
log.debug "Executing: #{cmd}"
`#{cmd}`
log.info 'Local file removed'
```
I've checked and double-checked all the paths and they're correct. Both **sftp.yml** (SFTP credentials) and **database.yml** (MySQL credentials) are owned by the executing user (deploy) with read-only permissions for that user (chmod 400). I'm using the 1.1.x versions of net-ssh and net-sftp. I know they're not the latest, but they're what I'm familiar with at the moment.
What could be causing the cron job to fail? | Are you sure the temporary file is being created correctly when running as a cron job? The working directory for your script will either be specified in the HOME environment variable, or the /etc/passwd entry for the user that installed the cron job. If deploy does not have write permissions for the directory in which it is executing, then you could specify an absolute path for the dump file to fix the problem. |
13,217 | <p>I am uploading multiple files using the BeginGetRequestStream of HttpWebRequest but I want to update the progress control I have written whilst I post up the data stream. </p>
<p>How should this be done, I have tried calling Dispatch.BeginInvoke (as below) from within the loop that pushes the data into the stream but it locks the browser until its finished so it seems to be in some sort of worker/ui thread deadlock. </p>
<p>This is a code snippet of pretty much what I am doing:</p>
<pre><code>class RequestState
{
public HttpWebRequest request; // holds the request
public FileDialogFileInfo file; // store our file stream data
public RequestState( HttpWebRequest request, FileDialogFileInfo file )
{
this.request = request;
this.file = file;
}
}
private void UploadFile( FileDialogFileInfo file )
{
UriBuilder ub = new UriBuilder( app.receiverURL );
ub.Query = string.Format( "filename={0}", file.Name );
// Open the selected file to read.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create( ub.Uri );
request.Method = "POST";
RequestState state = new RequestState( request, file );
request.BeginGetRequestStream( new AsyncCallback( OnUploadReadCallback ), state );
}
private void OnUploadReadCallback( IAsyncResult asynchronousResult )
{
RequestState state = (RequestState)asynchronousResult.AsyncState;
HttpWebRequest request = (HttpWebRequest)state.request;
Stream postStream = request.EndGetRequestStream( asynchronousResult );
PushData( state.file, postStream );
postStream.Close();
state.request.BeginGetResponse( new AsyncCallback( OnUploadResponseCallback ), state.request );
}
private void PushData( FileDialogFileInfo file, Stream output )
{
byte[] buffer = new byte[ 4096 ];
int bytesRead = 0;
Stream input = file.OpenRead();
while( ( bytesRead = input.Read( buffer, 0, buffer.Length ) ) != 0 )
{
output.Write( buffer, 0, bytesRead );
bytesReadTotal += bytesRead;
App app = App.Current as App;
int totalPercentage = Convert.ToInt32( ( bytesReadTotal / app.totalBytesToUpload ) * 100 );
// enabling the following locks up my UI and browser
Dispatcher.BeginInvoke( () =>
{
this.ProgressBarWithPercentage.Percentage = totalPercentage;
} );
}
}
</code></pre>
| [
{
"answer_id": 16648,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 2,
"selected": true,
"text": "<p>I was going to say that, I didn't think that Silverlight 2's HttpWebRequest supported streaming, because the request dat... | 2008/08/16 | [
"https://Stackoverflow.com/questions/13217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1478/"
] | I am uploading multiple files using the BeginGetRequestStream of HttpWebRequest but I want to update the progress control I have written whilst I post up the data stream.
How should this be done, I have tried calling Dispatch.BeginInvoke (as below) from within the loop that pushes the data into the stream but it locks the browser until its finished so it seems to be in some sort of worker/ui thread deadlock.
This is a code snippet of pretty much what I am doing:
```
class RequestState
{
public HttpWebRequest request; // holds the request
public FileDialogFileInfo file; // store our file stream data
public RequestState( HttpWebRequest request, FileDialogFileInfo file )
{
this.request = request;
this.file = file;
}
}
private void UploadFile( FileDialogFileInfo file )
{
UriBuilder ub = new UriBuilder( app.receiverURL );
ub.Query = string.Format( "filename={0}", file.Name );
// Open the selected file to read.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create( ub.Uri );
request.Method = "POST";
RequestState state = new RequestState( request, file );
request.BeginGetRequestStream( new AsyncCallback( OnUploadReadCallback ), state );
}
private void OnUploadReadCallback( IAsyncResult asynchronousResult )
{
RequestState state = (RequestState)asynchronousResult.AsyncState;
HttpWebRequest request = (HttpWebRequest)state.request;
Stream postStream = request.EndGetRequestStream( asynchronousResult );
PushData( state.file, postStream );
postStream.Close();
state.request.BeginGetResponse( new AsyncCallback( OnUploadResponseCallback ), state.request );
}
private void PushData( FileDialogFileInfo file, Stream output )
{
byte[] buffer = new byte[ 4096 ];
int bytesRead = 0;
Stream input = file.OpenRead();
while( ( bytesRead = input.Read( buffer, 0, buffer.Length ) ) != 0 )
{
output.Write( buffer, 0, bytesRead );
bytesReadTotal += bytesRead;
App app = App.Current as App;
int totalPercentage = Convert.ToInt32( ( bytesReadTotal / app.totalBytesToUpload ) * 100 );
// enabling the following locks up my UI and browser
Dispatcher.BeginInvoke( () =>
{
this.ProgressBarWithPercentage.Percentage = totalPercentage;
} );
}
}
``` | I was going to say that, I didn't think that Silverlight 2's HttpWebRequest supported streaming, because the request data gets buffered into memory entirely. It had been a while since the last time I looked at it though, therefore I went back to see if Beta 2 supported it. Well turns out it does. I am glad I went back and read before stating that. You can enable it by setting AllowReadStreamBuffering to false. Did you set this property on your HttpWebRequest? That could be causing your block.
* [MSDN Reference](http://shrinkster.com/11cn)
* [File upload component for Silverlight and ASP.NET](http://www.wilcob.com/Wilco/View.aspx?NewsID=212)
Edit, found another reference for you. You may want to follow this approach by breaking the file into chunks. This was written last March, therefore I am not sure if it will work in Beta 2 or not. |
13,225 | <p>I've recently inherited a internationalized and text-heavy Struts 1.1 web application. Many of the JSP files look like:</p>
<pre class="lang-jsp prettyprint-override"><code><p>
<bean:message key="alert" />
</p>
</code></pre>
<p>and the properties files look like:</p>
<pre><code>messages.properties
alert=Please update your <a href="/address.do">address</a> and <a href="/contact.do">contact information</a>.
</code></pre>
<p>with the appropriate translations in N other languages (messages_fr.properties, etc).</p>
<p>Problems:</p>
<ol>
<li><em><strong>DRY violation</strong></em> - I have N references to my Struts action URLs instead of 1, which makes refactoring action URLs error-prone.</li>
<li><em><strong>Mixed concerns</strong></em> - My application's markup is now in more than just my JSP files, making it difficult for a web specialist to tweak the markup (using CSS, etc).</li>
<li><em><strong>Post-translation markup</strong></em> - Anytime I receive newly-translated text, I must decide what to surround with the <code><a>...</a></code> markup. Easy for English but less so for unfamiliar languages.</li>
</ol>
<p>I've considered adding placeholders in the messages file, like:</p>
<pre><code>alert=Please update your {0} and {1}.
</code></pre>
<p>but then the words "address" and "contact information" would somehow need to be localized, wrapped with markup, and passed to my message tag - and I can't see an easy way to do it.</p>
<p>What can I do to improve this?</p>
| [
{
"answer_id": 13239,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps:</p>\n\n<pre><code>#\nalert=Please update your {0}address{1} and {2}contact information{3}.\n</code></pre>\n"
},
... | 2008/08/16 | [
"https://Stackoverflow.com/questions/13225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1557/"
] | I've recently inherited a internationalized and text-heavy Struts 1.1 web application. Many of the JSP files look like:
```jsp
<p>
<bean:message key="alert" />
</p>
```
and the properties files look like:
```
messages.properties
alert=Please update your <a href="/address.do">address</a> and <a href="/contact.do">contact information</a>.
```
with the appropriate translations in N other languages (messages\_fr.properties, etc).
Problems:
1. ***DRY violation*** - I have N references to my Struts action URLs instead of 1, which makes refactoring action URLs error-prone.
2. ***Mixed concerns*** - My application's markup is now in more than just my JSP files, making it difficult for a web specialist to tweak the markup (using CSS, etc).
3. ***Post-translation markup*** - Anytime I receive newly-translated text, I must decide what to surround with the `<a>...</a>` markup. Easy for English but less so for unfamiliar languages.
I've considered adding placeholders in the messages file, like:
```
alert=Please update your {0} and {1}.
```
but then the words "address" and "contact information" would somehow need to be localized, wrapped with markup, and passed to my message tag - and I can't see an easy way to do it.
What can I do to improve this? | >
> Avoid creating links within long
> blocks of text. Prefer shorter text
> that can act as a logically complete
> and independent link.
>
>
>
Generally, it will lead to fewer problems. Sometimes you have to compromise your UI design to accommodate localization; sometimes you need to compromise your localization process to accommodate the UI.
Any time a developer manually manipulates post-translation strings is a source of potentially expensive bugs. Cutting/pasting or string editing can result in character corruption, misplaced strings, etc. A translation defect needs the participation of outside parties to fix which involves cost and takes time.
Thinking on it, something like this might be less ugly:
```html
<p>Please update your address and contact information.
<br />
<a href="/address.do">update address</a>
<br />
<a href="/contact.do">update contact information</a></p>
```
...but I'm no UI designer. |
13,362 | <p>I've got a div that uses overflow:auto to keep the contents inside the div as it is resized and dragged around the page. I'm using some ajax to retrieve lines of text from the server, then append them to the end of the div, so the content is growing downwards. Every time this happens, I'd like to use JS to scroll the div to the bottom so the most recently added content is visible, similar to the way a chat room or command line console would work.</p>
<p>So far I've been using this snippet to do it (I'm also using jQuery, hence the $() function):</p>
<pre><code>$("#thediv").scrollTop = $("#thediv").scrollHeight;
</code></pre>
<p>However it's been giving me inconsistent results. Sometimes it works, sometimes not, and it completely ceases to work if the user ever resizes the div or moves the scroll bar manually.</p>
<p>The target browser is Firefox 3, and it's being deployed in a controlled environment so it doesn't need to work in IE at all.</p>
<p>Any ideas guys? This one's got me stumped. Thanks!</p>
| [
{
"answer_id": 13365,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 7,
"selected": true,
"text": "<p><code>scrollHeight</code> should be the total height of content. <code>scrollTop</code> specifies the pixel offset into that co... | 2008/08/16 | [
"https://Stackoverflow.com/questions/13362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384/"
] | I've got a div that uses overflow:auto to keep the contents inside the div as it is resized and dragged around the page. I'm using some ajax to retrieve lines of text from the server, then append them to the end of the div, so the content is growing downwards. Every time this happens, I'd like to use JS to scroll the div to the bottom so the most recently added content is visible, similar to the way a chat room or command line console would work.
So far I've been using this snippet to do it (I'm also using jQuery, hence the $() function):
```
$("#thediv").scrollTop = $("#thediv").scrollHeight;
```
However it's been giving me inconsistent results. Sometimes it works, sometimes not, and it completely ceases to work if the user ever resizes the div or moves the scroll bar manually.
The target browser is Firefox 3, and it's being deployed in a controlled environment so it doesn't need to work in IE at all.
Any ideas guys? This one's got me stumped. Thanks! | `scrollHeight` should be the total height of content. `scrollTop` specifies the pixel offset into that content to be displayed at the top of the element's client area.
So you really want (still using jQuery):
```
$("#thediv").each( function()
{
// certain browsers have a bug such that scrollHeight is too small
// when content does not fill the client area of the element
var scrollHeight = Math.max(this.scrollHeight, this.clientHeight);
this.scrollTop = scrollHeight - this.clientHeight;
});
```
...which will set the scroll offset to the last `clientHeight` worth of content. |
13,396 | <p>I love list comprehensions in Python, because they concisely represent a transformation of a list.</p>
<p>However, in other languages, I frequently find myself writing something along the lines of:</p>
<pre><code>foreach (int x in intArray)
if (x > 3) //generic condition on x
x++
//do other processing
</code></pre>
<p>This example is in C#, where I'm under the impression LINQ can help with this, but is there some common programming construct which can replace this slightly less-than-elegant solution? Perhaps a data structure I'm not considering?</p>
| [
{
"answer_id": 13399,
"author": "jdd",
"author_id": 242853,
"author_profile": "https://Stackoverflow.com/users/242853",
"pm_score": -1,
"selected": false,
"text": "<p>Depends on the language and what you need to do, a \"map\" as it's called in many languages could be what you're looking ... | 2008/08/16 | [
"https://Stackoverflow.com/questions/13396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1266/"
] | I love list comprehensions in Python, because they concisely represent a transformation of a list.
However, in other languages, I frequently find myself writing something along the lines of:
```
foreach (int x in intArray)
if (x > 3) //generic condition on x
x++
//do other processing
```
This example is in C#, where I'm under the impression LINQ can help with this, but is there some common programming construct which can replace this slightly less-than-elegant solution? Perhaps a data structure I'm not considering? | The increment in the original `foreach` loop will not affect the contents of the array, the only way to do this remains a `for` loop:
```
for(int i = 0; i < intArray.Length; ++i)
{
if(intArray[i] > 3) ++intArray[i];
}
```
Linq is not intended to modify existing collections or sequences. It creates new sequences based on existing ones. It is possible to achieve the above code using Linq, though it is slightly against its purposes:
```
var newArray1 = from i in intArray select ((i > 3) ? (i + 1) : (i));
var newArray2 = intArray.Select(i => (i > 3) ? (i + 1) : (i));
```
Using `where` (or equivalent), as shown in some of the other answers, will exclude any values less than or equal to 3 from the resulting sequence.
```
var intArray = new int[] { 10, 1, 20, 2 };
var newArray = from i in intArray where i > 3 select i + 1;
// newArray == { 11, 21 }
```
There is a `ForEach` method on arrays that will allow you to use a lambda function instead of a `foreach` block, though for anything more than a method call I would stick with `foreach`.
```
intArray.ForEach(i => DoSomething(i));
``` |
13,454 | <p>I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:</p>
<pre><code>cleaned = stringwithslashes
cleaned = cleaned.replace('\\n', '\n')
cleaned = cleaned.replace('\\r', '\n')
cleaned = cleaned.replace('\\', '')
</code></pre>
<p>How can I condense it? </p>
| [
{
"answer_id": 13456,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 0,
"selected": false,
"text": "<p>You can obviously concatenate everything together:</p>\n\n<pre><code>cleaned = stringwithslashes.replace(\"\\\\n\",\"\... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:
```
cleaned = stringwithslashes
cleaned = cleaned.replace('\\n', '\n')
cleaned = cleaned.replace('\\r', '\n')
cleaned = cleaned.replace('\\', '')
```
How can I condense it? | Not totally sure this is what you want, but..
```
cleaned = stringwithslashes.decode('string_escape')
``` |
13,470 | <p>I was reading <a href="https://stackoverflow.com/questions/6173/regular-expression-for-parsing-links-from-a-webpage">this question</a> about how to parse URLs out of web pages and had a question about the <a href="https://stackoverflow.com/questions/6173/regular-expression-for-parsing-links-from-a-webpage#6183">accepted answer</a> which offered this solution:</p>
<pre class="lang-none prettyprint-override"><code>((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)
</code></pre>
<p>The solution was offered by <a href="https://stackoverflow.com/users/350/csmba">csmba</a> and he credited it to <a href="http://regexlib.com/Search.aspx?k=URL" rel="nofollow noreferrer">regexlib.com</a>. Whew. Credits done.</p>
<p>I think this is a fairly naive regular expression but it's a fine starting point for building something better. But, my question is this:</p>
<p>What is the point of <code>{1}</code>? It means "exactly one of the previous grouping", right? Isn't that the default behavior of a grouping in a regular expression? Would the expression be changed in any way if the <code>{1}</code> were removed?</p>
<p>If I saw this from a coworker I would point out his or her error but as I write this the response is rated at a 6 and the expression on regexlib.com is rated a 4 of 5. So maybe I'm missing something?</p>
| [
{
"answer_id": 13475,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think it has any purpose. But because RegEx is almost impossible to understand/decompose, people rarely point out e... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/430/"
] | I was reading [this question](https://stackoverflow.com/questions/6173/regular-expression-for-parsing-links-from-a-webpage) about how to parse URLs out of web pages and had a question about the [accepted answer](https://stackoverflow.com/questions/6173/regular-expression-for-parsing-links-from-a-webpage#6183) which offered this solution:
```none
((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)
```
The solution was offered by [csmba](https://stackoverflow.com/users/350/csmba) and he credited it to [regexlib.com](http://regexlib.com/Search.aspx?k=URL). Whew. Credits done.
I think this is a fairly naive regular expression but it's a fine starting point for building something better. But, my question is this:
What is the point of `{1}`? It means "exactly one of the previous grouping", right? Isn't that the default behavior of a grouping in a regular expression? Would the expression be changed in any way if the `{1}` were removed?
If I saw this from a coworker I would point out his or her error but as I write this the response is rated at a 6 and the expression on regexlib.com is rated a 4 of 5. So maybe I'm missing something? | @Jeff Atwood, your interpretation is a little off - the {1} means match exactly once, but has no effect on the "capturing" - the capturing occurs because of the parens - the braces only specify the number of times the pattern must match the source - once, as you say.
I agree with @Marius, even if his answer is a little terse and may come off as being flippant. Regular expressions are tough, if one's not used to using them, and the {1} in the question isn't quite error - in systems that support it, it does mean "exactly one match". In this sense, it doesn't really do anything.
Unfortunately, contrary to a now-deleted post, it doesn't keep the regexp from matching `http://http://example.org`, since the \S+ at the end will match one or more non-whitespace characters, including the `http://example.org` in `http://http://example.org` (verified using Python 2.5, just in case my regexp reading was off). So, the regexp given isn't really the best. I'm not a URL expert, but probably something limiting the appearance of ":"s and "//"s after the first one would be necessary (but hardly sufficient) to ensure good URLs. |
13,473 | <p>I would like to sort an array in ascending order using <code>C/C++</code>. The outcome is an array containing element indexes. Each index is corespondent to the element location in the sorted array.</p>
<p><strong>Example</strong></p>
<pre><code>Input: 1, 3, 4, 9, 6
Output: 1, 2, 3, 5, 4
</code></pre>
<p><strong>Edit:</strong> I am using shell sort procedure. The duplicate value indexes are arbitrarily chosen based on which duplicate values are first in the original array.</p>
<h3>Update:</h3>
<p>Despite my best efforts, I haven't been able to implement a sorting algorithm for an array of pointers. The current example won't compile.</p>
<p>Could someone please tell me what's wrong?</p>
<p>I'd very much appreciate some help!</p>
<pre><code>void SortArray(int ** pArray, int ArrayLength)
{
int i, j, flag = 1; // set flag to 1 to begin initial pass
int * temp; // holding variable orig with no *
for (i = 1; (i <= ArrayLength) && flag; i++)
{
flag = 0;
for (j = 0; j < (ArrayLength - 1); j++)
{
if (*pArray[j + 1] > *pArray[j]) // ascending order simply changes to <
{
&temp = &pArray[j]; // swap elements
&pArray[j] = &pArray[j + 1]; //the problem lies somewhere in here
&pArray[j + 1] = &temp;
flag = 1; // indicates that a swap occurred.
}
}
}
};
</code></pre>
| [
{
"answer_id": 13477,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 0,
"selected": false,
"text": "<p>Well, there's a trival n^2 solution.</p>\n\n<p>In python:</p>\n\n<pre><code>newArray = sorted(oldArray)\nblankArray = [0] * ... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522/"
] | I would like to sort an array in ascending order using `C/C++`. The outcome is an array containing element indexes. Each index is corespondent to the element location in the sorted array.
**Example**
```
Input: 1, 3, 4, 9, 6
Output: 1, 2, 3, 5, 4
```
**Edit:** I am using shell sort procedure. The duplicate value indexes are arbitrarily chosen based on which duplicate values are first in the original array.
### Update:
Despite my best efforts, I haven't been able to implement a sorting algorithm for an array of pointers. The current example won't compile.
Could someone please tell me what's wrong?
I'd very much appreciate some help!
```
void SortArray(int ** pArray, int ArrayLength)
{
int i, j, flag = 1; // set flag to 1 to begin initial pass
int * temp; // holding variable orig with no *
for (i = 1; (i <= ArrayLength) && flag; i++)
{
flag = 0;
for (j = 0; j < (ArrayLength - 1); j++)
{
if (*pArray[j + 1] > *pArray[j]) // ascending order simply changes to <
{
&temp = &pArray[j]; // swap elements
&pArray[j] = &pArray[j + 1]; //the problem lies somewhere in here
&pArray[j + 1] = &temp;
flag = 1; // indicates that a swap occurred.
}
}
}
};
``` | Since you're using C++, I would do it something like this. The `SortIntPointers` function can be any sort algorithm, the important part is that it sorts the array of pointers based on the `int` that they are pointing to. Once that is done, you can go through the array of pointers and assign their sorted index which will end up in the original position in the original array.
```
int* intArray; // set somewhere else
int arrayLen; // set somewhere else
int** pintArray = new int*[arrayLen];
for(int i = 0; i < arrayLen; ++i)
{
pintArray[i] = &intArray[i];
}
// This function sorts the pointers according to the values they
// point to. In effect, it sorts intArray without losing the positional
// information.
SortIntPointers(pintArray, arrayLen);
// Dereference the pointers and assign their sorted position.
for(int i = 0; i < arrayLen; ++i)
{
*pintArray[i] = i;
}
```
Hopefully that's clear enough. |
13,540 | <p>I've written a stored proc that will do an update if a record exists, otherwise it will do an insert. It looks something like this:</p>
<pre><code>update myTable set Col1=@col1, Col2=@col2 where ID=@ID
if @@rowcount = 0
insert into myTable (Col1, Col2) values (@col1, @col2)
</code></pre>
<p>My logic behind writing it in this way is that the update will perform an implicit select using the where clause and if that returns 0 then the insert will take place.</p>
<p>The alternative to doing it this way would be to do a select and then based on the number of rows returned either do an update or insert. This I considered inefficient because if you are to do an update it will cause 2 selects (the first explicit select call and the second implicit in the where of the update). If the proc were to do an insert then there'd be no difference in efficiency.</p>
<p>Is my logic sound here?
Is this how you would combine an insert and update into a stored proc?</p>
| [
{
"answer_id": 13554,
"author": "binOr",
"author_id": 990,
"author_profile": "https://Stackoverflow.com/users/990",
"pm_score": 7,
"selected": true,
"text": "<p>Your assumption is right, this is the optimal way to do it and it's called <a href=\"http://en.wikipedia.org/wiki/Upsert\" rel=... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | I've written a stored proc that will do an update if a record exists, otherwise it will do an insert. It looks something like this:
```
update myTable set Col1=@col1, Col2=@col2 where ID=@ID
if @@rowcount = 0
insert into myTable (Col1, Col2) values (@col1, @col2)
```
My logic behind writing it in this way is that the update will perform an implicit select using the where clause and if that returns 0 then the insert will take place.
The alternative to doing it this way would be to do a select and then based on the number of rows returned either do an update or insert. This I considered inefficient because if you are to do an update it will cause 2 selects (the first explicit select call and the second implicit in the where of the update). If the proc were to do an insert then there'd be no difference in efficiency.
Is my logic sound here?
Is this how you would combine an insert and update into a stored proc? | Your assumption is right, this is the optimal way to do it and it's called [upsert/merge](http://en.wikipedia.org/wiki/Upsert).
[Importance of UPSERT - from sqlservercentral.com](http://www.sqlservercentral.com/articles/T-SQL/61773/):
>
> For every update in the case mentioned above we are removing one
> additional read from the table if we
> use the UPSERT instead of EXISTS.
> Unfortunately for an Insert, both the
> UPSERT and IF EXISTS methods use the
> same number of reads on the table.
> Therefore the check for existence
> should only be done when there is a
> very valid reason to justify the
> additional I/O. The optimized way to
> do things is to make sure that you
> have little reads as possible on the
> DB.
>
>
> The best strategy is to attempt the
> update. If no rows are affected by the
> update then insert. In most
> circumstances, the row will already
> exist and only one I/O will be
> required.
>
>
>
**Edit**:
Please check out [this answer](https://stackoverflow.com/questions/13540/insert-update-stored-proc-on-sql-server/193876#193876) and the linked blog post to learn about the problems with this pattern and how to make it work safe. |
13,569 | <p>In our place we're split between using mysqli and PDO for stuff like prepared statements and transaction support. Some projects use one, some the other. There is little realistic likelihood of us ever moving to another RDBMS.</p>
<p>I prefer PDO for the single reason that it allows named parameters for prepared statements, and as far as I am aware mysqli does not.</p>
<p>Are there any other pros and cons to choosing one over the other as a standard as we consolidate our projects to use just one approach?</p>
| [
{
"answer_id": 13571,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 6,
"selected": false,
"text": "<p>Moving an application from one database to another isn't very common, but sooner or later you may find yourself working on an... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137/"
] | In our place we're split between using mysqli and PDO for stuff like prepared statements and transaction support. Some projects use one, some the other. There is little realistic likelihood of us ever moving to another RDBMS.
I prefer PDO for the single reason that it allows named parameters for prepared statements, and as far as I am aware mysqli does not.
Are there any other pros and cons to choosing one over the other as a standard as we consolidate our projects to use just one approach? | Well, you could argue with the object oriented aspect, the prepared statements, the fact that it becomes a standard, etc. But I know that most of the time, convincing somebody works better with a killer feature. So there it is:
A really nice thing with PDO is you can fetch the data, injecting it automatically in an object. If you don't want to use an [ORM](http://en.wikipedia.org/wiki/Object-relational_mapping) (cause it's a just a quick script) but you do like object mapping, it's REALLY cool :
```
class Student {
public $id;
public $first_name;
public $last_name
public function getFullName() {
return $this->first_name.' '.$this->last_name
}
}
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=school", $username, $password)
$stmt = $dbh->query("SELECT * FROM students");
/* MAGIC HAPPENS HERE */
$stmt->setFetchMode(PDO::FETCH_INTO, new Student);
foreach($stmt as $student)
{
echo $student->getFullName().'<br />';
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
``` |
13,578 | <p>The need arose, in our product, to determine how long the current user has been logged on to Windows (specifically, Vista). It seems there is no straight forward API function for this and I couldn't find anything relevant with WMI (although I'm no expert with WMI, so I might have missed something).</p>
<p>Any ideas?</p>
| [
{
"answer_id": 13581,
"author": "Michał Piaskowski",
"author_id": 1534,
"author_profile": "https://Stackoverflow.com/users/1534",
"pm_score": 1,
"selected": false,
"text": "<p>In WMI do: \"select * from Win32_Session\"\nthere you'll have \"StartTime\" value.</p>\n\n<p>Hope that helps.</p... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1596/"
] | The need arose, in our product, to determine how long the current user has been logged on to Windows (specifically, Vista). It seems there is no straight forward API function for this and I couldn't find anything relevant with WMI (although I'm no expert with WMI, so I might have missed something).
Any ideas? | For people not familiar with WMI (like me), here are some links:
* MSDN page on using WMI from various languages: <http://msdn.microsoft.com/en-us/library/aa393964(VS.85).aspx>
* reference about Win32\_Session: <http://msdn.microsoft.com/en-us/library/aa394422(VS.85).aspx>, but the objects in Win32\_session are of type Win32\_LogonSession (<http://msdn.microsoft.com/en-us/library/aa394189(VS.85).aspx>), which has more interesting properties.
* [WMI Explorer](http://www.ks-soft.net/hostmon.eng/wmi/index.htm) - a tool you can use to easily run queries like the one Michal posted.
And here's example querying Win32\_Session from VBS:
```
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set sessions = objWMIService.ExecQuery _
("select * from Win32_Session")
For Each objSession in sessions
Wscript.Echo objSession.StartTime
Next
```
It alerts 6 sessions for my personal computer, perhaps you can filter by LogonType to only list the real ("interactive") users. I couldn't see how you can select the session of the "current user".
[edit] and here's a result from Google to your problem: <http://forum.sysinternals.com/forum_posts.asp?TID=3755> |