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
244,854
<p>When I construct my control (which inherits DataGrid), I add specific rows and columns. This works great at design time. Unfortunately, at runtime I add my rows and columns in the same constructor, but then the DataGrid is serialized (after the constructor runs) adding <strong>more</strong> rows and columns.</p> <p>After serialization is complete, I need to clear everything and re-initialize the rows and columns. Is there a protected method that I can override to know when the control is done serializing?</p> <p>Of course, I'd prefer to not have to do the work in the constructor, throw it away, and do it again after (potential) serialization. Is there a preferred event that is the equivalent of "set yourself up now", so that it is called once whether I'm serialized or not?</p> <hr> <p>The serialization i speak of comes from the InitializeComponent() method in the form's code-behind file. </p> <pre><code>#region Windows Form Designer generated code /// &lt;summary&gt; /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// &lt;/summary&gt; private void InitializeComponent() { ... } </code></pre> <p>It would have been perfect if InitializeComponent was a virtual method defined by Control, then i could just override it and then perform my processing after i call base:</p> <pre><code>protected override void InitializeComponent() { base.InitializeComponent(); InitializeMe(); } </code></pre> <p>But it's not an ancestor method, it's declared only in the code-behind file.</p> <p>i notice that InitializeComponent calls SuspendLayout and ResumeLayout on various Controls. i thought it could override ResumeLayout, and perform my initialization then:</p> <pre><code>public override void ResumeLayout() { base.ResumeLayout(); InitializeMe(); } </code></pre> <p>But ResumeLayout is not virtual, so that's out.</p> <p>Anymore ideas? i can't be the first person to create a custom control.</p>
[ { "answer_id": 248782, "author": "Tim Robinson", "author_id": 32133, "author_profile": "https://Stackoverflow.com/users/32133", "pm_score": 1, "selected": false, "text": "<p>What seems to be happening is this:</p>\n\n<ol>\n<li>You've designed a custom DataGrid that adds its own rows and columns in the constructor</li>\n<li>You've added your custom DataGrid to a form</li>\n<li>You've found that the form designer has written code inside the form's InitializeComponent that adds those rows and columns a second time</li>\n</ol>\n\n<p>The way the Windows Forms designer code generator works is that it looks at all of your object's properties, determines what the default values should be, and generates code for the properties that aren't set to the defaults. Unfortunately for you, the default state of a DataGrid is to have no rows and no columns.</p>\n\n<p>You can alter this behaviour with a set of attributes, though. A straightforward way might be to add new copies of the Rows and Columns properties to your class, which just return base.Rows and base.Columns. Adding duplicate properties in this way lets you apply the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.designerserializationvisibility.aspx\" rel=\"nofollow noreferrer\">DesignerSerializationVisibilty</a> attribute to them, which you can use to force the forms designer to ignore the pre-populated rows and columns.</p>\n" }, { "answer_id": 2985632, "author": "Joe White", "author_id": 87399, "author_profile": "https://Stackoverflow.com/users/87399", "pm_score": 0, "selected": false, "text": "<p>\"Is there a protected method that I can override to know when the control is done serializing?\"</p>\n\n<p>No, not a protected method, but there is an interface. If your control implements <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.isupportinitialize.aspx\" rel=\"nofollow noreferrer\">ISupportInitialize</a>, then when Visual Studio next saves the .designer.cs of a Form/UserControl that contains your custom control, it will automatically add a call to your <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.isupportinitialize.begininit.aspx\" rel=\"nofollow noreferrer\">BeginInit</a> method immediately after your control is instantiated (but before any property values are assigned), and a call to <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.isupportinitialize.endinit.aspx\" rel=\"nofollow noreferrer\">EndInit</a> after all properties are done being set.</p>\n\n<p>However, while this gives you a lot of flexibility, it's kind of fiddly to get right for the kind of thing you describe (I've used it for much the same thing, so I know). If your descendant takes total control over the rows and columns, and it never makes sense for the user to edit them in the designer, then Tim's suggestion (DesignerSerializationVisibility) would be much simpler and easier to get right.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
When I construct my control (which inherits DataGrid), I add specific rows and columns. This works great at design time. Unfortunately, at runtime I add my rows and columns in the same constructor, but then the DataGrid is serialized (after the constructor runs) adding **more** rows and columns. After serialization is complete, I need to clear everything and re-initialize the rows and columns. Is there a protected method that I can override to know when the control is done serializing? Of course, I'd prefer to not have to do the work in the constructor, throw it away, and do it again after (potential) serialization. Is there a preferred event that is the equivalent of "set yourself up now", so that it is called once whether I'm serialized or not? --- The serialization i speak of comes from the InitializeComponent() method in the form's code-behind file. ``` #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { ... } ``` It would have been perfect if InitializeComponent was a virtual method defined by Control, then i could just override it and then perform my processing after i call base: ``` protected override void InitializeComponent() { base.InitializeComponent(); InitializeMe(); } ``` But it's not an ancestor method, it's declared only in the code-behind file. i notice that InitializeComponent calls SuspendLayout and ResumeLayout on various Controls. i thought it could override ResumeLayout, and perform my initialization then: ``` public override void ResumeLayout() { base.ResumeLayout(); InitializeMe(); } ``` But ResumeLayout is not virtual, so that's out. Anymore ideas? i can't be the first person to create a custom control.
What seems to be happening is this: 1. You've designed a custom DataGrid that adds its own rows and columns in the constructor 2. You've added your custom DataGrid to a form 3. You've found that the form designer has written code inside the form's InitializeComponent that adds those rows and columns a second time The way the Windows Forms designer code generator works is that it looks at all of your object's properties, determines what the default values should be, and generates code for the properties that aren't set to the defaults. Unfortunately for you, the default state of a DataGrid is to have no rows and no columns. You can alter this behaviour with a set of attributes, though. A straightforward way might be to add new copies of the Rows and Columns properties to your class, which just return base.Rows and base.Columns. Adding duplicate properties in this way lets you apply the [DesignerSerializationVisibilty](http://msdn.microsoft.com/en-us/library/system.componentmodel.designerserializationvisibility.aspx) attribute to them, which you can use to force the forms designer to ignore the pre-populated rows and columns.
244,875
<p>I have a custom webpart that is displaying dynamic list data, it needs to render an image from a Picture Library (or at least provide me the URL so I can encapsulate it with an tag), however, none of the fields in the Picture Library seem to contain the image URL? Is there a 'image utility' (SPImageUtility) or something I can use to pull this out? Or am I simply missing something?</p>
[ { "answer_id": 244989, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 0, "selected": false, "text": "<p>Are getting information from a CAML query? If so you will need to add the required field to the query.</p>\n\n<p>Otherwise the spListItem object from the spList has the property URL which has a web relative URL for the image.</p>\n" }, { "answer_id": 248978, "author": "Ryan", "author_id": 20198, "author_profile": "https://Stackoverflow.com/users/20198", "pm_score": 2, "selected": false, "text": "<p>Assuming you are using the object model then the you should use this (c#)</p>\n\n<pre><code>SPListItem[\"EncodedAbsUrl\"]\n</code></pre>\n\n<p>to get the HTML encoded absolute URL of the image (where \"<strong>EncodedAbsUrl</strong>\" is the name of the field/column).</p>\n\n<p>To get the unencoded site relative url you can use <strong>ServerUrl</strong> or <strong>FileRef</strong> (they appear to return the same)</p>\n\n<p>You can also use <strong>EncodedAbsThumbnailUrl</strong> to get a thumbnail image.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.aspx</a></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105/" ]
I have a custom webpart that is displaying dynamic list data, it needs to render an image from a Picture Library (or at least provide me the URL so I can encapsulate it with an tag), however, none of the fields in the Picture Library seem to contain the image URL? Is there a 'image utility' (SPImageUtility) or something I can use to pull this out? Or am I simply missing something?
Assuming you are using the object model then the you should use this (c#) ``` SPListItem["EncodedAbsUrl"] ``` to get the HTML encoded absolute URL of the image (where "**EncodedAbsUrl**" is the name of the field/column). To get the unencoded site relative url you can use **ServerUrl** or **FileRef** (they appear to return the same) You can also use **EncodedAbsThumbnailUrl** to get a thumbnail image. <http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.aspx>
244,884
<p>I'm really stumped on this one. I want to output a list and have the tag file take care of commas, singular versus plural, etc. but when I display the list it completely ignores whitespace so everythingrunstogetherlikethis. I tried using the HTML entities "thinsp", "ensp" and "emsp" (I can't use "nbsp", these have to be breaking), but they're all hideously wide on IE except thinsp which is way too skinny on everything else.</p> <p>Edit: won't work. The output from the tag has no spaces at all. Although any content in the JSP has normal spacing. Obviously I could just put everything in the JSP but this is code that goes on multiple JSPs, so tag files would make a lot of sense.</p>
[ { "answer_id": 245305, "author": "alex77", "author_id": 1555, "author_profile": "https://Stackoverflow.com/users/1555", "pm_score": 2, "selected": false, "text": "<p>Maybe put the jsp content in an html <code>&lt;pre&gt;</code> tag?\nThis seems to me to be the right thing to do as the list is pre-formatted content.</p>\n" }, { "answer_id": 656765, "author": "evnafets", "author_id": 56479, "author_profile": "https://Stackoverflow.com/users/56479", "pm_score": 0, "selected": false, "text": "<p>So you are saying your <em>tag</em> doesn't print out white space at all?\nIs there any whitespace for it to print out?</p>\n\n<p>Can you post the code, and a short example of how you use it?</p>\n" }, { "answer_id": 2133587, "author": "gshegosh", "author_id": 258570, "author_profile": "https://Stackoverflow.com/users/258570", "pm_score": 1, "selected": false, "text": "<p>I used <code>&amp;#32;</code> entity instead of space but generally I think this sucks that either ALL whitespace is eaten and one has to hack with entities or you have vast space in the generated HTML code.</p>\n" }, { "answer_id": 2134454, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 4, "selected": false, "text": "<p>It's actually a bug in the EL parser which causes spaces in between EL expressions to be eaten. E.g.</p>\n\n<pre><code>${bean.foo} ${bean.bar} ${bean.waa}\n</code></pre>\n\n<p>would get printed as (assuming that they returns the very same String value as its property name is):</p>\n\n<pre><code>foobarwaa\n</code></pre>\n\n<p>I recall that this issue was reported somewhere before, but I can't seem to find it right now. As far now you can fix it by using JSTL <code>c:out</code> tag:</p>\n\n<pre><code>&lt;c:out value=\"${bean.foo} ${bean.bar} ${bean.waa}\" /&gt;\n</code></pre>\n\n<p>which correctly get printed as:</p>\n\n<pre><code>foo bar waa\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/484/" ]
I'm really stumped on this one. I want to output a list and have the tag file take care of commas, singular versus plural, etc. but when I display the list it completely ignores whitespace so everythingrunstogetherlikethis. I tried using the HTML entities "thinsp", "ensp" and "emsp" (I can't use "nbsp", these have to be breaking), but they're all hideously wide on IE except thinsp which is way too skinny on everything else. Edit: won't work. The output from the tag has no spaces at all. Although any content in the JSP has normal spacing. Obviously I could just put everything in the JSP but this is code that goes on multiple JSPs, so tag files would make a lot of sense.
It's actually a bug in the EL parser which causes spaces in between EL expressions to be eaten. E.g. ``` ${bean.foo} ${bean.bar} ${bean.waa} ``` would get printed as (assuming that they returns the very same String value as its property name is): ``` foobarwaa ``` I recall that this issue was reported somewhere before, but I can't seem to find it right now. As far now you can fix it by using JSTL `c:out` tag: ``` <c:out value="${bean.foo} ${bean.bar} ${bean.waa}" /> ``` which correctly get printed as: ``` foo bar waa ```
244,886
<p>Consider the following code:</p> <pre><code>Public Class Animal Public Overridable Function Speak() As String Return "Hello" End Function End Class Public Class Dog Inherits Animal Public Overrides Function Speak() As String Return "Ruff" End Function End Class Dim dog As New Dog Dim animal As Animal animal = CType(dog, Animal) // Want "Hello", getting "Ruff" animal.Speak() </code></pre> <p>How can I convert/ctype the instance of Dog to Animal and have Animal.Speak get called?</p>
[ { "answer_id": 244910, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 4, "selected": false, "text": "<p>You don't; the subclass's method overrides the superclass's method, by definition of inheritance.</p>\n\n<p>If you want the overridden method to be available, expose it in the subclass, e.g.</p>\n\n<pre><code>Public Class Dog \n Inherits Animal\n Public Overrides Function Speak() As String\n Return \"Ruff\"\n End Function\n Public Function SpeakAsAnimal() As String\n Return MyBase.Speak()\n End Function\nEnd Class\n</code></pre>\n" }, { "answer_id": 244915, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "<p>I don't think you can. </p>\n\n<p>The thing is that the object is still a dog. the behavior you're describing (getting \"ruff\" from the casted object rather than \"hello\") is standard because you want to be able to use the animal class to let a bunch of different type of animals speak.</p>\n\n<p>For example, if you had a third class as thus:</p>\n\n<pre><code>Public Class Cat\n Inherits Animal\n\n Public Overrides Function Speak() As String\n Return \"Meow\"\n End Function\nEnd Class\n</code></pre>\n\n<p>Then you'd be able to access them like thus:</p>\n\n<pre><code>protected sub Something\n Dim oCat as New Cat\n Dim oDog as New Dog\n\n MakeSpeak(oCat)\n MakeSpeak(oDog)\nEnd sub\n\nprotected sub MakeSpeak(ani as animal)\n Console.WriteLine(ani.Speak())\nend sub \n</code></pre>\n\n<p>What you're talking about doing basically breaks the inheritance chain. Now, this can be done, by setting up the <strong>Speak</strong> function to accept a parameter which tells it to return it's base value or not or a separate SPEAK function for the base value, but out of the box, you're not going to get things that behave this way.</p>\n" }, { "answer_id": 245039, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 1, "selected": false, "text": "<p>I would ask why you are trying to get this type of behavior. It seems to me that the fact you need to invoke the parent class' implementation of a method is an indication that you have a design flaw somewhere else in the system.</p>\n\n<p>Bottom line though, as others have stated there is no way to invoke the parent class' implementation given the way you've structured your classes. Now within the Dog class you could call</p>\n\n<pre><code>MyBase.Speak()\n</code></pre>\n\n<p>which would invoke the parent class' implementation, but from outside the Dog class there's no way to do it.</p>\n" }, { "answer_id": 321115, "author": "Matt Burke", "author_id": 29691, "author_profile": "https://Stackoverflow.com/users/29691", "pm_score": 0, "selected": false, "text": "<p>I think if you drop \"Overridable\" and change \"Overrides\" to \"New\" you'll get what you want.</p>\n\n<pre><code>Public Class Animal\n\nPublic Function Speak() As String\n Return \"Hello\"\nEnd Function\n\nEnd Class\n\nPublic Class Dog\n Inherits Animal\n\n Public New Function Speak() As String\n Return \"Ruff\"\n End Function\n\nEnd Class\n\nDim dog As New Dog\nDim animal As Animal\ndog.Speak() ' should be \"Ruff\"\nanimal = CType(dog, Animal)\nanimal.Speak() ' should be \"Hello\"\n</code></pre>\n" }, { "answer_id": 27599112, "author": "tfrascaroli", "author_id": 1420614, "author_profile": "https://Stackoverflow.com/users/1420614", "pm_score": 0, "selected": false, "text": "<p>I know this has been posted a few months back, but I'm still going to try and reply, maybe just for the sake of completeness.</p>\n\n<p>You've been told that you can access the overriden method from <em>within</em> the <code>dog</code> class, and that you can then expose it with a different name. But what about using a conditional?</p>\n\n<p>You can just do:</p>\n\n<pre><code>Public Class Animal\n\nPublic Overridable Function Speak(Optional ByVal speakNormal as Boolean = False) As String\n Return \"Hello\"\nEnd Function\n\nEnd Class\n\nPublic Class Dog\n Inherits Animal\n\n Public Overrides Function Speak(Optional ByVal speakNormal as Boolean = False) As String\n If speakNormal then\n return MyBase.Speak()\n Else\n Return \"Ruff\"\n End If\n End Function\n\nEnd Class\n</code></pre>\n\n<p>And then call them like:</p>\n\n<pre><code>Dim dog As New Dog\nDim animal As new Animal\nanimal.Speak() //\"Hello\"\ndog.Speak()//\"Ruff\"\ndog.Speak(true)//\"Hello\"\n</code></pre>\n\n<p>Alternatively, you can <code>getTheAnimalInTheDog</code> and make <em>it</em> <code>Speak()</code> :</p>\n\n<p>You can just do:</p>\n\n<pre><code>Public Class Animal\n\nPublic Overridable Function Speak() As String\n Return \"Hello\"\nEnd Function\n\nPublic MustOverride Function GetTheAnimalInMe() As Animal\n\nEnd Class\n\nPublic Class Dog\n Inherits Animal\n\n Public Overrides Function Speak() As String\n Return \"Ruff\"\n End Function\n\n Public Overrides Function GetTheAnimalInMe() As Animal\n Dim a As New Animal\n //Load a with the necessary custom parameters (if any)\n Return a\n End Function\nEnd Class\n</code></pre>\n\n<p>And then again:</p>\n\n<pre><code>Dim dog As New Dog\nDim animal As new Animal\nanimal.Speak() //\"Hello\"\ndog.Speak()//\"Ruff\"\ndog.GetTheAnimalInMe().Speak()//\"Hello\"\n</code></pre>\n\n<p>Hope it helps ;)</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81/" ]
Consider the following code: ``` Public Class Animal Public Overridable Function Speak() As String Return "Hello" End Function End Class Public Class Dog Inherits Animal Public Overrides Function Speak() As String Return "Ruff" End Function End Class Dim dog As New Dog Dim animal As Animal animal = CType(dog, Animal) // Want "Hello", getting "Ruff" animal.Speak() ``` How can I convert/ctype the instance of Dog to Animal and have Animal.Speak get called?
You don't; the subclass's method overrides the superclass's method, by definition of inheritance. If you want the overridden method to be available, expose it in the subclass, e.g. ``` Public Class Dog Inherits Animal Public Overrides Function Speak() As String Return "Ruff" End Function Public Function SpeakAsAnimal() As String Return MyBase.Speak() End Function End Class ```
244,889
<p>I have a performance problem with my ruby on my machine, which I think I have isolated to loading libraries (when #require is called), so I'm trying to work out whether ruby is searching too many folders for libraries.</p> <p>When I run </p> <pre><code>$ gem environment RubyGems Environment: - RUBYGEMS VERSION: 1.3.0 - RUBY VERSION: 1.8.6 (2008-03-03 patchlevel 114) [universal-darwin9.0] - INSTALLATION DIRECTORY: /Library/Ruby/Gems/1.8 - RUBY EXECUTABLE: /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby - EXECUTABLE DIRECTORY: /usr/bin - RUBYGEMS PLATFORMS: - ruby - universal-darwin-9 - GEM PATHS: - /Library/Ruby/Gems/1.8 - /Users/matt/.gem/ruby/1.8 - /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8 - GEM CONFIGURATION: - :update_sources =&gt; true - :verbose =&gt; true - :benchmark =&gt; false - :backtrace =&gt; false - :bulk_threshold =&gt; 1000 - :sources =&gt; ["http://gems.rubyforge.org", "http://gems.github.com/"] - REMOTE SOURCES: - http://gems.rubyforge.org - http://gems.github.com/ </code></pre> <p>There's nothing much on /Users/matt/.gem, but there's tons in both /Library/Ruby and in /System/Library/Frameworks/Ruby.framework.</p> <p>What gives? Is this normal?</p> <p>Thanks in advance, folks.</p>
[ { "answer_id": 248064, "author": "Gabe Hollombe", "author_id": 30632, "author_profile": "https://Stackoverflow.com/users/30632", "pm_score": 4, "selected": true, "text": "<p>Yep. That all looks pretty standard to me. My mac running MacOS 10.5 similarly has nothing in ~/.gem/ruby/1.8/gems/ and quite a bit in the other two locations.</p>\n" }, { "answer_id": 1794502, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>As Gabe mentioned, yes, this is normal.</p>\n\n<p>A little more info:</p>\n\n<p>/System/Library/Frameworks/Ruby.framework &lt;-- used system wide for all users, usually owned by root.\nWhen you 'sudo gem install ...' the gem you're installing goes here...</p>\n\n<p>/Users/matt/.gem &lt;-- user 'matt' has his own gem directory. every user gets one.</p>\n\n<p>When you just 'gem install' as 'matt' it will fall-back to your private gem dir. This gets created automatically the first time it's needed.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20011/" ]
I have a performance problem with my ruby on my machine, which I think I have isolated to loading libraries (when #require is called), so I'm trying to work out whether ruby is searching too many folders for libraries. When I run ``` $ gem environment RubyGems Environment: - RUBYGEMS VERSION: 1.3.0 - RUBY VERSION: 1.8.6 (2008-03-03 patchlevel 114) [universal-darwin9.0] - INSTALLATION DIRECTORY: /Library/Ruby/Gems/1.8 - RUBY EXECUTABLE: /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby - EXECUTABLE DIRECTORY: /usr/bin - RUBYGEMS PLATFORMS: - ruby - universal-darwin-9 - GEM PATHS: - /Library/Ruby/Gems/1.8 - /Users/matt/.gem/ruby/1.8 - /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8 - GEM CONFIGURATION: - :update_sources => true - :verbose => true - :benchmark => false - :backtrace => false - :bulk_threshold => 1000 - :sources => ["http://gems.rubyforge.org", "http://gems.github.com/"] - REMOTE SOURCES: - http://gems.rubyforge.org - http://gems.github.com/ ``` There's nothing much on /Users/matt/.gem, but there's tons in both /Library/Ruby and in /System/Library/Frameworks/Ruby.framework. What gives? Is this normal? Thanks in advance, folks.
Yep. That all looks pretty standard to me. My mac running MacOS 10.5 similarly has nothing in ~/.gem/ruby/1.8/gems/ and quite a bit in the other two locations.
244,892
<p>I have a protected Excel worksheet, without a password. What I'd like to do is trap the event that a user unprotects the worksheet, so that I can generate a message (and nag 'em!). I can setup event checking for the application, for when new workbooks are opened, etc., but not for Unprotect.<br> Does anyone have an idea?</p>
[ { "answer_id": 245036, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 2, "selected": false, "text": "<p>It is possible to modify the menu using Tools->Customize. Protect/Unprotect can be set to run a macro, for example:</p>\n\n<pre><code>Sub UnprotectTrap()\nIf ActiveSheet.ProtectContents = True Then\n MsgBox \"Tut,tut!\"\n ActiveSheet.Unprotect\nElse\n ActiveSheet.Protect\n\nEnd If\nEnd Sub\n</code></pre>\n" }, { "answer_id": 245139, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 0, "selected": false, "text": "<p>There is no way to trap the user unprotecting the sheet, but you can warn them if they save the workbook without reprotecting the sheet(s).</p>\n\n<p>In the Workbook module, put this code, or something like it</p>\n\n<pre><code>Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)\n If Sheets(\"MyProtectedSheet\").ProtectContents = False Then\n MsgBox \"The sheet 'MyProtectedSheet' should not be left unprotected. I will protect it before saving\", vbInformation\n Sheets(\"MyProtectedSheet\").Protect\n End If\nEnd Sub\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a protected Excel worksheet, without a password. What I'd like to do is trap the event that a user unprotects the worksheet, so that I can generate a message (and nag 'em!). I can setup event checking for the application, for when new workbooks are opened, etc., but not for Unprotect. Does anyone have an idea?
It is possible to modify the menu using Tools->Customize. Protect/Unprotect can be set to run a macro, for example: ``` Sub UnprotectTrap() If ActiveSheet.ProtectContents = True Then MsgBox "Tut,tut!" ActiveSheet.Unprotect Else ActiveSheet.Protect End If End Sub ```
244,913
<p>I need to match a string like "one. two. three. four. five. six. seven. eight. nine. ten. eleven" into groups of four sentences. I need a regular expression to break the string into a group after every fourth period. Something like: </p> <pre><code> string regex = @"(.*.\s){4}"; System.Text.RegularExpressions.Regex exp = new System.Text.RegularExpressions.Regex(regex); string result = exp.Replace(toTest, ".\n"); </code></pre> <p>doesn't work because it will replace the text before the periods, not just the periods themselves. How can I count just the periods and replace them with a period and new line character?</p>
[ { "answer_id": 244955, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 1, "selected": false, "text": "<p>Try defining the method</p>\n\n<pre><code>private string AppendNewLineToMatch(Match match) {\n return match.Value + Environment.NewLine;\n}\n</code></pre>\n\n<p>and using</p>\n\n<pre><code>string result = exp.Replace(toTest, AppendNewLineToMatch);\n</code></pre>\n\n<p>This should call the method for each match, and replace it with that method's result. The method's result would be the matching text and a newline.</p>\n\n<hr>\n\n<p>EDIT: Also, I agree with Oliver. The correct regex definition should be:</p>\n\n<pre><code> string regex = @\"([^.]*[.]\\s*){4}\";\n</code></pre>\n\n<p>Another edit: Fixed the regex, hopefully I got it right this time.</p>\n" }, { "answer_id": 244964, "author": "Oliver Hallam", "author_id": 19995, "author_profile": "https://Stackoverflow.com/users/19995", "pm_score": 2, "selected": false, "text": "<p><code>.</code> in a regex means \"any character\"</p>\n\n<p>so in your regex, you have used <code>.*.</code> which will match a word (this is equivalent to <code>.+</code>)</p>\n\n<p>You were probably looking for <code>[^.]\\*[.]</code> - a series of characters that are not \"<code>.</code>\"s followed by a \"<code>.</code>\".</p>\n" }, { "answer_id": 244969, "author": "Ben", "author_id": 26633, "author_profile": "https://Stackoverflow.com/users/26633", "pm_score": 0, "selected": false, "text": "<p>Search expression: <code>@\"(?:([^\\.]+?).\\s)(?:([^\\.]+?).\\s)(?:([^\\.]+?).\\s)(?:([^\\.]+?).\\s)\"</code>\nReplace expression: <code>\"$1 $2 $3 $4.\\n\"</code></p>\n\n<p>I've ran this expression in RegexBuddy with .NET regex selected, and the output is:</p>\n\n<pre><code>one two three four.\nfive six seven eight.\nnine. ten. eleven\n</code></pre>\n\n<p>I tried with a <code>@\"(?:([^.]+?).\\s){4}\"</code> type of arrangement, but the capturing will only capture the last occurrence (i.e. word), so when it comes to replacing, you will lose three words out of 4. Please someone correct me if I am wrong.</p>\n" }, { "answer_id": 244973, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 0, "selected": false, "text": "<p>Are you forced to do this via regex? Wouldn't it be easier to just split the string then process the array?</p>\n" }, { "answer_id": 244980, "author": "Matthew Brubaker", "author_id": 21311, "author_profile": "https://Stackoverflow.com/users/21311", "pm_score": -1, "selected": false, "text": "<p>In this case it would seem that regex is a bit of overkill. I would recommend using String.split and then breaking up the resulting array of strings. It should be far simpler and far more reliable than trying to make a regex do what you're trying to do.</p>\n\n<p>Something like this might be a bit easier to read and debug.</p>\n\n<pre><code>String s = \"one. two. three. four. five. six. seven. eight. nine. ten. eleven\"\nString[] splitString = s.split(\".\")\nList li = new ArrayList(splitString.length/2)\nfor(int i=0;i&lt;splitString.length;i+=4) {\n st = splitString[i]+\".\"\n st += splitString[i+1]+\".\"\n st += splitString[i+2]+\".\"\n st += splitString[i+3]+\".\"\n li.add(st)\n}\n</code></pre>\n" }, { "answer_id": 245606, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>I'm not sure if configurator's answer got mangled by the editor or what, but it doesn't work. \nThe Correct pattern is </p>\n\n<pre><code>string regex = @\"([^.]*[.]){4}\\s*\";\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4555/" ]
I need to match a string like "one. two. three. four. five. six. seven. eight. nine. ten. eleven" into groups of four sentences. I need a regular expression to break the string into a group after every fourth period. Something like: ``` string regex = @"(.*.\s){4}"; System.Text.RegularExpressions.Regex exp = new System.Text.RegularExpressions.Regex(regex); string result = exp.Replace(toTest, ".\n"); ``` doesn't work because it will replace the text before the periods, not just the periods themselves. How can I count just the periods and replace them with a period and new line character?
`.` in a regex means "any character" so in your regex, you have used `.*.` which will match a word (this is equivalent to `.+`) You were probably looking for `[^.]\*[.]` - a series of characters that are not "`.`"s followed by a "`.`".
244,918
<p>I'm writing an application and I'm trying to tie simple AJAX functionality in. It works well in Mozilla Firefox, but there's an interesting bug in Internet Explorer: Each of the links can only be clicked once. The browser must be completely restarted, simply reloading the page won't work. I've written a <a href="http://static.stillinbeta.com/page/" rel="noreferrer">very simple example application</a> that demonstrates this.</p> <p>Javascript reproduced below:</p> <pre><code>var xmlHttp = new XMLHttpRequest(); /* item: the object clicked on type: the type of action to perform (one of 'image','text' or 'blurb' */ function select(item,type) { //Deselect the previously selected 'selected' object if(document.getElementById('selected')!=null) { document.getElementById('selected').id = ''; } //reselect the new selcted object item.id = 'selected'; //get the appropriate page if(type=='image') xmlHttp.open("GET","image.php"); else if (type=='text') xmlHttp.open("GET","textbox.php"); else if(type=='blurb') xmlHttp.open("GET","blurb.php"); xmlHttp.send(null); xmlHttp.onreadystatechange = catchResponse; return false; } function catchResponse() { if(xmlHttp.readyState == 4) { document.getElementById("page").innerHTML=xmlHttp.responseText; } return false; } </code></pre> <p>Any help would be appreciated.</p>
[ { "answer_id": 244923, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 3, "selected": false, "text": "<p>It looks like IE is caching the response. If you either change your calls to POST methods, or send the appropriate headers to tell IE not to cache the response, it should work.</p>\n\n<p>The headers I send to be sure it doesn't cache are:</p>\n\n<pre><code>Pragma: no-cache\nCache-Control: no-cache\nExpires: Fri, 30 Oct 1998 14:19:41 GMT\n</code></pre>\n\n<p>Note the expiration date can be any time in the past.</p>\n" }, { "answer_id": 244931, "author": "TJ L", "author_id": 12605, "author_profile": "https://Stackoverflow.com/users/12605", "pm_score": 5, "selected": true, "text": "<p>This happens because Internet Explorer ignores the no-cache directive, and caches the results of ajax calls. Then, if the next request is identical, it will just serve up the cached version. There's an easy workaround, and that is to just append random string on the end of your query.</p>\n\n<pre><code> xmlHttp.open(\"GET\",\"blurb.php?\"+Math.random();\n</code></pre>\n" }, { "answer_id": 245339, "author": "jcampbell1", "author_id": 20512, "author_profile": "https://Stackoverflow.com/users/20512", "pm_score": 2, "selected": false, "text": "<p>The problem is that IE does wacky things when the response handler is set before <code>open</code> is called. You aren't doing that for the first xhr request, but since you reuse the xhr object, when the second open is called, the response handler is already set. That may be confusing, but the solution is simple. Create a new xhr object for each request:</p>\n\n<p>move the: </p>\n\n<pre><code>var xmlHttp = new XMLHttpRequest();\n</code></pre>\n\n<p>inside the select function.</p>\n" }, { "answer_id": 356490, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>xmlHttp.open(\"GET\",\"blurb.php?\"+Math.random();</p>\n</blockquote>\n\n<p>I agree with this one.. it works perfectly as a solution to this problem.\nthe problem is that IE7's caching of urls were terrible, ignoring the no-cache header and save the resource to its cache using its url as key index, so the best solution is to add a random parameter to the GET url.</p>\n" }, { "answer_id": 536237, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Read No Problems section in [link text][1] [1]: <a href=\"http://en.wikipedia.org/wiki/XMLHttpRequest\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/XMLHttpRequest</a></p>\n" }, { "answer_id": 744933, "author": "Kevin Hakanson", "author_id": 22514, "author_profile": "https://Stackoverflow.com/users/22514", "pm_score": 1, "selected": false, "text": "<p>The response header that has worked best for me in the IE AJAX case is <code>Expires: -1</code>, which is probably not per spec but mentioned in a Microsoft Support Article (<a href=\"http://support.microsoft.com/kb/234067\" rel=\"nofollow noreferrer\">How to prevent caching in Internet Explorer</a>). This is used in conjunction with <code>Cache-Control: no-cache</code> and <code>Pragma: no-cache</code>.</p>\n" }, { "answer_id": 9699660, "author": "Erel Segal-Halevi", "author_id": 827927, "author_profile": "https://Stackoverflow.com/users/827927", "pm_score": 0, "selected": false, "text": "<p>In jQuery.ajax, you can set the \"cache\" setting to false:</p>\n\n<p><a href=\"http://api.jquery.com/jQuery.ajax/\" rel=\"nofollow\">http://api.jquery.com/jQuery.ajax/</a></p>\n" }, { "answer_id": 13214083, "author": "Alfredo Carrillo", "author_id": 332819, "author_profile": "https://Stackoverflow.com/users/332819", "pm_score": 0, "selected": false, "text": "<p>Using Dojo, this can be done using <code>dojo.date.stamp</code>, just adding the following to the url: </p>\n\n<pre><code>\"...&amp;amp;ts=\" + dojo.date.stamp.toISOString(new Date())\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23335/" ]
I'm writing an application and I'm trying to tie simple AJAX functionality in. It works well in Mozilla Firefox, but there's an interesting bug in Internet Explorer: Each of the links can only be clicked once. The browser must be completely restarted, simply reloading the page won't work. I've written a [very simple example application](http://static.stillinbeta.com/page/) that demonstrates this. Javascript reproduced below: ``` var xmlHttp = new XMLHttpRequest(); /* item: the object clicked on type: the type of action to perform (one of 'image','text' or 'blurb' */ function select(item,type) { //Deselect the previously selected 'selected' object if(document.getElementById('selected')!=null) { document.getElementById('selected').id = ''; } //reselect the new selcted object item.id = 'selected'; //get the appropriate page if(type=='image') xmlHttp.open("GET","image.php"); else if (type=='text') xmlHttp.open("GET","textbox.php"); else if(type=='blurb') xmlHttp.open("GET","blurb.php"); xmlHttp.send(null); xmlHttp.onreadystatechange = catchResponse; return false; } function catchResponse() { if(xmlHttp.readyState == 4) { document.getElementById("page").innerHTML=xmlHttp.responseText; } return false; } ``` Any help would be appreciated.
This happens because Internet Explorer ignores the no-cache directive, and caches the results of ajax calls. Then, if the next request is identical, it will just serve up the cached version. There's an easy workaround, and that is to just append random string on the end of your query. ``` xmlHttp.open("GET","blurb.php?"+Math.random(); ```
244,926
<p>I'm using a the TreeView control and it scrolls automatically to left-align TreeViewItem when one of them is clicked. I've gone looking at my Styles and ControlTemplates, but I haven't found anything. Is there a default ControlTemplate that causes this? I want to disable it.</p>
[ { "answer_id": 244986, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 0, "selected": false, "text": "<p>It looks like I found a good clue on <a href=\"http://social.msdn.microsoft.com/forums/en-US/wpf/thread/9abff78f-481d-4db1-a545-c461f7d19200/\" rel=\"nofollow noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p>Sounds like this is an interaction\n with the scrollviewer and the focus\n system.</p>\n \n <p>When an element is focused within a\n ScrollViewer (which is part of the\n TreeView template), the ScrollViewer\n is instructed to make the element\n visible. It automatically responds by\n scrolling to the requested element.</p>\n \n <p>The methods inside of ScrollViewer\n that handle these focus requests are\n all private and / or internal so you\n really can't get to them. I don't\n think there's too much you can do in\n this case; it's just how focus works.</p>\n</blockquote>\n\n<p>So, is that it? Surely there's a way to modify the TreeView template so that the ScrollViewer won't have this behavior...</p>\n" }, { "answer_id": 246610, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 0, "selected": false, "text": "<p>Ok, I was finally able to get the default style like this:</p>\n\n<pre><code> using (Stream sw = File.Open(@\"C:\\TreeViewDefaults.xaml\", FileMode.Truncate, FileAccess.Write))\n {\n Style ts = Application.Current.FindResource(typeof(TreeView)) as Style;\n if (ts != null)\n XamlWriter.Save(ts, sw);\n }\n</code></pre>\n\n<p>Which produced:</p>\n\n<pre><code>&lt;Style TargetType=\"TreeView\" \n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:s=\"clr-namespace:System;assembly=mscorlib\" \n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"&gt;\n &lt;Style.Triggers&gt;\n &lt;Trigger Property=\"VirtualizingStackPanel.IsVirtualizing\"&gt;\n &lt;Setter Property=\"ItemsControl.ItemsPanel\"&gt;\n &lt;Setter.Value&gt;\n &lt;ItemsPanelTemplate&gt;&lt;VirtualizingStackPanel IsItemsHost=\"True\" /&gt;&lt;/ItemsPanelTemplate&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Trigger.Value&gt;\n &lt;s:Boolean&gt;True&lt;/s:Boolean&gt;\n &lt;/Trigger.Value&gt;\n &lt;/Trigger&gt;\n &lt;/Style.Triggers&gt;\n &lt;Style.Resources&gt;\n &lt;ResourceDictionary /&gt;\n &lt;/Style.Resources&gt;\n &lt;Setter Property=\"Panel.Background\"&gt;\n &lt;Setter.Value&gt;&lt;DynamicResource ResourceKey=\"{x:Static SystemColors.WindowBrushKey}\" /&gt;&lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Setter Property=\"Border.BorderBrush\"&gt;\n &lt;Setter.Value&gt;&lt;SolidColorBrush&gt;#FF828790&lt;/SolidColorBrush&gt;&lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Setter Property=\"Border.BorderThickness\"&gt;\n &lt;Setter.Value&gt;&lt;Thickness&gt;1,1,1,1&lt;/Thickness&gt;&lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Setter Property=\"Control.Padding\"&gt;\n &lt;Setter.Value&gt;&lt;Thickness&gt;1,1,1,1&lt;/Thickness&gt;&lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Setter Property=\"TextElement.Foreground\"&gt;\n &lt;Setter.Value&gt;&lt;DynamicResource ResourceKey=\"{x:Static SystemColors.ControlTextBrushKey}\" /&gt;&lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Setter Property=\"ScrollViewer.HorizontalScrollBarVisibility\"&gt;\n &lt;Setter.Value&gt;&lt;x:Static Member=\"ScrollBarVisibility.Auto\" /&gt;&lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Setter Property=\"ScrollViewer.VerticalScrollBarVisibility\"&gt;\n &lt;Setter.Value&gt;&lt;x:Static Member=\"ScrollBarVisibility.Auto\" /&gt;&lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Setter Property=\"Control.VerticalContentAlignment\"&gt;\n &lt;Setter.Value&gt;&lt;x:Static Member=\"VerticalAlignment.Center\" /&gt;&lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Setter Property=\"Control.Template\"&gt;\n &lt;Setter.Value&gt;\n &lt;ControlTemplate TargetType=\"TreeView\"&gt;\n &lt;Border BorderThickness=\"{TemplateBinding Border.BorderThickness}\" \n BorderBrush=\"{TemplateBinding Border.BorderBrush}\" \n Name=\"Bd\" SnapsToDevicePixels=\"True\"&gt;\n &lt;ScrollViewer CanContentScroll=\"False\" \n HorizontalScrollBarVisibility=\"{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}\" \n VerticalScrollBarVisibility=\"{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}\" \n Background=\"{TemplateBinding Panel.Background}\" \n Padding=\"{TemplateBinding Control.Padding}\" \n Name=\"_tv_scrollviewer_\" \n SnapsToDevicePixels=\"{TemplateBinding UIElement.SnapsToDevicePixels}\" \n Focusable=\"False\"&gt;\n &lt;ItemsPresenter /&gt;\n &lt;/ScrollViewer&gt;\n &lt;/Border&gt;\n &lt;ControlTemplate.Triggers&gt;\n &lt;Trigger Property=\"UIElement.IsEnabled\"&gt;\n &lt;Setter Property=\"Panel.Background\" TargetName=\"Bd\"&gt;\n &lt;Setter.Value&gt;\n &lt;DynamicResource ResourceKey=\"{x:Static SystemColors.ControlBrushKey}\" /&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Trigger.Value&gt;\n &lt;s:Boolean&gt;False&lt;/s:Boolean&gt;\n &lt;/Trigger.Value&gt;\n &lt;/Trigger&gt;\n &lt;Trigger Property=\"VirtualizingStackPanel.IsVirtualizing\"&gt;\n &lt;Setter Property=\"ScrollViewer.CanContentScroll\" TargetName=\"_tv_scrollviewer_\"&gt;\n &lt;Setter.Value&gt;&lt;s:Boolean&gt;True&lt;/s:Boolean&gt;&lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Trigger.Value&gt;\n &lt;s:Boolean&gt;True&lt;/s:Boolean&gt;\n &lt;/Trigger.Value&gt;\n &lt;/Trigger&gt;\n &lt;/ControlTemplate.Triggers&gt;\n &lt;/ControlTemplate&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n&lt;/Style&gt;\n</code></pre>\n\n<p>Which, unfortunately, doesn't look helpful. I don't see any properties in there for stopping the auto-scroll-focus thing.</p>\n\n<p>Still looking...</p>\n" }, { "answer_id": 248497, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Another fun tidbit: there is a overridable boolean value called HandlesScrolling that always returns true. After decompiling the source, it looks like this property is NEVER used (or it's being used in some deep, dark, secret place in XAML). I tried making my own TreeView control to set this value to false and it didn't work.</p>\n" }, { "answer_id": 260409, "author": "brian sharon", "author_id": 16935, "author_profile": "https://Stackoverflow.com/users/16935", "pm_score": 4, "selected": true, "text": "<p>The items scroll because the ScrollViewer calls BringIntoView() on them. So one way to avoid scrolling is to suppress the handling of the RequestBringIntoView event. You can try that out quickly by subclassing TreeView and instantiating this control instead:</p>\n\n<pre><code>public class NoScrollTreeView : TreeView\n{\n public class NoScrollTreeViewItem : TreeViewItem\n {\n public NoScrollTreeViewItem() : base()\n {\n this.RequestBringIntoView += delegate (object sender, RequestBringIntoViewEventArgs e) {\n e.Handled = true;\n };\n }\n\n protected override DependencyObject GetContainerForItemOverride()\n {\n return new NoScrollTreeViewItem();\n }\n }\n protected override DependencyObject GetContainerForItemOverride()\n {\n return new NoScrollTreeViewItem();\n }\n}\n</code></pre>\n" }, { "answer_id": 976339, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>after spending some hours on this problem i found a solution that works for me.</p>\n\n<p>brians solution to prevent the RequestBringIntoView event on a TreeViewItem from bubbling was the first step. unfortunately this also stops a treeviewitem to be shown if you change the selected item programmatically by</p>\n\n<pre><code>yourtreeview.SelectedItem = yourtreeviewitem\n</code></pre>\n\n<p>so, for me the solution is to modify the controltemplate of the treeview as follows:</p>\n\n<pre><code>&lt;Style x:Key=\"{x:Type TreeView}\" TargetType=\"TreeView\"&gt;\n &lt;Setter Property=\"OverridesDefaultStyle\" Value=\"True\" /&gt;\n &lt;Setter Property=\"SnapsToDevicePixels\" Value=\"True\" /&gt;\n &lt;Setter Property=\"ScrollViewer.HorizontalScrollBarVisibility\" Value=\"Auto\"/&gt;\n &lt;Setter Property=\"ScrollViewer.VerticalScrollBarVisibility\" Value=\"Auto\"/&gt;\n &lt;Setter Property=\"Template\"&gt;\n &lt;Setter.Value&gt;\n &lt;ControlTemplate TargetType=\"TreeView\"&gt;\n &lt;Border Name=\"Border\" BorderThickness=\"0\" Padding=\"0\" Margin=\"1\"&gt;\n &lt;ScrollViewer Focusable=\"False\" CanContentScroll=\"False\" Padding=\"0\"&gt;\n &lt;Components:AutoScrollPreventer Margin=\"0\"&gt;\n &lt;ItemsPresenter/&gt;\n &lt;/Components:AutoScrollPreventer&gt;\n &lt;/ScrollViewer&gt;\n &lt;/Border&gt;\n &lt;/ControlTemplate&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;/Style&gt;\n</code></pre>\n\n<p>the \"autoscrollpreventer\" is:</p>\n\n<pre><code>using System;\nusing System.Windows;\nusing System.Windows.Controls;\n\nnamespace LiveContext.Designer.GUI.Components {\n public class AutoScrollPreventer : StackPanel\n {\n public AutoScrollPreventer() {\n\n this.RequestBringIntoView += delegate(object sender, RequestBringIntoViewEventArgs e)\n {\n // stop this event from bubbling so that a scrollviewer doesn't try to BringIntoView..\n e.Handled = true;\n };\n\n }\n}\n</code></pre>\n\n<p>}</p>\n\n<p>hope it helps..</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3279/" ]
I'm using a the TreeView control and it scrolls automatically to left-align TreeViewItem when one of them is clicked. I've gone looking at my Styles and ControlTemplates, but I haven't found anything. Is there a default ControlTemplate that causes this? I want to disable it.
The items scroll because the ScrollViewer calls BringIntoView() on them. So one way to avoid scrolling is to suppress the handling of the RequestBringIntoView event. You can try that out quickly by subclassing TreeView and instantiating this control instead: ``` public class NoScrollTreeView : TreeView { public class NoScrollTreeViewItem : TreeViewItem { public NoScrollTreeViewItem() : base() { this.RequestBringIntoView += delegate (object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; }; } protected override DependencyObject GetContainerForItemOverride() { return new NoScrollTreeViewItem(); } } protected override DependencyObject GetContainerForItemOverride() { return new NoScrollTreeViewItem(); } } ```
244,934
<p>I'd like to create a table which has an integer primary key limited between 000 and 999. Is there any way to enforce this 3 digit limit within the sql?</p> <p>I'm using sqlite3. Thanks.</p>
[ { "answer_id": 244972, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 1, "selected": false, "text": "<p>You may be able to do so using a CHECK constraint.</p>\n\n<p>But, </p>\n\n<blockquote>\n <p>CHECK constraints are supported as of version 3.3.0. Prior to version 3.3.0, CHECK constraints were parsed but not enforced.</p>\n</blockquote>\n\n<p>(from <a href=\"http://www.sqlite.org/lang_createtable.html\" rel=\"nofollow noreferrer\">here</a>)</p>\n\n<p>So unless SQLite 3 = SQLite 3.3 this probably won't work</p>\n" }, { "answer_id": 244982, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "<p>SQLite supports two ways of doing this:</p>\n\n<p>Define a <code>CHECK</code> constraint on the primary key column:</p>\n\n<pre><code>CREATE TABLE mytable (\n mytable_id INT PRIMARY KEY CHECK (mytable_id BETWEEN 0 and 999)\n);\n</code></pre>\n\n<p>Create a trigger on the table that aborts any <code>INSERT</code> or <code>UPDATE</code> that attempts to set the primary key column to a value you don't want.</p>\n\n<pre><code>CREATE TRIGGER mytable_pk_enforcement\nBEFORE INSERT ON mytable\nFOR EACH ROW \n WHEN mytable_id NOT BETWEEN 0 AND 999\nBEGIN\n RAISE(ABORT, 'primary key out of range');\nEND\n</code></pre>\n\n<p>If you use an auto-assigned primary key, as shown above, you may need to run the trigger <code>AFTER INSERT</code> instead of before insert. The primary key value may not be generated yet at the time the <code>BEFORE</code> trigger executes.</p>\n\n<p>You may also need to write a trigger on <code>UPDATE</code> to prevent people from changing the value outside the range. Basically, the <code>CHECK</code> constraint is preferable if you use SQLite 3.3 or later.</p>\n\n<p><strong>note:</strong> I have not tested the code above.</p>\n" }, { "answer_id": 245040, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 1, "selected": false, "text": "<p>jmisso, I would not recommend reusing primary keys that have been deleted. You can create data integrity problems that way if all other tables that might have that key in them were not deleted first (one reason to always enforce setting up foreign key relationships in a database to prevent orphaned data like this). Do not do this unless you are positive that you have no orphaned data that might get attached to the new record.</p>\n\n<p>Why would you even want to limit the primary key to 1000 possible values? What happens when you need 1500 records in the table? This doesn't strike me as a very good thing to even be trying to do.</p>\n" }, { "answer_id": 262762, "author": "Eric Sabine", "author_id": 1493157, "author_profile": "https://Stackoverflow.com/users/1493157", "pm_score": 0, "selected": false, "text": "<p>What about pre-populating the table with the 1000 rows at the start. Toggle the available rows with some kind of 1/0 column like Is_Available or similar. Then don't allow inserts or deletes, only updates. Under this scenario your app only has to be coded for updates. </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20883/" ]
I'd like to create a table which has an integer primary key limited between 000 and 999. Is there any way to enforce this 3 digit limit within the sql? I'm using sqlite3. Thanks.
SQLite supports two ways of doing this: Define a `CHECK` constraint on the primary key column: ``` CREATE TABLE mytable ( mytable_id INT PRIMARY KEY CHECK (mytable_id BETWEEN 0 and 999) ); ``` Create a trigger on the table that aborts any `INSERT` or `UPDATE` that attempts to set the primary key column to a value you don't want. ``` CREATE TRIGGER mytable_pk_enforcement BEFORE INSERT ON mytable FOR EACH ROW WHEN mytable_id NOT BETWEEN 0 AND 999 BEGIN RAISE(ABORT, 'primary key out of range'); END ``` If you use an auto-assigned primary key, as shown above, you may need to run the trigger `AFTER INSERT` instead of before insert. The primary key value may not be generated yet at the time the `BEFORE` trigger executes. You may also need to write a trigger on `UPDATE` to prevent people from changing the value outside the range. Basically, the `CHECK` constraint is preferable if you use SQLite 3.3 or later. **note:** I have not tested the code above.
244,935
<p>How can I inject the value of an appSettings entry (from app.config or web.config) into a service using the Windsor container? If I wanted to inject the value of a Windsor property into a service, I would do something like this:</p> <pre><code>&lt;properties&gt; &lt;importantIntegerProperty&gt;666&lt;/importantIntegerProperty&gt; &lt;/properties&gt; &lt;component id="myComponent" service="MyApp.IService, MyApp" type="MyApp.Service, MyApp" &gt; &lt;parameters&gt; &lt;importantInteger&gt;#{importantIntegerProperty}&lt;/importantInteger&gt; &lt;/parameters&gt; &lt;/component&gt; </code></pre> <p>However, what I'd really like to do is take the value represented by <code>#{importantIntegerProperty}</code> from an app settings variable which might be defined like this:</p> <pre><code>&lt;appSettings&gt; &lt;add key="importantInteger" value="666"/&gt; &lt;/appSettings&gt; </code></pre> <p><strong>EDIT:</strong> To clarify; I realise that this is not natively possible with Windsor and the <a href="http://davidhayden.com/blog/dave/archive/2007/10/04/DependencyInjectionParametersPropertiesCastleWindsor.aspx" rel="nofollow noreferrer">David Hayden article</a> that <a href="https://stackoverflow.com/users/31385/sliderhouserules">sliderhouserules</a> refers to is actually about his own (David Hayden's) IoC container, not Windsor.</p> <p>I'm surely not the first person to have this problem so what I'd like to know is how have other people solved this issue?</p>
[ { "answer_id": 283875, "author": "Mauricio Scheffer", "author_id": 21239, "author_profile": "https://Stackoverflow.com/users/21239", "pm_score": 2, "selected": false, "text": "<p>I <a href=\"http://bugsquash.blogspot.com/2008/09/changing-windsor-components.html\" rel=\"nofollow noreferrer\">wrote a post</a> about a similar case a couple of months ago. It uses a SubDependencyResolver to inject the appropriate parameters. In your case, you can just change DynamicConfigurationSettings for ConfigurationManager.</p>\n" }, { "answer_id": 2659265, "author": "Damian Powell", "author_id": 30321, "author_profile": "https://Stackoverflow.com/users/30321", "pm_score": 4, "selected": true, "text": "<p>I came up with a solution for this eventually based on hints from various sources on the web. The end result though involved pretty much copying three classes from Windsor verbatim and modifying them just a little bit. The end result is up on codeplex for your enjoyment.</p>\n\n<p><a href=\"http://windsorappcfgprops.codeplex.com/\" rel=\"nofollow noreferrer\">http://windsorappcfgprops.codeplex.com/</a></p>\n\n<p>I originally wrote this code quite some time ago so it's based on Windsor 1.0.3 - yes, it took me <em>that</em> long to get around to publishing the result!</p>\n\n<p>The code allows you to have this in your app.config (or web.config, obviously):</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;configuration&gt;\n &lt;appSettings&gt;\n &lt;add key=\"theAnswer\" value=\"42\"/&gt;\n &lt;/appSettings&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>...and access it from your Windsor XML config file like this:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;castle&gt;\n &lt;components&gt;\n &lt;component\n id=\"answerProvider\"\n service=\"Acme.IAnswerProvider, Acme\"\n type=\"Acme.AnswerProvider, Acme\"\n &gt;\n &lt;parameters&gt;\n &lt;theAnswer&gt;#{AppSetting.theAnswer}&lt;/theAnswer&gt;\n &lt;/parameters&gt;\n &lt;/component&gt;\n &lt;/components&gt;\n&lt;/castle&gt;\n</code></pre>\n\n<p>There's a working example in the solution.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30321/" ]
How can I inject the value of an appSettings entry (from app.config or web.config) into a service using the Windsor container? If I wanted to inject the value of a Windsor property into a service, I would do something like this: ``` <properties> <importantIntegerProperty>666</importantIntegerProperty> </properties> <component id="myComponent" service="MyApp.IService, MyApp" type="MyApp.Service, MyApp" > <parameters> <importantInteger>#{importantIntegerProperty}</importantInteger> </parameters> </component> ``` However, what I'd really like to do is take the value represented by `#{importantIntegerProperty}` from an app settings variable which might be defined like this: ``` <appSettings> <add key="importantInteger" value="666"/> </appSettings> ``` **EDIT:** To clarify; I realise that this is not natively possible with Windsor and the [David Hayden article](http://davidhayden.com/blog/dave/archive/2007/10/04/DependencyInjectionParametersPropertiesCastleWindsor.aspx) that [sliderhouserules](https://stackoverflow.com/users/31385/sliderhouserules) refers to is actually about his own (David Hayden's) IoC container, not Windsor. I'm surely not the first person to have this problem so what I'd like to know is how have other people solved this issue?
I came up with a solution for this eventually based on hints from various sources on the web. The end result though involved pretty much copying three classes from Windsor verbatim and modifying them just a little bit. The end result is up on codeplex for your enjoyment. <http://windsorappcfgprops.codeplex.com/> I originally wrote this code quite some time ago so it's based on Windsor 1.0.3 - yes, it took me *that* long to get around to publishing the result! The code allows you to have this in your app.config (or web.config, obviously): ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="theAnswer" value="42"/> </appSettings> </configuration> ``` ...and access it from your Windsor XML config file like this: ``` <?xml version="1.0" encoding="utf-8" ?> <castle> <components> <component id="answerProvider" service="Acme.IAnswerProvider, Acme" type="Acme.AnswerProvider, Acme" > <parameters> <theAnswer>#{AppSetting.theAnswer}</theAnswer> </parameters> </component> </components> </castle> ``` There's a working example in the solution.
244,953
<p>I have a class with a nullable int? datatype set to serialize as an xml element. Is there any way to set it up so the xml serializer will not serialize the element if the value is null? </p> <p>I've tried to add the [System.Xml.Serialization.XmlElement(IsNullable=false)] attribute, but I get a runtime serialization exception saying there was a an error reflecting the type, because "IsNullable may not be set to 'false' for a Nullable type. Consider using 'System.Int32' type or removing the IsNullable property from the XmlElement attribute."</p> <pre><code>[Serializable] [System.Xml.Serialization.XmlRoot("Score", Namespace = "http://mycomp.com/test/score/v1")] public class Score { private int? iID_m; ... /// &lt;summary&gt; /// /// &lt;/summary&gt; public int? ID { get { return iID_m; } set { iID_m = value; } } ... } </code></pre> <p>The above class will serialize to:</p> <pre><code>&lt;Score xmlns="http://mycomp.com/test/score/v1"&gt; &lt;ID xsi:nil="true" /&gt; &lt;/Score&gt; </code></pre> <p>But for IDs that are null I don't want the ID element at all, primarily because when I use OPENXML in MSSQL, it returns a 0 instead of null for an element that looks like </p>
[ { "answer_id": 244998, "author": "Serge Wautier", "author_id": 12379, "author_profile": "https://Stackoverflow.com/users/12379", "pm_score": 1, "selected": false, "text": "<p>Unfortunately, the behaviours you describe are accurately documented as such in the docs for XmlElementAttribute.IsNullable.</p>\n" }, { "answer_id": 245028, "author": "Jeremy", "author_id": 9266, "author_profile": "https://Stackoverflow.com/users/9266", "pm_score": 4, "selected": false, "text": "<p>I figured out a workaround utilizing two properties. An int? property with an XmlIgnore attribute and an object property which gets serialized.</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Score db record\n /// &lt;/summary&gt; \n [System.Xml.Serialization.XmlIgnore()]\n public int? ID \n { \n get \n { \n return iID_m; \n } \n set \n { \n iID_m = value; \n } \n }\n\n /// &lt;summary&gt;\n /// Score db record\n /// &lt;/summary&gt; \n [System.Xml.Serialization.XmlElement(\"ID\",IsNullable = false)]\n public object IDValue\n {\n get\n {\n return ID;\n }\n set\n {\n if (value == null)\n {\n ID = null;\n }\n else if (value is int || value is int?)\n {\n ID = (int)value;\n }\n else\n {\n ID = int.Parse(value.ToString());\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 246359, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 8, "selected": true, "text": "<p>XmlSerializer supports the <code>ShouldSerialize{Foo}()</code> pattern, so you can add a method:</p>\n\n<pre><code>public bool ShouldSerializeID() {return ID.HasValue;}\n</code></pre>\n\n<p>There is also the <code>{Foo}Specified</code> pattern - not sure if XmlSerializer supports that one.</p>\n" }, { "answer_id": 279588, "author": "scobi", "author_id": 14582, "author_profile": "https://Stackoverflow.com/users/14582", "pm_score": 3, "selected": false, "text": "<p>Wow thanks this question/answer really helped me out. I heart Stackoverflow.</p>\n\n<p>I made what you are doing above a little more generic. All we're really looking for is to have Nullable with slightly different serialization behavior. I used Reflector to build my own Nullable, and added a few things here and there to make the XML serialization work the way we want. Seems to work pretty well:</p>\n\n<pre><code>public class Nullable&lt;T&gt;\n{\n public Nullable(T value)\n {\n _value = value;\n _hasValue = true;\n }\n\n public Nullable()\n {\n _hasValue = false;\n }\n\n [XmlText]\n public T Value\n {\n get\n {\n if (!HasValue)\n throw new InvalidOperationException();\n return _value;\n }\n set\n {\n _value = value;\n _hasValue = true;\n }\n }\n\n [XmlIgnore]\n public bool HasValue\n { get { return _hasValue; } }\n\n public T GetValueOrDefault()\n { return _value; }\n public T GetValueOrDefault(T i_defaultValue)\n { return HasValue ? _value : i_defaultValue; }\n\n public static explicit operator T(Nullable&lt;T&gt; i_value)\n { return i_value.Value; }\n public static implicit operator Nullable&lt;T&gt;(T i_value)\n { return new Nullable&lt;T&gt;(i_value); }\n\n public override bool Equals(object i_other)\n {\n if (!HasValue)\n return (i_other == null);\n if (i_other == null)\n return false;\n return _value.Equals(i_other);\n }\n\n public override int GetHashCode()\n {\n if (!HasValue)\n return 0;\n return _value.GetHashCode();\n }\n\n public override string ToString()\n {\n if (!HasValue)\n return \"\";\n return _value.ToString();\n }\n\n bool _hasValue;\n T _value;\n}\n</code></pre>\n\n<p>You lose the ability to have your members as int? and so on (have to use Nullable&lt;int&gt; instead) but other than that all behavior stays the same.</p>\n" }, { "answer_id": 610630, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 5, "selected": false, "text": "<p>I'm using this micro-pattern to implement Nullable serialization:</p>\n\n<pre><code>[XmlIgnore]\npublic double? SomeValue { get; set; }\n\n[XmlAttribute(\"SomeValue\")] // or [XmlElement(\"SomeValue\")]\n[EditorBrowsable(EditorBrowsableState.Never)]\npublic double XmlSomeValue { get { return SomeValue.Value; } set { SomeValue= value; } } \n[EditorBrowsable(EditorBrowsableState.Never)]\npublic bool XmlSomeValueSpecified { get { return SomeValue.HasValue; } }\n</code></pre>\n\n<p>This provides the right interface to the user without compromise and still does the right thing when serializing. </p>\n" }, { "answer_id": 3989153, "author": "James Close", "author_id": 470183, "author_profile": "https://Stackoverflow.com/users/470183", "pm_score": 1, "selected": false, "text": "<p>Very useful posting helped a great deal.</p>\n\n<p>I opted to go with Scott's revision to the Nullable(Of T) datatype, however the code posted still serializes the Nullable element when it is Null - albeit without the \"xs:nil='true'\" attribute.</p>\n\n<p>I needed to force the serializer to drop the tag completely so I simply implemented IXmlSerializable on the structure (this is in VB but you get the picture):</p>\n\n<pre><code> '----------------------------------------------------------------------------\n ' GetSchema\n '----------------------------------------------------------------------------\n Public Function GetSchema() As System.Xml.Schema.XmlSchema Implements System.Xml.Serialization.IXmlSerializable.GetSchema\n Return Nothing\n End Function\n\n '----------------------------------------------------------------------------\n ' ReadXml\n '----------------------------------------------------------------------------\n Public Sub ReadXml(ByVal reader As System.Xml.XmlReader) Implements System.Xml.Serialization.IXmlSerializable.ReadXml\n If (Not reader.IsEmptyElement) Then\n If (reader.Read AndAlso reader.NodeType = System.Xml.XmlNodeType.Text) Then\n Me._value = reader.ReadContentAs(GetType(T), Nothing)\n End If\n End If\n End Sub\n\n '----------------------------------------------------------------------------\n ' WriteXml\n '----------------------------------------------------------------------------\n Public Sub WriteXml(ByVal writer As System.Xml.XmlWriter) Implements System.Xml.Serialization.IXmlSerializable.WriteXml\n If (_hasValue) Then\n writer.WriteValue(Me.Value)\n End If\n End Sub\n</code></pre>\n\n<p>I prefer this method to using the (foo)Specified pattern as that requires adding bucket loads of redundant properties to my objects, whereas using the new Nullable type just requires the retyping of the properties.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9266/" ]
I have a class with a nullable int? datatype set to serialize as an xml element. Is there any way to set it up so the xml serializer will not serialize the element if the value is null? I've tried to add the [System.Xml.Serialization.XmlElement(IsNullable=false)] attribute, but I get a runtime serialization exception saying there was a an error reflecting the type, because "IsNullable may not be set to 'false' for a Nullable type. Consider using 'System.Int32' type or removing the IsNullable property from the XmlElement attribute." ``` [Serializable] [System.Xml.Serialization.XmlRoot("Score", Namespace = "http://mycomp.com/test/score/v1")] public class Score { private int? iID_m; ... /// <summary> /// /// </summary> public int? ID { get { return iID_m; } set { iID_m = value; } } ... } ``` The above class will serialize to: ``` <Score xmlns="http://mycomp.com/test/score/v1"> <ID xsi:nil="true" /> </Score> ``` But for IDs that are null I don't want the ID element at all, primarily because when I use OPENXML in MSSQL, it returns a 0 instead of null for an element that looks like
XmlSerializer supports the `ShouldSerialize{Foo}()` pattern, so you can add a method: ``` public bool ShouldSerializeID() {return ID.HasValue;} ``` There is also the `{Foo}Specified` pattern - not sure if XmlSerializer supports that one.
244,959
<p>Suppose I have the following two strings containing regular expressions. How do I coalesce them? More specifically, I want to have the two expressions as alternatives.</p> <pre><code>$a = '# /[a-z] #i'; $b = '/ Moo /x'; $c = preg_magic_coalesce('|', $a, $b); // Desired result should be equivalent to: // '/ \/[a-zA-Z] |Moo/' </code></pre> <p>Of course, doing this as string operations isn't practical because it would involve parsing the expressions, constructing syntax trees, coalescing the trees and then outputting another regular expression equivalent to the tree. I'm completely happy without this last step. Unfortunately, PHP doesn't have a RegExp class (or does it?).</p> <p>Is there <em>any</em> way to achieve this? Incidentally, does any other language offer a way? Isn't this a pretty normal scenario? Guess not. :-(</p> <p><strong>Alternatively</strong>, is there a way to check <strong>efficiently</strong> if either of the two expressions matches, and which one matches earlier (and if they match at the same position, which match is longer)? This is what I'm doing at the moment. Unfortunately, I do this on long strings, very often, for more than two patterns. The result is <em>slow</em> (and yes, this is definitely the bottleneck).</p> <h2>EDIT:</h2> <p>I should have been more specific – sorry. <code>$a</code> and <code>$b</code> are <em>variables</em>, their content is outside of my control! Otherwise, I would just coalesce them manually. Therefore, I can't make any assumptions about the delimiters or regex modifiers used. Notice, for example, that my first expression uses the <code>i</code> modifier (ignore casing) while the second uses <code>x</code> (extended syntax). Therefore, I can't just concatenate the two because the second expression does <em>not</em> ignore casing and the first doesn't use the extended syntax (and any whitespace therein is significant!</p>
[ { "answer_id": 244985, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": false, "text": "<p>I'm pretty sure it's not possible to just put regexps together like that in any language - they could have incompatible modifiers.</p>\n\n<p>I'd probably just put them in an array and loop through them, or combine them by hand.</p>\n\n<p>Edit: If you're doing them one at a time as described in your edit, you maybe be able to run the second one on a substring (from the start up to the earliest match). That might help things.</p>\n" }, { "answer_id": 244991, "author": "TJ L", "author_id": 12605, "author_profile": "https://Stackoverflow.com/users/12605", "pm_score": 0, "selected": false, "text": "<pre><code>function preg_magic_coalasce($split, $re1, $re2) {\n $re1 = rtrim($re1, \"\\/#is\");\n $re2 = ltrim($re2, \"\\/#\");\n return $re1.$split.$re2;\n}\n</code></pre>\n" }, { "answer_id": 245097, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 0, "selected": false, "text": "<p>You could do it the alternative way like this:</p>\n\n<pre><code>$a = '# /[a-z] #i';\n$b = '/ Moo /x';\n\n$a_matched = preg_match($a, $text, $a_matches);\n$b_matched = preg_match($b, $text, $b_matches);\n\nif ($a_matched &amp;&amp; $b_matched) {\n $a_pos = strpos($text, $a_matches[1]);\n $b_pos = strpos($text, $b_matches[1]);\n\n if ($a_pos == $b_pos) {\n if (strlen($a_matches[1]) == strlen($b_matches[1])) {\n // $a and $b matched the exact same string\n } else if (strlen($a_matches[1]) &gt; strlen($b_matches[1])) {\n // $a and $b started matching at the same spot but $a is longer\n } else {\n // $a and $b started matching at the same spot but $b is longer\n }\n } else if ($a_pos &lt; $b_pos) {\n // $a matched first\n } else {\n // $b matched first\n }\n} else if ($a_matched) {\n // $a matched, $b didn't\n} else if ($b_matched) {\n // $b matched, $a didn't\n} else {\n // neither one matched\n}\n</code></pre>\n" }, { "answer_id": 245326, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 2, "selected": false, "text": "<ol>\n<li><p>Strip delimiters and flags from each. This regex should do it:</p>\n\n<pre><code>/^(.)(.*)\\1([imsxeADSUXJu]*)$/\n</code></pre></li>\n<li><p>Join expressions together. You'll need non-capturing parenthesis to inject flags: </p>\n\n<pre><code>\"(?$flags1:$regexp1)|(?$flags2:$regexp2)\"\n</code></pre></li>\n<li><p>If there are any back references, count capturing parenthesis and update back references accordingly (e.g. properly joined <code>/(.)x\\1/</code> and <code>/(.)y\\1/</code> is <code>/(.)x\\1|(.)y\\2/</code> ).</p></li>\n</ol>\n" }, { "answer_id": 245661, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": true, "text": "<p>I see that porneL actually <a href=\"https://stackoverflow.com/questions/244959/coalescing-regular-expressions-in-php#245326\">described</a> a bunch of this, but this handles most of the problem. It cancels modifiers set in previous sub-expressions (which the other answer missed) and sets modifiers as specified in each sub-expression. It also handles non-slash delimiters (I could not find a specification of what characters are <strong>allowed</strong> here so I used <code>.</code>, you may want to narrow further).</p>\n\n<p>One weakness is it doesn't handle back-references within expressions. My biggest concern with that is the limitations of back-references themselves. I'll leave that as an exercise to the reader/questioner.</p>\n\n<pre><code>// Pass as many expressions as you'd like\nfunction preg_magic_coalesce() {\n $active_modifiers = array();\n\n $expression = '/(?:';\n $sub_expressions = array();\n foreach(func_get_args() as $arg) {\n // Determine modifiers from sub-expression\n if(preg_match('/^(.)(.*)\\1([eimsuxADJSUX]+)$/', $arg, $matches)) {\n $modifiers = preg_split('//', $matches[3]);\n if($modifiers[0] == '') {\n array_shift($modifiers);\n }\n if($modifiers[(count($modifiers) - 1)] == '') {\n array_pop($modifiers);\n }\n\n $cancel_modifiers = $active_modifiers;\n foreach($cancel_modifiers as $key =&gt; $modifier) {\n if(in_array($modifier, $modifiers)) {\n unset($cancel_modifiers[$key]);\n }\n }\n $active_modifiers = $modifiers;\n } elseif(preg_match('/(.)(.*)\\1$/', $arg)) {\n $cancel_modifiers = $active_modifiers;\n $active_modifiers = array();\n }\n\n // If expression has modifiers, include them in sub-expression\n $sub_modifier = '(?';\n $sub_modifier .= implode('', $active_modifiers);\n\n // Cancel modifiers from preceding sub-expression\n if(count($cancel_modifiers) &gt; 0) {\n $sub_modifier .= '-' . implode('-', $cancel_modifiers);\n }\n\n $sub_modifier .= ')';\n\n $sub_expression = preg_replace('/^(.)(.*)\\1[eimsuxADJSUX]*$/', $sub_modifier . '$2', $arg);\n\n // Properly escape slashes\n $sub_expression = preg_replace('/(?&lt;!\\\\\\)\\//', '\\\\\\/', $sub_expression);\n\n $sub_expressions[] = $sub_expression;\n }\n\n // Join expressions\n $expression .= implode('|', $sub_expressions);\n\n $expression .= ')/';\n return $expression;\n}\n</code></pre>\n\n<p>Edit: I've rewritten this (because I'm OCD) and ended up with:</p>\n\n<pre><code>function preg_magic_coalesce($expressions = array(), $global_modifier = '') {\n if(!preg_match('/^((?:-?[eimsuxADJSUX])+)$/', $global_modifier)) {\n $global_modifier = '';\n }\n\n $expression = '/(?:';\n $sub_expressions = array();\n foreach($expressions as $sub_expression) {\n $active_modifiers = array();\n // Determine modifiers from sub-expression\n if(preg_match('/^(.)(.*)\\1((?:-?[eimsuxADJSUX])+)$/', $sub_expression, $matches)) {\n $active_modifiers = preg_split('/(-?[eimsuxADJSUX])/',\n $matches[3], -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);\n }\n\n // If expression has modifiers, include them in sub-expression\n if(count($active_modifiers) &gt; 0) {\n $replacement = '(?';\n $replacement .= implode('', $active_modifiers);\n $replacement .= ':$2)';\n } else {\n $replacement = '$2';\n }\n\n $sub_expression = preg_replace('/^(.)(.*)\\1(?:(?:-?[eimsuxADJSUX])*)$/',\n $replacement, $sub_expression);\n\n // Properly escape slashes if another delimiter was used\n $sub_expression = preg_replace('/(?&lt;!\\\\\\)\\//', '\\\\\\/', $sub_expression);\n\n $sub_expressions[] = $sub_expression;\n }\n\n // Join expressions\n $expression .= implode('|', $sub_expressions);\n\n $expression .= ')/' . $global_modifier;\n return $expression;\n}\n</code></pre>\n\n<p>It now uses <code>(?modifiers:sub-expression)</code> rather than <code>(?modifiers)sub-expression|(?cancel-modifiers)sub-expression</code> but I've noticed that both have some weird modifier side-effects. For instance, in both cases if a sub-expression has a <code>/u</code> modifier, it will fail to match (but if you pass <code>'u'</code> as the second argument of the new function, that will match just fine).</p>\n" }, { "answer_id": 248361, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<h2>EDIT</h2>\n\n<p><strong>I’ve rewritten the code!</strong> It now contains the changes that are listed as follows. Additionally, I've done extensive tests (which I won’t post here because they’re too many) to look for errors. So far, I haven’t found any.</p>\n\n<ul>\n<li><p>The function is now split into two parts: There’s a separate function <code>preg_split</code> which takes a regular expression and returns an array containing the bare expression (without delimiters) and an array of modifiers. This might come in handy (it already has, in fact; this is why I made this change). </p></li>\n<li><p><strong>The code now correctly handles back-references.</strong> This was necessary for my purpose after all. It wasn’t difficult to add, the regular expression used to capture the back-references just looks weird (and may actually be extremely inefficient, it looks NP-hard to me – but that’s only an intuition and only applies in weird edge cases). By the way, does anyone know a better way of checking for an uneven number of matches than my way? Negative lookbehinds won't work here because they only accept fixed-length strings instead of regular expressions. However, I need the regex here to test whether the preceeding backslash is actually escaped itself.</p>\n\n<p>Additionally, I don’t know how good PHP is at caching anonymous <code>create_function</code> use. Performance-wise, this might not be the best solution but it seems good enough.</p></li>\n<li><p>I’ve fixed a bug in the sanity check.</p></li>\n<li><p>I’ve removed the cancellation of obsolete modifiers since my tests show that it isn't necessary.</p></li>\n</ul>\n\n<p>By the way, this code is one of the core components of a syntax highlighter for various languages that I’m working on in PHP since I’m not satisfied with the alternatives listed <a href=\"https://stackoverflow.com/questions/230270/php-syntax-highlighting\">elsewhere</a>.</p>\n\n<h2>Thanks!</h2>\n\n<p><strong>porneL</strong>, <strong>eyelidlessness</strong>, amazing work! Many, many thanks. I had actually given up.</p>\n\n<p>I've built upon your solution and I'd like to share it here. <del>I didn't implement re-numbering back-references since this isn't relevant in my case (I think …). Perhaps this will become necessary later, though.</del></p>\n\n<h2>Some Questions …</h2>\n\n<p>One thing, <em>@eyelidlessness</em>: <del>Why do you feel the necessity to cancel old modifiers? As far as I see it, this isn't necessary since the modifiers are only applied locally anyway.\nAh yes, one other thing. Your escaping of the delimiter seems overly complicated. Care to explain why you think this is needed? I believe my version should work as well but I could be very wrong.</del></p>\n\n<p>Also, I've changed the signature of your function to match my needs. I also thing that my version is more generally useful. Again, I might be wrong.</p>\n\n<p>BTW, you should now realize the importance of real names on SO. ;-) I can't give you real credit in the code. :-/</p>\n\n<h2>The Code</h2>\n\n<p>Anyway, I'd like to share my result so far because I can't believe that nobody else ever needs something like that. The code <em>seems</em> to work very well. <del>Extensive tests are yet to be done, though.</del> <strong>Please comment!</strong></p>\n\n<p>And without further ado …</p>\n\n<pre><code>/**\n * Merges several regular expressions into one, using the indicated 'glue'.\n *\n * This function takes care of individual modifiers so it's safe to use\n * &lt;em&gt;different&lt;/em&gt; modifiers on the individual expressions. The order of\n * sub-matches is preserved as well. Numbered back-references are adapted to\n * the new overall sub-match count. This means that it's safe to use numbered\n * back-refences in the individual expressions!\n * If {@link $names} is given, the individual expressions are captured in\n * named sub-matches using the contents of that array as names.\n * Matching pair-delimiters (e.g. &lt;code&gt;\"{…}\"&lt;/code&gt;) are currently\n * &lt;strong&gt;not&lt;/strong&gt; supported.\n *\n * The function assumes that all regular expressions are well-formed.\n * Behaviour is undefined if they aren't.\n *\n * This function was created after a {@link https://stackoverflow.com/questions/244959/\n * StackOverflow discussion}. Much of it was written or thought of by\n * “porneL” and “eyelidlessness”. Many thanks to both of them.\n *\n * @param string $glue A string to insert between the individual expressions.\n * This should usually be either the empty string, indicating\n * concatenation, or the pipe (&lt;code&gt;|&lt;/code&gt;), indicating alternation.\n * Notice that this string might have to be escaped since it is treated\n * like a normal character in a regular expression (i.e. &lt;code&gt;/&lt;/code&gt;)\n * will end the expression and result in an invalid output.\n * @param array $expressions The expressions to merge. The expressions may\n * have arbitrary different delimiters and modifiers.\n * @param array $names Optional. This is either an empty array or an array of\n * strings of the same length as {@link $expressions}. In that case,\n * the strings of this array are used to create named sub-matches for the\n * expressions.\n * @return string An string representing a regular expression equivalent to the\n * merged expressions. Returns &lt;code&gt;FALSE&lt;/code&gt; if an error occurred.\n */\nfunction preg_merge($glue, array $expressions, array $names = array()) {\n // … then, a miracle occurs.\n\n // Sanity check …\n\n $use_names = ($names !== null and count($names) !== 0);\n\n if (\n $use_names and count($names) !== count($expressions) or\n !is_string($glue)\n )\n return false;\n\n $result = array();\n // For keeping track of the names for sub-matches.\n $names_count = 0;\n // For keeping track of *all* captures to re-adjust backreferences.\n $capture_count = 0;\n\n foreach ($expressions as $expression) {\n if ($use_names)\n $name = str_replace(' ', '_', $names[$names_count++]);\n\n // Get delimiters and modifiers:\n\n $stripped = preg_strip($expression);\n\n if ($stripped === false)\n return false;\n\n list($sub_expr, $modifiers) = $stripped;\n\n // Re-adjust backreferences:\n\n // We assume that the expression is correct and therefore don't check\n // for matching parentheses.\n\n $number_of_captures = preg_match_all('/\\([^?]|\\(\\?[^:]/', $sub_expr, $_);\n\n if ($number_of_captures === false)\n return false;\n\n if ($number_of_captures &gt; 0) {\n // NB: This looks NP-hard. Consider replacing.\n $backref_expr = '/\n ( # Only match when not escaped:\n [^\\\\\\\\] # guarantee an even number of backslashes\n (\\\\\\\\*?)\\\\2 # (twice n, preceded by something else).\n )\n \\\\\\\\ (\\d) # Backslash followed by a digit.\n /x';\n $sub_expr = preg_replace_callback(\n $backref_expr,\n create_function(\n '$m',\n 'return $m[1] . \"\\\\\\\\\" . ((int)$m[3] + ' . $capture_count . ');'\n ),\n $sub_expr\n );\n $capture_count += $number_of_captures;\n }\n\n // Last, construct the new sub-match:\n\n $modifiers = implode('', $modifiers);\n $sub_modifiers = \"(?$modifiers)\";\n if ($sub_modifiers === '(?)')\n $sub_modifiers = '';\n\n $sub_name = $use_names ? \"?&lt;$name&gt;\" : '?:';\n $new_expr = \"($sub_name$sub_modifiers$sub_expr)\";\n $result[] = $new_expr;\n }\n\n return '/' . implode($glue, $result) . '/';\n}\n\n/**\n * Strips a regular expression string off its delimiters and modifiers.\n * Additionally, normalize the delimiters (i.e. reformat the pattern so that\n * it could have used '/' as delimiter).\n *\n * @param string $expression The regular expression string to strip.\n * @return array An array whose first entry is the expression itself, the\n * second an array of delimiters. If the argument is not a valid regular\n * expression, returns &lt;code&gt;FALSE&lt;/code&gt;.\n *\n */\nfunction preg_strip($expression) {\n if (preg_match('/^(.)(.*)\\\\1([imsxeADSUXJu]*)$/s', $expression, $matches) !== 1)\n return false;\n\n $delim = $matches[1];\n $sub_expr = $matches[2];\n if ($delim !== '/') {\n // Replace occurrences by the escaped delimiter by its unescaped\n // version and escape new delimiter.\n $sub_expr = str_replace(\"\\\\$delim\", $delim, $sub_expr);\n $sub_expr = str_replace('/', '\\\\/', $sub_expr);\n }\n $modifiers = $matches[3] === '' ? array() : str_split(trim($matches[3]));\n\n return array($sub_expr, $modifiers);\n}\n</code></pre>\n\n<p>PS: I've made this posting community wiki editable. You know what this means …!</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1968/" ]
Suppose I have the following two strings containing regular expressions. How do I coalesce them? More specifically, I want to have the two expressions as alternatives. ``` $a = '# /[a-z] #i'; $b = '/ Moo /x'; $c = preg_magic_coalesce('|', $a, $b); // Desired result should be equivalent to: // '/ \/[a-zA-Z] |Moo/' ``` Of course, doing this as string operations isn't practical because it would involve parsing the expressions, constructing syntax trees, coalescing the trees and then outputting another regular expression equivalent to the tree. I'm completely happy without this last step. Unfortunately, PHP doesn't have a RegExp class (or does it?). Is there *any* way to achieve this? Incidentally, does any other language offer a way? Isn't this a pretty normal scenario? Guess not. :-( **Alternatively**, is there a way to check **efficiently** if either of the two expressions matches, and which one matches earlier (and if they match at the same position, which match is longer)? This is what I'm doing at the moment. Unfortunately, I do this on long strings, very often, for more than two patterns. The result is *slow* (and yes, this is definitely the bottleneck). EDIT: ----- I should have been more specific – sorry. `$a` and `$b` are *variables*, their content is outside of my control! Otherwise, I would just coalesce them manually. Therefore, I can't make any assumptions about the delimiters or regex modifiers used. Notice, for example, that my first expression uses the `i` modifier (ignore casing) while the second uses `x` (extended syntax). Therefore, I can't just concatenate the two because the second expression does *not* ignore casing and the first doesn't use the extended syntax (and any whitespace therein is significant!
I see that porneL actually [described](https://stackoverflow.com/questions/244959/coalescing-regular-expressions-in-php#245326) a bunch of this, but this handles most of the problem. It cancels modifiers set in previous sub-expressions (which the other answer missed) and sets modifiers as specified in each sub-expression. It also handles non-slash delimiters (I could not find a specification of what characters are **allowed** here so I used `.`, you may want to narrow further). One weakness is it doesn't handle back-references within expressions. My biggest concern with that is the limitations of back-references themselves. I'll leave that as an exercise to the reader/questioner. ``` // Pass as many expressions as you'd like function preg_magic_coalesce() { $active_modifiers = array(); $expression = '/(?:'; $sub_expressions = array(); foreach(func_get_args() as $arg) { // Determine modifiers from sub-expression if(preg_match('/^(.)(.*)\1([eimsuxADJSUX]+)$/', $arg, $matches)) { $modifiers = preg_split('//', $matches[3]); if($modifiers[0] == '') { array_shift($modifiers); } if($modifiers[(count($modifiers) - 1)] == '') { array_pop($modifiers); } $cancel_modifiers = $active_modifiers; foreach($cancel_modifiers as $key => $modifier) { if(in_array($modifier, $modifiers)) { unset($cancel_modifiers[$key]); } } $active_modifiers = $modifiers; } elseif(preg_match('/(.)(.*)\1$/', $arg)) { $cancel_modifiers = $active_modifiers; $active_modifiers = array(); } // If expression has modifiers, include them in sub-expression $sub_modifier = '(?'; $sub_modifier .= implode('', $active_modifiers); // Cancel modifiers from preceding sub-expression if(count($cancel_modifiers) > 0) { $sub_modifier .= '-' . implode('-', $cancel_modifiers); } $sub_modifier .= ')'; $sub_expression = preg_replace('/^(.)(.*)\1[eimsuxADJSUX]*$/', $sub_modifier . '$2', $arg); // Properly escape slashes $sub_expression = preg_replace('/(?<!\\\)\//', '\\\/', $sub_expression); $sub_expressions[] = $sub_expression; } // Join expressions $expression .= implode('|', $sub_expressions); $expression .= ')/'; return $expression; } ``` Edit: I've rewritten this (because I'm OCD) and ended up with: ``` function preg_magic_coalesce($expressions = array(), $global_modifier = '') { if(!preg_match('/^((?:-?[eimsuxADJSUX])+)$/', $global_modifier)) { $global_modifier = ''; } $expression = '/(?:'; $sub_expressions = array(); foreach($expressions as $sub_expression) { $active_modifiers = array(); // Determine modifiers from sub-expression if(preg_match('/^(.)(.*)\1((?:-?[eimsuxADJSUX])+)$/', $sub_expression, $matches)) { $active_modifiers = preg_split('/(-?[eimsuxADJSUX])/', $matches[3], -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE); } // If expression has modifiers, include them in sub-expression if(count($active_modifiers) > 0) { $replacement = '(?'; $replacement .= implode('', $active_modifiers); $replacement .= ':$2)'; } else { $replacement = '$2'; } $sub_expression = preg_replace('/^(.)(.*)\1(?:(?:-?[eimsuxADJSUX])*)$/', $replacement, $sub_expression); // Properly escape slashes if another delimiter was used $sub_expression = preg_replace('/(?<!\\\)\//', '\\\/', $sub_expression); $sub_expressions[] = $sub_expression; } // Join expressions $expression .= implode('|', $sub_expressions); $expression .= ')/' . $global_modifier; return $expression; } ``` It now uses `(?modifiers:sub-expression)` rather than `(?modifiers)sub-expression|(?cancel-modifiers)sub-expression` but I've noticed that both have some weird modifier side-effects. For instance, in both cases if a sub-expression has a `/u` modifier, it will fail to match (but if you pass `'u'` as the second argument of the new function, that will match just fine).
245,012
<p>By default Windows (XP) shows the <strong>underlined hotkeys</strong> only, when ALT is pressed. This can be changed in display-properties in the subdialog "Effects" so, that the hotkeys are <strong>always underlined</strong></p> <p>How can it be changed programmatically? Which API-call or registry-setting can be used to change this setting?</p>
[ { "answer_id": 245151, "author": "Mentat", "author_id": 30198, "author_profile": "https://Stackoverflow.com/users/30198", "pm_score": 2, "selected": false, "text": "<p>Do you mean you want to change this system-wide setting, or that you want to be able to override the behavior only in your program?</p>\n\n<p>If it's the latter and you're using the Win32 API, it looks like you might be able to catch the WM_CHANGEUISTATE notification: <a href=\"http://blogs.msdn.com/oldnewthing/archive/2005/05/03/414317.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2005/05/03/414317.aspx</a> I've not tried it myself but it seems feasible.</p>\n\n<p>If it's the former you're aiming for, I've not yet been able to discover a method. </p>\n" }, { "answer_id": 452379, "author": "Christof Schardt", "author_id": 26820, "author_profile": "https://Stackoverflow.com/users/26820", "pm_score": 3, "selected": true, "text": "<p>I found the solution, how to query and to set:</p>\n\n<pre><code>BOOL b\nSystemParametersInfo(SPI_GETKEYBOARDCUES, 0, &amp;b, 0);\nif (!b) {\n b = TRUE;\n SystemParametersInfo(SPI_SETKEYBOARDCUES, 0, &amp;b, 0);\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26820/" ]
By default Windows (XP) shows the **underlined hotkeys** only, when ALT is pressed. This can be changed in display-properties in the subdialog "Effects" so, that the hotkeys are **always underlined** How can it be changed programmatically? Which API-call or registry-setting can be used to change this setting?
I found the solution, how to query and to set: ``` BOOL b SystemParametersInfo(SPI_GETKEYBOARDCUES, 0, &b, 0); if (!b) { b = TRUE; SystemParametersInfo(SPI_SETKEYBOARDCUES, 0, &b, 0); } ```
245,019
<p>Has anybody else had trouble with getting the .Net Framework source code? Google doesn't have anything to say about this error message, and neither does the CodePlex issue tracker.</p> <p>Here is the command I'm using to get the source code for the modules that make up mscorlib.dll. Am I doing something obviously wrong?</p> <p>NetMassDownloader.exe -o source -f "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll"</p>
[ { "answer_id": 245151, "author": "Mentat", "author_id": 30198, "author_profile": "https://Stackoverflow.com/users/30198", "pm_score": 2, "selected": false, "text": "<p>Do you mean you want to change this system-wide setting, or that you want to be able to override the behavior only in your program?</p>\n\n<p>If it's the latter and you're using the Win32 API, it looks like you might be able to catch the WM_CHANGEUISTATE notification: <a href=\"http://blogs.msdn.com/oldnewthing/archive/2005/05/03/414317.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2005/05/03/414317.aspx</a> I've not tried it myself but it seems feasible.</p>\n\n<p>If it's the former you're aiming for, I've not yet been able to discover a method. </p>\n" }, { "answer_id": 452379, "author": "Christof Schardt", "author_id": 26820, "author_profile": "https://Stackoverflow.com/users/26820", "pm_score": 3, "selected": true, "text": "<p>I found the solution, how to query and to set:</p>\n\n<pre><code>BOOL b\nSystemParametersInfo(SPI_GETKEYBOARDCUES, 0, &amp;b, 0);\nif (!b) {\n b = TRUE;\n SystemParametersInfo(SPI_SETKEYBOARDCUES, 0, &amp;b, 0);\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31205/" ]
Has anybody else had trouble with getting the .Net Framework source code? Google doesn't have anything to say about this error message, and neither does the CodePlex issue tracker. Here is the command I'm using to get the source code for the modules that make up mscorlib.dll. Am I doing something obviously wrong? NetMassDownloader.exe -o source -f "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll"
I found the solution, how to query and to set: ``` BOOL b SystemParametersInfo(SPI_GETKEYBOARDCUES, 0, &b, 0); if (!b) { b = TRUE; SystemParametersInfo(SPI_SETKEYBOARDCUES, 0, &b, 0); } ```
245,027
<p>...I want to Show the 'delete' button when user is an admin, and show the 'add item' button when user is a contributor:</p> <pre><code>&lt;!-- More code above --&gt; &lt;asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" /&gt; &lt;asp:TemplateField ShowHeader="False"&gt; &lt;ItemTemplate&gt; &lt;asp:LinkButton CSSClass="TableRightLink" ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" Visible=&lt;%# User.IsInRole(@"DOMAIN\CMDB_ADMIN") %&gt; Text="Delete" OnClientClick="return confirm('Are you certain you want to delete this item?');"&gt;&lt;/asp:LinkButton&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;SelectedRowStyle VerticalAlign="Top" /&gt; &lt;HeaderStyle ForeColor="White" CssClass="TableHeader" BackColor="SteelBlue" /&gt; &lt;/asp:GridView&gt; &lt;asp:table width="100%" runat="server" CSSclass="PromptTable" Visible=&lt;%# User.IsInRole(@"DOMAIN\CMDB_CONTRIBUTE") %&gt; &gt; &lt;asp:tablerow&gt;&lt;asp:tablecell HorizontalAlign=Center&gt; &lt;asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="AddConfigItem.aspx" ForeColor="LightCyan"&gt;Add Item&lt;/asp:HyperLink&gt; &lt;/asp:tablecell&gt;&lt;/asp:tablerow&gt;&lt;/asp:table&gt; </code></pre> <p>The Delete button 'visible' attribute works fine. But, the "add item' hyperlink doesn't. It always shows. View-source tells me that %# User.IsInRole(@"DOMAIN\CMDB_CONTRIBUTE") %> isn't evaluating to anything. Any idea why this is?</p>
[ { "answer_id": 245032, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 1, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>Visible='&lt;%= User.IsInRole(@\"DOMAIN\\CMDB_CONTRIBUTE\") %&gt;'\n</code></pre>\n\n<p>The asp:table doesn't appear to be databound.</p>\n" }, { "answer_id": 245268, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "<p>Try setting it in code behind, instead of in mark up, in Page_Load. Assuming the id is promptTable (it wasn't given in your example), just add:</p>\n\n<pre><code>promptTable.Visible = User.IsInRole(@\"DOMAIN\\CMDB_CONTRIBUTE\");\n</code></pre>\n\n<p>Presumably this needs to be done regardless of whether it is a postback or not.</p>\n\n<p>FWIW, @Keltex is right about the control not being databound so <code>&lt;%# %&gt;</code> won't work. Unfortunately, the <code>&lt;%= %&gt;</code> syntax won't either because it always returns a string and you need a boolean value there. I couldn't find any other syntax that would work in this case. You could probably do this by turing off display using javascript, but I suspect that you don't want the table to be rendered to the page if not in the correct group (as opposed to just being hidden or removed from the DOM once on the client). Doing it in the code behind, I think is the right way to go about it.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13959/" ]
...I want to Show the 'delete' button when user is an admin, and show the 'add item' button when user is a contributor: ``` <!-- More code above --> <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" /> <asp:TemplateField ShowHeader="False"> <ItemTemplate> <asp:LinkButton CSSClass="TableRightLink" ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" Visible=<%# User.IsInRole(@"DOMAIN\CMDB_ADMIN") %> Text="Delete" OnClientClick="return confirm('Are you certain you want to delete this item?');"></asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> <SelectedRowStyle VerticalAlign="Top" /> <HeaderStyle ForeColor="White" CssClass="TableHeader" BackColor="SteelBlue" /> </asp:GridView> <asp:table width="100%" runat="server" CSSclass="PromptTable" Visible=<%# User.IsInRole(@"DOMAIN\CMDB_CONTRIBUTE") %> > <asp:tablerow><asp:tablecell HorizontalAlign=Center> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="AddConfigItem.aspx" ForeColor="LightCyan">Add Item</asp:HyperLink> </asp:tablecell></asp:tablerow></asp:table> ``` The Delete button 'visible' attribute works fine. But, the "add item' hyperlink doesn't. It always shows. View-source tells me that %# User.IsInRole(@"DOMAIN\CMDB\_CONTRIBUTE") %> isn't evaluating to anything. Any idea why this is?
Try setting it in code behind, instead of in mark up, in Page\_Load. Assuming the id is promptTable (it wasn't given in your example), just add: ``` promptTable.Visible = User.IsInRole(@"DOMAIN\CMDB_CONTRIBUTE"); ``` Presumably this needs to be done regardless of whether it is a postback or not. FWIW, @Keltex is right about the control not being databound so `<%# %>` won't work. Unfortunately, the `<%= %>` syntax won't either because it always returns a string and you need a boolean value there. I couldn't find any other syntax that would work in this case. You could probably do this by turing off display using javascript, but I suspect that you don't want the table to be rendered to the page if not in the correct group (as opposed to just being hidden or removed from the DOM once on the client). Doing it in the code behind, I think is the right way to go about it.
245,045
<p>I'm looking for a way to add a close button to a .NET ToolTip object similar to the one the NotifyIcon has. I'm using the tooltip as a message balloon called programatically with the Show() method. That works fine but there is no onclick event or easy way to close the tooltip. You have to call the Hide() method somewhere else in your code and I would rather have the tooltip be able to close itself. I know there are several balloon tooltips around the net that use manage and unmanaged code to perform this with the windows API, but I would rather stay in my comfy .NET world. I have a thrid party application that calls my .NET application and it has crashes when trying to display unmanaged tooltips.</p>
[ { "answer_id": 245128, "author": "avgbody", "author_id": 8737, "author_profile": "https://Stackoverflow.com/users/8737", "pm_score": 3, "selected": true, "text": "<p>You could try an implement your own tool tip window by overriding the existing one and customizing the onDraw function. I never tried adding a button, but have done other customizations with the tooltip before.</p>\n\n<pre><code> 1 class MyToolTip : ToolTip\n 2 {\n 3 public MyToolTip()\n 4 {\n 5 this.OwnerDraw = true;\n 6 this.Draw += new DrawToolTipEventHandler(OnDraw);\n 7 \n 8 }\n 9 \n 10 public MyToolTip(System.ComponentModel.IContainer Cont)\n 11 {\n 12 this.OwnerDraw = true;\n 13 this.Draw += new DrawToolTipEventHandler(OnDraw);\n 14 }\n 15 \n 16 private void OnDraw(object sender, DrawToolTipEventArgs e)\n 17 {\n ...Code Stuff...\n 24 }\n 25 }\n</code></pre>\n" }, { "answer_id": 4972205, "author": "MMsoft", "author_id": 613432, "author_profile": "https://Stackoverflow.com/users/613432", "pm_score": 2, "selected": false, "text": "<p>You can try to override CreateParams method in your implementation of ToolTip class...\ni.e.</p>\n\n<pre><code> protected override CreateParams CreateParams\n {\n get\n {\n CreateParams cp = base.CreateParams;\n cp.Style = 0x80 | 0x40; //TTS_BALLOON &amp; TTS_CLOSE\n\n return cp;\n }\n }\n</code></pre>\n" }, { "answer_id": 13805404, "author": "Joel Rein", "author_id": 20961, "author_profile": "https://Stackoverflow.com/users/20961", "pm_score": 2, "selected": false, "text": "<p>You can subclass the ToolTip class with your own CreateParams that sets the TTS_CLOSE style:</p>\n\n<pre><code>private const int TTS_BALLOON = 0x80;\nprivate const int TTS_CLOSE = 0x40;\nprotected override CreateParams CreateParams\n{\n get\n {\n var cp = base.CreateParams;\n cp.Style = TTS_BALLOON | TTS_CLOSE;\n return cp;\n }\n}\n</code></pre>\n\n<p>The TTS_CLOSE style also <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/bb760248(v=vs.85).aspx\" rel=\"nofollow noreferrer\">requires</a> the TTS_BALLOON style and you must also set the ToolTipTitle property on the tooltip.</p>\n\n<p>To get this style to work, you need to enable the Common Controls v6 styles <a href=\"http://blog.kalmbachnet.de/?postid=103\" rel=\"nofollow noreferrer\">using an application manifest</a>.</p>\n\n<p>Add a new \"Application Manifest File\" and add the following under the &lt;assembly&gt; element:</p>\n\n<pre><code>&lt;dependency&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity\n type=\"win32\"\n name=\"Microsoft.Windows.Common-Controls\"\n version=\"6.0.0.0\"\n processorArchitecture=\"*\"\n publicKeyToken=\"6595b64144ccf1df\"\n language=\"*\"\n /&gt;\n &lt;/dependentAssembly&gt;\n&lt;/dependency&gt; \n</code></pre>\n\n<p>In Visual Studio 2012, at least, this stuff is included in the default template but commented out - you can just uncomment it.</p>\n\n<p><img src=\"https://i.stack.imgur.com/4ShRa.png\" alt=\"Tooltip with close button\"></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13556/" ]
I'm looking for a way to add a close button to a .NET ToolTip object similar to the one the NotifyIcon has. I'm using the tooltip as a message balloon called programatically with the Show() method. That works fine but there is no onclick event or easy way to close the tooltip. You have to call the Hide() method somewhere else in your code and I would rather have the tooltip be able to close itself. I know there are several balloon tooltips around the net that use manage and unmanaged code to perform this with the windows API, but I would rather stay in my comfy .NET world. I have a thrid party application that calls my .NET application and it has crashes when trying to display unmanaged tooltips.
You could try an implement your own tool tip window by overriding the existing one and customizing the onDraw function. I never tried adding a button, but have done other customizations with the tooltip before. ``` 1 class MyToolTip : ToolTip 2 { 3 public MyToolTip() 4 { 5 this.OwnerDraw = true; 6 this.Draw += new DrawToolTipEventHandler(OnDraw); 7 8 } 9 10 public MyToolTip(System.ComponentModel.IContainer Cont) 11 { 12 this.OwnerDraw = true; 13 this.Draw += new DrawToolTipEventHandler(OnDraw); 14 } 15 16 private void OnDraw(object sender, DrawToolTipEventArgs e) 17 { ...Code Stuff... 24 } 25 } ```
245,055
<p>So what I have right now is something like this:</p> <pre><code>PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public); </code></pre> <p>where <code>obj</code> is some object.</p> <p>The problem is some of the properties I want aren't in <code>obj.GetType()</code> they're in one of the base classes further up. If I stop the debugger and look at obj, the I have to dig through a few "base" entries to see the properties I want to get at. Is there some binding flag I can set to have it return those or do I have to recursively dig through the <code>Type.BaseType</code> hierarchy and do <code>GetProperties</code> on all of them?</p>
[ { "answer_id": 245105, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 3, "selected": false, "text": "<p>If you access <code>Type.BaseType</code>, you can get the base type. You can recursively access each base type and you'll know when you've hit the bottom when your type is <code>System.Object</code>.</p>\n\n<pre><code>Type type = obj.GetType();\nPropertyInfo[] info = type.GetProperties(BindingFlags.Public);\nPropertyInfo[] baseProps = type.BaseType.GetProperties(BindingFlags.Public);\n</code></pre>\n" }, { "answer_id": 245119, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 6, "selected": true, "text": "<p>Use this:</p>\n\n<pre><code>PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);\n</code></pre>\n\n<p>EDIT: Of course the correct answer is that of <a href=\"https://stackoverflow.com/questions/245055/how-do-you-get-the-all-properties-of-a-class-and-its-base-classes-up-the-hierar#245131\">Jay</a>. <code>GetProperties()</code> without parameters is equivalent to <code>GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static )</code>. The <code>BindingFlags.FlattenHierarchy</code> plays no role here.</p>\n" }, { "answer_id": 245131, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 4, "selected": false, "text": "<p>I don't think it's that complicated.</p>\n\n<p>If you remove the <code>BindingFlags</code> parameter to GetProperties, I think you get the results you're looking for:</p>\n\n<pre><code> class B\n {\n public int MyProperty { get; set; }\n }\n\n class C : B\n {\n public string MyProperty2 { get; set; }\n }\n\n static void Main(string[] args)\n {\n PropertyInfo[] info = new C().GetType().GetProperties();\n foreach (var pi in info)\n {\n Console.WriteLine(pi.Name);\n }\n }\n</code></pre>\n\n<p>produces</p>\n\n<pre>\n MyProperty2\n MyProperty\n</pre>\n" }, { "answer_id": 245140, "author": "Nicolas Cadilhac", "author_id": 29244, "author_profile": "https://Stackoverflow.com/users/29244", "pm_score": 2, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>TypeDescriptor.GetProperties(obj);\n</code></pre>\n" }, { "answer_id": 245160, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>I would tend to agree with Nicolas; unless you know you need reflection, then <code>ComponentModel</code> is a viable alternative, with the advantage that you will get the correct metadata even for runtime models (such as <code>DataView</code>/<code>DataRowView</code>).</p>\n\n<p>For example:</p>\n\n<pre><code> foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(obj))\n {\n Console.WriteLine(\"{0}={1}\", prop.Name, prop.GetValue(obj));\n }\n</code></pre>\n\n<p>As an aside, you can also do some simple <a href=\"http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx\" rel=\"nofollow noreferrer\">performance tricks</a> with this; you can do the same with reflection and <code>Delegate.CreateDelegate</code>, but there is no centralised place to hide the logic away, unlike <code>TypeDescriptor</code> with a <code>TypeDescriptionProvider</code> (don't worry if these are unfamiliar; you can just use the code \"as is\" ;-p).</p>\n" }, { "answer_id": 72461513, "author": "Luc Bloom", "author_id": 1783320, "author_profile": "https://Stackoverflow.com/users/1783320", "pm_score": 0, "selected": false, "text": "<p>Just to be complete, you can't get PRIVATE fields and properties from base classes this way. You'll have to use a recursive loop for that:</p>\n<pre><code>public static IEnumerable&lt;PropertyInfo&gt; GetProperties(Type type, bool forGetter)\n{\n // Loop over public and protected members\n foreach (var item in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))\n {\n yield return item;\n }\n\n // Get first base type\n type = type.BaseType;\n\n // Find their &quot;private&quot; memebers\n while (type != null &amp;&amp; type != typeof(object))\n {\n // Loop over non-public members\n foreach (var item in type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic))\n {\n // Make sure it's private!\n // To prevent doubleing up on protected members\n var methodInfo = forGetter ? item.GetGetMethod(true) : item.GetSetMethod(true);\n if (methodInfo != null &amp;&amp; methodInfo.IsPrivate)\n {\n yield return item;\n }\n }\n\n // Get next base type.\n type = type.BaseType;\n }\n}\n</code></pre>\n<p>and</p>\n<pre><code>public static IEnumerable&lt;FieldInfo&gt; GetFields(Type type)\n{\n // Loop over public and protected members\n foreach (var item in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))\n {\n yield return item;\n }\n\n // Get first base type\n type = type.BaseType;\n\n // Find their &quot;private&quot; memebers\n while (type != null &amp;&amp; type != typeof(object))\n {\n // Loop over non-public members\n foreach (var item in type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic))\n {\n // Make sure it's private!\n // To prevent doubleing up on protected members\n if (item.IsPrivate)\n {\n yield return item;\n }\n }\n\n // Get next base type.\n type = type.BaseType;\n }\n}\n</code></pre>\n<p>Note: you will get PROTECTED fields &amp; properties twice.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23822/" ]
So what I have right now is something like this: ``` PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public); ``` where `obj` is some object. The problem is some of the properties I want aren't in `obj.GetType()` they're in one of the base classes further up. If I stop the debugger and look at obj, the I have to dig through a few "base" entries to see the properties I want to get at. Is there some binding flag I can set to have it return those or do I have to recursively dig through the `Type.BaseType` hierarchy and do `GetProperties` on all of them?
Use this: ``` PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); ``` EDIT: Of course the correct answer is that of [Jay](https://stackoverflow.com/questions/245055/how-do-you-get-the-all-properties-of-a-class-and-its-base-classes-up-the-hierar#245131). `GetProperties()` without parameters is equivalent to `GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static )`. The `BindingFlags.FlattenHierarchy` plays no role here.
245,058
<p>Lately I've been using XPathDocument and XNavigator to parse an XML file for a given XPath and attribute. It's been working very well, when I know in advance what the XPath is. </p> <p>Sometimes though, the XPath will be one of several possible XPath values, and I'd like to be able to test whether or not a given XPath exists. </p> <p>In case I'm getting the nomenclature wrong, here's what I'm calling an XPath - given this XML blob:</p> <pre><code>&lt;foo&gt; &lt;bar baz="This is the value of the attribute named baz"&gt; &lt;/foo&gt; </code></pre> <p>I might be looking for what I'm calling an XPath of "//foo/bar" and then reading the attribute "baz" to get the value. </p> <p>Example of the code that I use to do this: </p> <pre><code>XPathDocument document = new XPathDocument(filename); XPathNavigator navigator = document.CreateNavigator(); XPathNavigator node = navigator.SelectSingleNode("//foo/bar"); if(node.HasAttributes) { Console.WriteLine(node.GetAttribute("baz", string.Empty)); } </code></pre> <p>Now, if the call to navigator.SelectSingleNode fails, it will return a NullReferenceException or an XPathException. I can catch both of those and refactor the above into a test to see whether or not a given XPath returns an exception, but I was wondering whether there was a better way? </p> <p>I didn't see anything obvious in the Intellisense. XPathNavigator has .HasAttributes and .HasChildren but short of iterating through the path one node at a time, I don't see anything nicer to use. </p>
[ { "answer_id": 245077, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>If you've given valid XPath but it doesn't match anything, <code>SelectSingleNode</code> won't <em>throw</em> a <code>NullReferenceException</code> - it will just return null.</p>\n\n<p>If you pass <code>SelectSingleNode</code> some syntactically invalid XPath, that's when it will throw an <code>XPathException</code>.</p>\n\n<p>So normally, you'd just need to test whether the returned value was null or not.</p>\n" }, { "answer_id": 245085, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 0, "selected": false, "text": "<p>From memory, may contain errors.</p>\n\n<pre><code>XDocument doc = XDocument.Load(\"foo.xml\");\n\nvar att = from a in doc.Descendants(\"bar\")\n select a.Attribute(\"baz\")\n\nforeach (var item in att) {\n if (item != null) { ... }\n}\n</code></pre>\n" }, { "answer_id": 245091, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "<p>If <code>node == null</code> then <code>node.HasAttributes</code> will throw a <code>NullReferenceException</code>. This situation will occur when <code>//foo/bar</code> does not match any elements in the XML document.</p>\n" }, { "answer_id": 245112, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<pre><code>var node = XDocument.Load(filename)\n .Descendants(\"bar\")\n .SingleOrDefault(e=&gt;e.Attribute(\"baz\") != null);\n\nif (node != null) Console.WriteLine(node.Attribute(\"baz\").Value);\n</code></pre>\n" }, { "answer_id": 245123, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "<pre><code> var baz = navigator.SelectSingleNode(\"//foo/bar/@baz\");\n if (baz != null) Console.WriteLine(baz);\n</code></pre>\n" }, { "answer_id": 245136, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I would probably be more specific in my xpath.</p>\n\n<pre><code> var doc = XDocument.Load(fileName);\n\n var results = from r in doc.XPathSelectElements(\"/foo/bar[count(@baz) &gt; 0]\")\n select r.Attribute(\"baz\");\n\n foreach (String s in results)\n Console.WriteLine(s);\n</code></pre>\n" }, { "answer_id": 40181030, "author": "Ron", "author_id": 1903747, "author_profile": "https://Stackoverflow.com/users/1903747", "pm_score": 1, "selected": false, "text": "<p>I think it is not good to create an XMLNode object by executing navigator.SelectSingleNode(...).</p>\n\n<p>You have to use navigator.Evaluate() instead:</p>\n\n<pre><code>if (Convert.ToBoolean(navigator.Evaluate(@\"boolean(//foo/bar)\"))) {...}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5948/" ]
Lately I've been using XPathDocument and XNavigator to parse an XML file for a given XPath and attribute. It's been working very well, when I know in advance what the XPath is. Sometimes though, the XPath will be one of several possible XPath values, and I'd like to be able to test whether or not a given XPath exists. In case I'm getting the nomenclature wrong, here's what I'm calling an XPath - given this XML blob: ``` <foo> <bar baz="This is the value of the attribute named baz"> </foo> ``` I might be looking for what I'm calling an XPath of "//foo/bar" and then reading the attribute "baz" to get the value. Example of the code that I use to do this: ``` XPathDocument document = new XPathDocument(filename); XPathNavigator navigator = document.CreateNavigator(); XPathNavigator node = navigator.SelectSingleNode("//foo/bar"); if(node.HasAttributes) { Console.WriteLine(node.GetAttribute("baz", string.Empty)); } ``` Now, if the call to navigator.SelectSingleNode fails, it will return a NullReferenceException or an XPathException. I can catch both of those and refactor the above into a test to see whether or not a given XPath returns an exception, but I was wondering whether there was a better way? I didn't see anything obvious in the Intellisense. XPathNavigator has .HasAttributes and .HasChildren but short of iterating through the path one node at a time, I don't see anything nicer to use.
If you've given valid XPath but it doesn't match anything, `SelectSingleNode` won't *throw* a `NullReferenceException` - it will just return null. If you pass `SelectSingleNode` some syntactically invalid XPath, that's when it will throw an `XPathException`. So normally, you'd just need to test whether the returned value was null or not.
245,082
<p>I'm making a shell script to find bigrams, which works, sort of.</p> <pre><code>#tokenise words tr -sc 'a-zA-z0-9.' '\012' &lt; $1 &gt; out1 #create 2nd list offset by 1 word tail -n+2 out1 &gt; out2 #paste list together paste out1 out2 #clean up rm out1 out2 </code></pre> <p>The only problem is that it pairs words from the end and start of the previous sentence.</p> <p>eg for the two sentences 'hello world.' and 'foo bar.' i'll get a line with ' world. foo'. Would it be possible to filter these out with grep or something?</p> <p>I know i can find all bigrams containing a full stop with grep [.] but that also finds the legitimate bigrams.</p>
[ { "answer_id": 245065, "author": "Kirk Strauser", "author_id": 32538, "author_profile": "https://Stackoverflow.com/users/32538", "pm_score": 4, "selected": false, "text": "<p>Everything. They're unrelated languages.</p>\n" }, { "answer_id": 245066, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 5, "selected": false, "text": "<p>Everything.</p>\n\n<p>JavaScript was named this way by Netscape to confuse the unwary into thinking it had something to do with Java, the buzzword of the day, and it succeeded.</p>\n\n<p>The two languages are entirely distinct.</p>\n" }, { "answer_id": 245068, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 10, "selected": true, "text": "<p>Java and Javascript are similar like Car and Carpet are similar.</p>\n" }, { "answer_id": 245069, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 8, "selected": false, "text": "<p>Here are some differences between the two languages:</p>\n\n<ul>\n<li>Java is a statically typed language; JavaScript is dynamic.</li>\n<li>Java is class-based; JavaScript is prototype-based.</li>\n<li>Java constructors are special functions that can only be called at object creation; JavaScript \"constructors\" are just standard functions.</li>\n<li>Java requires all non-block statements to end with a semicolon; JavaScript inserts semicolons at the ends of certain lines.</li>\n<li>Java uses block-based scoping; JavaScript uses function-based scoping.</li>\n<li>Java has an implicit <code>this</code> scope for non-static methods, and implicit class scope; JavaScript has implicit global scope.</li>\n</ul>\n\n<p>Here are some features that I think are particular strengths of JavaScript:</p>\n\n<ul>\n<li>JavaScript supports closures; Java can simulate sort-of \"closures\" using anonymous classes. (Real closures may be supported in a future version of Java.)</li>\n<li>All JavaScript functions are variadic; Java functions are only variadic if explicitly marked.</li>\n<li>JavaScript prototypes can be redefined at runtime, and has immediate effect for all referring objects. Java classes cannot be redefined in a way that affects any existing object instances.</li>\n<li>JavaScript allows methods in an object to be redefined independently of its prototype (think eigenclasses in Ruby, but on steroids); methods in a Java object are tied to its class, and cannot be redefined at runtime.</li>\n</ul>\n" }, { "answer_id": 245073, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 9, "selected": false, "text": "<p>One is essentially a toy, designed for writing small pieces of code, and traditionally used and abused by inexperienced programmers.</p>\n\n<p>The other is a scripting language for web browsers.</p>\n" }, { "answer_id": 245076, "author": "Don Wakefield", "author_id": 3778, "author_profile": "https://Stackoverflow.com/users/3778", "pm_score": 3, "selected": false, "text": "<p>They are independent languages with unrelated lineages. Brendan Eich created Javascript originally at Netscape. It was initially called Mocha. The choice of Javascript as a name was a nod, if you will, to the then ascendant Java programming language, developed at Sun by Patrick Naughton, James Gosling, et. al.</p>\n" }, { "answer_id": 245083, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 5, "selected": false, "text": "<p>JavaScript is an object-oriented <em>scripting</em> language that allows you to create dynamic HTML pages, allowing you to process input data and maintain data, usually within the browser.</p>\n\n<p>Java is a programming language, core set of libraries, and virtual machine platform that allows you to create compiled programs that run on nearly every platform, without distribution of source code in its raw form or recompilation.</p>\n\n<p>While the two have similar names, they are really two completely different programming languages/models/platforms, and are used to solve completely different sets of problems.</p>\n\n<p>Also, this is directly from the Wikipedia <a href=\"http://en.wikipedia.org/wiki/JavaScript\" rel=\"nofollow noreferrer\">Javascript article</a>:</p>\n\n<blockquote>\n <p>A common misconception is that JavaScript is similar or closely related to Java; this is not so. Both have a C-like syntax, are object-oriented, are typically sandboxed and are widely used in client-side Web applications, but the similarities end there. Java has static typing; JavaScript's typing is dynamic (meaning a variable can hold an object of any type and cannot be restricted). Java is loaded from compiled bytecode; JavaScript is loaded as human-readable code. C is their last common ancestor language.</p>\n</blockquote>\n" }, { "answer_id": 245088, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 6, "selected": false, "text": "<p>Take a look at the <a href=\"http://en.wikipedia.org/wiki/JavaScript\" rel=\"nofollow noreferrer\">Wikipedia link</a> </p>\n\n<blockquote>\n <p>JavaScript, despite the name, is essentially unrelated to the Java programming language, although both have the common C syntax, and JavaScript copies many Java names and naming conventions. The language was originally named \"LiveScript\" but was renamed in a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with their then-dominant browser. The key design principles within JavaScript are inherited from the Self and Scheme programming languages.</p>\n</blockquote>\n" }, { "answer_id": 245090, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "<p>They have nothing to do with each other.</p>\n\n<p>Java is statically typed, compiles, runs on its own VM.</p>\n\n<p>Javascript is dynamically typed, interpreted, and runs in a browser. It also has first-class functions and anonymous functions, which Java does not. It has direct access to web-page elements, which makes it useful for doing client-side processing.</p>\n\n<p>They are also somewhat similar in syntax, but that's about it.</p>\n" }, { "answer_id": 248151, "author": "Darcy Casselman", "author_id": 5062, "author_profile": "https://Stackoverflow.com/users/5062", "pm_score": 3, "selected": false, "text": "<p>Like everybody's saying, they're pretty much entirely different.</p>\n\n<p>However, if you need a <em>scripting</em> language for your <em>Java</em> application, Javascript is actually a really good choice. There are ways to get Javascript running in the JVM and you can access and manipulate Java classes pretty seamlessly once you do. </p>\n" }, { "answer_id": 347435, "author": "Stein G. Strindhaug", "author_id": 26115, "author_profile": "https://Stackoverflow.com/users/26115", "pm_score": 4, "selected": false, "text": "<p>In addittion to being entirely different languages, in my experience:</p>\n\n<ul>\n<li>Java looks nice at first, later it gets annoying.</li>\n<li>JavaScript looks awful and hopeless at first, then gradually you really start to like it.</li>\n</ul>\n\n<p>(But this may just have more to do with my preference of functional programming over OO programming... ;)</p>\n" }, { "answer_id": 2042160, "author": "Will Peavy", "author_id": 458333, "author_profile": "https://Stackoverflow.com/users/458333", "pm_score": 1, "selected": false, "text": "<p>Practically every PC in the world sells with at least one JavaScript interpreter installed on it.</p>\n\n<p>Most (but not \"practically all\") PCs have a Java VM installed.</p>\n" }, { "answer_id": 3697022, "author": "isomorphismes", "author_id": 563329, "author_profile": "https://Stackoverflow.com/users/563329", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://developer.mozilla.org/en/a_re-introduction_to_javascript\" rel=\"nofollow noreferrer\">A Re-Introduction to Javascript</a> by the Mozilla team (they make Firefox) should explain it.</p>\n" }, { "answer_id": 5184356, "author": "Alpine", "author_id": 617750, "author_profile": "https://Stackoverflow.com/users/617750", "pm_score": 5, "selected": false, "text": "<p><img src=\"https://i.stack.imgur.com/TsJyw.jpg\" alt=\"enter image description here\"><br>\n<a href=\"http://coding.smashingmagazine.com/2009/07/29/misunderstanding-markup-xhtml-2-comic-strip/\" rel=\"nofollow noreferrer\">Java is to JavaScript as ham is to hamster</a></p>\n" }, { "answer_id": 7958249, "author": "user577898", "author_id": 577898, "author_profile": "https://Stackoverflow.com/users/577898", "pm_score": 2, "selected": false, "text": "<p>Don't be confused with name..<br>\nJava was created at Sun Microsystems (now Oracle).<br>\nBut, JavaScript was created at Netscape (now Mozilla) in the early days of the Web, and technically, “Java-Script” is a trademark licensed from Sun Microsystems used to describe\nNetscape’s implementation of the language. Netscape submitted the\nlanguage for standardization to ECMA (European Computer Manufacturer’s Association)\nand because of trademark issues, the standardized version of the language\nwas stuck with the awkward name “ECMAScript.” For the same trademark reasons,\nMicrosoft’s version of the language is formally known as “JScript.” In practice, just\nabout everyone calls the language JavaScript. The real name is “ECMAScript”. </p>\n\n<p><strong>Both are fully different languages!!!</strong></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm making a shell script to find bigrams, which works, sort of. ``` #tokenise words tr -sc 'a-zA-z0-9.' '\012' < $1 > out1 #create 2nd list offset by 1 word tail -n+2 out1 > out2 #paste list together paste out1 out2 #clean up rm out1 out2 ``` The only problem is that it pairs words from the end and start of the previous sentence. eg for the two sentences 'hello world.' and 'foo bar.' i'll get a line with ' world. foo'. Would it be possible to filter these out with grep or something? I know i can find all bigrams containing a full stop with grep [.] but that also finds the legitimate bigrams.
Java and Javascript are similar like Car and Carpet are similar.
245,121
<p>I'm looking for a code library that converts ANSI escape sequences into HTML color, via plain tags or CSS. For example, something that would convert this:</p> <pre>ESC[00mESC[01;34mbinESC[00m ESC[01;34mcodeESC[00m ESC[01;31mdropbox-lnx.x86-0.6.404.tar.gzESC[00m ESC[00mfooESC[00m</pre> <p>Into this:</p> <pre><code>&lt;span style="color:blue"&gt;bin&lt;/span&gt; &lt;span style="color:blue"&gt;code&lt;/span&gt; &lt;span style="color:red"&gt;dropbox-lnx.x86-0.6.404.tar.gz&lt;/span&gt; foo </code></pre> <p>Converting breaks into &lt;br/&gt; isn't necessary, it's just the escape codes that I don't know. I could hack it together myself, but I'd probably miss something important like underlines or mess up how background colors work. I'd rather just sit on top of someone else's code.</p> <p>Does such a tool (command line linux) or library (perl, python, or ruby preferably) exist?</p>
[ { "answer_id": 252452, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 5, "selected": true, "text": "<p>There seems to be <a href=\"http://search.cpan.org/perldoc?HTML::FromANSI\" rel=\"noreferrer\">an HTML::FromANSI Perl module</a>.</p>\n" }, { "answer_id": 2975843, "author": "Alexander Matthes", "author_id": 358638, "author_profile": "https://Stackoverflow.com/users/358638", "pm_score": 7, "selected": false, "text": "<p><code>aha</code> is a C-language program, available in an Ubuntu package, at <a href=\"http://ziz.delphigl.com/tool_aha.php\" rel=\"noreferrer\">http://ziz.delphigl.com/tool_aha.php</a> or on github <a href=\"https://github.com/theZiz/aha\" rel=\"noreferrer\">https://github.com/theZiz/aha</a>, that takes an input with terminal colors by pipe or file and puts a (w3c conform) HTML-File in stdout. Example:</p>\n\n<pre><code>ls --color=always | aha &gt; ls-output.htm\n</code></pre>\n\n<p>or</p>\n\n<pre><code>ls --color=always | aha --black &gt; ls-output.htm\n</code></pre>\n\n<p>for a terminal-like look with black background.</p>\n\n<p>Compile it by \"make\" and put it where ever you want.</p>\n\n<p>It would be great to get Feedback. ;-)</p>\n" }, { "answer_id": 20289135, "author": "Janus Troelsen", "author_id": 309483, "author_profile": "https://Stackoverflow.com/users/309483", "pm_score": 5, "selected": false, "text": "<p>Mature Python library and command line tool which is still maintained: <a href=\"https://github.com/pycontribs/ansi2html\" rel=\"nofollow noreferrer\">pycontribs/ansi2html</a></p>\n<p>Alternatively, for the Bourne shell: <a href=\"https://github.com/pixelb/scripts/blob/master/scripts/ansi2html.sh\" rel=\"nofollow noreferrer\">ansi2html.sh</a></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9084/" ]
I'm looking for a code library that converts ANSI escape sequences into HTML color, via plain tags or CSS. For example, something that would convert this: ``` ESC[00mESC[01;34mbinESC[00m ESC[01;34mcodeESC[00m ESC[01;31mdropbox-lnx.x86-0.6.404.tar.gzESC[00m ESC[00mfooESC[00m ``` Into this: ``` <span style="color:blue">bin</span> <span style="color:blue">code</span> <span style="color:red">dropbox-lnx.x86-0.6.404.tar.gz</span> foo ``` Converting breaks into <br/> isn't necessary, it's just the escape codes that I don't know. I could hack it together myself, but I'd probably miss something important like underlines or mess up how background colors work. I'd rather just sit on top of someone else's code. Does such a tool (command line linux) or library (perl, python, or ruby preferably) exist?
There seems to be [an HTML::FromANSI Perl module](http://search.cpan.org/perldoc?HTML::FromANSI).
245,124
<p>I need to set the onload attribute for a newly popped-up window. The following code works for Firefox:</p> <pre><code>&lt;a onclick="printwindow=window.open('www.google.com');printwindow.document.body.onload=self.print();return false;" href='www.google.com'&gt; </code></pre> <p>However, when I try this in IE, I get an error - "printwindow.document.body null or not defined'</p> <p>The goal is to pop open a new window, and call up the print dialog for that window once it's been opened. </p> <p>Any clues on how to make this work? It is important not to use javascript elsewhere on the target page, as I do not have control over it. All functionality must be contained in the link I posted above.</p>
[ { "answer_id": 245203, "author": "buti-oxa", "author_id": 2515, "author_profile": "https://Stackoverflow.com/users/2515", "pm_score": 0, "selected": false, "text": "<p>You are relying on \"printwindow.document.body.onload=self.print();\" line being executed before the child document finishes loading. I don't think you can be guaranteed that.</p>\n\n<p>Here's an idea: prepare HTML or a page that has nothing but the page you need in an iframe. This page will have body.onload=self.print().</p>\n" }, { "answer_id": 245214, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 0, "selected": false, "text": "<p>onload is a property if window objects, not body elements, despite what the HTML attribute might lead you to believe. This is the reference:</p>\n\n<pre><code>printwindow.onload\n</code></pre>\n\n<p>However, in this context you can't pass it a string of JavaScript - you need to hand it a function. So, the full script like would look like this</p>\n\n<pre><code>printwindow.onload=function(){self.print();}\n</code></pre>\n\n<p>Now, putting it all together</p>\n\n<pre><code>&lt;a href=\"www.google.com\" onclick=\"var printwindow=window.open(this.href,'printwindow');printwindow.onload=function(){self.print();};return false;\" &gt;try it&lt;/a&gt;\n</code></pre>\n\n<p>HOWEVER! This will not work for you for the URL \"www.google.com\". The browser security model prevents parent windows from accessing the window objects of child windows, UNLESS they both reside @ the same domain name. </p>\n" }, { "answer_id": 245226, "author": "Eli", "author_id": 27580, "author_profile": "https://Stackoverflow.com/users/27580", "pm_score": 0, "selected": false, "text": "<p>Check our jQuery. Particularly the document ready feature.</p>\n\n<p><a href=\"http://docs.jquery.com/Tutorials:How_jQuery_Works#Launching_Code_on_Document_Ready\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Tutorials:How_jQuery_Works#Launching_Code_on_Document_Ready</a></p>\n" }, { "answer_id": 245256, "author": "jcampbell1", "author_id": 20512, "author_profile": "https://Stackoverflow.com/users/20512", "pm_score": 1, "selected": false, "text": "<p>This is not possible unless both pages are on the same domain. Your code does not work in FF, but rather prints the current page. If the pages are on the same domain, then you would write:</p>\n\n<pre><code>printwindow=window.open('/mypage.html');\nprintwindow.onload = function() {\n printwindow.focus();\n printwindow.print();\n}\n</code></pre>\n" }, { "answer_id": 247915, "author": "SocialCensus", "author_id": 26001, "author_profile": "https://Stackoverflow.com/users/26001", "pm_score": -1, "selected": false, "text": "<p>The final (admittedly, poor) solution that worked for all browsers was to use setTimeout and call print() that way, instead of modifying the onload attribute:</p>\n\n<pre><code>&lt;a onclick=\"self.printwindow=window.open('print.html');setTimeout('self.printwindow.print()',3000);return false;\" href='print.html'&gt;\n</code></pre>\n" }, { "answer_id": 5493229, "author": "ace", "author_id": 439699, "author_profile": "https://Stackoverflow.com/users/439699", "pm_score": 2, "selected": false, "text": "<p>While earlier answers correctly stated the new window must be from the same domain, they incorrectly answered why he got the error 'printwindow.document.body null or not defined'. It's because IE doesn't return any status from window.open() which means you can open a page and try to access it BEFORE onload is available.</p>\n\n<p>For this reason you need to use something like setTimeout to check. For example:</p>\n\n<pre><code>printwindow = window.open('print.html');\nvar body;\nfunction ieLoaded(){\n body = printwindow.document.getElementsByTagName(\"body\");\n if(body[0]==null){\n // Page isn't ready yet!\n setTimeout(ieLoaded, 10);\n }else{\n // Here you can inject javascript if you like\n var n = printwindow.document.createElement(\"script\");\n n.src = \"injectableScript.js\";\n body.appendChild(n);\n\n // Or you can just call your script as originally planned\n printwindow.print();\n }\n}\nieLoaded();\n</code></pre>\n\n<p>This is further discussed <a href=\"http://flightschool.acylt.com/devnotes/window-open-onload-window-events/\" rel=\"nofollow\">here</a></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26001/" ]
I need to set the onload attribute for a newly popped-up window. The following code works for Firefox: ``` <a onclick="printwindow=window.open('www.google.com');printwindow.document.body.onload=self.print();return false;" href='www.google.com'> ``` However, when I try this in IE, I get an error - "printwindow.document.body null or not defined' The goal is to pop open a new window, and call up the print dialog for that window once it's been opened. Any clues on how to make this work? It is important not to use javascript elsewhere on the target page, as I do not have control over it. All functionality must be contained in the link I posted above.
While earlier answers correctly stated the new window must be from the same domain, they incorrectly answered why he got the error 'printwindow.document.body null or not defined'. It's because IE doesn't return any status from window.open() which means you can open a page and try to access it BEFORE onload is available. For this reason you need to use something like setTimeout to check. For example: ``` printwindow = window.open('print.html'); var body; function ieLoaded(){ body = printwindow.document.getElementsByTagName("body"); if(body[0]==null){ // Page isn't ready yet! setTimeout(ieLoaded, 10); }else{ // Here you can inject javascript if you like var n = printwindow.document.createElement("script"); n.src = "injectableScript.js"; body.appendChild(n); // Or you can just call your script as originally planned printwindow.print(); } } ieLoaded(); ``` This is further discussed [here](http://flightschool.acylt.com/devnotes/window-open-onload-window-events/)
245,168
<p>How do I properly convert two columns from SQL (2008) using Linq into a <code>Dictionary</code> (for caching)?</p> <p>I currently loop through the <code>IQueryable</code> b/c I can't get the <code>ToDictionary</code> method to work. Any ideas? This works:</p> <pre><code>var query = from p in db.Table select p; Dictionary&lt;string, string&gt; dic = new Dictionary&lt;string, string&gt;(); foreach (var p in query) { dic.Add(sub.Key, sub.Value); } </code></pre> <p>What I'd really like to do is something like this, which doesn't seem to work:</p> <pre><code>var dic = (from p in db.Table select new {p.Key, p.Value }) .ToDictionary&lt;string, string&gt;(p =&gt; p.Key); </code></pre> <p>But I get this error:</p> <blockquote> <p>Cannot convert from 'System.Linq.IQueryable&lt;AnonymousType#1&gt;' to 'System.Collections.Generic.IEnumerable'</p> </blockquote>
[ { "answer_id": 245174, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 8, "selected": true, "text": "<pre><code>var dictionary = db\n .Table\n .Select(p =&gt; new { p.Key, p.Value })\n .AsEnumerable()\n .ToDictionary(kvp =&gt; kvp.Key, kvp =&gt; kvp.Value)\n;\n</code></pre>\n" }, { "answer_id": 245187, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": false, "text": "<p>You are only defining the key, but you need to include the value also:</p>\n\n<pre><code>var dic = (from p in db.Table\n select new {p.Key, p.Value })\n .ToDictionary(p =&gt; p.Key, p=&gt; p.Value);\n</code></pre>\n" }, { "answer_id": 245216, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 3, "selected": false, "text": "<p>Thanks guys, your answers helped me fix this, should be:</p>\n\n<pre><code>var dic = db\n .Table\n .Select(p =&gt; new { p.Key, p.Value })\n .AsEnumerable()\n .ToDictionary(k=&gt; k.Key, v =&gt; v.Value);\n</code></pre>\n" }, { "answer_id": 2088742, "author": "TWiStErRob", "author_id": 253468, "author_profile": "https://Stackoverflow.com/users/253468", "pm_score": 2, "selected": false, "text": "<p>Why would you create an anonymous object for every item in the table just to convert it?</p>\n\n<p>You could simply use something like:\n<code>IDictionary&lt;string, string&gt; dic = db.Table.ToDictionary(row =&gt; row.Key, row =&gt; row.Value);</code>\nYou may need to include an AsEnumerable() call between Table and ToDictionary().\nI don't know the exact type of db.Table.</p>\n\n<hr>\n\n<p>Also correct the first sample, your second loop variable is mismatching at declaration and usage.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17729/" ]
How do I properly convert two columns from SQL (2008) using Linq into a `Dictionary` (for caching)? I currently loop through the `IQueryable` b/c I can't get the `ToDictionary` method to work. Any ideas? This works: ``` var query = from p in db.Table select p; Dictionary<string, string> dic = new Dictionary<string, string>(); foreach (var p in query) { dic.Add(sub.Key, sub.Value); } ``` What I'd really like to do is something like this, which doesn't seem to work: ``` var dic = (from p in db.Table select new {p.Key, p.Value }) .ToDictionary<string, string>(p => p.Key); ``` But I get this error: > > Cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to > 'System.Collections.Generic.IEnumerable' > > >
``` var dictionary = db .Table .Select(p => new { p.Key, p.Value }) .AsEnumerable() .ToDictionary(kvp => kvp.Key, kvp => kvp.Value) ; ```
245,178
<p>I read some properties from an xml file, amongst which is a string that refers to an llblgen object for example 'article'. For now I have set up a rather long </p> <pre><code>Select Case myString Case "article" return New ArticleEntity() </code></pre> <p>Etc. which is getting rather ugly as it gets longer and longer ;). Is there a better way to do this ?</p> <p>(the above is vb.net, but c# examples are fine as well)</p>
[ { "answer_id": 245181, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "<p>You could store the type names in the file and use:</p>\n\n<pre><code>return Activator.CreateInstance(Type.GetType(\"Some.Type.String\"));\n</code></pre>\n\n<p>(that would work as long as <code>Some.Type.String</code> has a default parameterless constructor.)</p>\n" }, { "answer_id": 245191, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 1, "selected": false, "text": "<p>Do the strings exactly represent the name of the object type. If so you could probably do.</p>\n\n<pre><code> Object obj = Activator.CreateInstance(\"AssemblyName\", \"TypeName\");\n</code></pre>\n\n<p>so if you had the types coming back from a list you could do...</p>\n\n<pre><code>List&lt;object&gt; list = new List&lt;object&gt;();\n\n\nforeach(string typename in GetFromXMLFile())\n{\n list.Add(Activator.CreateInstance(\"AssemblyName\", typename);\n}\n</code></pre>\n" }, { "answer_id": 245195, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>Notice that <code>Activator.CreateInstance</code> has got a generic version that makes a cast to a base class unnecessary (if such a base class or interface is available):</p>\n\n<pre><code>public static IMyTrait MakeMyTrait(Type t) {\n return Activator.CreateInstance&lt;IMyTrait&gt;(t);\n}\n</code></pre>\n" }, { "answer_id": 245200, "author": "Morph", "author_id": 31489, "author_profile": "https://Stackoverflow.com/users/31489", "pm_score": 0, "selected": false, "text": "<p>Ah very nice. Not sure if the objects are exactly as in the file, but I rather edit that file than keep on using that ugly select case thingy :). </p>\n\n<p>Thanks for the suggestions !</p>\n" }, { "answer_id": 245287, "author": "Oliver Hallam", "author_id": 19995, "author_profile": "https://Stackoverflow.com/users/19995", "pm_score": 3, "selected": true, "text": "<p>you could create a dictionary mapping strings to factory methods eg</p>\n\n<pre><code>Dictionary&lt;string, Func&lt;Animal&gt;&gt; _map = new Dictionary\n{\n (\"cat\", () =&gt; new Cat()),\n (\"dog\", () =&gt; new Dog())\n ...\n}\n</code></pre>\n\n<p>Then your case statement becomes</p>\n\n<pre><code>return _map[myString]();\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31489/" ]
I read some properties from an xml file, amongst which is a string that refers to an llblgen object for example 'article'. For now I have set up a rather long ``` Select Case myString Case "article" return New ArticleEntity() ``` Etc. which is getting rather ugly as it gets longer and longer ;). Is there a better way to do this ? (the above is vb.net, but c# examples are fine as well)
you could create a dictionary mapping strings to factory methods eg ``` Dictionary<string, Func<Animal>> _map = new Dictionary { ("cat", () => new Cat()), ("dog", () => new Dog()) ... } ``` Then your case statement becomes ``` return _map[myString](); ```
245,180
<p>I am writing a stored procedure where I have an input parameter called <em>my_size</em> that is an <em>INTEGER</em>. I want to be able to use it in a <code>LIMIT</code> clause in a <code>SELECT</code> statement. Apparently this is not supported, is there a way to work around this?</p> <pre><code># I want something like: SELECT * FROM some_table LIMIT my_size; # Instead of hardcoding a permanent limit: SELECT * FROM some_table LIMIT 100; </code></pre>
[ { "answer_id": 245210, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 5, "selected": true, "text": "<p>A search turned up <a href=\"http://bugs.mysql.com/bug.php?id=8094\" rel=\"noreferrer\">this article</a>. I've pasted the relevant text below.</p>\n\n<blockquote>\n <p>Here's a forum post showing an example of prepared statements letting\n you assign a variable value to the limit clause:</p>\n \n <p><a href=\"http://forums.mysql.com/read.php?98,126379,133966#msg-133966\" rel=\"noreferrer\">http://forums.mysql.com/read.php?98,126379,133966#msg-133966</a></p>\n \n <p>However, I think this bug should get some attention because I can't\n imagine that prepared statements within a procedure will allow for any\n procedure-compile-time optimizations. I have a feeling that prepared\n statements are compiled and executed at the runtime of the procedure,\n which probaby has a negative impact on efficiency. If the limit\n clause could accept normal procedure variables (say, a procedure\n argument), then the database could still perform compile-time\n optimizations on the rest of the query, within the procedure. This\n would likely yield faster execution of the procedure. I'm no expert\n though.</p>\n</blockquote>\n" }, { "answer_id": 7051824, "author": "user888112", "author_id": 888112, "author_profile": "https://Stackoverflow.com/users/888112", "pm_score": 4, "selected": false, "text": "<p>I know this answer has come late, but try SQL_SELECT_LIMIT.</p>\n\n<p>Example:</p>\n\n<pre><code>Declare rowCount int;\nSet rowCount = 100;\nSet SQL_SELECT_LIMIT = rowCount;\nSelect blah blah\nSet SQL_SELECT_LIMIT = Default;\n</code></pre>\n" }, { "answer_id": 8962289, "author": "Jiho Kang", "author_id": 818351, "author_profile": "https://Stackoverflow.com/users/818351", "pm_score": 4, "selected": false, "text": "<p>This feature has been added to MySQL 5.5.6.\nCheck this <a href=\"http://bugs.mysql.com/bug.php?id=11918\" rel=\"noreferrer\">link</a> out.</p>\n\n<p>I've upgraded to MySQL 5.5 just for this feature and works great.\n5.5 also has a lot of performance upgrades in place and I totally recommend it.</p>\n" }, { "answer_id": 10025538, "author": "Pradeep Sanjaya", "author_id": 529218, "author_profile": "https://Stackoverflow.com/users/529218", "pm_score": 4, "selected": false, "text": "<p><strong>STORED PROCEDURE</strong></p>\n<pre><code>DELIMITER $\nCREATE PROCEDURE get_users(page_from INT, page_size INT)\nBEGIN\n SET @_page_from = page_from;\n SET @_page_size = page_size;\n PREPARE stmt FROM &quot;select u.user_id, u.firstname, u.lastname from users u limit ?, ?;&quot;;\n EXECUTE stmt USING @_page_from, @_page_size;\n DEALLOCATE PREPARE stmt;\nEND$\n\nDELIMITER ;\n</code></pre>\n<p><strong>USAGE</strong></p>\n<p>In the following example it retrieves 10 records each time by providing start as 1 and 11. 1 and 11 could be your page number received as GET/POST parameter from pagination.</p>\n<pre><code>call get_users(1, 10);\ncall get_users(11, 10);\n</code></pre>\n" }, { "answer_id": 14856587, "author": "Алексей Пузенко", "author_id": 1098030, "author_profile": "https://Stackoverflow.com/users/1098030", "pm_score": 2, "selected": false, "text": "<p>Another way, the same as wrote \"Pradeep Sanjaya\", but using CONCAT:</p>\n\n<pre><code>CREATE PROCEDURE `some_func`(startIndex INT, countNum INT)\nREADS SQL DATA\n COMMENT 'example'\nBEGIN\n SET @asd = CONCAT('SELECT `id` FROM `table` LIMIT ',startIndex,',',countNum);\n PREPARE zxc FROM @asd;\n EXECUTE zxc;\nEND;\n</code></pre>\n" }, { "answer_id": 17059426, "author": "ENargit", "author_id": 676623, "author_profile": "https://Stackoverflow.com/users/676623", "pm_score": 5, "selected": false, "text": "<p>For those, who cannot use MySQL 5.5.6+ and don't want to write a stored procedure, there is another variant. We can add where clause on a subselect with ROWNUM.</p>\n\n<pre><code>SET @limit = 10;\nSELECT * FROM (\n SELECT instances.*, \n @rownum := @rownum + 1 AS rank\n FROM instances, \n (SELECT @rownum := 0) r\n) d WHERE rank &lt; @limit;\n</code></pre>\n" }, { "answer_id": 30612069, "author": "rekaszeru", "author_id": 506879, "author_profile": "https://Stackoverflow.com/users/506879", "pm_score": 1, "selected": false, "text": "<p>As of MySQL version 5.5.6, you can specify <strong><code>LIMIT</code></strong> and <strong><code>OFFSET</code></strong> with variables / parameters.</p>\n\n<p>For reference, see the <a href=\"http://dev.mysql.com/doc/refman/5.5/en/select.html#idm140195666212032\" rel=\"nofollow noreferrer\">5.5 Manual</a>, the <a href=\"http://dev.mysql.com/doc/refman/5.6/en/select.html#idm140462371147952\" rel=\"nofollow noreferrer\">5.6 Manual</a> and @Quassnoi's <a href=\"https://stackoverflow.com/a/2875365/506879\">answer</a></p>\n" }, { "answer_id": 60102915, "author": "juan_carlos_yl", "author_id": 10102494, "author_profile": "https://Stackoverflow.com/users/10102494", "pm_score": 0, "selected": false, "text": "<p>I've faced the same problem using MySql 5.0 and wrote a procedure with the help of @ENargit's answer:</p>\n\n<pre><code>CREATE PROCEDURE SOME_PROCEDURE_NAME(IN _length INT, IN _start INT)\nBEGIN\n SET _start = (SELECT COALESCE(_start, 0));\n SET _length = (SELECT COALESCE(_length, 999999)); -- USING ~0 GIVES OUT OF RANGE ERROR\n SET @row_num_personalized_variable = 0;\n\n SELECT\n *,\n @row_num_personalized_variable AS records_total \n FROM(\n SELECT\n *,\n (@row_num_personalized_variable := @row_num_personalized_variable + 1) AS row_num\n FROM some_table\n ) tb\n WHERE row_num &gt; _start AND row_num &lt;= (_start + _length);\nEND;\n</code></pre>\n\n<p>Also included the total rows obtained by the query with records_total.</p>\n" }, { "answer_id": 72050341, "author": "marisxanis", "author_id": 1249945, "author_profile": "https://Stackoverflow.com/users/1249945", "pm_score": 0, "selected": false, "text": "<p>you must DECLARE a variable and after that set it. then the LIMIt will work and put it in a StoredProcedure not sure if it works in normal query</p>\n<p>like this:</p>\n<pre><code>DECLARE rowsNr INT DEFAULT 0; \nSET rowsNr = 15; \nSELECT * FROM Table WHERE ... LIMIT rowsNr;\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24694/" ]
I am writing a stored procedure where I have an input parameter called *my\_size* that is an *INTEGER*. I want to be able to use it in a `LIMIT` clause in a `SELECT` statement. Apparently this is not supported, is there a way to work around this? ``` # I want something like: SELECT * FROM some_table LIMIT my_size; # Instead of hardcoding a permanent limit: SELECT * FROM some_table LIMIT 100; ```
A search turned up [this article](http://bugs.mysql.com/bug.php?id=8094). I've pasted the relevant text below. > > Here's a forum post showing an example of prepared statements letting > you assign a variable value to the limit clause: > > > <http://forums.mysql.com/read.php?98,126379,133966#msg-133966> > > > However, I think this bug should get some attention because I can't > imagine that prepared statements within a procedure will allow for any > procedure-compile-time optimizations. I have a feeling that prepared > statements are compiled and executed at the runtime of the procedure, > which probaby has a negative impact on efficiency. If the limit > clause could accept normal procedure variables (say, a procedure > argument), then the database could still perform compile-time > optimizations on the rest of the query, within the procedure. This > would likely yield faster execution of the procedure. I'm no expert > though. > > >
245,183
<p>How do you go about verifying the type of an uploaded file reliably without using the extension? I'm guessing that you have to examine the header / read some of the bytes, but I really have no idea how to go about it. Im using c# and asp.net.</p> <p>Thanks for any advice.</p> <hr> <p>ok, so from the above links I now know that I am looking for 'ff d8 ff e0' to positively identify a .jpg file for example.</p> <p>In my code I can read the first twenty bytes no problem:</p> <pre><code> FileStream fs = File.Open(filePath, FileMode.Open); Byte[] b = new byte[20]; fs.Read(b, 0, 20); </code></pre> <p>so (and please excuse my total inexperience here) but how do I check whether the byte array contains 'ff d8 ff e0'?</p>
[ { "answer_id": 245196, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 1, "selected": false, "text": "<p>The first few bytes of a file will often tell you the file type. See, for example,<br>\n<a href=\"http://www.garykessler.net/library/file_sigs.html\" rel=\"nofollow noreferrer\">http://www.garykessler.net/library/file_sigs.html</a><br>\n<a href=\"http://www.astro.keele.ac.uk/oldusers/rno/Computing/File_magic.html\" rel=\"nofollow noreferrer\">http://www.astro.keele.ac.uk/oldusers/rno/Computing/File_magic.html</a> </p>\n\n<p>Use System.IO to read the byes as binary after the upload.</p>\n\n<p>I'm curious, though, why you can't rely on on the ContentType header?</p>\n" }, { "answer_id": 245201, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>That indeed is what the Unix <code>file</code> program does, with greater or lesser degrees of reliability. In part, it depends on whether the programs whose files you are trying to detect emits a file header; the program <code>tar</code> is notorious for not doing so. It depends on how many types of files you plan to try and recognize, but it might well be simplest to use an implementation of <code>file</code>; it recognizes many file types, and modern versions are extensible via a file of extra file type definitions that can handle a multitude of scenarios.</p>\n" }, { "answer_id": 245262, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": false, "text": "<p><s>Wotsit</s> is a good resource for finding out the magic numbers for various file types.</p>\n<p>Edit: link is broken. Here’s a better resource that is still being updated</p>\n<p><a href=\"https://www.garykessler.net/library/file_sigs.html\" rel=\"nofollow noreferrer\">https://www.garykessler.net/library/file_sigs.html</a></p>\n" }, { "answer_id": 245479, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 3, "selected": true, "text": "<p>Here's a quick-and-dirty response to the followup question you posted:</p>\n\n<pre><code>byte[] jpg = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 };\nbool match = true;\nfor (int i = 0; i &lt; jpg.Length; i++)\n{\n if (jpg[i] != b[i])\n {\n match = false;\n break;\n }\n}\n</code></pre>\n" }, { "answer_id": 307407, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Reading the contents of the file is the fool proof way. Since you are building it in .Net, you could probably check the MIME Type of the uploaded file.</p>\n\n<p>You can DllImport urlmon.dll to help. Please refer a post at:\n<a href=\"http://coding-passion.blogspot.com/2008/11/validating-file-type.html\" rel=\"nofollow noreferrer\">http://coding-passion.blogspot.com/2008/11/validating-file-type.html</a></p>\n\n<p>And to clarify regarding Content-type, it invariably is driven by the extension of the file. So even a .zip file got its extension renamed to .txt, the content type will still say Text only.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
How do you go about verifying the type of an uploaded file reliably without using the extension? I'm guessing that you have to examine the header / read some of the bytes, but I really have no idea how to go about it. Im using c# and asp.net. Thanks for any advice. --- ok, so from the above links I now know that I am looking for 'ff d8 ff e0' to positively identify a .jpg file for example. In my code I can read the first twenty bytes no problem: ``` FileStream fs = File.Open(filePath, FileMode.Open); Byte[] b = new byte[20]; fs.Read(b, 0, 20); ``` so (and please excuse my total inexperience here) but how do I check whether the byte array contains 'ff d8 ff e0'?
Here's a quick-and-dirty response to the followup question you posted: ``` byte[] jpg = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 }; bool match = true; for (int i = 0; i < jpg.Length; i++) { if (jpg[i] != b[i]) { match = false; break; } } ```
245,192
<p>When are objects or something else said to be &quot;first-class&quot; in a given programming language, and why? In what way do they differ from languages where they are not?</p> <p>When one says &quot;everything is an object&quot; (like in Python), do they indeed mean that &quot;everything is first-class&quot;?</p>
[ { "answer_id": 245208, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 9, "selected": true, "text": "<p>In short, it means there are no restrictions on the object's use. It's the same as\nany other object.</p>\n\n<p>A first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have. </p>\n\n<blockquote>\n <p>Depending on the language, this can\n imply:</p>\n \n <ul>\n <li>being expressible as an anonymous literal value</li>\n <li>being storable in variables</li>\n <li>being storable in data structures</li>\n <li>having an intrinsic identity (independent of any given name)</li>\n <li>being comparable for equality with other entities</li>\n <li>being passable as a parameter to a procedure/function</li>\n <li>being returnable as the result of a procedure/function</li>\n <li>being constructible at runtime</li>\n <li>being printable</li>\n <li>being readable</li>\n <li>being transmissible among distributed processes</li>\n <li>being storable outside running processes</li>\n </ul>\n</blockquote>\n\n<p><a href=\"http://en.wikipedia.org/wiki/First-class_object\" rel=\"noreferrer\">Source</a>.</p>\n\n<p>In C++ functions themselves are not first class objects, however:</p>\n\n<ul>\n<li>You can override the '()' operator making it possible to have an object function, which is first class.</li>\n<li>Function pointers are first class. </li>\n<li>boost bind, lambda and function do offer first class functions</li>\n</ul>\n\n<p>In C++, classes are not first class objects but instances of those classes are. In Python both the classes <em>and</em> the objects are first class objects. (See <a href=\"https://stackoverflow.com/a/6581949/1612701\">this answer</a> for more details about classes as objects).</p>\n\n<p>Here is an example of Javascript first class functions:</p>\n\n<pre><code>// f: function that takes a number and returns a number\n// deltaX: small positive number\n// returns a function that is an approximate derivative of f\nfunction makeDerivative( f, deltaX )\n{\n var deriv = function(x)\n { \n return ( f(x + deltaX) - f(x) )/ deltaX;\n }\n return deriv;\n}\nvar cos = makeDerivative( Math.sin, 0.000001);\n// cos(0) ~&gt; 1\n// cos(pi/2) ~&gt; 0\n</code></pre>\n\n<p><a href=\"http://en.wikipedia.org/wiki/First-class_function\" rel=\"noreferrer\">Source</a>.</p>\n\n<p>Entities that are not first class objects are referred to as second-class objects. Functions in C++ are second class because they can't be dynamically created. </p>\n\n<p><strong>Regarding the edit:</strong></p>\n\n<blockquote>\n <p>EDIT. When one says \"everything is\n an object\" (like in Python), does he\n indeed mean that \"everything is\n first-class\"?</p>\n</blockquote>\n\n<p>The term object can be used loosely and doesn't imply being first class. And it would probably make more sense to call the whole concept 'first class entities'. But in Python they do aim to make everything first class. I believe the intent of the person who made your statement meant first class. </p>\n" }, { "answer_id": 245209, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "<p>“First class” means you can operate on them in the usual manner. Most of the times, this just means you can pass these first-class citizens as arguments to functions, or return them from functions.</p>\n<p>This is self-evident for objects but not always so evident for functions, or even classes:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>void f(int n) { return n * 2; }\n\nvoid g(Action&lt;int&gt; a, int n) { return a(n); }\n\n// Now call g and pass f:\n\ng(f, 10); // = 20\n</code></pre>\n<p>This is an example in C# where functions actually <em>aren't</em> first-class objects. The above code therefore uses a small workaround (namely a generic delegate called <code>Action&lt;&gt;</code>) to pass a function as an argument. Other languages, such as Ruby or Python, allow treating even classes and code blocks as normal variables (or in the case of Ruby, constants).</p>\n" }, { "answer_id": 245238, "author": "questzen", "author_id": 25210, "author_profile": "https://Stackoverflow.com/users/25210", "pm_score": 2, "selected": false, "text": "<p>IMO this is one of those metaphors used to describe things in a natural language. The term is essentially used in context of describing functions as first class objects. </p>\n\n<p>If you consider a object oriented language, we can impart various features to objects for eg: inheritance, class definition, ability to pass to other sections of code(method arguments), ability to store in a data structure etc. If we can do the same with an entity which is not normally considered as a object, like functions in the case of java script, such entities are considered to be first class objects.</p>\n\n<p>First class essentially here means, not handled as second class (with degraded behaviour). Essentially the mocking is perfect or indistinguishable.</p>\n" }, { "answer_id": 245295, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 5, "selected": false, "text": "<p>\"When one says \"everything is an object\" (like in Python), does he indeed mean that \"everything is first-class\"?\"</p>\n\n<p>Yes.</p>\n\n<p>Everything in Python is a proper object. Even things that are \"primitive types\" in other languages.</p>\n\n<p>You find that an object like <code>2</code> actually has a fairly rich and sophisticated interface.</p>\n\n<pre><code>&gt;&gt;&gt; dir(2)\n['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__']\n</code></pre>\n\n<p>Because everything's a first-class object in Python, there are relatively few obscure special cases. </p>\n\n<p>In Java, for example, there are primitive types (int, bool, double, char) that aren't proper objects. That's why Java has to introduce Integer, Boolean, Double, and Character as first-class types. This can be hard to teach to beginners -- it isn't obvious why both a primitive type and a class have to exist side-by-side.</p>\n\n<p>It also means that an object's class is -- itself -- an object. This is different from C++, where the classes don't always have a distinct existence at run-time.</p>\n\n<p>The type of <code>2</code> is the <code>type 'int'</code> object, which has methods, attributes, and a type.</p>\n\n<pre><code>&gt;&gt;&gt; type(2)\n&lt;class 'int'&gt;\n</code></pre>\n\n<p>The type of a built-in type like <code>int</code> is the <code>type 'type'</code> object. This has methods and attributes, also.</p>\n\n<pre><code>&gt;&gt;&gt; type(type(2))\n&lt;class 'type'&gt;\n</code></pre>\n" }, { "answer_id": 417721, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 4, "selected": false, "text": "<p>From a slide in <a href=\"http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/\" rel=\"noreferrer\">Structure and Interpretation of Computer Programs</a>, lecture 2A (1986), which in turns quotes <a href=\"http://en.wikipedia.org/wiki/Christopher_Strachey\" rel=\"noreferrer\">Christopher Stracey</a>:</p>\n\n<p><strong>The rights and privileges of first-class citizens:</strong></p>\n\n<ul>\n<li>To be named by variables.</li>\n<li>To be passed as arguments to procedures.</li>\n<li>To be returned as values of procedures.</li>\n<li>To be incorporated into data structures</li>\n</ul>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18770/" ]
When are objects or something else said to be "first-class" in a given programming language, and why? In what way do they differ from languages where they are not? When one says "everything is an object" (like in Python), do they indeed mean that "everything is first-class"?
In short, it means there are no restrictions on the object's use. It's the same as any other object. A first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have. > > Depending on the language, this can > imply: > > > * being expressible as an anonymous literal value > * being storable in variables > * being storable in data structures > * having an intrinsic identity (independent of any given name) > * being comparable for equality with other entities > * being passable as a parameter to a procedure/function > * being returnable as the result of a procedure/function > * being constructible at runtime > * being printable > * being readable > * being transmissible among distributed processes > * being storable outside running processes > > > [Source](http://en.wikipedia.org/wiki/First-class_object). In C++ functions themselves are not first class objects, however: * You can override the '()' operator making it possible to have an object function, which is first class. * Function pointers are first class. * boost bind, lambda and function do offer first class functions In C++, classes are not first class objects but instances of those classes are. In Python both the classes *and* the objects are first class objects. (See [this answer](https://stackoverflow.com/a/6581949/1612701) for more details about classes as objects). Here is an example of Javascript first class functions: ``` // f: function that takes a number and returns a number // deltaX: small positive number // returns a function that is an approximate derivative of f function makeDerivative( f, deltaX ) { var deriv = function(x) { return ( f(x + deltaX) - f(x) )/ deltaX; } return deriv; } var cos = makeDerivative( Math.sin, 0.000001); // cos(0) ~> 1 // cos(pi/2) ~> 0 ``` [Source](http://en.wikipedia.org/wiki/First-class_function). Entities that are not first class objects are referred to as second-class objects. Functions in C++ are second class because they can't be dynamically created. **Regarding the edit:** > > EDIT. When one says "everything is > an object" (like in Python), does he > indeed mean that "everything is > first-class"? > > > The term object can be used loosely and doesn't imply being first class. And it would probably make more sense to call the whole concept 'first class entities'. But in Python they do aim to make everything first class. I believe the intent of the person who made your statement meant first class.
245,236
<p>Is there a pure-Java equivalent to &lt;jsp:forward page="..." /&gt; that I can use within a &lt;% ... %> block?</p> <p>For example, I currently have a JSP page something like this:</p> <pre><code>&lt;% String errorMessage = SomeClass.getInstance().doSomething(); if (errorMessage != null) { session.setAttribute("error", errorMessage); %&gt; &lt;jsp:forward page="error.jsp" /&gt; &lt;% } else { String url = response.encodeRedirectURL("index.jsp"); response.sendRedirect(url); } %&gt; </code></pre> <p>Having to break the &lt;% ... %> block to use the jsp:forward is ugly and makes it harder to read due to indentation, among other things.</p> <p>So, can I do the forward in the Java code without use the JSP tag?</p> <p>Something like this would be ideal:</p> <pre><code>&lt;% String errorMessage = SomeClass.getInstance().doSomething(); if (errorMessage != null) { session.setAttribute("error", errorMessage); someObject.forward("error.jsp"); } else { String url = response.encodeRedirectURL("index.jsp"); response.sendRedirect(url); } %&gt; </code></pre>
[ { "answer_id": 245257, "author": "Adam", "author_id": 8604, "author_profile": "https://Stackoverflow.com/users/8604", "pm_score": 6, "selected": true, "text": "<p>The <code>someObject</code> you are looking for is <a href=\"http://java.sun.com/products/jsp/2.1/docs/jsp-2_1-pfd2/javax/servlet/jsp/PageContext.html#forward(java.lang.String)\" rel=\"noreferrer\">pageContext</a>.</p>\n\n<p>This object is implicitly defined in JSP, so you can use it like this:</p>\n\n<pre><code>pageContext.forward(\"&lt;some relative jsp&gt;\");\n</code></pre>\n" }, { "answer_id": 245515, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 3, "selected": false, "text": "<p>You really should try and avoid scriplets if you can, and in your case, a lot of what you are doing can be replaced with JSTL code. The following replacement for your example is much cleaner, IMO:</p>\n\n<pre><code>&lt;%\n // Consider moving to a servlet or controller/action class\n String errorMessage = SomeClass.getInstance().doSomething();\n pageContext.setAttribute(\"errorMessage\", errorMessage);\n%&gt;\n&lt;c:choose&gt;\n &lt;c:when test=\"${not empty errorMessage}\"&gt;\n &lt;c:set var=\"error\" scope=\"session\" value=\"${errorMessage}\" /&gt;\n &lt;jsp:forward page=\"error.jsp\" /&gt;\n &lt;/c:when&gt;\n &lt;c:otherwise&gt;\n &lt;c:redirect url=\"index.jsp\" /&gt;\n &lt;/c:otherwise&gt;\n&lt;/c:choose&gt;\n</code></pre>\n\n<p>Ideally, you'd modify error.jsp so that the error message doesn't even need to be set in the session, but I didn't want to change your design too much.</p>\n" }, { "answer_id": 246488, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>A simple approach:</p>\n\n<pre><code>&lt;%@page errorPage=\"Error.jsp\" %&gt;\n\n&lt;%\n String errorMessage = SomeClass.getInstance().doSomething();\n if (errorMessage != null) {\n throw new Exception(errorMessage); // Better throw the exception from doSomething()\n }\n pageContext.forward(\"index.jsp\");\n%&gt;\n\n\nError.jsp\n.........\n&lt;%@ page isErrorPage='true' %&gt;\n&lt;%\nout.print(\"Error!!!\"); \nout.print(exception.getMessage());\n%&gt;\n</code></pre>\n\n<p>Better approach:</p>\n\n<p>Invoke the doSomething() from a servlet.\nSet your error page in web.xml </p>\n\n<pre><code>&lt;error-page&gt;\n &lt;exception-type&gt;java.lang.Exception&lt;/exception-type&gt;\n &lt;location&gt;/WEB-INF/jsp/Error.jsp&lt;/location&gt;\n&lt;/error-page&gt;\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1119/" ]
Is there a pure-Java equivalent to <jsp:forward page="..." /> that I can use within a <% ... %> block? For example, I currently have a JSP page something like this: ``` <% String errorMessage = SomeClass.getInstance().doSomething(); if (errorMessage != null) { session.setAttribute("error", errorMessage); %> <jsp:forward page="error.jsp" /> <% } else { String url = response.encodeRedirectURL("index.jsp"); response.sendRedirect(url); } %> ``` Having to break the <% ... %> block to use the jsp:forward is ugly and makes it harder to read due to indentation, among other things. So, can I do the forward in the Java code without use the JSP tag? Something like this would be ideal: ``` <% String errorMessage = SomeClass.getInstance().doSomething(); if (errorMessage != null) { session.setAttribute("error", errorMessage); someObject.forward("error.jsp"); } else { String url = response.encodeRedirectURL("index.jsp"); response.sendRedirect(url); } %> ```
The `someObject` you are looking for is [pageContext](http://java.sun.com/products/jsp/2.1/docs/jsp-2_1-pfd2/javax/servlet/jsp/PageContext.html#forward(java.lang.String)). This object is implicitly defined in JSP, so you can use it like this: ``` pageContext.forward("<some relative jsp>"); ```
245,241
<p>I'd like to check ancestry using two jQuery objects. They don't have IDs, and are only going to be available as jQuery objects (or DOM nodes if you called <code>get()</code>). jQuery's <code>is()</code> only works with expressions, so this code would be ideal but will not work:</p> <pre><code>var someDiv = $('#div'); $('a').click(function() { if ($(this).parents().is(someDiv)) { alert('boo'); } } </code></pre> <p>Just want to see if one element is a child of another and I'd like to avoid stepping back into DOM land if possible.</p>
[ { "answer_id": 245266, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 5, "selected": true, "text": "<p>You can use the index() method to check if an element exists in a list, so would the following work?</p>\n\n<pre><code>var someDiv = $('#div');\n\n$('a').click(function() {\n if ($(this).parents().index(someDiv) &gt;= 0) {\n alert('boo');\n }\n}\n</code></pre>\n\n<p>From <a href=\"http://docs.jquery.com/Core/index#subject\" rel=\"nofollow noreferrer\">#index reference</a>.</p>\n" }, { "answer_id": 245291, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 1, "selected": false, "text": "<p>Along those lines, parents() optionally accepts a selector itself:</p>\n\n<pre><code>$('a').click(function() {\n if ($(this).parents(\"#div\").length) {\n alert('boo');\n }\n});\n</code></pre>\n" }, { "answer_id": 245310, "author": "jcampbell1", "author_id": 20512, "author_profile": "https://Stackoverflow.com/users/20512", "pm_score": 0, "selected": false, "text": "<p>One way would be to use the filter function</p>\n\n<pre><code>$('a').click(function() {\n $(this).parents().filter(function() {\n return this == someDiv[0];\n }).each(function() {\n alert('foo');\n })\n}\n</code></pre>\n\n<p>I think you may also be able to get away with using jQuery.inArray</p>\n\n<pre><code>if ($.inArray( someDiv, $(this).parents() ) ) {\n alert('boo');\n}\n</code></pre>\n" }, { "answer_id": 245321, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 0, "selected": false, "text": "<p>Would you not get the result you want from simply using a CSS selector?</p>\n\n<pre><code>$( '#div a' ).click( function() { ... } );\n</code></pre>\n" }, { "answer_id": 245640, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 3, "selected": false, "text": "<p>Checking for <code>(this).parents().index(someDiv) &gt;= 0</code>, as @Gareth suggests, will work just fine.</p>\n\n<p>However, using the <a href=\"http://plugins.jquery.com/project/ancestry\" rel=\"noreferrer\">jQuery ancestry plugin</a> is <strong>way faster / more efficient</strong>.</p>\n" }, { "answer_id": 246069, "author": "Pier Luigi", "author_id": 27789, "author_profile": "https://Stackoverflow.com/users/27789", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>var someDiv = $('#div');\n\n$('a').click(function() {\n if ($.inArray($(this).parents().get(), someDiv.get(0)) {\n alert('boo');\n }\n}\n</code></pre>\n" }, { "answer_id": 3615358, "author": "Jonas Fischer", "author_id": 436633, "author_profile": "https://Stackoverflow.com/users/436633", "pm_score": 0, "selected": false, "text": "<pre><code>var $element = $('a');\nwhile ($element &amp;&amp; !$element.is('someDiv')) {\n var $element = $element.parent();\n};\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32229/" ]
I'd like to check ancestry using two jQuery objects. They don't have IDs, and are only going to be available as jQuery objects (or DOM nodes if you called `get()`). jQuery's `is()` only works with expressions, so this code would be ideal but will not work: ``` var someDiv = $('#div'); $('a').click(function() { if ($(this).parents().is(someDiv)) { alert('boo'); } } ``` Just want to see if one element is a child of another and I'd like to avoid stepping back into DOM land if possible.
You can use the index() method to check if an element exists in a list, so would the following work? ``` var someDiv = $('#div'); $('a').click(function() { if ($(this).parents().index(someDiv) >= 0) { alert('boo'); } } ``` From [#index reference](http://docs.jquery.com/Core/index#subject).
245,251
<p>Is there an <strong>efficient</strong> way to create a file with a given size in Java?</p> <p>In C it can be done with <a href="http://linux.die.net/man/2/ftruncate" rel="noreferrer">ftruncate</a> (see <a href="https://stackoverflow.com/questions/139261/how-to-create-a-file-with-a-given-size-in-linux#245239">that answer</a>). </p> <p>Most people would just write <strong>n</strong> dummy bytes into the file, but there must be a faster way. I'm thinking of <a href="http://linux.die.net/man/2/ftruncate" rel="noreferrer">ftruncate</a> and also of <a href="http://en.wikipedia.org/wiki/Sparse_file" rel="noreferrer">Sparse files</a>…</p>
[ { "answer_id": 245271, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>You can open the file for writing, seek to offset (n-1), and write a single byte. The OS will automatically extend the file to the desired number of bytes.</p>\n" }, { "answer_id": 245278, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 8, "selected": true, "text": "<p>Create a new <a href=\"https://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html\" rel=\"noreferrer\">RandomAccessFile</a> and call the setLength method, specifying the desired file length. The underlying JRE implementation should use the most efficient method available in your environment.</p>\n\n<p>The following program</p>\n\n<pre><code>import java.io.*;\n\nclass Test {\n public static void main(String args[]) throws Exception {\n RandomAccessFile f = new RandomAccessFile(\"t\", \"rw\");\n f.setLength(1024 * 1024 * 1024);\n }\n}\n</code></pre>\n\n<p>on a Linux machine will allocate the space using the ftruncate(2)</p>\n\n<pre><code>6070 open(\"t\", O_RDWR|O_CREAT, 0666) = 4\n6070 fstat(4, {st_mode=S_IFREG|0644, st_size=0, ...}) = 0\n6070 lseek(4, 0, SEEK_CUR) = 0\n6070 ftruncate(4, 1073741824) = 0\n</code></pre>\n\n<p>while on a Solaris machine it will use the the F_FREESP64 function of the fcntl(2) system call.</p>\n\n<pre><code>/2: open64(\"t\", O_RDWR|O_CREAT, 0666) = 14\n/2: fstat64(14, 0xFE4FF810) = 0\n/2: llseek(14, 0, SEEK_CUR) = 0\n/2: fcntl(14, F_FREESP64, 0xFE4FF998) = 0\n</code></pre>\n\n<p>In both cases this will result in the creation of a sparse file.</p>\n" }, { "answer_id": 58261085, "author": "mandev", "author_id": 12173657, "author_profile": "https://Stackoverflow.com/users/12173657", "pm_score": 3, "selected": false, "text": "<p>Since Java 8, this method works on Linux and Windows :</p>\n\n<pre><code>final ByteBuffer buf = ByteBuffer.allocate(4).putInt(2);\nbuf.rewind();\n\nfinal OpenOption[] options = { StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW , StandardOpenOption.SPARSE };\nfinal Path hugeFile = Paths.get(\"hugefile.txt\");\n\ntry (final SeekableByteChannel channel = Files.newByteChannel(hugeFile, options);) {\n channel.position(HUGE_FILE_SIZE);\n channel.write(buf);\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4308/" ]
Is there an **efficient** way to create a file with a given size in Java? In C it can be done with [ftruncate](http://linux.die.net/man/2/ftruncate) (see [that answer](https://stackoverflow.com/questions/139261/how-to-create-a-file-with-a-given-size-in-linux#245239)). Most people would just write **n** dummy bytes into the file, but there must be a faster way. I'm thinking of [ftruncate](http://linux.die.net/man/2/ftruncate) and also of [Sparse files](http://en.wikipedia.org/wiki/Sparse_file)…
Create a new [RandomAccessFile](https://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html) and call the setLength method, specifying the desired file length. The underlying JRE implementation should use the most efficient method available in your environment. The following program ``` import java.io.*; class Test { public static void main(String args[]) throws Exception { RandomAccessFile f = new RandomAccessFile("t", "rw"); f.setLength(1024 * 1024 * 1024); } } ``` on a Linux machine will allocate the space using the ftruncate(2) ``` 6070 open("t", O_RDWR|O_CREAT, 0666) = 4 6070 fstat(4, {st_mode=S_IFREG|0644, st_size=0, ...}) = 0 6070 lseek(4, 0, SEEK_CUR) = 0 6070 ftruncate(4, 1073741824) = 0 ``` while on a Solaris machine it will use the the F\_FREESP64 function of the fcntl(2) system call. ``` /2: open64("t", O_RDWR|O_CREAT, 0666) = 14 /2: fstat64(14, 0xFE4FF810) = 0 /2: llseek(14, 0, SEEK_CUR) = 0 /2: fcntl(14, F_FREESP64, 0xFE4FF998) = 0 ``` In both cases this will result in the creation of a sparse file.
245,292
<p>I've been running into this problem with Flex for nearly a year, and each time I work up a quick hack solution that works for the time being. I'd like to see if anyone has a better idea.</p> <p>Here are the conditions of a problem:</p> <pre><code>|------Container ------------| | explicitHeight: 400 (or whatever) | | | |-------- VBox -------| | | | percentHeight: 100 | | | | | | | | |-Repeater------| | | | | | Potentially | | | | | | a lot of stuff. | | |--|--|---------------|---|---| </code></pre> <p>The problem is that, contrary to what I would like to happen, the VBox will ALWAYS expand to accommodate the content inside it, instead of sticking to the explicit height of its parent and creating a scroll bar.</p> <p>My solution has been to hard code in a reference to the parent (or however far up the display list we need to go to find an explicitly set value as opposed to a percentage).</p> <p>I've even considered using this in a utility class:</p> <pre><code>public static function getFirstExplicitHeightInDisplayList(comp:UIComponent):Number{ if (!isNaN(comp.explicitHeight)) return comp.explicitHeight; if (comp.parent is UIComponent) return getFirstExplicitHeightInDisplayList(UIComponent(comp.parent)); else return 0; } </code></pre> <p>Please tell me there's a better way.</p>
[ { "answer_id": 246363, "author": "netsuo", "author_id": 27911, "author_profile": "https://Stackoverflow.com/users/27911", "pm_score": 4, "selected": true, "text": "<p>You have to use the \"autoLayout\" parameter on the VBox as documentation say:<br /><br />\n<i>\"By default, the size of the VBox container is big enough to hold the image at it original size. If you disable layout updates, and use the Zoom effect to enlarge the image, or use the Move effect to reposition the image, the image might extend past the boundaries of the VBox container.</i><br /><br />\n<i>You set the autoLayout property to false, so the VBox container does not resize as the image resizes. If the image grows to a size so that it extends beyond the boundaries of the VBox container, the container adds scroll bars and clips the image at its boundaries.</i><br /><br /></p>\n\n<p>I hope that will help you.</p>\n" }, { "answer_id": 267370, "author": "Glenn", "author_id": 11814, "author_profile": "https://Stackoverflow.com/users/11814", "pm_score": 1, "selected": false, "text": "<p>Set the properties of your Container:</p>\n\n<pre><code>clipContent = true;\nverticalScrollPolicy = \"off\"\n</code></pre>\n\n<p>Then your VBox should automatically clip when it has <code>percentHeight = 100</code>;</p>\n\n<p>Works for me in Flex 3. </p>\n\n<p>If you need to get really fancy, you can set the scrollRect on objects:</p>\n\n<pre><code>scrollRect = new Rectangle(x, y, w, h);\n</code></pre>\n\n<p>depending on what you need it to do. </p>\n" }, { "answer_id": 375149, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>setting minHeight = 0 is all you need to do. </p>\n\n<p>This tells the VBox to ignore it's children's measurements when sizing itself, and calculate its height instead based on it's own/it's parents constraints. Set everything else as you normally would, scrolling and everything else will work perfectly.</p>\n\n<p>Spent DAYS on this one a year ago- it's not intuitive, they could have probably named the property better. Hope this saves u guys some time...</p>\n" }, { "answer_id": 417524, "author": "Dave", "author_id": 52129, "author_profile": "https://Stackoverflow.com/users/52129", "pm_score": 2, "selected": false, "text": "<p>AutoLayout=false seems to only prevent layout from being rerun when the childrens' <em>size</em> change. However if you add or remove children, layout will rerun anyway.</p>\n\n<p>Setting minHeight=0 does indeed completely disconnect the (outer) size of the VBox from the size and number of the children, which is what I wanted.</p>\n\n<p>Pawing through the Flex source code I didn't see the mechanism by which setting minHeight=0 made it work like I wanted, so I salute Yarin for discovering it. Thanks!</p>\n" }, { "answer_id": 14834046, "author": "user1919265", "author_id": 1919265, "author_profile": "https://Stackoverflow.com/users/1919265", "pm_score": 0, "selected": false, "text": "<p>In fact, Yarin Kessler brought us the only right answer here\n(unfortunately, i don't have the rights to comment its post, that's why i'm doing it here).</p>\n\n<p>When your HBox sizing is based on a percentage value, you are hoping that only its container will influence its size. That's wrong, there is an other rule, a stronger one.\nIt's the fact that a container (which HBox is) has a minimal size, which is the addition of the default/explicit sizes of its own childs components.</p>\n\n<p>So, if your percentage value result in a value smaller than the minimal size, the minimal size wins and applied to the HBox. Since the HBox is displaying all of its children, there is no need for scrollbars.</p>\n\n<p>So using :</p>\n\n<pre><code>minHeight = 0;\nminWidth = 0;\n</code></pre>\n\n<p>is like telling to the HBox that's its minimal size is 0 instead of its children default sizes. You are redefining it and that way the minimal size is smaller than the percentage value and lose the battle.</p>\n\n<p>The only phrase i found in Adobe documentation explaining this is this one :</p>\n\n<blockquote>\n <p>A percentage-based container size is advisory. Flex makes the container large enough to fit its children at their minimum sizes.</p>\n</blockquote>\n\n<p>Hope i made myself clear,</p>\n\n<p>(feel free to correct my incorrect english sentences...)</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23965/" ]
I've been running into this problem with Flex for nearly a year, and each time I work up a quick hack solution that works for the time being. I'd like to see if anyone has a better idea. Here are the conditions of a problem: ``` |------Container ------------| | explicitHeight: 400 (or whatever) | | | |-------- VBox -------| | | | percentHeight: 100 | | | | | | | | |-Repeater------| | | | | | Potentially | | | | | | a lot of stuff. | | |--|--|---------------|---|---| ``` The problem is that, contrary to what I would like to happen, the VBox will ALWAYS expand to accommodate the content inside it, instead of sticking to the explicit height of its parent and creating a scroll bar. My solution has been to hard code in a reference to the parent (or however far up the display list we need to go to find an explicitly set value as opposed to a percentage). I've even considered using this in a utility class: ``` public static function getFirstExplicitHeightInDisplayList(comp:UIComponent):Number{ if (!isNaN(comp.explicitHeight)) return comp.explicitHeight; if (comp.parent is UIComponent) return getFirstExplicitHeightInDisplayList(UIComponent(comp.parent)); else return 0; } ``` Please tell me there's a better way.
You have to use the "autoLayout" parameter on the VBox as documentation say: *"By default, the size of the VBox container is big enough to hold the image at it original size. If you disable layout updates, and use the Zoom effect to enlarge the image, or use the Move effect to reposition the image, the image might extend past the boundaries of the VBox container.* *You set the autoLayout property to false, so the VBox container does not resize as the image resizes. If the image grows to a size so that it extends beyond the boundaries of the VBox container, the container adds scroll bars and clips the image at its boundaries.* I hope that will help you.
245,317
<p>Has anyone else had any problems using google's Domain Tracking API, I am specifically talking about the _link() method.</p> <p><a href="http://code.google.com/apis/analytics/docs/gaJS/gaJSApiDomainDirectory.html#_gat.GA_Tracker_._link" rel="nofollow noreferrer">The documentation is here</a></p> <p>The example provided shows that the _link() method should be used in the onclick event like this:</p> <pre><code>&lt;a href="http://www.newsite.com" onclick="pageTracker._link('http://www.newsite.com');return false;"&gt;Go to our sister site&lt;/a&gt; </code></pre> <p>However, this essentially just makes the link...do nothing (most probably because of the 'return false').</p> <p>My understanding is that the pageTracker._link() method is 'supposed' to add additional parameters to the url and do it's own document.location style redirect.</p> <p>Any ideas / catches / previous posts??</p>
[ { "answer_id": 245330, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>You should ensure that you are using the correct version of <code>svnadmin</code> for your repository version. It's possible to get errors like this by using the wrong version.</p>\n\n<p>Having said that, version 1.3.x is pretty old now and you should consider upgrading to the latest 1.5.x.</p>\n\n<p>I also found through google that <a href=\"http://www.nabble.com/Re:-svn:-Invalid-diff-stream:-insn-0-cannot-be-decoded-p17756765.html\" rel=\"nofollow noreferrer\">some versions of SVNKit</a> can cause this problem.</p>\n" }, { "answer_id": 246471, "author": "SAL9000", "author_id": 11609, "author_profile": "https://Stackoverflow.com/users/11609", "pm_score": 2, "selected": false, "text": "<p>I do not know how to fix your actual problem, unfortunately. </p>\n\n<p>Regarding future preventive measures:\nI agree with Greg Hewgill: There are several known data repository corruption bugs in subversion 1.3.1. The last known one being patched in 1.4.6 (and also patched in all 1.5.x and all future versions of course). So you could upgrade to Ubuntu 8.04 (dapper drake), if possible, which comes with subversion 1.4.6 (as well as some ext3 file system patches). If you upgrade to dapper drake, make sure to reformat your ext3 partition with the dapper drake version of the e2fslibs and also do a bad block check with that (this might take several hours on big partitions):\ne2fsck -c -c -j /dev/</p>\n\n<p>Also, in many cases it is not subversion being responsible for repository corruptions, but the underlying platform (i.e. the hardware in most cases). Subversion trusts the underlying platform and does not do checksumming by itself. This means that if you really have a valuable source code repository and do not want to have to play back backups of uncorrupted repository backup versions from time to time, than you should invest some money and put the repository on a dedicated box with ECC memory, Solaris operating system and ZFS file system on a 3-way RAID-1 ZFS-mirror (redundant zfs softare raid mirror on three drives). ZFS checksums every bit before it goes to the storage controller, which ext3 does not.</p>\n\n<p><strong>Hardware bit errors do occur</strong> again and again in real life. Subversion does not detect those. So you have to use an OS with a file system which does checksumming as well as ECC memory.</p>\n" }, { "answer_id": 247155, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 2, "selected": true, "text": "<p>I had this same error with svnadmin 1.5 awhile back after renaming files and directories. Specifically I renamed some files from \"Filename\" to \"filename\" and SVN pretended it was okay with this... only to freak out later when I tried doing a fresh checkout. When I tried a fresh checkout I got a weird abort message about the files not existing.</p>\n\n<p>So this naturally led to me doing a svnadmin dump, followed by svnadmin verify only to get the same message that you specified. </p>\n\n<p>I don't know of a fix. I worked around this problem like so:</p>\n\n<ol>\n<li>Dumped the next previous version of the repository and ran svnadmin verify on the dump.</li>\n<li>If error still occurs goto step 1.</li>\n<li>After verifying a good dump, I deleted the entire SVN repository, recreated it, and imported from the good dump file. </li>\n</ol>\n\n<p>Make sure your dump file has all deltas so you get the change history up to the last good point. </p>\n\n<p>I lost a bit of code, but not too much to be really painful. </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/245317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25767/" ]
Has anyone else had any problems using google's Domain Tracking API, I am specifically talking about the \_link() method. [The documentation is here](http://code.google.com/apis/analytics/docs/gaJS/gaJSApiDomainDirectory.html#_gat.GA_Tracker_._link) The example provided shows that the \_link() method should be used in the onclick event like this: ``` <a href="http://www.newsite.com" onclick="pageTracker._link('http://www.newsite.com');return false;">Go to our sister site</a> ``` However, this essentially just makes the link...do nothing (most probably because of the 'return false'). My understanding is that the pageTracker.\_link() method is 'supposed' to add additional parameters to the url and do it's own document.location style redirect. Any ideas / catches / previous posts??
I had this same error with svnadmin 1.5 awhile back after renaming files and directories. Specifically I renamed some files from "Filename" to "filename" and SVN pretended it was okay with this... only to freak out later when I tried doing a fresh checkout. When I tried a fresh checkout I got a weird abort message about the files not existing. So this naturally led to me doing a svnadmin dump, followed by svnadmin verify only to get the same message that you specified. I don't know of a fix. I worked around this problem like so: 1. Dumped the next previous version of the repository and ran svnadmin verify on the dump. 2. If error still occurs goto step 1. 3. After verifying a good dump, I deleted the entire SVN repository, recreated it, and imported from the good dump file. Make sure your dump file has all deltas so you get the change history up to the last good point. I lost a bit of code, but not too much to be really painful.
245,334
<p>Ok, this is very weird. I'm trying to do a database migration, and all of a sudden, I'm getting these errors:</p> <pre> [C:\source\fe]: rake db:migrate --trace (in C:/source/fe) ** Invoke db:migrate (first_time) ** Invoke setup (first_time) ** Invoke gems:install (first_time) ** Invoke gems:set_gem_status (first_time) ** Execute gems:set_gem_status ** Execute gems:install rake aborted! can`'t activate rake (> 0.0.0), already activated rake-0.8.3] c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:139:in `activate' c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:155:in `activate' c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:154:in `each' c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:154:in `activate' c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:49:in `gem' C:/source/fe/config/../vendor/rails/railties/lib/rails/gem_dependency.rb:36:in `add_load_paths' C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:245:in `add_gem_load_paths' C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:245:in `each' C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:245:in `add_gem_load_paths' C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:97:in `send' C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:97:in `run' C:/source/fe/config/gems.rb:45:in `init_dependencies' C:/source/fe/lib/tasks/overridegems.rake:15 c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `call' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `execute' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `each' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `execute' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:578:in `invoke_with_call_chain' c:/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:588:in `invoke_prerequisites' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `each' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `invoke_prerequisites' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:577:in `invoke_with_call_chain' c:/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:588:in `invoke_prerequisites' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `each' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `invoke_prerequisites' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:577:in `invoke_with_call_chain' c:/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:564:in `invoke' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2019:in `invoke_task' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `each' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1991:in `top_level' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1970:in `run' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1967:in `run' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/bin/rake:31 c:/ruby/bin/rake:19:in `load' c:/ruby/bin/rake:19 [C:\source\fe]: </pre> <p>Any suggestions? I've tried uninstalling and reinstalling rake, as well as updating rails.</p> <p>FYI, I'm using Gem 1.1.1.</p> <p>I've also tried gem update rails, gem update rake and just about anything else.</p>
[ { "answer_id": 245340, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": -1, "selected": false, "text": "<pre><code>rake aborted!\ncan`'t activate rake\n</code></pre>\n\n<p>It is mid-Autumn - perhaps too many leaves have fallen and the rake can't be used. Try using the leaf-blower instead.</p>\n\n<p>Next time, keep up with the raking to prevent this.</p>\n" }, { "answer_id": 273134, "author": "Cameron Price", "author_id": 35526, "author_profile": "https://Stackoverflow.com/users/35526", "pm_score": 1, "selected": false, "text": "<p>I had a problem similar to this, which I ended up working around by hacking my rails version to not initialize active resource (by modifying the components method in /rails/railties/builtin/rails_info/rails/info.rb )</p>\n\n<p>This is clearly a hack, but I didn't have a chance to work out why active_resource specifically was causing the rake conflict, and since I wasn't using active_resource anyway, it got me through the night.</p>\n" }, { "answer_id": 296492, "author": "aronchick", "author_id": 4322, "author_profile": "https://Stackoverflow.com/users/4322", "pm_score": 3, "selected": true, "text": "<p>Interestingly, the solution here was that i needed to downgrade my rake version. The local version (in my C:\\ruby dir) was overriding the one in the source directory, and couldn't be loaded. I had done gem update and updated all my local gems. </p>\n\n<p>The commands were:</p>\n\n<pre><code>gem uninstall rake\ngem install rake -v ('= 1.5.1')\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4322/" ]
Ok, this is very weird. I'm trying to do a database migration, and all of a sudden, I'm getting these errors: ``` [C:\source\fe]: rake db:migrate --trace (in C:/source/fe) ** Invoke db:migrate (first_time) ** Invoke setup (first_time) ** Invoke gems:install (first_time) ** Invoke gems:set_gem_status (first_time) ** Execute gems:set_gem_status ** Execute gems:install rake aborted! can`'t activate rake (> 0.0.0), already activated rake-0.8.3] c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:139:in `activate' c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:155:in `activate' c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:154:in `each' c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:154:in `activate' c:/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:49:in `gem' C:/source/fe/config/../vendor/rails/railties/lib/rails/gem_dependency.rb:36:in `add_load_paths' C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:245:in `add_gem_load_paths' C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:245:in `each' C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:245:in `add_gem_load_paths' C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:97:in `send' C:/source/fe/config/../vendor/rails/railties/lib/initializer.rb:97:in `run' C:/source/fe/config/gems.rb:45:in `init_dependencies' C:/source/fe/lib/tasks/overridegems.rake:15 c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `call' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `execute' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `each' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `execute' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:578:in `invoke_with_call_chain' c:/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:588:in `invoke_prerequisites' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `each' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `invoke_prerequisites' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:577:in `invoke_with_call_chain' c:/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:588:in `invoke_prerequisites' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `each' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:585:in `invoke_prerequisites' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:577:in `invoke_with_call_chain' c:/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:564:in `invoke' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2019:in `invoke_task' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `each' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1991:in `top_level' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1970:in `run' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1967:in `run' c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/bin/rake:31 c:/ruby/bin/rake:19:in `load' c:/ruby/bin/rake:19 [C:\source\fe]: ``` Any suggestions? I've tried uninstalling and reinstalling rake, as well as updating rails. FYI, I'm using Gem 1.1.1. I've also tried gem update rails, gem update rake and just about anything else.
Interestingly, the solution here was that i needed to downgrade my rake version. The local version (in my C:\ruby dir) was overriding the one in the source directory, and couldn't be loaded. I had done gem update and updated all my local gems. The commands were: ``` gem uninstall rake gem install rake -v ('= 1.5.1') ```
245,342
<p>Does anybody know how to call the <code>import data</code> built-in dialog excel from a macro (vba)?</p> <p>I've tried <code>Application.Dialogs.Item(...).Show</code> but I can´t find the right dialog. Please help.</p> <p>Thanks in advance.</p>
[ { "answer_id": 245378, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 0, "selected": false, "text": "<p>If you choose the Object Browser and search for say, xlDialogImportTextFile, you will get a list of possible dialogs.</p>\n\n<p>EDIT:\nPerhaps something on these lines would suit:</p>\n\n<pre><code>'Allow user to select text file\nsf = Application _\n .GetOpenFilename(\"Text Files (*.txt), *.txt\")\nIf sf &lt;&gt; False Then\n 'Open text file\n Workbooks.OpenText sf\nEnd If\n</code></pre>\n" }, { "answer_id": 245385, "author": "Tom Mayfield", "author_id": 2314, "author_profile": "https://Stackoverflow.com/users/2314", "pm_score": 3, "selected": true, "text": "<p>The closest I can find using the dialog system is:</p>\n\n<pre><code>Application.Dialogs(xlDialogImportTextFile).Show\n</code></pre>\n\n<p>You can get a reference to the command bar button (at least for me in both 2k3 and 2k7) via:</p>\n\n<pre><code>Set button = Application.CommandBars.FindControl(ID:=6262)\n</code></pre>\n\n<p>But calling the <code>Execute</code> method on the button fails. Sadly, the short answer seems to be that it's not possible.</p>\n\n<p>You can add QueryTable objects by hand. While not an optimum path, you could design your own simple interface for selecting the source data.</p>\n" }, { "answer_id": 246054, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 0, "selected": false, "text": "<p>I don't think there is a VBA equivalent, because in one case you are returning data to a worksheet, while in the other case, the data is put into a recordset in memory.</p>\n\n<p>This kludge should pop up the dialog for you, however:</p>\n\n<pre><code>SendKeys \"%ddd\"\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24927/" ]
Does anybody know how to call the `import data` built-in dialog excel from a macro (vba)? I've tried `Application.Dialogs.Item(...).Show` but I can´t find the right dialog. Please help. Thanks in advance.
The closest I can find using the dialog system is: ``` Application.Dialogs(xlDialogImportTextFile).Show ``` You can get a reference to the command bar button (at least for me in both 2k3 and 2k7) via: ``` Set button = Application.CommandBars.FindControl(ID:=6262) ``` But calling the `Execute` method on the button fails. Sadly, the short answer seems to be that it's not possible. You can add QueryTable objects by hand. While not an optimum path, you could design your own simple interface for selecting the source data.
245,345
<p>I have a series of text that contains mixed numbers (ie: a whole part and a fractional part). The problem is that the text is full of human-coded sloppiness:</p> <ol> <li>The whole part may or may not exist (ex: "10")</li> <li>The fractional part may or may not exist (ex: "1/3")</li> <li>The two parts may be separated by spaces and/or a hyphens (ex: "10 1/3", "10-1/3", "10 - 1/3").</li> <li>The fraction itself may or may not have spaces between the number and the slash (ex: "1 /3", "1/ 3", "1 / 3").</li> <li>There may be other text after the fraction that needs to be ignored</li> </ol> <p>I need a regex that can parse these elements so that I can create a proper number out of this mess.</p>
[ { "answer_id": 245351, "author": "Craig Walker", "author_id": 3488, "author_profile": "https://Stackoverflow.com/users/3488", "pm_score": 5, "selected": true, "text": "<p>Here's a regex that will handle all of the data I can throw at it:</p>\n\n<pre><code>(\\d++(?! */))? *-? *(?:(\\d+) */ *(\\d+))?.*$\n</code></pre>\n\n<p>This will put the digits into the following groups:</p>\n\n<ol>\n<li>The whole part of the mixed number, if it exists</li>\n<li>The numerator, if a fraction exits</li>\n<li>The denominator, if a fraction exists</li>\n</ol>\n\n<p>Also, here's the RegexBuddy explanation for the elements (which helped me immensely when constructing it):</p>\n\n<pre><code>Match the regular expression below and capture its match into backreference number 1 «(\\d++(?! */))?»\n Between zero and one times, as many times as possible, giving back as needed (greedy) «?»\n Match a single digit 0..9 «\\d++»\n Between one and unlimited times, as many times as possible, without giving back (possessive) «++»\n Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?! */)»\n Match the character “ ” literally « *»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\n Match the character “/” literally «/»\nMatch the character “ ” literally « *»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\nMatch the character “-” literally «-?»\n Between zero and one times, as many times as possible, giving back as needed (greedy) «?»\nMatch the character “ ” literally « *»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\nMatch the regular expression below «(?:(\\d+) */ *(\\d+))?»\n Between zero and one times, as many times as possible, giving back as needed (greedy) «?»\n Match the regular expression below and capture its match into backreference number 2 «(\\d+)»\n Match a single digit 0..9 «\\d+»\n Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»\n Match the character “ ” literally « *»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\n Match the character “/” literally «/»\n Match the character “ ” literally « *»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\n Match the regular expression below and capture its match into backreference number 3 «(\\d+)»\n Match a single digit 0..9 «\\d+»\n Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»\nMatch any single character that is not a line break character «.*»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\nAssert position at the end of the string (or before the line break at the end of the string, if any) «$»\n</code></pre>\n" }, { "answer_id": 245399, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": false, "text": "<p>I think it may be easier to tackle the different cases (full mixed, fraction only, number only) separately from each other. For example:</p>\n\n<pre><code>sub parse_mixed {\n my($mixed) = @_;\n\n if($mixed =~ /^ *(\\d+)[- ]+(\\d+) *\\/ *(\\d)+(\\D.*)?$/) {\n return $1+$2/$3;\n } elsif($mixed =~ /^ *(\\d+) *\\/ *(\\d+)(\\D.*)?$/) {\n return $1/$2;\n } elsif($mixed =~ /^ *(\\d+)(\\D.*)?$/) {\n return $1;\n }\n}\n\nprint parse_mixed(\"10\"), \"\\n\";\nprint parse_mixed(\"1/3\"), \"\\n\";\nprint parse_mixed(\"1 / 3\"), \"\\n\";\nprint parse_mixed(\"10 1/3\"), \"\\n\";\nprint parse_mixed(\"10-1/3\"), \"\\n\";\nprint parse_mixed(\"10 - 1/3\"), \"\\n\";\n</code></pre>\n" }, { "answer_id": 249236, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 1, "selected": false, "text": "<p>If you are using <code>Perl 5.10</code>, this is how I would write it.</p>\n\n<pre>\nm{\n ^\n \\s* # skip leading spaces\n\n (?'whole'\n \\d++\n (?! \\s*[\\/] ) # there should not be a slash immediately following a whole number\n )\n\n \\s*\n\n (?: # the rest should fail or succeed as a group\n\n -? # ignore possible neg sign\n \\s*\n\n (?'numerator'\n \\d+\n )\n\n \\s*\n [\\/]\n \\s*\n\n (?'denominator'\n \\d+\n )\n )?\n}x\n</pre>\n\n<p>Then you can access the values from the <code>%+</code> variable like this:</p>\n\n<pre><code>$+{whole};\n$+{numerator};\n$+{denominator};\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
I have a series of text that contains mixed numbers (ie: a whole part and a fractional part). The problem is that the text is full of human-coded sloppiness: 1. The whole part may or may not exist (ex: "10") 2. The fractional part may or may not exist (ex: "1/3") 3. The two parts may be separated by spaces and/or a hyphens (ex: "10 1/3", "10-1/3", "10 - 1/3"). 4. The fraction itself may or may not have spaces between the number and the slash (ex: "1 /3", "1/ 3", "1 / 3"). 5. There may be other text after the fraction that needs to be ignored I need a regex that can parse these elements so that I can create a proper number out of this mess.
Here's a regex that will handle all of the data I can throw at it: ``` (\d++(?! */))? *-? *(?:(\d+) */ *(\d+))?.*$ ``` This will put the digits into the following groups: 1. The whole part of the mixed number, if it exists 2. The numerator, if a fraction exits 3. The denominator, if a fraction exists Also, here's the RegexBuddy explanation for the elements (which helped me immensely when constructing it): ``` Match the regular expression below and capture its match into backreference number 1 «(\d++(?! */))?» Between zero and one times, as many times as possible, giving back as needed (greedy) «?» Match a single digit 0..9 «\d++» Between one and unlimited times, as many times as possible, without giving back (possessive) «++» Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?! */)» Match the character “ ” literally « *» Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» Match the character “/” literally «/» Match the character “ ” literally « *» Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» Match the character “-” literally «-?» Between zero and one times, as many times as possible, giving back as needed (greedy) «?» Match the character “ ” literally « *» Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» Match the regular expression below «(?:(\d+) */ *(\d+))?» Between zero and one times, as many times as possible, giving back as needed (greedy) «?» Match the regular expression below and capture its match into backreference number 2 «(\d+)» Match a single digit 0..9 «\d+» Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» Match the character “ ” literally « *» Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» Match the character “/” literally «/» Match the character “ ” literally « *» Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» Match the regular expression below and capture its match into backreference number 3 «(\d+)» Match a single digit 0..9 «\d+» Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» Match any single character that is not a line break character «.*» Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» Assert position at the end of the string (or before the line break at the end of the string, if any) «$» ```
245,349
<p>I'd like to show an image in an iPhone app, but the image I'm using is too big. I'd like to scale it to fit the iPhone screen, I can't find any class to handle it.</p>
[ { "answer_id": 245364, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 5, "selected": true, "text": "<pre><code>UIImageView* view = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @\"your_image.png\"]];\nview.frame = CGRectMake(0, 0, width, height);\n</code></pre>\n\n<p>To get the frame of the iPhone screen you can use</p>\n\n<pre><code>CGRect frame = [[UIScreen mainScreen] bounds];\n</code></pre>\n" }, { "answer_id": 245459, "author": "BlueDolphin", "author_id": 32096, "author_profile": "https://Stackoverflow.com/users/32096", "pm_score": 0, "selected": false, "text": "<p>My ImageView was set in IB, and I would need to show multiple images, so set the image of imageView, instead of creating ImageView for individual image. </p>\n\n<p>After I set the image view frame size, I am still see the same result, the image was too big, so that only part of the image was displayed on the screen.</p>\n" }, { "answer_id": 245473, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 4, "selected": false, "text": "<p>In Interface Builder, select your UIImageView. From the Tools menu, select \"Attribute Inspector\". In the Image View Attributes palette, select \"Scale to Fill\" from the Mode popup. That should scale your image to fit.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32096/" ]
I'd like to show an image in an iPhone app, but the image I'm using is too big. I'd like to scale it to fit the iPhone screen, I can't find any class to handle it.
``` UIImageView* view = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"your_image.png"]]; view.frame = CGRectMake(0, 0, width, height); ``` To get the frame of the iPhone screen you can use ``` CGRect frame = [[UIScreen mainScreen] bounds]; ```
245,352
<p>I have the following intentionally trivial function:</p> <pre><code>void ReplaceSome(ref string text) { StringBuilder sb = new StringBuilder(text); sb[5] = 'a'; text = sb.ToString(); } </code></pre> <p>It appears to be inefficient to convert this to a StringBuilder to index into and replace some of the characters only to copy it back to the ref'd param. Is it possible to index directly into the text param as an L-Value?</p> <p>Or how else can I improve this?</p>
[ { "answer_id": 245371, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": -1, "selected": false, "text": "<p>I don't know if this is more efficient, but it works. Either way you'll have to recreate the string after each change since they're immutable.</p>\n\n<pre><code> string test = \"hello world\";\n Console.WriteLine(test);\n\n test = test.Remove(5, 1);\n test = test.Insert(5, \"z\");\n\n Console.WriteLine(test);\n</code></pre>\n\n<p>Or if you want it more concise:</p>\n\n<pre><code>string test = \"hello world\".Remove(5, 1).Insert(5, \"z\");\n</code></pre>\n" }, { "answer_id": 245373, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 3, "selected": true, "text": "<p>C# strings are \"immutable,\" which means that they can't be modified. If you have a string, and you want a similar but different string, you must create a new string. Using a StringBuilder as you do above is probably as easy a method as any.</p>\n" }, { "answer_id": 245379, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": -1, "selected": false, "text": "<pre><code>text = text.Substring(0, 4) + \"a\" + text.Substring(5);\n</code></pre>\n\n<p>Not dramatically different than your StringBuilder solution, but slightly more concise than the Remove(), Insert() answer.</p>\n" }, { "answer_id": 245449, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 2, "selected": false, "text": "<p>Armed with Reflector and the decompiled IL - On a pure LOC basis then the StringBuilder approach is definitely the most efficient. Eg tracing the IL calls that StringBuilder makes internally vs the IL calls for String::Remove and String::Insert etc. </p>\n\n<p>I couldn't be bothered testing the memory overhead of each approach, but would imagine it would be in line with reflector results - the StringBuilder approach would be the best.</p>\n\n<p>I think the fact the StringBuilder has a set memory size using the constructor </p>\n\n<pre><code>StringBuilder sb = new StringBuilder(text);\n</code></pre>\n\n<p>would help overall too.</p>\n\n<p>Like others have mentioned, it would come down to readability vs efficiency... </p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
I have the following intentionally trivial function: ``` void ReplaceSome(ref string text) { StringBuilder sb = new StringBuilder(text); sb[5] = 'a'; text = sb.ToString(); } ``` It appears to be inefficient to convert this to a StringBuilder to index into and replace some of the characters only to copy it back to the ref'd param. Is it possible to index directly into the text param as an L-Value? Or how else can I improve this?
C# strings are "immutable," which means that they can't be modified. If you have a string, and you want a similar but different string, you must create a new string. Using a StringBuilder as you do above is probably as easy a method as any.
245,354
<p>I'm fairly new to Castle Windsor and am looking into the in's and out's of the logging facility. It seems fairly impressive but the only thing i can't work out is where Windsor sets the Logger property on my classes. As in the following code will set Logger to the nullLogger if the class hasn't been setup yet but when Resolve is finished running the Logger property is set. </p> <pre><code>private ILogger logger; public ILogger Logger { get { if (logger == null) logger = NullLogger.Instance; return logger; } set { logger = value; } } </code></pre> <p>So what I am wondering is how and where windsor sets my Logger property. </p> <p>Cheers Anthony</p>
[ { "answer_id": 245478, "author": "Todd", "author_id": 31940, "author_profile": "https://Stackoverflow.com/users/31940", "pm_score": 4, "selected": false, "text": "<p>The logger is setup by the logging facility, which is in the <code>&lt;facilities&gt;</code> section of the configuration. For example to use log4net your app or web.config would look something like this:</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;configuration&gt;\n &lt;configSections&gt;\n &lt;section name=\"castle\" type=\"Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor\"/&gt;\n &lt;/configSections&gt;\n&lt;Configuration&gt;\n\n&lt;castle&gt;\n\n &lt;facilities&gt;\n &lt;facility id=\"loggingfacility\" \n type=\"Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging\" \n loggingApi=\"log4net\" \n configFile=\"logging.config\" /&gt;\n &lt;/facilities&gt;\n\n&lt;/castle&gt;\n&lt;/configuration&gt;\n</code></pre>\n" }, { "answer_id": 258826, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": 1, "selected": false, "text": "<p>Since you have a public Property with a Setter, every time you resolve your object from Windsor, it will also try to set any public properties with appropriate values from the container (in your case, an ILogger which your facility will populate into Windsor).</p>\n\n<p>Meaning, if you resolve the Class from Windsor, this will be set. But not if you do new Class().</p>\n\n<p>That's atleast how I understand it.</p>\n\n<p>The other approach is to use constructors, meaning if you have a constructor named </p>\n\n<p>public Class(ILogger logger) it will be instantiated with ILogger as a parameter. </p>\n\n<p>Example:</p>\n\n<pre>\n\nvar yourClassObject = Kernel.Resolve&lt;IClass&gt;();\n\n</pre>\n\n<p>IF you don't have an interface specification (and registered as such), you will need to register your component as the concrete type if you want to resolve it using that concrete type(and not by interface).</p>\n" }, { "answer_id": 1572119, "author": "UpTheCreek", "author_id": 324381, "author_profile": "https://Stackoverflow.com/users/324381", "pm_score": 4, "selected": false, "text": "<p>You can also configure this programatically when you initialise windsor (e.g. from your global.asax.cs):</p>\n\n<pre><code>container.AddFacility(\"logging\", new LoggingFacility(LoggerImplementation.Log4net));\n</code></pre>\n\n<p>You can of course choose any of the logger implimentations.</p>\n\n<p>This this will be wired up whenever windsor instantiates any class expecting a logger. I wouldn't put this in the constructor as it's a cross cutting concern - better to do like you suggested in my opinion. You can simplify it a little:</p>\n\n<pre><code> private ILogger logger = NullLogger.Instance;\n public ILogger Logger\n {\n get { return logger; }\n set { logger = value; }\n }\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30572/" ]
I'm fairly new to Castle Windsor and am looking into the in's and out's of the logging facility. It seems fairly impressive but the only thing i can't work out is where Windsor sets the Logger property on my classes. As in the following code will set Logger to the nullLogger if the class hasn't been setup yet but when Resolve is finished running the Logger property is set. ``` private ILogger logger; public ILogger Logger { get { if (logger == null) logger = NullLogger.Instance; return logger; } set { logger = value; } } ``` So what I am wondering is how and where windsor sets my Logger property. Cheers Anthony
The logger is setup by the logging facility, which is in the `<facilities>` section of the configuration. For example to use log4net your app or web.config would look something like this: ``` <?xml version="1.0"?> <configuration> <configSections> <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/> </configSections> <Configuration> <castle> <facilities> <facility id="loggingfacility" type="Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging" loggingApi="log4net" configFile="logging.config" /> </facilities> </castle> </configuration> ```
245,369
<p>If I have the following string:</p> <pre><code>string s = "abcdefghab"; </code></pre> <p>Then how do I get a string (or char[]) that has just the characters that are repeated in the original string using C# and LINQ. In my example I want to end up with "ab".</p> <p>Although not necessary, I was trying to do this in a single line of LINQ and had so far come up with:</p> <pre><code>s.ToCharArray().OrderBy(a =&gt; a)... </code></pre>
[ { "answer_id": 245363, "author": "Benson", "author_id": 13816, "author_profile": "https://Stackoverflow.com/users/13816", "pm_score": 3, "selected": false, "text": "<p>There isn't likely to be a foolproof method, as that's an intrusion into the privacy of the user. </p>\n\n<p>One thing that comes to mind is checking for a referrer. If the user arrived at your page without following a link, they a) typed the url, b) followed a bookmark, or c) have your page set as their homepage. But that's about the best I can do. </p>\n" }, { "answer_id": 245365, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": false, "text": "<p>Nope. You can tell if they got to your page by following a link or not. Check the referrer. However, the browser going to your page as the home page will not appear any different than the user typing in your page or using a bookmark.</p>\n" }, { "answer_id": 245389, "author": "Chris Ballance", "author_id": 1551, "author_profile": "https://Stackoverflow.com/users/1551", "pm_score": 0, "selected": false, "text": "<p>Simple solution, you shouldn't be checking if you or anyone else's site is set as the user's homepage. If they want it as their homepage, they'll make it so. </p>\n\n<p>However, if you've got some Javascript that will check their email and see if they've sent links to your site to their friends or colleagues, I'd be <strong>very</strong> interested in that functionality ;-)</p>\n" }, { "answer_id": 245621, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 1, "selected": true, "text": "<p>Mozilla/Firefox has a <a href=\"https://developer.mozilla.org/En/DOM/Window.home\" rel=\"nofollow noreferrer\"><code>window.home()</code></a> method which loads the user's home page. This method could be used (in an iframe, maybe) combined with server access logging, to see if the site's home page is instantly requested loaded by the current user.</p>\n\n<p>However, other browsers don't seem to support this javascript method.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
If I have the following string: ``` string s = "abcdefghab"; ``` Then how do I get a string (or char[]) that has just the characters that are repeated in the original string using C# and LINQ. In my example I want to end up with "ab". Although not necessary, I was trying to do this in a single line of LINQ and had so far come up with: ``` s.ToCharArray().OrderBy(a => a)... ```
Mozilla/Firefox has a [`window.home()`](https://developer.mozilla.org/En/DOM/Window.home) method which loads the user's home page. This method could be used (in an iframe, maybe) combined with server access logging, to see if the site's home page is instantly requested loaded by the current user. However, other browsers don't seem to support this javascript method.
245,395
<p>What are some of the lesser know, but important and useful features of Windows batch files?</p> <p>Guidelines:</p> <ul> <li>One feature per answer</li> <li>Give both a short <strong>description</strong> of the feature and an <strong>example</strong>, not just a link to documentation</li> <li>Limit answers to <strong>native funtionality</strong>, i.e., does not require additional software, like the <em>Windows Resource Kit</em></li> </ul> <p>Clarification: We refer here to scripts that are processed by cmd.exe, which is the default on WinNT variants.</p> <p>(See also: <a href="https://stackoverflow.com/questions/148968/windows-batch-files-bat-vs-cmd">Windows batch files: .bat vs .cmd?</a>)</p>
[ { "answer_id": 245398, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 6, "selected": false, "text": "<p>I have always found it difficult to read comments that are marked by a keyword on each line:</p>\n\n<pre><code>REM blah blah blah\n</code></pre>\n\n<p>Easier to read:</p>\n\n<pre><code>:: blah blah blah\n</code></pre>\n" }, { "answer_id": 245403, "author": "RealHowTo", "author_id": 25122, "author_profile": "https://Stackoverflow.com/users/25122", "pm_score": 6, "selected": false, "text": "<p>The path (with drive) where the script is : ~dp0</p>\n\n<pre><code>set BAT_HOME=%~dp0\necho %BAT_HOME%\ncd %BAT_HOME%\n</code></pre>\n" }, { "answer_id": 245407, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 6, "selected": false, "text": "<p>Variable substrings:</p>\n\n<pre><code>&gt; set str=0123456789\n&gt; echo %str:~0,5%\n01234\n&gt; echo %str:~-5,5%\n56789\n&gt; echo %str:~3,-3%\n3456\n</code></pre>\n" }, { "answer_id": 245412, "author": "raven", "author_id": 4228, "author_profile": "https://Stackoverflow.com/users/4228", "pm_score": 7, "selected": false, "text": "<pre><code>PUSHD path\n</code></pre>\n\n<p>Takes you to the directory specified by <em>path</em>.</p>\n\n<pre><code>POPD\n</code></pre>\n\n<p>Takes you back to the directory you \"pushed\" from.</p>\n" }, { "answer_id": 245414, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 6, "selected": false, "text": "<p><a href=\"http://www.robvanderwoude.com/ntfor.html\" rel=\"nofollow noreferrer\">The FOR command</a>! While I hate writing batch files, I'm thankful for it.</p>\n\n<pre><code>FOR /F \"eol=; tokens=2,3* delims=, \" %i in (myfile.txt) do @echo %i %j %k\n</code></pre>\n\n<p>would parse each line in myfile.txt, ignoring lines that begin with a semicolon, passing the 2nd and 3rd token from each line to the for body, with tokens delimited by commas and/or spaces.\nNotice the for body statements reference %i to get the 2nd token, %j to get the 3rd token, and %k to get all remaining tokens after the 3rd.</p>\n\n<p>You can also use this to iterate over directories, directory contents, etc...</p>\n" }, { "answer_id": 245417, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 4, "selected": false, "text": "<p>Integer arithmetic:</p>\n\n<pre><code>&gt; SET /A result=10/3 + 1\n4\n</code></pre>\n" }, { "answer_id": 245419, "author": "rbrayb", "author_id": 9922, "author_profile": "https://Stackoverflow.com/users/9922", "pm_score": 5, "selected": false, "text": "<p>Creating an empty file:</p>\n\n<pre><code>&gt; copy nul filename.ext\n</code></pre>\n" }, { "answer_id": 245425, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 5, "selected": false, "text": "<p>By using CALL, EXIT /B, SETLOCAL &amp; ENDLOCAL you can implement subroutines with local variables.</p>\n\n<p>example:</p>\n\n<pre><code>@echo off\n\nset x=xxxxx\ncall :sub 10\necho %x%\nexit /b\n\n:sub\nsetlocal\nset /a x=%1 + 1\necho %x%\nendlocal\nexit /b\n</code></pre>\n\n<p>This will print</p>\n\n<pre><code>11\nxxxxx\n</code></pre>\n\n<p>even though :sub modifies x.</p>\n" }, { "answer_id": 245428, "author": "raven", "author_id": 4228, "author_profile": "https://Stackoverflow.com/users/4228", "pm_score": 5, "selected": false, "text": "<pre><code>PAUSE\n</code></pre>\n\n<p>Stops execution and displays the following prompt:</p>\n\n<pre>Press any key to continue . . .</pre>\n\n<p>Useful if you want to run a batch by double-clicking it in Windows Explorer and want to actually see the output rather than just a flash of the command window.</p>\n" }, { "answer_id": 245430, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "<p>Total control over output with spacing and escape characters.:</p>\n\n<pre><code>echo. ^&lt;resourceDir^&gt;/%basedir%/resources^&lt;/resourceDir^&gt;\n</code></pre>\n" }, { "answer_id": 245434, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 9, "selected": true, "text": "<p>Line continuation:</p>\n\n<pre><code>call C:\\WINDOWS\\system32\\ntbackup.exe ^\n backup ^\n /V:yes ^\n /R:no ^\n /RS:no ^\n /HC:off ^\n /M normal ^\n /L:s ^\n @daily.bks ^\n /F daily.bkf\n</code></pre>\n" }, { "answer_id": 245435, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "<p>Subroutines (outputs 42):</p>\n\n<pre><code> @echo off\n call :answer 42\n goto :eof\n:do_something\n echo %1\n goto :eof\n</code></pre>\n\n<p>and subroutines returning a value (outputs 0, 1, 2, and so on):</p>\n\n<pre><code> @echo off\n setlocal enableextensions enabledelayedexpansion\n call :seq_init seq1\n:loop1\n if not %seq1%== 10 (\n call :seq_next seq1\n echo !seq1!\n goto :loop1\n )\n endlocal\n goto :eof\n\n:seq_init\n set /a \"%1 = -1\"\n goto :eof\n:seq_next\n set /a \"seq_next_tmp1 = %1\"\n set /a \"%1 = %seq_next_tmp1% + 1\"\n set seq_next_tmp1=\n goto :eof\n</code></pre>\n" }, { "answer_id": 245440, "author": "raven", "author_id": 4228, "author_profile": "https://Stackoverflow.com/users/4228", "pm_score": 2, "selected": false, "text": "<p>I find the ease with which you can redirect the output of commands to files extremely useful:</p>\n\n<pre><code>DIR *.txt &gt; tmp.txt\nDIR *.exe &gt;&gt; tmp.txt\n</code></pre>\n\n<p>Single arrow creates, or overwrites the file, double arrow appends to it. Now I can open tmp.txt in my text editor and do all kinds of good stuff.</p>\n" }, { "answer_id": 245442, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": false, "text": "<p>Delayed expansion of variables (with substrings thrown in for good measure):</p>\n\n<pre><code> @echo off\n setlocal enableextensions enabledelayedexpansion\n set full=/u01/users/pax\n:loop1\n if not \"!full:~-1!\" == \"/\" (\n set full2=!full:~-1!!full2!\n set full=!full:~,-1!\n goto :loop1\n )\n echo !full!\n endlocal\n</code></pre>\n" }, { "answer_id": 245455, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 5, "selected": false, "text": "<p>Sneaky trick to wait N seconds (not part of cmd.exe but isn't extra software since it comes with Windows), see the ping line. You need N+1 pings since the first ping goes out without a delay.</p>\n\n<pre><code> echo %time%\n call :waitfor 5\n echo %time%\n goto :eof\n:waitfor\n setlocal\n set /a \"t = %1 + 1\"\n &gt;nul ping 127.0.0.1 -n %t%\n endlocal\n goto :eof\n</code></pre>\n" }, { "answer_id": 245498, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": false, "text": "<p>Output a blank line:</p>\n\n<pre><code>echo.\n</code></pre>\n" }, { "answer_id": 245504, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "<p>The subdirectory option on 'remove directory':</p>\n\n<pre><code>rd /s /q junk\n</code></pre>\n" }, { "answer_id": 245511, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "<p>For loops with numeric counters (outputs 1 through 10):</p>\n\n<pre><code>for /l %i in (1,1,10) do echo %i\n</code></pre>\n" }, { "answer_id": 245518, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 5, "selected": false, "text": "<p>Being able to run commands and process the output (like backticks of '$()' in bash).</p>\n\n<pre><code>for /f %i in ('dir /on /b *.jpg') do echo --^&gt; %i\n</code></pre>\n\n<p>If there are spaces in filenames, use this:</p>\n\n<pre><code>for /f \"tokens=*\" %i in ('dir /on /b *.jpg') do echo --^&gt; %i\n</code></pre>\n" }, { "answer_id": 245635, "author": "RealHowTo", "author_id": 25122, "author_profile": "https://Stackoverflow.com/users/25122", "pm_score": 4, "selected": false, "text": "<p>To quickly convert an Unicode text file (16bit/char) to a ASCII DOS file (8bit/char).</p>\n\n<pre><code>C:\\&gt; type unicodeencoded.txt &gt; dosencoded.txt\n</code></pre>\n\n<p>as a bonus, if possible, characters are correctly mapped.</p>\n" }, { "answer_id": 245641, "author": "LeopardSkinPillBoxHat", "author_id": 22489, "author_profile": "https://Stackoverflow.com/users/22489", "pm_score": 7, "selected": false, "text": "<p>Not sure how useful this would be in a <em>batch</em> file, but it's a very convenient command to use in the command prompt:</p>\n\n<pre><code>C:\\some_directory&gt; start .\n</code></pre>\n\n<p>This will open up Windows Explorer in the \"some_directory\" folder.</p>\n\n<p>I have found this a great time-saver.</p>\n" }, { "answer_id": 245774, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 4, "selected": false, "text": "<p>if block structure:</p>\n\n<pre><code>if \"%VS90COMNTOOLS%\"==\"\" (\n echo: Visual Studio 2008 is not installed\n exit /b\n)\n</code></pre>\n" }, { "answer_id": 245982, "author": "RWendi", "author_id": 15152, "author_profile": "https://Stackoverflow.com/users/15152", "pm_score": 0, "selected": false, "text": "<p>here's one trick that I use to run My Nant Build script consecutively without having to click the batch file over and over again.</p>\n\n<pre><code>:CODELINE\nNANT.EXE -buildfile:alltargets.build -l:build.log build.product\n@pause\nGOTO :CODELINE\n</code></pre>\n\n<p>What will happen is that after your solution finished building, it will be paused. And then if you press any key it will rerun the build script again. Very handy I must say.</p>\n" }, { "answer_id": 246210, "author": "remonedo", "author_id": 11920, "author_profile": "https://Stackoverflow.com/users/11920", "pm_score": 3, "selected": false, "text": "<p>TheSoftwareJedi already mentioned the for command, but I'm going to mention it again as it is very powerful.</p>\n\n<p>The following outputs the current date in the format YYYYMMDD, I use this when generating directories for backups.</p>\n\n<pre><code>for /f \"tokens=2-4 delims=/- \" %a in ('DATE/T') do echo %c%b%a\n</code></pre>\n" }, { "answer_id": 246691, "author": "aphoria", "author_id": 2441, "author_profile": "https://Stackoverflow.com/users/2441", "pm_score": 5, "selected": false, "text": "<p>To hide all output from a command redirect to >nul 2>&amp;1.</p>\n\n<p>For example, the some command line programs display output even if you redirect to >nul. But, if you redirect the output like the line below, all the output will be suppressed.</p>\n\n<pre><code>PSKILL NOTEPAD &gt;nul 2&gt;&amp;1\n</code></pre>\n\n<p>EDIT: See <a href=\"http://blogs.msdn.com/myocom/archive/2005/06/08/427043.aspx\" rel=\"nofollow noreferrer\">Ignoring the output of a command</a> for an explanation of how this works.</p>\n" }, { "answer_id": 248573, "author": "RealHowTo", "author_id": 25122, "author_profile": "https://Stackoverflow.com/users/25122", "pm_score": 1, "selected": false, "text": "<p>Here how to build a CLASSPATH by scanning a given directory.</p>\n\n<pre><code>setlocal ENABLEDELAYEDEXPANSION\nif defined CLASSPATH (set CLASSPATH=%CLASSPATH%;.) else (set CLASSPATH=.)\nFOR /R .\\lib %%G IN (*.jar) DO set CLASSPATH=!CLASSPATH!;%%G\nEcho The Classpath definition is %CLASSPATH%\n</code></pre>\n\n<p>works in XP (or better). With W2K, you need to use a couple of BAT files to achieve the same result (see <a href=\"http://www.rgagnon.com/javadetails/java-0587.html\" rel=\"nofollow noreferrer\">Include all jars in the classpath definition</a> ).</p>\n\n<p>It's not needed for 1.6 since you can specify a wildcard directly in CLASSPATH (ex. -cp \".\\lib*\").</p>\n" }, { "answer_id": 252310, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 1, "selected": false, "text": "<p>Multiple commands in one line, useful in many situations:</p>\n\n<p>&amp; Used to combine two commands, executes command1 and then command2<br>\n&amp;&amp; A conditional combination, executes command2 if command1 completes successfully<br>\n¦¦ Command2 executes only if command1 does not complete successfully.</p>\n\n<p>Examples:</p>\n\n<pre><code>:: ** Edit the most recent .TXT file and exit, useful in a .CMD / .BAT **\nFOR /F %%I IN ('DIR *.TXT /B /O:-N') DO NOTEPAD %%I &amp; EXIT\n\n\n:: ** If exist any .TXT file, display the list in NOTEPAD, if not it \n:: ** exits without any error (note the &amp;&amp; and the 2&gt; error redirection)\nDIR *.TXT &gt; TXT.LST 2&gt; NUL &amp;&amp; NOTEPAD TXT.LST\n</code></pre>\n" }, { "answer_id": 252402, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>You can chain if statements to get an effect like a short-circuiting boolean `and'.</p>\n\n<pre><code>if foo if bar baz\n</code></pre>\n" }, { "answer_id": 252404, "author": "MoreThanChaos", "author_id": 24824, "author_profile": "https://Stackoverflow.com/users/24824", "pm_score": 4, "selected": false, "text": "<p>example of string subtraction on <code>date</code> and <code>time</code> to get file named \"YYYY-MM-DD HH:MM:SS.txt\"</p>\n\n<blockquote>\n <p><code>echo test &gt; \"%date:~0,4%-%date:~5,2%-%date:~8,2% %time:~0,2%_%time:~3,2%_%time:~6,2%.txt\"</code></p>\n</blockquote>\n\n<p>I use <code>color</code> to indicate if my script end up successfully, failed, or need some input by changing color of text and background. It really helps when you have some machine in reach of your view but quite far away</p>\n\n<blockquote>\n <p>color XY</p>\n</blockquote>\n\n<p>where X and Y is hex value from <code>0</code> to <code>F</code>, where X - background, Y - text, when X = Y color will not change.</p>\n\n<blockquote>\n <p>color Z</p>\n</blockquote>\n\n<p>changes text color to 'Z' and sets black background, 'color 0' won't work </p>\n\n<p>for names of colors call </p>\n\n<blockquote>\n <p>color ?</p>\n</blockquote>\n" }, { "answer_id": 252443, "author": "SqlACID", "author_id": 19797, "author_profile": "https://Stackoverflow.com/users/19797", "pm_score": 4, "selected": false, "text": "<p>Search and replace when setting environment variables:</p>\n\n<pre><code>&gt; @set fname=%date:/=%\n</code></pre>\n\n<p>...removes the \"/\" from a date for use in timestamped file names.</p>\n\n<p>and substrings too...</p>\n\n<pre><code>&gt; @set dayofweek=%fname:~0,3%\n</code></pre>\n" }, { "answer_id": 252470, "author": "Dean Rather", "author_id": 14966, "author_profile": "https://Stackoverflow.com/users/14966", "pm_score": 2, "selected": false, "text": "<p><b>/c</b> param for the cmd.exe itself, tells it to run and then do these commands.</p>\n\n<p>I used to find myself frequently doing:</p>\n\n<p><b>win+r</b>, <b>cmd</b> RETURN, <b>ping google.com</b> RETURN</p>\n\n<p>but now I just do:</p>\n\n<p><b>win+r</b>, <b>cmd /c ping google.com</b> RETURN</p>\n\n<p>much faster. also helpful if you're using pstools and you want to use psexec to do some command line function on the remote machine.</p>\n\n<p><b>EDIT:</b> <b>/k</b> Works the same, but leaves the prompt open. This might come in handy more often.</p>\n" }, { "answer_id": 253456, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Quick edit mode in cmd.exe is my favorite. This is slightly off topic, but when interacting with the command shell it can be a lifesaver. No, I'm not being hyperbolic--you will only see <strong>caret-capitol-v</strong> a certain number of times before you die; the more you see, the faster you die.</p>\n\n<ol>\n<li>Open up regedit (caution, not my\nfault, blue screen, etc)</li>\n<li>Go to HKCU/Console</li>\n<li>Set QuickEdit to 1</li>\n</ol>\n\n<p>(You can set this from the UI as well, which is probably the better way. See the comments for instructions. Also there's a nice one line script to do this as well.)</p>\n\n<p>Now, to copy, just left-click and drag to select and right click to copy. To paste, just right click. </p>\n\n<p>NO MORE ^V^V^V^V^V^V^V^V^V^V^V^V^V^V!!! </p>\n\n<p>Crap, I think I just killed somebody. Sorry!</p>\n" }, { "answer_id": 254169, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 5, "selected": false, "text": "<p>Escaping the \"plumbing\":</p>\n\n<pre><code>echo ^| ^&lt; ^&gt; ^&amp; ^\\ ^^\n</code></pre>\n" }, { "answer_id": 258335, "author": "Alin Sfetcu", "author_id": 30694, "author_profile": "https://Stackoverflow.com/users/30694", "pm_score": 2, "selected": false, "text": "<p>the correct format for loops with numeric variables is</p>\n\n<pre><code>for /l %%i in (startNumber, counter, endNumber) do echo %%i\n</code></pre>\n\n<p>more details > <a href=\"http://www.ss64.com/nt/for.html\" rel=\"nofollow noreferrer\">http://www.ss64.com/nt/for.html</a></p>\n" }, { "answer_id": 259840, "author": "Mark Arnott", "author_id": 31037, "author_profile": "https://Stackoverflow.com/users/31037", "pm_score": 0, "selected": false, "text": "<pre><code>HELP\n</code></pre>\n\n<p>When working with different OS version it's important to know what commands are available natively. Typing HELP at the command prompt shows what commands are available, with a brief description of what they do.</p>\n\n<pre><code>cmd.exe /? \n</code></pre>\n\n<p>This will list all the command line parameters for launching a command prompt as well as registry tweaks that change system wide behavior.</p>\n" }, { "answer_id": 259882, "author": "Patrick Cuff", "author_id": 7903, "author_profile": "https://Stackoverflow.com/users/7903", "pm_score": 6, "selected": false, "text": "<p>Rather than litter a script with REM or :: lines, I do the following at the top of each script:</p>\n\n<pre><code>@echo OFF\ngoto :START\n\nDescription of the script.\n\nUsage:\n myscript -parm1|parm2 &gt; result.txt\n\n:START\n</code></pre>\n\n<p>Note how you can use the pipe and redirection characters without escaping them.</p>\n" }, { "answer_id": 263270, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Doesn't provide much functionality, but you can use the title command for a couple of uses, like providing status on a long script in the task bar, or just to enhance user feedback.</p>\n\n<pre><code>@title Searching for ...\n:: processing search\n@title preparing search results\n:: data processing\n</code></pre>\n" }, { "answer_id": 270987, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 2, "selected": false, "text": "<p>For parsing <strong>stdin</strong> from inside a script you need that trick with the FOR and FIND commands:</p>\n\n<pre><code>for /f \"tokens=*\" %%g in ('find /V \"\"') do (\n :: do what you want with %%g\n echo %%g\n)\n</code></pre>\n" }, { "answer_id": 271009, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 0, "selected": false, "text": "<p>When using <strong>command extensions</strong> shell options in a script, it is HIGHLY suggested that you do the following trick at the beginning of your scripts.</p>\n\n<p>-- Information pasted from <a href=\"http://www.ss64.com/nt/setlocal.html\" rel=\"nofollow noreferrer\" title=\"http://www.ss64.com/nt/setlocal.html\">http://www.ss64.com/nt/setlocal.html</a></p>\n\n<blockquote>\n <p>SETLOCAL will set an ERRORLEVEL if given an argument. It will be zero if one of the two valid arguments is given and one otherwise.</p>\n \n <p>You can use this in a batch file to determine if command extensions are available, using the following technique:</p>\n</blockquote>\n\n<pre><code>VERIFY errors 2&gt;nul\nSETLOCAL ENABLEEXTENSIONS\nIF ERRORLEVEL 1 echo Unable to enable extensions\n</code></pre>\n\n<blockquote>\n <p>This works because \"VERIFY errors\" sets ERRORLEVEL to 1 and then the SETLOCAL will fail to reset the ERRORLEVEL value if extensions are not available (e.g. if the script is running under command.com)</p>\n \n <p>If Command Extensions are permanently disabled then SETLOCAL ENABLEEXTENSIONS will not restore them.</p>\n</blockquote>\n" }, { "answer_id": 300410, "author": "Lara Dougan", "author_id": 4081, "author_profile": "https://Stackoverflow.com/users/4081", "pm_score": 3, "selected": false, "text": "<p>You can use call to evaluate names later, leading to some useful properties.</p>\n\n<pre><code>call set SomeEnvVariable_%extension%=%%%somevalue%%%\n</code></pre>\n\n<p>Using call to set variables whose names depend on other variables. If used with some variable naming rules, you can emulate data collections like arrays or dictionaries by using careful naming rules. The triple %'s around somevalue are so it will evaluate to one variable name surrounded by single %'s after the call and before set is invoked. This means two %'s in a row escape down to a single % character, and then it will expand it again, so somevalue is effectively a name pointer.</p>\n\n<pre><code>call set TempVar=%%SomeEnvVariable_%extension%%%\n</code></pre>\n\n<p>Using it with a temp variable to retrieve the value, which you can then use in logic. This most useful when used in conjunction with delayed variable expansion.</p>\n\n<p>To use this method properly, delayed variable expansion needs to be enabled. Because it is off by default, it is best to enable it within the script by putting this as one of the first instructions:</p>\n\n<pre><code>setlocal EnableDelayedExpansion\n</code></pre>\n" }, { "answer_id": 304851, "author": "some", "author_id": 36866, "author_profile": "https://Stackoverflow.com/users/36866", "pm_score": 0, "selected": false, "text": "<p>A very old (ca 1990) trick to get the total size of the environment variables:</p>\n\n<pre><code>set &gt; test\ndir test\ndel test\n</code></pre>\n" }, { "answer_id": 314953, "author": "Sascha", "author_id": 36372, "author_profile": "https://Stackoverflow.com/users/36372", "pm_score": 0, "selected": false, "text": "<p>This batch file works <strong>both</strong> with simple <strong>files</strong> as well as <strong>directories</strong> as command line parameters (you can mix them in any order). The loop runs the command ('echo' in this example) on any specified file, if a parameter is a directory it runs the command recursively on each file in it.</p>\n\n<pre><code>@echo off\nfor /f \"delims=\" %%f in ('dir %* /a-d /b /s') do echo %%f\n</code></pre>\n" }, { "answer_id": 334023, "author": "doekman", "author_id": 56, "author_profile": "https://Stackoverflow.com/users/56", "pm_score": 4, "selected": false, "text": "<p>Command separators:</p>\n\n<pre><code>cls &amp; dir\ncopy a b &amp;&amp; echo Success\ncopy a b || echo Failure\n</code></pre>\n\n<p>At the 2nd line, the command after &amp;&amp; only runs if the first command is successful.</p>\n\n<p>At the 3rd line, the command after || only runs if the first command failed.</p>\n" }, { "answer_id": 351641, "author": "reuben", "author_id": 41646, "author_profile": "https://Stackoverflow.com/users/41646", "pm_score": 2, "selected": false, "text": "<pre><code>SHIFT\n</code></pre>\n\n<p>It's a way to iterate through a variable number of arguments passed into a script (or sub-routine) on the command line. In its simplest usage, it shifts %2 to be %1, %3 to be %2, and so-on. (You can also pass in a parameter to SHIFT to skip multiple arguments.) This makes the command \"destructive\" (i.e. %1 goes away forever), but it allows you to avoid hard-coding a maximum number of supported arguments.</p>\n\n<p>Here's a short example to process command-line arguments one at a time:</p>\n\n<pre><code>:ParseArgs\n\nif \"%1\"==\"\" (\n goto :DoneParsingArgs\n)\n\nrem ... do something with %1 ...\n\nshift\n\ngoto :ParseArgs\n\n\n:DoneParsingArgs\n\nrem ...\n</code></pre>\n" }, { "answer_id": 358149, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Allows you to change directory based on environment variable without\nhaving to specify the '%' directive. If the variable specified does not\nexist then try the directory name.</p>\n\n<pre><code>@if defined %1 (call cd \"%%%1%%\") else (call cd %1)\n</code></pre>\n" }, { "answer_id": 374361, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 5, "selected": false, "text": "<p>The equivalent of the bash (and other shells)</p>\n\n<pre><code>echo -n Hello # or\necho Hello\\\\c\n</code></pre>\n\n<p>which outputs \"<code>Hello</code>\" without a trailing newline. A cmd hack to do this:</p>\n\n<pre><code>&lt;nul set /p any-variable-name=Hello\n</code></pre>\n\n<p><code>set /p</code> is a way to prompt the user for input. It emits the given string and then waits, (on the same line, i.e., no CRLF), for the user to type a response.</p>\n\n<p><code>&lt;nul</code> simply pipes an empty response to the <code>set /p</code> command, so the net result is the emitted prompt string. (The variable used remains unchanged due to the empty reponse.)</p>\n\n<p>Problems are: It's not possible to output a leading equal sign, and on Vista leading whitespace characters are removed, but not on XP.</p>\n" }, { "answer_id": 374363, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "<p>Searching for an executable on the path (or other path-like string if necessary):</p>\n\n<pre><code>c:\\&gt; for %i in (cmd.exe) do @echo. %~$PATH:i\nC:\\WINDOWS\\system32\\cmd.exe\n\nc:\\&gt; for %i in (python.exe) do @echo. %~$PATH:i\nC:\\Python25\\python.exe\n\nc:\\&gt;\n</code></pre>\n" }, { "answer_id": 382349, "author": "matt wilkie", "author_id": 14420, "author_profile": "https://Stackoverflow.com/users/14420", "pm_score": 3, "selected": false, "text": "<p>With regard to using <code>::</code> instead of <code>REM</code> for comments: be careful! <code>::</code> is a special case of a CALL label that acts like a comment. When used inside brackets, for instance in a FOR or IF loop, the function will prematurely exit. Very frustrating to debug! </p>\n\n<p>See <a href=\"http://www.ss64.com/nt/rem.html\" rel=\"nofollow noreferrer\">http://www.ss64.com/nt/rem.html</a> for a full description.</p>\n\n<p><em>(adding as a new answer instead of a comment to the <a href=\"https://stackoverflow.com/questions/245395/underused-features-of-windows-batch-files#245398\">first mention of this above</a> because I'm not worthy of commeting yet :0)</em></p>\n" }, { "answer_id": 422692, "author": "NicJ", "author_id": 43815, "author_profile": "https://Stackoverflow.com/users/43815", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://www.ss64.com/nt/choice.html\" rel=\"nofollow noreferrer\">CHOICE</a> command prompts the user for one of multiple options (via a single keypress)</p>\n\n<pre><code>@echo off\necho Please choose one of the following options\necho 1. Apple\necho 2. Orange\necho 3. Pizza\necho a, b, c. Something else\nchoice /c:123abc /m \"Answer?\"\nset ChoiceLevel=%ErrorLevel%\necho Choice was: %ChoiceLevel%\n</code></pre>\n\n<p><code>%ChoiceLevel%</code> will be the nth option selected (in the above example, <code>b=5</code>).</p>\n\n<p>More details at the <a href=\"http://www.ss64.com/nt/choice.html\" rel=\"nofollow noreferrer\">CHOICE</a> reference page on <a href=\"http://www.ss64.com/nt/\" rel=\"nofollow noreferrer\">SS64.com</a>.</p>\n" }, { "answer_id": 422697, "author": "NicJ", "author_id": 43815, "author_profile": "https://Stackoverflow.com/users/43815", "pm_score": 2, "selected": false, "text": "<p>Redirecting output to the console, even if the batch's output is already redirected to a file via the <code>&gt; con</code> syntax.</p>\n\n<p>Example:\nfoo.cmd:</p>\n\n<pre><code>echo a\necho b &gt; con\n</code></pre>\n\n<p>Calling:</p>\n\n<pre><code>foo.cmd &gt; output.txt\n</code></pre>\n\n<p>This will result in <code>\"a\"</code> going to <code>output.txt</code> yet <code>\"b\"</code> going to the console.</p>\n" }, { "answer_id": 534767, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>The %~dp0 piece was mentioned already, but there is actually more to it:\nthe character(s) after the ~ define the information that is extracted.<br>\nNo letter result in the return of the patch file name<br>\nd - returns the drive letter<br>\np - returns the path<br>\ns - returns the short path<br>\nx - returns the file extension<br>\nSo if you execute the script test.bat below from the c:\\Temp\\long dir name\\ folder,</p>\n\n<pre><code>@echo off\necho %0\necho %~d0\necho %~p0\necho %~dp0\necho %~x0\necho %~s0\necho %~sp0\n</code></pre>\n\n<p>you get the following output</p>\n\n<blockquote>\n<pre><code>test\nc:\n\\Temp\\long dir name\\\nc:\\Temp\\long dir name\\\n.bat\nc:\\Temp\\LONGDI~1\\test.bat\n\\Temp\\LONGDI~1\\\n</code></pre>\n</blockquote>\n\n<p>And if a parameter is passed into your script as in<br>\ntest c:\\temp\\mysrc\\test.cpp<br>\nthe same manipulations can be done with the %1 variable.</p>\n\n<p>But the result of the expansion of %0 depends on the location!<br>\nAt the \"top level\" of the batch it expands to the current batch filename.<br>\nIn a function (call), it expands to the function name.</p>\n\n<pre><code>@echo off\necho %0\ncall :test\ngoto :eof\n\n:test\necho %0\necho %~0\necho %~n0\n</code></pre>\n\n<p>The output is (the batchfile is started with myBatch.bat )</p>\n\n<pre><code>myBatch.bat\n:test\n:test\nmyBatch\n</code></pre>\n" }, { "answer_id": 534890, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Don't have an editor handy and need to create a batch file?</p>\n\n<pre><code>copy con test.bat\n</code></pre>\n\n<p>Just type away the commands, press enter for a new line.\nPress Ctrl-Z and Enter to close the file.</p>\n" }, { "answer_id": 904295, "author": "Deniz Zoeteman", "author_id": 111731, "author_profile": "https://Stackoverflow.com/users/111731", "pm_score": 0, "selected": false, "text": "<p>The IF command! Without it my batch file was junk!</p>\n\n<pre><code>@echo off\nIF exist %windir%\\system32\\iexplore.exe goto end\n\necho Hmm... it seems you do not have Internet Explorer.\necho Great! You seem to understand ;)\n\n:end\necho Hmm... You have Internet Explorer.\necho That is bad :)\n</code></pre>\n" }, { "answer_id": 904360, "author": "leander", "author_id": 80074, "author_profile": "https://Stackoverflow.com/users/80074", "pm_score": 0, "selected": false, "text": "<p>I really like this <a href=\"http://www.ss64.com/nt/\" rel=\"nofollow noreferrer\">Windows XP Commands</a> reference, as well as the <a href=\"http://www.ss64.com/nt/syntax.html\" rel=\"nofollow noreferrer\">Syntax</a> link at the top; it covers many of the tips and tricks already found in other answers.</p>\n" }, { "answer_id": 904419, "author": "cookre", "author_id": 39195, "author_profile": "https://Stackoverflow.com/users/39195", "pm_score": -1, "selected": false, "text": "<p>Extract random lines of text</p>\n\n<pre><code>@echo off\n\n:: Get time (alas, it's only HH:MM xM\n\nfor /f %%a in ('time /t') do set zD1=%%a\n\n\n\n:: Get last digit of MM\n\nset zD2=%zD1:~4,1%\n\n\n\n:: Seed the randomizer, if needed\n\nif not defined zNUM1 set /a zNUM1=%zD2%\n\n\n:: Get a kinda random number\n\nset /a zNUM1=zNUM1 * 214013 + 2531011\n\nset /a zNUM2=zNUM1 ^&gt;^&gt; 16 ^&amp; 0x7fff\n\n\n:: Pull off the first digit\n\n:: (Last digit would be better, but it's late, and I'm tired)\n\nset zIDX=%zNUM2:~0,1%\n\n\n:: Map it down to 0-3\n\nset /a zIDX=zIDX/3\n\n\n:: Finally, we can set do some proper initialization\n\nset /a zIIDX=0\n\nset zLO=\n\nset zLL=\"\"\n\n\n:: Step through each line in the file, looking for line zIDX\n\nfor /f \"delims=@\" %%a in (c:\\lines.txt) do call :zoo %zIDX% %%a\n\n\n:: If line zIDX wasn't found, we'll settle for zee LastLine\n\nif \"%zLO%\"==\"\" set zLO=%zLL%\n\ngoto awdun\n\n\n:: See if the current line is line zIDX\n\n:zoo\n\n\n:: Save string of all parms\n\nset zALL=%*\n\n\n:: Strip off the first parm (sure hope lines aren't longer than 254 chars)\n\nset zWORDS=%zALL:~2,255%\n\n\n:: Make this line zee LastLine\n\nset zLL=%zWORDS%\n\n\n:: If this is the line we're looking for, make it zee LineOut\n\nif {%1}=={%zIIDX%} set zLO=%zWORDS%\n\n\n:: Keep track of line numbers\n\nset /a zIIDX=%zIIDX% + 1\n\ngoto :eof\n\n\n\n\n:awdun\n\necho ==%zLO%==\n\n\n:: Be socially responsible\n\nset zALL=\n\nset zD1=\n\nset zD2=\n\nset zIDX=\n\nset zIIDX=\n\nset zLL=\n\nset zLO=\n\n:: But don't mess with seed\n\n::set zNUM1=\n\nset zNUM2=\n\nset zWORDS=\n</code></pre>\n" }, { "answer_id": 1061064, "author": "Coding With Style", "author_id": 130718, "author_profile": "https://Stackoverflow.com/users/130718", "pm_score": 1, "selected": false, "text": "<p>I would say DEBUG.EXE is a VERY useful and VERY underused feature of batch files.</p>\n\n<p>The DEBUG command allows you to...</p>\n\n<ol><li>Assemble and disassemble 16-bit code\n<li>Read/write memory (Modern protected memory makes this considerably less useful.)\n<li>Read data sectors from the hard drive, raw\n<li>Hex edit</ol>\n\n<p>In short, this tool is EXTREMELY powerful. It might not be used much these days anymore, but the power to call up and control this functionality from a batch script adds a staggering amount of power to batch scripting.</p>\n\n<p>NOTE: Microsoft has removed this command from 64 bit editions of Windows Xp and Vista and intends to remove it from Windows 7 altogether, from what I've heard.</p>\n" }, { "answer_id": 1061089, "author": "Coding With Style", "author_id": 130718, "author_profile": "https://Stackoverflow.com/users/130718", "pm_score": 0, "selected": false, "text": "<p>There is also the EDLIN command. While it may be an old bastard tool once used for line-based text editing, the fact that it's controllable from the command line makes it rather useful for batch scripting, mostly because, just like any other case you'd be using EDLIN, it's the only tool available. After all, EDLIN is not a tool you would ordinarily want to use for text editing, unless you are somewhat masochistic. To quote Tim Patterson (the fellow who wrote it): \"I was aghast when I heard that IBM was using it and not throwing it out the window.\"</p>\n\n<p>NOTE: EDLIN adds old-fashioned EOF (1A) markers to files it edits. If you need to remove them, you'll probably have to use DEBUG.</p>\n" }, { "answer_id": 1077234, "author": "Coding With Style", "author_id": 130718, "author_profile": "https://Stackoverflow.com/users/130718", "pm_score": 3, "selected": false, "text": "<p>A lot of people use GOTO :EOF these days to terminate their batch files, but you can also use EXIT /B for this purpose.</p>\n\n<p>The advantage behind using EXIT /B is that you can add an errorlevel after EXIT /B, and it will exit with that errorlevel.</p>\n" }, { "answer_id": 1077250, "author": "Anton Tykhyy", "author_id": 77724, "author_profile": "https://Stackoverflow.com/users/77724", "pm_score": 1, "selected": false, "text": "<p>Setting environment variables from a file with <code>SET /P</code></p>\n\n<pre><code>SET /P SVNVERSION=&lt;ver.tmp\n</code></pre>\n" }, { "answer_id": 1077308, "author": "Coding With Style", "author_id": 130718, "author_profile": "https://Stackoverflow.com/users/130718", "pm_score": 3, "selected": false, "text": "<p>Local variables are still parsed for the line that ENDLOCAL uses. This allows for tricks like:</p>\n\n<pre><code>ENDLOCAL &amp; SET MYGLOBAL=%SOMELOCAL% &amp; SET MYOTHERGLOBAL=%SOMEOTHERLOCAL%\n</code></pre>\n\n<p>This is is a useful way to transmit results to the calling context. Specifically, %SOMELOCAL% goes out of scope as soon as ENDLOCAL completes, but by then %SOMELOCAL% is already expanded, so the MYGLOBAL is assigned in the calling context with the local variable.</p>\n\n<p>For the same reason, if you decide to do:</p>\n\n<pre><code>ENDLOCAL &amp; SET MYLOCAL=%MYLOCAL%\n</code></pre>\n\n<p>You'll discover your new MYLOCAL variable is actually now around as a regular environment variable instead of the localized variable you may have intended it to be.</p>\n" }, { "answer_id": 1168561, "author": "Coding With Style", "author_id": 130718, "author_profile": "https://Stackoverflow.com/users/130718", "pm_score": 1, "selected": false, "text": "<p>A method to set the errorlevel to any number you desire:</p>\n\n<pre>CMD /C EXIT number</pre>\n" }, { "answer_id": 1228895, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 1, "selected": false, "text": "<p>The goto :eof pasteboard</p>\n\n<p>I add \"goto :eof\" to end of my scripts as a handy space for code fragments. That way I can quickly copy/paste to and from this area, without having to comment/uncomment.</p>\n\n<pre><code>goto :eof\n:: code scraps\ncall this.bat\ncall that.bat\nset TS=%DATE:~10%%DATE:~4,2%%DATE:~7,2%-%TIME:~0,2%%TIME:~3,2%%TIME:~6%%\nfor /R C:\\temp\\ %%G in (*.bak) DO del %%G\n</code></pre>\n" }, { "answer_id": 1397803, "author": "Igor Dvorkin", "author_id": 141158, "author_profile": "https://Stackoverflow.com/users/141158", "pm_score": 2, "selected": false, "text": "<p>A handy trick when you want to copy files between branches: </p>\n\n<pre><code>C:\\src\\branch1\\mydir\\mydir2\\mydir3\\mydir4&gt;xcopy %cd:branch1=branch2%\\foo*\nOverwrite C:\\src\\branch1\\mydir\\mydir2\\mydir3\\mydir4\\foo.txt (Yes/No/All)? y\nC:\\src\\branch2\\mydir\\mydir2\\mydir3\\mydir4\\foo.txt\n</code></pre>\n\n<p>This uses both the %cd% environment variable, and environment variable substitution.</p>\n" }, { "answer_id": 1549505, "author": "sahmeepee", "author_id": 187834, "author_profile": "https://Stackoverflow.com/users/187834", "pm_score": 0, "selected": false, "text": "<p>When passing an unknown number of parameters to a batch file, e.g. when several files are dragged and dropped onto the batch file to launch it, you could refer to each parameter variable by name, e.g.</p>\n\n<pre><code>TYPE %1\nTYPE %2\nTYPE %3\nTYPE %4\nTYPE %5\n...etc\n</code></pre>\n\n<p>but this gets very messy when you want to check if each parameter exists:</p>\n\n<pre><code>if [%1] NEQ [] (\nTYPE %1\n)\nif [%2] NEQ [] (\nTYPE %2\n)\nif [%3] NEQ [] (\nTYPE %3\n)\nif [%4] NEQ [] (\nTYPE %4\n)\nif [%5] NEQ [] (\nTYPE %5\n)\n...etc\n</code></pre>\n\n<p>Also, you can only accept a limited number of parameters with this approach.</p>\n\n<p>Instead, try using the SHIFT command:</p>\n\n<pre><code>:loop\nIF [%1] NEQ [] (\nTYPE %1\n) ELSE (\nGOTO end\n)\nSHIFT\nGOTO loop\n:end\n</code></pre>\n\n<p>SHIFT will move all the parameters down by one, so %2 becomes %1 and %3 becomes %2 etc.</p>\n" }, { "answer_id": 1613169, "author": "guerda", "author_id": 32043, "author_profile": "https://Stackoverflow.com/users/32043", "pm_score": 0, "selected": false, "text": "<p><code>FIND</code> as a replacement for grep.<br>\nI hacked a little \"phonebook\" for myself with find. Very usefull:</p>\n\n<pre><code>@echo off\n:begin\nset /p term=Enter query: \ntype phonebookfile.txt |find /i \"%term%\"\nif %errorlevel% == 0 GOTO :choose\necho No entry found\nset /p new_entry=Add new entry: \necho %new_entry% &gt;&gt; phonebookfile.txt \n:choose\nset /p action=(q)uit, (n)ew query or (e)dit? [q] \nif \"%action%\"==\"n\" GOTO anfang\nif \"%action%\"==\"e\" (\n notepad phonebookfile.txt\n goto :choose\n)\n</code></pre>\n\n<p>Very fast and effective.</p>\n" }, { "answer_id": 3296461, "author": "batch fool", "author_id": 397527, "author_profile": "https://Stackoverflow.com/users/397527", "pm_score": 2, "selected": false, "text": "<p>You can use errorlevel to check if a given program is available on the system (current dir or path) where your batchfile will run. For this to work the program you are testing for must run, exit and set an exit code when it does. In the example I use -? as an arg to myExe, most CLI programs have a similar arg such as -h, --help, -v etc ... this ensures it simply runs and exits leaving or setting errorlevel 0</p>\n\n<pre><code>myExe -? &gt;nul 2&gt;&amp;1 \nSet errCode=%errorlevel%\n@if %errCode% EQU 0 (\n echo myExe -? does not return an error (exists)\n) ELSE (\n echo myExe -? returns an error (does not exist)\n)\n</code></pre>\n\n<p>Yes, you could test errorlevel directly rather than assigning it to errCode but this way you can have commands between the test and the condition and you test the condition repeatedly as needed.</p>\n" }, { "answer_id": 3752322, "author": "Andy Morris", "author_id": 174447, "author_profile": "https://Stackoverflow.com/users/174447", "pm_score": 3, "selected": false, "text": "<p>Call Set - Expands Environment variables several levels deep.</p>\n\n<p>Found this at <a href=\"http://ss64.com/nt/call.html#advanced\" rel=\"nofollow noreferrer\">http://ss64.com/nt/call.html#advanced</a> from answer to another SO question <a href=\"https://stackoverflow.com/questions/691047/batch-file-variables-initialized-in-a-for-loop\">Batch file variables initialized in a for loop</a></p>\n\n<pre><code>set VarName=Param\nset Param=This\n\ncall set Answer=%%%Varname%%%\nEcho %Answer%\n</code></pre>\n\n<p>gives </p>\n\n<pre><code>set VarName=Param\nset Param=This\ncall set Answer=%Param%\nEcho This\nThis\n</code></pre>\n" }, { "answer_id": 3786683, "author": "Andrei Coșcodan", "author_id": 359381, "author_profile": "https://Stackoverflow.com/users/359381", "pm_score": 1, "selected": false, "text": "<p>Hide input for an interactive batch script:</p>\n\n<pre><code> @echo off\n\n echo hP1X500P[PZBBBfh#b##fXf-V@`$fPf]f3/f1/5++u5&gt;in.com\n\n set /p secret_password=\"Enter password:\"&lt;nul\n\n for /f \"tokens=*\" %%i in ('in.com') do (set secret_password=%%i)\n\n del in.com\n</code></pre>\n" }, { "answer_id": 3786739, "author": "JUST MY correct OPINION", "author_id": 282658, "author_profile": "https://Stackoverflow.com/users/282658", "pm_score": 2, "selected": false, "text": "<p>Inline comments using <code>&amp;::</code>.</p>\n\n<pre><code>:: This is my batch file which does stuff.\ncopy thisstuff thatstuff &amp;:: We need to make a backup in case we screw up!\n\n:: ... do lots of other stuff\n</code></pre>\n\n<p>How does this work? It's an ugly hack. The <code>&amp;</code> is the command separator roughly approximating the <code>;</code> of UNIX shells. The <code>::</code> is another ugly hack that kinda-sorta emulates a <code>REM</code> statement. The end result is that you execute your command and then you execute a do-nothing command, thus approximating a comment.</p>\n\n<p>This doesn't work in all situations, but it works often enough to be a useful hack.</p>\n" }, { "answer_id": 3786752, "author": "Andrei Coșcodan", "author_id": 359381, "author_profile": "https://Stackoverflow.com/users/359381", "pm_score": 1, "selected": false, "text": "<p>List all drives:</p>\n\n<pre><code>fsutil fsinfo drives\n</code></pre>\n" }, { "answer_id": 3787015, "author": "Andrei Coșcodan", "author_id": 359381, "author_profile": "https://Stackoverflow.com/users/359381", "pm_score": 2, "selected": false, "text": "<p>Get the current day, month and year (locale-independently):</p>\n\n<pre><code>for /f \"tokens=1-4 delims=/-. \" %%i in ('date /t') do (call :set_date %%i %%j %%k %%l)\ngoto :end_set_date\n\n:set_date\nif (\"%1:~0,1%\" gtr \"9\") shift\nfor /f \"skip=1 tokens=2-4 delims=(-)\" %%m in ('echo,^|date') do (set %%m=%1&amp;set %%n=%2&amp;set %%o=%3)\ngoto :eof\n\n:end_set_date\n\necho day in 'DD' format is %dd%; month in 'MM' format is %mm%; year in 'YYYY' format is %yy%\n</code></pre>\n" }, { "answer_id": 3787110, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 2, "selected": false, "text": "<p>For what it's worth, <a href=\"http://ss64.com/nt/\" rel=\"nofollow\">this</a> is quite a good online reference for Windows CMD or batch files. I learned a few things I didn't know from it.</p>\n" }, { "answer_id": 5419090, "author": "dave1010", "author_id": 315435, "author_profile": "https://Stackoverflow.com/users/315435", "pm_score": 1, "selected": false, "text": "<p>Create and start editing a new file</p>\n\n<pre><code>copy con new.txt\nThis is the contents of my file\n^Z\n</code></pre>\n\n<p>Ctrl+Z sends the ASCII EOF character. This is like heredocs in bash:</p>\n\n<pre><code>cat &lt;&lt;EOF &gt; new.txt\nThis is the contents of my file\nEOF\n</code></pre>\n" }, { "answer_id": 5419228, "author": "Fadrian Sudaman", "author_id": 276556, "author_profile": "https://Stackoverflow.com/users/276556", "pm_score": 1, "selected": false, "text": "<p>Remove surrounding quote. </p>\n\n<pre><code>for /f \"useback tokens=*\" %%a in ('%str%') do set str=%%~a\n</code></pre>\n\n<p>I recently have to write a batch file that is called by VS prebuild event and I want to pass in the project directory as parameter. In the batch file I need to concatenate the path with nested subfolder name, but first the surrounding quote need to be removed.</p>\n" }, { "answer_id": 5419611, "author": "Brecht Yperman", "author_id": 674927, "author_profile": "https://Stackoverflow.com/users/674927", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://technet.microsoft.com/nl-nl/library/cc753551%28WS.10%29.aspx\" rel=\"nofollow\" title=\"forfiles\">forfiles</a> is very useful, for instance, to recursive delete all files older than two days</p>\n\n<pre><code>forfiles /D -2 /P \"C:\\Temp\" /S /C \"cmd /c del @path\"\n</code></pre>\n" }, { "answer_id": 5419979, "author": "BartekB", "author_id": 674943, "author_profile": "https://Stackoverflow.com/users/674943", "pm_score": 2, "selected": false, "text": "<p>Findstr with regular expression support:</p>\n\n<pre><code>findstr \"^[0-9].*\" c:\\windows\\system32\\drivers\\etc\\hosts\n</code></pre>\n" }, { "answer_id": 5420385, "author": "caseyboardman", "author_id": 807, "author_profile": "https://Stackoverflow.com/users/807", "pm_score": 1, "selected": false, "text": "<p>Bail on error.</p>\n\n<pre><code>IF \"%errorlevel%\" NEQ \"0\" (\n echo \"ERROR: Something broke. Bailing out.\"\n exit /B 1\n)\n</code></pre>\n" }, { "answer_id": 5420982, "author": "thatbrentguy", "author_id": 226705, "author_profile": "https://Stackoverflow.com/users/226705", "pm_score": 2, "selected": false, "text": "<p>Using pushd to a UNC path will create a temporary drive mapping (starting with Z and working backward to find the next available letter) and put you in that drive and path. When you popd or exit the command prompt, the temporary mapping is gone.</p>\n\n<pre><code> C:\\&gt;pushd \\\\yourmom\\jukebox\n\n Z:\\&gt;pushd \\\\yourmom\\business\n\n Y:\\&gt;\n</code></pre>\n\n<p>Also, not so much a batch tip as a command-line environment tip, but when you're working at the commandline with pushd and popd and network shares, it's useful to modify your prompt with the $+ (show pushd stack depth) and $M (show network share path).</p>\n\n<pre><code> C:\\utils&gt;prompt $+$m$p$g\n\n C:\\utils&gt;pushd m:\n\n +\\\\yourmom\\pub M:\\&gt;pushd c:\\\n\n ++c:\\&gt;pushd\n M:\\\n C:\\utils \n\n ++c:\\&gt;popd\n\n +\\\\yourmom\\pub M:\\&gt;popd\n\n C:\\utils&gt;\n</code></pre>\n" }, { "answer_id": 5421017, "author": "Frans Bouma", "author_id": 44991, "author_profile": "https://Stackoverflow.com/users/44991", "pm_score": 2, "selected": false, "text": "<p>Find strings in files in a folder using the pipe '|' command:</p>\n\n<pre><code>dir /b *.* | findstr /f:/ \"thepattern\"\n</code></pre>\n" }, { "answer_id": 5421140, "author": "Soulman", "author_id": 368491, "author_profile": "https://Stackoverflow.com/users/368491", "pm_score": 1, "selected": false, "text": "<p>Symbolic links:</p>\n\n<pre><code>mklink /d directorylink ..\\realdirectory\nmklink filelink realfile\n</code></pre>\n\n<p>The command is native on Windows Server 2008 and newer, including Vista and Windows 7. (It is also included in some Windows Resource Kits.)</p>\n" }, { "answer_id": 5422998, "author": "John Fisher", "author_id": 50358, "author_profile": "https://Stackoverflow.com/users/50358", "pm_score": 0, "selected": false, "text": "<p>Line-based execution</p>\n\n<p>While not a clear benefit in most cases, it can help when trying to update things while they are running. For example:</p>\n\n<p>UpdateSource.bat</p>\n\n<pre><code>copy UpdateSource.bat Current.bat\necho \"Hi!\"\n</code></pre>\n\n<p>Current.bat</p>\n\n<pre><code>copy UpdateSource.bat Current.bat\n</code></pre>\n\n<p>Now, executing Current.bat produces this output.</p>\n\n<pre><code>HI!\n</code></pre>\n\n<p><em>Watch out</em> though, the batch execution proceeds by line number. An update like this could end up skipping or moving back a line if the essential lines don't have exactly the same line numbers.</p>\n" }, { "answer_id": 5423169, "author": "DaWolfman", "author_id": 162900, "author_profile": "https://Stackoverflow.com/users/162900", "pm_score": 1, "selected": false, "text": "<p>Append files using copy:</p>\n\n<pre><code>copy file1.txt+file2.txt+file3.txt append.txt\n</code></pre>\n\n<p>Also, to set all CLI parameters to a single variable:</p>\n\n<pre><code>SET MSG=%*\n</code></pre>\n\n<p>This will take every word (or symbol) that is separated by spaces and save it to a single batch file variable. Technically, each parameter is %1, %2, $3, etc., but this SET command uses a wildcard to reference every parameter in stdin.</p>\n\n<p>Batch File:</p>\n\n<pre><code>@SET MSG=%*\n@echo %MSG%\n</code></pre>\n\n<p>Command Line:</p>\n\n<pre><code>C:\\test&gt;test.bat Hello World!\nHello World!\n</code></pre>\n" }, { "answer_id": 5423452, "author": "bneal", "author_id": 489548, "author_profile": "https://Stackoverflow.com/users/489548", "pm_score": 1, "selected": false, "text": "<p>Recursively search for a string in a directory tree:</p>\n\n<pre><code>findstr /S /C:\"string literal\" *.*\n</code></pre>\n\n<p>You can also use regular expressions:</p>\n\n<pre><code>findstr /S /R \"^ERROR\" *.log\n</code></pre>\n\n<p>Recursive file search:</p>\n\n<pre><code>dir /S myfile.txt\n</code></pre>\n" }, { "answer_id": 5423809, "author": "jon_brockman", "author_id": 97269, "author_profile": "https://Stackoverflow.com/users/97269", "pm_score": 0, "selected": false, "text": "<p>I use them as quick shortcuts to commonly used directories. \nAn example file named \"sandbox.bat\" which lives in a directory in my PATH </p>\n\n<pre><code>EXPLORER \"C:\\Documents and Settings\\myusername\\Desktop\\sandbox\"\n</code></pre>\n\n<p>Invoking the script is just WIN+R --> sandbox </p>\n" }, { "answer_id": 5423962, "author": "jftuga", "author_id": 452281, "author_profile": "https://Stackoverflow.com/users/452281", "pm_score": 0, "selected": false, "text": "<p>To get the current date / time to use for log files, etc., I use this in my batch files:</p>\n\n<pre><code>for /f \"usebackq tokens=1,2,3,4,5,6,7 delims=/:. \" %%a in (`echo %DATE% %TIME%`) do set NOW=%%d%%b%%c_%%e%%f%%g\nset LOG=output_%NOW%.log\n</code></pre>\n" }, { "answer_id": 5424017, "author": "jftuga", "author_id": 452281, "author_profile": "https://Stackoverflow.com/users/452281", "pm_score": -1, "selected": false, "text": "<p>To set an enivroment variable from the first line of a file, I use this:</p>\n\n<pre><code>rem a.txt contains one line: abc123\nset /p DATA=&lt;a.txt\necho data: %DATA%\n</code></pre>\n\n<p>This will output: abc123</p>\n" }, { "answer_id": 5424388, "author": "Ben Burnett", "author_id": 675544, "author_profile": "https://Stackoverflow.com/users/675544", "pm_score": 2, "selected": false, "text": "<p>Arrays in batch-files.</p>\n\n<p>Set a value:</p>\n\n<pre><code>set count=1\nset var%count%=42\n</code></pre>\n\n<p>Extract a value at the command-line:</p>\n\n<pre><code>call echo %var%count%%\n</code></pre>\n\n<p>Extract a value in a batch-file:</p>\n\n<pre><code>call echo %%var%count%%%\n</code></pre>\n\n<p>Note the extra strafing % signs.</p>\n\n<p>The technique may look a little hairy, but it's quite useful. The above will print the contents of <em>var1</em> (i.e. 42) as we explained. We could also replace the <strong>echo</strong> command with a <strong>set</strong> if we wanted to set some other variable to the value in <em>var1</em>. Meaning the following is a valid assignment at the command line:</p>\n\n<pre><code>call set x=%var%count%%\n</code></pre>\n\n<p>Then to see the value of <em>va1</em>:</p>\n\n<pre><code>echo %x%\n</code></pre>\n" }, { "answer_id": 5424491, "author": "Ben Burnett", "author_id": 675544, "author_profile": "https://Stackoverflow.com/users/675544", "pm_score": 2, "selected": false, "text": "<p>Doskey Macros.</p>\n\n<p>I've long lost the reference for this, but I still think it's a good idea, and worth sharing.</p>\n\n<p>We can merge batch-files and doskey scripts into a single file. This might seem a little overly clever, but it works. </p>\n\n<pre><code>;= @echo off\n;= rem Call DOSKEY and use this file as the macrofile\n;= %SystemRoot%\\system32\\doskey /listsize=1000 /macrofile=%0%\n;= rem In batch mode, jump to the end of the file\n;= goto end\n\n;= Doskey aliases\nh=doskey /history\n\n;= File listing enhancements\nls=dir /x $*\n\n;= Directory navigation\nup=cd ..\npd=pushd\n\n;= :end\n;= rem ******************************************************************\n;= rem * EOF - Don't remove the following line. It clears out the ';' \n;= rem * macro. Were using it because there is no support for comments\n;= rem * in a DOSKEY macro file.\n;= rem ******************************************************************\n;=\n</code></pre>\n\n<p>It works by defining a fake doskey macro ';' which is gracefully (or silently) ignored when it is interpreted as a batch-file.</p>\n\n<p>I've shortened the version listed here, if you want more, go <a href=\"http://ben.versionzero.org/wiki/Doskey_Macros\" rel=\"nofollow\">here</a>.</p>\n" }, { "answer_id": 5425444, "author": "Anonymous", "author_id": 675705, "author_profile": "https://Stackoverflow.com/users/675705", "pm_score": -1, "selected": false, "text": "<p>One of the <strong>most</strong> common requirements of batch scripting is to log the output generated for later review. Yes, you can redirect the stdout and stderr to a file but then you can't see what is going on unless you tail the log file.</p>\n\n<p>So consider running your batch scripts using a stdout/stderr logging utility like logger which will log the output with a timestamp and you are still able to see the script progress as it happens.</p>\n\n<p><a href=\"http://code.google.com/p/mulder/downloads/list?sort=-uploaded\" rel=\"nofollow\">Yet another stdout/stderr logging utility</a></p>\n\n<pre><code>Yet another stdout/stderr logging utility [2010-08-05]\nCopyright (C) 2010 LoRd_MuldeR &lt;[email protected]&gt;\nReleased under the terms of the GNU General Public License (see License.txt)\n\nUsage:\n logger.exe [logger options] : program.exe [program arguments]\n program.exe [program arguments] | logger.exe [logger options] : -\n\nOptions:\n -log &lt;file name&gt; Name of the log file to create (default: \"&lt;program&gt; &lt;time&gt;.log\")\n -append Append to the log file instead of replacing the existing file\n -mode &lt;mode&gt; Write 'stdout' or 'stderr' or 'both' to log file (default: 'both')\n -format &lt;format&gt; Format of log file, 'raw' or 'time' or 'full' (default: 'time')\n -filter &lt;filter&gt; Don't write lines to log file that contain this string\n -invert Invert filter, i.e. write only lines to log file that match filter\n -ignorecase Apply filter in a case-insensitive way (default: case-sensitive)\n -nojobctrl Don't add child process to job object (applies to Win2k and later)\n -noescape Don't escape double quotes when forwarding command-line arguments\n -silent Don't print additional information to the console\n -priority &lt;flag&gt; Change process priority (idle/belownormal/normal/abovenormal/high)\n -inputcp &lt;cpid&gt; Use the specified codepage for input processing (default: 'utf8')\n -outputcp &lt;cpid&gt; Use the specified codepage for log file output (default: 'utf8')\n</code></pre>\n" }, { "answer_id": 5425807, "author": "MadKat", "author_id": 675731, "author_profile": "https://Stackoverflow.com/users/675731", "pm_score": 1, "selected": false, "text": "<p>Much like above, using CALL, EXIT /B, SETLOCAL &amp; ENDLOCAL you can implement functions with local variables and return values.</p>\n\n<p>example:</p>\n\n<pre><code>@echo off\n\nset x=xxxxx\ncall :fun 10\necho \"%x%\"\necho \"%y%\"\nexit /b\n\n:fun\nsetlocal\nset /a y=%1 + 1\nendlocal &amp; set x=%y%\nexit /b\n</code></pre>\n\n<p>This will print:</p>\n\n<pre><code>\"11\"\n\"\"\n</code></pre>\n\n<p>The y variable never leaves the local scope, but because of the way CMD resolves a single line at a time, you can extract the value into the x variable in the parent scope.</p>\n" }, { "answer_id": 9386014, "author": "Mashmagar", "author_id": 276120, "author_profile": "https://Stackoverflow.com/users/276120", "pm_score": 0, "selected": false, "text": "<p>You can modify a batch file while it is running. For example you can add a forgotten <code>pause</code> to the end of the file while it's running if you wanted to see the results before the batch file quit.</p>\n\n<p>see <a href=\"https://stackoverflow.com/questions/906586/changing-a-batch-file-when-its-running\">Changing a batch file when its running</a></p>\n\n<p>I personally think of this more as a gotcha than a feature.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14749/" ]
What are some of the lesser know, but important and useful features of Windows batch files? Guidelines: * One feature per answer * Give both a short **description** of the feature and an **example**, not just a link to documentation * Limit answers to **native funtionality**, i.e., does not require additional software, like the *Windows Resource Kit* Clarification: We refer here to scripts that are processed by cmd.exe, which is the default on WinNT variants. (See also: [Windows batch files: .bat vs .cmd?](https://stackoverflow.com/questions/148968/windows-batch-files-bat-vs-cmd))
Line continuation: ``` call C:\WINDOWS\system32\ntbackup.exe ^ backup ^ /V:yes ^ /R:no ^ /RS:no ^ /HC:off ^ /M normal ^ /L:s ^ @daily.bks ^ /F daily.bkf ```
245,406
<p>I have done this:</p> <pre><code>$ z() { echo 'hello world'; } </code></pre> <p>How do I get rid of it?</p>
[ { "answer_id": 245409, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 9, "selected": true, "text": "<pre><code>unset -f z\n</code></pre>\n\n<p>Will unset the function named z. A couple people have answered with:</p>\n\n<pre><code>unset z\n</code></pre>\n\n<p>but if you have a function and a variable named z only the variable will be unset, not the function.</p>\n" }, { "answer_id": 59416087, "author": "Micah Elliott", "author_id": 326516, "author_profile": "https://Stackoverflow.com/users/326516", "pm_score": 3, "selected": false, "text": "<p>In Zsh:</p>\n\n<pre><code>unfunction z\n</code></pre>\n\n<p>That's another (arguably better) name for <code>unhash -f z</code> or <code>unset -f z</code> and is consistent with the rest of the family of:</p>\n\n<ul>\n<li><code>unset</code></li>\n<li><code>unhash</code></li>\n<li><code>unalias</code></li>\n<li><code>unlimit</code></li>\n<li><code>unsetopt</code></li>\n</ul>\n\n<p>When in doubt with such things, type <code>un&lt;tab&gt;</code> to see the complete list.</p>\n\n<p><em>(Slightly related: It's also nice to have functions/aliases like <code>realiases</code>, <code>refunctions</code>, <code>resetopts</code>, <code>reenv</code>, etc to \"re-<code>source</code>\" respective files, if you've separated/grouped them as such.)</em></p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
I have done this: ``` $ z() { echo 'hello world'; } ``` How do I get rid of it?
``` unset -f z ``` Will unset the function named z. A couple people have answered with: ``` unset z ``` but if you have a function and a variable named z only the variable will be unset, not the function.
245,418
<p>I have an ASHX handler that returns an XML response (FileStructureXML.ashx).</p> <p>Now I need to get the XML response from the ASHX handler and use it as a data source for my ASPX page.</p> <p>If I point the XMLDataSource to a static XML file on the server, the treeview populates as expected. However, if I point the XMLDataSource to the ASHX handler instead of a static XML file on the server, it doesn't work.</p> <p>Any help would be appreciated.</p> <pre><code>&lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;asp:TreeView ID="TreeView_Folders" runat="server" DataSourceID="FileXML"&gt; &lt;DataBindings&gt; &lt;asp:TreeNodeBinding DataMember="Directory" TextField="Name" /&gt; &lt;asp:TreeNodeBinding DataMember="File" TextField="Name" /&gt; &lt;/DataBindings&gt; &lt;/asp:TreeView&gt; &lt;/div&gt; &lt;div&gt; &lt;asp:XmlDataSource ID="FileXML" runat="server" DataFile="FileStructureXML.ashx"&gt; &lt;/asp:XmlDataSource&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; </code></pre>
[ { "answer_id": 245676, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>I think that the XmlDataSource only works with an actual file, not a URL. You might be able to work around this by not specifying a DataFile property and loading the Data property dynamically in your code behind. I think the FirstChild.OuterXml selection is correct, but you may need to experiment. I'm not in a place where I can test it.</p>\n\n<pre><code>XmlDocument treeDoc = new XmlDocument();\ntreeDoc.Load( \"~/FileStructureXML.ashx\" ); // this takes a URL\nFileXml.Data = treeDoc.FirstChild.OuterXml; // everything after the xml definition\n</code></pre>\n" }, { "answer_id": 1348951, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre>\nDim oDataSet As New DataSet\n Public Sub PopulateTree(ByVal ParentId As String, ByVal TVNode As TreeNode)\n Dim oDataView As New DataView(oDataSet.Tables(0), \"ParentID='\" & ParentId & \"'\", \n \"DATA\", DataViewRowState.OriginalRows)\n Dim oDataRow As DataRowView\n For Each oDataRow In oDataView\n Dim oTreeNode As New TreeNode(oDataRow(\"DATA\"))\n Dim oComboBox As New ComboBox\n If TVNode Is Nothing Then\n Else\n TVNode.Nodes.Add(oTreeNode)\n PopulateTree(oDataRow(\"ID\"), oTreeNode)\n End If\n Next\n End Sub\n\nThis is how U call the above function \nPopulateTree(0, tvPost.TopNode)\ntvPost - its the name of TreeView T\n\nTo Read More Click this link\n<a href=\"http://muruganad.com/ASP.NET/ASP_.NET_How_to_Populate_a_TreeView_Control_With_TreeNode_s_Using_recursive_algorithm_or_recursion_.html\" rel=\"nofollow noreferrer\">http://muruganad.com/ASP.NET/ASP_.NET_How_to_Populate_a_TreeView_Control_With_TreeNode_s_Using_recursive_algorithm_or_recursion_.html</a>\n</pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an ASHX handler that returns an XML response (FileStructureXML.ashx). Now I need to get the XML response from the ASHX handler and use it as a data source for my ASPX page. If I point the XMLDataSource to a static XML file on the server, the treeview populates as expected. However, if I point the XMLDataSource to the ASHX handler instead of a static XML file on the server, it doesn't work. Any help would be appreciated. ``` <body> <form id="form1" runat="server"> <div> <asp:TreeView ID="TreeView_Folders" runat="server" DataSourceID="FileXML"> <DataBindings> <asp:TreeNodeBinding DataMember="Directory" TextField="Name" /> <asp:TreeNodeBinding DataMember="File" TextField="Name" /> </DataBindings> </asp:TreeView> </div> <div> <asp:XmlDataSource ID="FileXML" runat="server" DataFile="FileStructureXML.ashx"> </asp:XmlDataSource> </div> </form> </body> ```
I think that the XmlDataSource only works with an actual file, not a URL. You might be able to work around this by not specifying a DataFile property and loading the Data property dynamically in your code behind. I think the FirstChild.OuterXml selection is correct, but you may need to experiment. I'm not in a place where I can test it. ``` XmlDocument treeDoc = new XmlDocument(); treeDoc.Load( "~/FileStructureXML.ashx" ); // this takes a URL FileXml.Data = treeDoc.FirstChild.OuterXml; // everything after the xml definition ```
245,420
<p>Here's the situation - I've got a shell that loads an external .swf. Now, that .swf is 800x600, but it's an animation piece, and there are elements that extends off the stage. When I load the .swf into the shell and call its width attribute, it returns 1200 - because it's including the elements that break out of the stage.</p> <p>This isn't what I want - ideally, there would be two properties, one to return the 'calculated width' and one to return the 'default width'. Do these properties exist, and if not, what's the best workaround?</p>
[ { "answer_id": 247078, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>The width and height of the loaded SWF as defined by the FLA it was created with can be found in the <code>Loader</code> object in which you've loaded the SWF into.</p>\n\n<pre><code>swfLoader.contentLoaderInfo.width\nswfLoader.contentLoaderInfo.height\n</code></pre>\n\n<p>This will always show you the dimensions as defined in the FLA properties. It makes no difference if any images, MovieClips, or what have you extend off the stage.</p>\n\n<p>The <code>stage.stageWidth</code> and <code>stage.stageHeight</code> properties will always return the width of the stage, the stage is always the top most SWF. In other words, it will always represent the dimensions of the shell's stage. There is only ever one stage in a Flash application.</p>\n" }, { "answer_id": 248774, "author": "James Fassett", "author_id": 27081, "author_profile": "https://Stackoverflow.com/users/27081", "pm_score": 0, "selected": false, "text": "<p>Mark is very likely right that the <a href=\"http://livedocs.adobe.com/flex/3/langref/flash/display/LoaderInfo.html#width\" rel=\"nofollow noreferrer\">content loader info</a> object will contain the correct width and height. I've never checked myself so I can't guarantee it. The docs say 'nominal' and contrast it with 'actual' so it seems reasonable.</p>\n\n<p>There are a couple of other options. You can mask the external swf. Create a mask that is the size of the stage and put all content underneath it. Another idea is to create a movieclip based on a rectangular shape set it's alpha to 0 place it at x:0, y:0 and match it's width and height to stage. Give it an instance name and then when it is loaded use that value for the size.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14026/" ]
Here's the situation - I've got a shell that loads an external .swf. Now, that .swf is 800x600, but it's an animation piece, and there are elements that extends off the stage. When I load the .swf into the shell and call its width attribute, it returns 1200 - because it's including the elements that break out of the stage. This isn't what I want - ideally, there would be two properties, one to return the 'calculated width' and one to return the 'default width'. Do these properties exist, and if not, what's the best workaround?
The width and height of the loaded SWF as defined by the FLA it was created with can be found in the `Loader` object in which you've loaded the SWF into. ``` swfLoader.contentLoaderInfo.width swfLoader.contentLoaderInfo.height ``` This will always show you the dimensions as defined in the FLA properties. It makes no difference if any images, MovieClips, or what have you extend off the stage. The `stage.stageWidth` and `stage.stageHeight` properties will always return the width of the stage, the stage is always the top most SWF. In other words, it will always represent the dimensions of the shell's stage. There is only ever one stage in a Flash application.
245,441
<p>I want to add complex databinding to my custom winforms control, so I can do the following:</p> <pre><code>myControl.DisplayMember = "Name"; myControl.ValueMember = "Name"; myControl.DataSource = new List&lt;someObject&gt;(); </code></pre> <p>Does anyone know what interfaces, etc. have to be implemented to achieve this?</p> <p>I have had a look into it and all I found is <code>IBindableComponent</code>, but that seems to be for Simple Binding rather than Complex Binding.</p>
[ { "answer_id": 23501663, "author": "2ndstep", "author_id": 3609356, "author_profile": "https://Stackoverflow.com/users/3609356", "pm_score": 0, "selected": false, "text": "<p>Your class needs to inherit the DataBoundControl class instead of UserControl.</p>\n" }, { "answer_id": 53775033, "author": "Chris Tollefson", "author_id": 10366669, "author_profile": "https://Stackoverflow.com/users/10366669", "pm_score": 2, "selected": false, "text": "<p>Apply one of the following attributes to your custom control, depending on which kind of data binding you need:</p>\n\n<ul>\n<li>For complex data binding: <a href=\"https://learn.microsoft.com/dotnet/api/system.componentmodel.complexbindingpropertiesattribute\" rel=\"nofollow noreferrer\" title=\"Documentation\"><code>ComplexBindingPropertiesAttribute</code></a></li>\n<li>For lookup data binding: <a href=\"https://learn.microsoft.com/dotnet/api/system.componentmodel.lookupbindingpropertiesattribute\" rel=\"nofollow noreferrer\" title=\"Documentation\"><code>LookupBindingPropertiesAttribute</code></a></li>\n</ul>\n\n<p>(The question specifically mentions <em>complex</em> data binding, but the given code example looks like <em>lookup</em> data binding to me, so I have included both.)</p>\n\n<p>For example implementations, look at the <a href=\"https://referencesource.microsoft.com/\" rel=\"nofollow noreferrer\" title=\"Source code\">.NET Framework source code</a>:</p>\n\n<ul>\n<li><code>ComplexBindindPropertiesAttribute</code> implementation in <a href=\"https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/DataGridView.cs\" rel=\"nofollow noreferrer\" title=\"Source code\"><code>DataGridView</code></a></li>\n<li><code>LookupBindingPropertiesAttribute</code> implementation in <a href=\"https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/ListControl.cs\" rel=\"nofollow noreferrer\" title=\"Source code\"><code>ListControl</code></a></li>\n</ul>\n\n<hr>\n\n<p>But those implementations look very complicated to me, so it might be easier to embed an existing control (such as a <code>DataGridView</code>, <code>ListBox</code> or <code>ComboBox</code>) within your own custom control to take advantage of its existing data binding implementation, rather than writing your own. (You could make the embedded control invisible if necessary.) That is the approach demonstrated by Microsoft in the following guides:</p>\n\n<ul>\n<li><a href=\"https://learn.microsoft.com/visualstudio/data-tools/create-a-windows-forms-user-control-that-supports-complex-data-binding\" rel=\"nofollow noreferrer\">Create a Windows Forms user control that supports complex data binding</a></li>\n<li><a href=\"https://learn.microsoft.com/visualstudio/data-tools/create-a-windows-forms-user-control-that-supports-lookup-data-binding\" rel=\"nofollow noreferrer\">Create a Windows Forms user control that supports lookup data binding</a></li>\n</ul>\n\n<p>In those guides, they create a data source to bind the custom control to an external database, but it looks like you're simply trying to bind your custom control to an internal collection such as a <code>List&lt;T&gt;</code>. In that case, the adapted code below might work for you.</p>\n\n<hr>\n\n<p>In a Windows Forms project in Visual Studio, add a new <code>UserControl</code>.</p>\n\n<p>For <em>complex</em> data binding, apply the <code>ComplexBindingPropertiesAttribute</code> to the custom control. Add a <code>DataGridView</code> control to it. Add <code>DataSource</code> and <code>DataMember</code> properties, and hook them into the <code>DataGridView</code>'s own properties.</p>\n\n<pre><code>// ComplexBindingControl.cs\n// Adapted from https://learn.microsoft.com/visualstudio/data-tools/create-a-windows-forms-user-control-that-supports-complex-data-binding\n\nusing System.ComponentModel;\nusing System.Windows.Forms;\n\nnamespace BindingDemo\n{\n [ComplexBindingProperties(\"DataSource\", \"DataMember\")]\n public partial class ComplexBindingControl : UserControl\n {\n public ComplexBindingControl()\n {\n InitializeComponent();\n }\n\n // Use a DataGridView for its complex data binding implementation.\n\n public object DataSource\n {\n get =&gt; dataGridView1.DataSource;\n set =&gt; dataGridView1.DataSource = value;\n }\n\n public string DataMember\n {\n get =&gt; dataGridView1.DataMember;\n set =&gt; dataGridView1.DataMember = value;\n }\n }\n}\n</code></pre>\n\n<p>For <em>lookup</em> data binding, apply the <code>LookupBindingPropertiesAttribute</code> to the custom control. Add a <code>ListBox</code> or <code>ComboBox</code> control to it. Add <code>DataSource</code>, <code>DisplayMember</code>, <code>ValueMember</code> and <code>LookupMember</code> properties, and hook them into the <code>ListBox</code>'s or <code>ComboBox</code>'s own properties.</p>\n\n<pre><code>// LookupBindingControl.cs\n// Adapted from https://learn.microsoft.com/visualstudio/data-tools/create-a-windows-forms-user-control-that-supports-lookup-data-binding\n\nusing System.ComponentModel;\nusing System.Windows.Forms;\n\nnamespace BindingDemo\n{\n [LookupBindingProperties(\"DataSource\", \"DisplayMember\", \"ValueMember\", \"LookupMember\")]\n public partial class LookupBindingControl : UserControl\n {\n public LookupBindingControl()\n {\n InitializeComponent();\n }\n\n // Use a ListBox or ComboBox for its lookup data binding implementation.\n\n public object DataSource\n {\n get =&gt; listBox1.DataSource;\n set =&gt; listBox1.DataSource = value;\n }\n\n public string DisplayMember\n {\n get =&gt; listBox1.DisplayMember;\n set =&gt; listBox1.DisplayMember = value;\n }\n\n public string ValueMember\n {\n get =&gt; listBox1.ValueMember;\n set =&gt; listBox1.ValueMember = value;\n }\n\n public string LookupMember\n {\n get =&gt; listBox1.SelectedValue?.ToString();\n set =&gt; listBox1.SelectedValue = value;\n }\n }\n}\n</code></pre>\n\n<p>(<em>Edit:</em> thanks to <a href=\"https://stackoverflow.com/a/56788463/10366669\">Frank's answer</a> for reminding me that <code>listBox1.SelectedValue</code> could be <code>null</code>.)</p>\n\n<p>To test it, build the project in Visual Studio, then add an instance of the custom control to a <code>Form</code>. Create some sample data, and bind it to the custom control using its relevant properties.</p>\n\n<pre><code>// Form1.cs\n\nusing System.Collections.Generic;\nusing System.Windows.Forms;\n\nnamespace BindingDemo\n{\n public partial class Form1 : Form\n {\n private readonly List&lt;SomeObject&gt; data;\n\n public Form1()\n {\n InitializeComponent();\n\n // Prepare some sample data.\n data = new List&lt;SomeObject&gt;\n {\n new SomeObject(\"Alice\"),\n new SomeObject(\"Bob\"),\n new SomeObject(\"Carol\"),\n };\n\n // Bind the data to your custom control...\n\n // ...for \"complex\" data binding:\n complexBindingControl1.DataSource = data;\n\n // ...for \"lookup\" data binding:\n lookupBindingControl1.DataSource = data;\n lookupBindingControl1.DisplayMember = \"Name\";\n lookupBindingControl1.ValueMember = \"Name\";\n }\n }\n\n internal class SomeObject\n {\n public SomeObject(string name)\n {\n Name = name;\n }\n\n public string Name { get; set; }\n }\n}\n</code></pre>\n" }, { "answer_id": 56788463, "author": "Frank", "author_id": 5674529, "author_profile": "https://Stackoverflow.com/users/5674529", "pm_score": 0, "selected": false, "text": "<p>To run the very helpfull example of Chris Tollefson BindingDemo without problems put a try/catch Block around the LookupMember getter like this:</p>\n\n<pre><code>public string LookupMember {\n get {\n try {\n return listBox1.SelectedValue.ToString();\n }\n catch { return null; }\n }\n set =&gt; listBox1.SelectedValue = value;\n }\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1736/" ]
I want to add complex databinding to my custom winforms control, so I can do the following: ``` myControl.DisplayMember = "Name"; myControl.ValueMember = "Name"; myControl.DataSource = new List<someObject>(); ``` Does anyone know what interfaces, etc. have to be implemented to achieve this? I have had a look into it and all I found is `IBindableComponent`, but that seems to be for Simple Binding rather than Complex Binding.
Apply one of the following attributes to your custom control, depending on which kind of data binding you need: * For complex data binding: [`ComplexBindingPropertiesAttribute`](https://learn.microsoft.com/dotnet/api/system.componentmodel.complexbindingpropertiesattribute "Documentation") * For lookup data binding: [`LookupBindingPropertiesAttribute`](https://learn.microsoft.com/dotnet/api/system.componentmodel.lookupbindingpropertiesattribute "Documentation") (The question specifically mentions *complex* data binding, but the given code example looks like *lookup* data binding to me, so I have included both.) For example implementations, look at the [.NET Framework source code](https://referencesource.microsoft.com/ "Source code"): * `ComplexBindindPropertiesAttribute` implementation in [`DataGridView`](https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/DataGridView.cs "Source code") * `LookupBindingPropertiesAttribute` implementation in [`ListControl`](https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/ListControl.cs "Source code") --- But those implementations look very complicated to me, so it might be easier to embed an existing control (such as a `DataGridView`, `ListBox` or `ComboBox`) within your own custom control to take advantage of its existing data binding implementation, rather than writing your own. (You could make the embedded control invisible if necessary.) That is the approach demonstrated by Microsoft in the following guides: * [Create a Windows Forms user control that supports complex data binding](https://learn.microsoft.com/visualstudio/data-tools/create-a-windows-forms-user-control-that-supports-complex-data-binding) * [Create a Windows Forms user control that supports lookup data binding](https://learn.microsoft.com/visualstudio/data-tools/create-a-windows-forms-user-control-that-supports-lookup-data-binding) In those guides, they create a data source to bind the custom control to an external database, but it looks like you're simply trying to bind your custom control to an internal collection such as a `List<T>`. In that case, the adapted code below might work for you. --- In a Windows Forms project in Visual Studio, add a new `UserControl`. For *complex* data binding, apply the `ComplexBindingPropertiesAttribute` to the custom control. Add a `DataGridView` control to it. Add `DataSource` and `DataMember` properties, and hook them into the `DataGridView`'s own properties. ``` // ComplexBindingControl.cs // Adapted from https://learn.microsoft.com/visualstudio/data-tools/create-a-windows-forms-user-control-that-supports-complex-data-binding using System.ComponentModel; using System.Windows.Forms; namespace BindingDemo { [ComplexBindingProperties("DataSource", "DataMember")] public partial class ComplexBindingControl : UserControl { public ComplexBindingControl() { InitializeComponent(); } // Use a DataGridView for its complex data binding implementation. public object DataSource { get => dataGridView1.DataSource; set => dataGridView1.DataSource = value; } public string DataMember { get => dataGridView1.DataMember; set => dataGridView1.DataMember = value; } } } ``` For *lookup* data binding, apply the `LookupBindingPropertiesAttribute` to the custom control. Add a `ListBox` or `ComboBox` control to it. Add `DataSource`, `DisplayMember`, `ValueMember` and `LookupMember` properties, and hook them into the `ListBox`'s or `ComboBox`'s own properties. ``` // LookupBindingControl.cs // Adapted from https://learn.microsoft.com/visualstudio/data-tools/create-a-windows-forms-user-control-that-supports-lookup-data-binding using System.ComponentModel; using System.Windows.Forms; namespace BindingDemo { [LookupBindingProperties("DataSource", "DisplayMember", "ValueMember", "LookupMember")] public partial class LookupBindingControl : UserControl { public LookupBindingControl() { InitializeComponent(); } // Use a ListBox or ComboBox for its lookup data binding implementation. public object DataSource { get => listBox1.DataSource; set => listBox1.DataSource = value; } public string DisplayMember { get => listBox1.DisplayMember; set => listBox1.DisplayMember = value; } public string ValueMember { get => listBox1.ValueMember; set => listBox1.ValueMember = value; } public string LookupMember { get => listBox1.SelectedValue?.ToString(); set => listBox1.SelectedValue = value; } } } ``` (*Edit:* thanks to [Frank's answer](https://stackoverflow.com/a/56788463/10366669) for reminding me that `listBox1.SelectedValue` could be `null`.) To test it, build the project in Visual Studio, then add an instance of the custom control to a `Form`. Create some sample data, and bind it to the custom control using its relevant properties. ``` // Form1.cs using System.Collections.Generic; using System.Windows.Forms; namespace BindingDemo { public partial class Form1 : Form { private readonly List<SomeObject> data; public Form1() { InitializeComponent(); // Prepare some sample data. data = new List<SomeObject> { new SomeObject("Alice"), new SomeObject("Bob"), new SomeObject("Carol"), }; // Bind the data to your custom control... // ...for "complex" data binding: complexBindingControl1.DataSource = data; // ...for "lookup" data binding: lookupBindingControl1.DataSource = data; lookupBindingControl1.DisplayMember = "Name"; lookupBindingControl1.ValueMember = "Name"; } } internal class SomeObject { public SomeObject(string name) { Name = name; } public string Name { get; set; } } } ```
245,447
<p>Using Python I want to be able to draw text at different angles using PIL.</p> <p>For example, imagine you were drawing the number around the face of a clock. The number <strong>3</strong> would appear as expected whereas <strong>12</strong> would we drawn rotated counter-clockwise 90 degrees.</p> <p>Therefore, I need to be able to draw many different strings at many different angles.</p>
[ { "answer_id": 245837, "author": "user12861", "author_id": 12861, "author_profile": "https://Stackoverflow.com/users/12861", "pm_score": 2, "selected": false, "text": "<p>I'm not saying this is going to be easy, or that this solution will necessarily be perfect for you, but look at the documentation here:<p>\n<a href=\"http://effbot.org/imagingbook/pil-index.htm\" rel=\"nofollow noreferrer\"><a href=\"http://effbot.org/imagingbook/pil-index.htm\" rel=\"nofollow noreferrer\">http://effbot.org/imagingbook/pil-index.htm</a></a>\n<p>\nand especially pay attention to the Image, ImageDraw, and ImageFont modules.</p>\n\n<p>Here's an example to help you out:<p></p>\n\n<pre><code>\nimport Image\nim = Image.new(\"RGB\", (100, 100))\nimport ImageDraw\ndraw = ImageDraw.Draw(im)\ndraw.text((50, 50), \"hey\")\nim.rotate(45).show()\n</code></pre>\n\n<p>To do what you really want you may need to make a bunch of separate correctly rotated text images and then compose them all together with some more fancy manipulation. And after all that it still may not look great. I'm not sure how antialiasing and such is handled for instance, but it might not be good. Good luck, and if anyone has an easier way, I'd be interested to know as well.</p>\n" }, { "answer_id": 245892, "author": "DarenW", "author_id": 10468, "author_profile": "https://Stackoverflow.com/users/10468", "pm_score": 7, "selected": true, "text": "<p>Draw text into a temporary blank image, rotate that, then paste that onto the original image. You could wrap up the steps in a function. Good luck figuring out the exact coordinates to use - my cold-fogged brain isn't up to it right now. </p>\n\n<p>This demo writes yellow text on a slant over an image:</p>\n\n<pre><code># Demo to add rotated text to an image using PIL\n\nimport Image\nimport ImageFont, ImageDraw, ImageOps\n\nim=Image.open(\"stormy100.jpg\")\n\nf = ImageFont.load_default()\ntxt=Image.new('L', (500,50))\nd = ImageDraw.Draw(txt)\nd.text( (0, 0), \"Someplace Near Boulder\", font=f, fill=255)\nw=txt.rotate(17.5, expand=1)\n\nim.paste( ImageOps.colorize(w, (0,0,0), (255,255,84)), (242,60), w)\n</code></pre>\n" }, { "answer_id": 741592, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>It's also usefull to know our text's size in pixels before we create an Image object. I used such code when drawing graphs. Then I got no problems e.g. with alignment of data labels (the image is exactly as big as the text).</p>\n\n<pre><code>(...)\nimg_main = Image.new(\"RGB\", (200, 200))\nfont = ImageFont.load_default()\n\n# Text to be rotated...\nrotate_text = u'This text should be rotated.'\n\n# Image for text to be rotated\nimg_txt = Image.new('L', font.getsize(rotate_text))\ndraw_txt = ImageDraw.Draw(img_txt)\ndraw_txt.text((0,0), rotate_text, font=font, fill=255)\nt = img_value_axis.rotate(90, expand=1)\n</code></pre>\n\n<p>The rest of joining the two images together is already described on this page.\nWhen you rotate by an \"unregular\" angle, you have to improve this code a little bit. It actually works for 90, 180, 270...</p>\n" }, { "answer_id": 35586716, "author": "stenci", "author_id": 1899628, "author_profile": "https://Stackoverflow.com/users/1899628", "pm_score": 3, "selected": false, "text": "<p>Here is a working version, inspired by the answer, but it works without opening or saving images.</p>\n\n<p>The two images have colored background and alpha channel different from zero to show what's going on. Changing the two alpha channels from 92 to 0 will make them completely transparent.</p>\n\n<pre><code>from PIL import Image, ImageFont, ImageDraw\n\ntext = 'TEST'\nfont = ImageFont.truetype(r'C:\\Windows\\Fonts\\Arial.ttf', 50)\nwidth, height = font.getsize(text)\n\nimage1 = Image.new('RGBA', (200, 150), (0, 128, 0, 92))\ndraw1 = ImageDraw.Draw(image1)\ndraw1.text((0, 0), text=text, font=font, fill=(255, 128, 0))\n\nimage2 = Image.new('RGBA', (width, height), (0, 0, 128, 92))\ndraw2 = ImageDraw.Draw(image2)\ndraw2.text((0, 0), text=text, font=font, fill=(0, 255, 128))\n\nimage2 = image2.rotate(30, expand=1)\n\npx, py = 10, 10\nsx, sy = image2.size\nimage1.paste(image2, (px, py, px + sx, py + sy), image2)\n\nimage1.show()\n</code></pre>\n" }, { "answer_id": 63005869, "author": "Harry Moreno", "author_id": 630752, "author_profile": "https://Stackoverflow.com/users/630752", "pm_score": 2, "selected": false, "text": "<p>Here's a fuller example of watermarking diagonally. Handles arbitrary image ratios, sizes and text lengths by calculating the angle of the diagonal and font size.</p>\n<pre><code>from PIL import Image, ImageFont, ImageDraw\nimport math\n\n# sample dimensions\npdf_width = 1000\npdf_height = 1500\n\n#text_to_be_rotated = 'Harry Moreno'\ntext_to_be_rotated = 'Harry Moreno ([email protected])'\nmessage_length = len(text_to_be_rotated)\n\n# load font (tweak ratio based on your particular font)\nFONT_RATIO = 1.5\nDIAGONAL_PERCENTAGE = .5\ndiagonal_length = int(math.sqrt((pdf_width**2) + (pdf_height**2)))\ndiagonal_to_use = diagonal_length * DIAGONAL_PERCENTAGE\nfont_size = int(diagonal_to_use / (message_length / FONT_RATIO))\nfont = ImageFont.truetype(r'./venv/lib/python3.7/site-packages/reportlab/fonts/Vera.ttf', font_size)\n#font = ImageFont.load_default() # fallback\n\n# target\nimage = Image.new('RGBA', (pdf_width, pdf_height), (0, 128, 0, 92))\n\n# watermark\nopacity = int(256 * .5)\nmark_width, mark_height = font.getsize(text_to_be_rotated)\nwatermark = Image.new('RGBA', (mark_width, mark_height), (0, 0, 0, 0))\ndraw = ImageDraw.Draw(watermark)\ndraw.text((0, 0), text=text_to_be_rotated, font=font, fill=(0, 0, 0, opacity))\nangle = math.degrees(math.atan(pdf_height/pdf_width))\nwatermark = watermark.rotate(angle, expand=1)\n\n# merge\nwx, wy = watermark.size\npx = int((pdf_width - wx)/2)\npy = int((pdf_height - wy)/2)\nimage.paste(watermark, (px, py, px + wx, py + wy), watermark)\n\nimage.show()\n</code></pre>\n<p>Here it is in a colab <a href=\"https://colab.research.google.com/drive/1ERl7PiX6xKy5H9EEMulBKPgglF6euCNA?usp=sharing\" rel=\"nofollow noreferrer\">https://colab.research.google.com/drive/1ERl7PiX6xKy5H9EEMulBKPgglF6euCNA?usp=sharing</a> you should provide an example image to the colab.\n<a href=\"https://i.stack.imgur.com/l4yeq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/l4yeq.png\" alt=\"500 by 300\" /></a><a href=\"https://i.stack.imgur.com/4vKrT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4vKrT.png\" alt=\"300 by 500\" /></a></p>\n" }, { "answer_id": 67285956, "author": "mafu", "author_id": 39590, "author_profile": "https://Stackoverflow.com/users/39590", "pm_score": 2, "selected": false, "text": "<p>The previous answers draw into a new image, rotate it, and draw it back into the source image. This leaves text artifacts. We don't want that.</p>\n<p>Here is a version that instead crops the area of the source image that will be drawn onto, rotates it, draws into that, and rotates it back. This means that we draw onto the final surface immediately, without having to resort to masks.</p>\n<pre><code>def draw_text_90_into (text: str, into, at):\n # Measure the text area\n font = ImageFont.truetype (r'C:\\Windows\\Fonts\\Arial.ttf', 16)\n wi, hi = font.getsize (text)\n\n # Copy the relevant area from the source image\n img = into.crop ((at[0], at[1], at[0] + hi, at[1] + wi))\n\n # Rotate it backwards\n img = img.rotate (270, expand = 1)\n\n # Print into the rotated area\n d = ImageDraw.Draw (img)\n d.text ((0, 0), text, font = font, fill = (0, 0, 0))\n\n # Rotate it forward again\n img = img.rotate (90, expand = 1)\n\n # Insert it back into the source image\n # Note that we don't need a mask\n into.paste (img, at)\n</code></pre>\n<p>Supporting other angles, colors etc is trivial to add.</p>\n" }, { "answer_id": 73445706, "author": "Tobias Teleman", "author_id": 803457, "author_profile": "https://Stackoverflow.com/users/803457", "pm_score": 0, "selected": false, "text": "<p>If you a using aggdraw, you can use settransform() to rotate the text. It's a bit undocumented, since effbot.org is offline.</p>\n<pre><code># Matrix operations\ndef translate(x, y):\n return np.array([[1, 0, x], [0, 1, y], [0, 0, 1]])\n\n\ndef rotate(angle):\n c, s = np.cos(angle), np.sin(angle)\n return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])\n\n\ndef draw_text(image, text, font, x, y, angle):\n &quot;&quot;&quot;Draw text at x,y and rotated angle radians on the given PIL image&quot;&quot;&quot;\n m = np.matmul(translate(x, y), rotate(angle))\n transform = [m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2]]\n draw = aggdraw.Draw(image)\n draw.settransform(transform)\n draw.text((tx, ty), text, font)\n draw.settransform()\n draw.flush()\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20498/" ]
Using Python I want to be able to draw text at different angles using PIL. For example, imagine you were drawing the number around the face of a clock. The number **3** would appear as expected whereas **12** would we drawn rotated counter-clockwise 90 degrees. Therefore, I need to be able to draw many different strings at many different angles.
Draw text into a temporary blank image, rotate that, then paste that onto the original image. You could wrap up the steps in a function. Good luck figuring out the exact coordinates to use - my cold-fogged brain isn't up to it right now. This demo writes yellow text on a slant over an image: ``` # Demo to add rotated text to an image using PIL import Image import ImageFont, ImageDraw, ImageOps im=Image.open("stormy100.jpg") f = ImageFont.load_default() txt=Image.new('L', (500,50)) d = ImageDraw.Draw(txt) d.text( (0, 0), "Someplace Near Boulder", font=f, fill=255) w=txt.rotate(17.5, expand=1) im.paste( ImageOps.colorize(w, (0,0,0), (255,255,84)), (242,60), w) ```
245,453
<p>I'm pretty new to the idea of recursion and this is actually my first attempt at writing a recursive method. </p> <p>I tried to implement a recursive function Max that passes an array, along with a variable that holds the array's size in order to print the largest element. </p> <p>It works, but it just doesn't <em>feel</em> right!</p> <p>I have also noticed that I seem to use the static modifier much more than my classmates in general...</p> <p>Can anybody please provide any general tips as well as feedback as to how I can improve my code?</p> <pre><code>public class RecursiveTry{ static int[] n = new int[] {1,2,4,3,3,32,100}; static int current = 0; static int maxValue = 0; static int SIZE = n.length; public static void main(String[] args){ System.out.println(Max(n, SIZE)); } public static int Max(int[] n, int SIZE) { if(current &lt;= SIZE - 1){ if (maxValue &lt;= n[current]) { maxValue = n[current]; current++; Max(n, SIZE); } else { current++; Max(n, SIZE); } } return maxValue; } </code></pre> <p>}</p>
[ { "answer_id": 245463, "author": "XPav", "author_id": 27550, "author_profile": "https://Stackoverflow.com/users/27550", "pm_score": 2, "selected": false, "text": "<p>A \"max\" function is the wrong type of thing to write a recursive function for -- and the fact you're using static values for \"current\" and \"maxValue\" makes your function not really a recursive function.</p>\n\n<p>Why not do something a little more amenable to a recursive algorithm, like factorial?</p>\n" }, { "answer_id": 245468, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": true, "text": "<p>Your use of static variables for holding state outside the function will be a source of difficulty.</p>\n\n<p>An example of a recursive implementation of a max() function in pseudocode might be:</p>\n\n<pre><code>function Max(data, size) {\n assert(size &gt; 0)\n if (size == 1) {\n return data[0]\n }\n maxtail = Max(data[1..size], size-1)\n if (data[0] &gt; maxtail) {\n return data[0]\n } else {\n return maxtail\n }\n}\n</code></pre>\n\n<p>The key here is the recursive call to Max(), where you pass everything <em>except</em> the first element, and one less than the size. The general idea is this function says \"the maximum value in this data is either the first element, or the maximum of the values in the rest of the array, whichever is larger\".</p>\n\n<p>This implementation requires no static data outside the function definition.</p>\n\n<p>One of the hallmarks of recursive implementations is a so-called \"termination condition\" which prevents the recursion from going on forever (or, until you get a stack overflow). In the above case, the test for <code>size == 1</code> is the termination condition.</p>\n" }, { "answer_id": 245472, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": -1, "selected": false, "text": "<p>First, let's take care of the static scope issue ... Your class is defining an object, but never actually instantiating one. Since main is statically scoped, the first thing to do is get an object, then execute it's methods like this:</p>\n\n<pre><code>public class RecursiveTry{\n\n private int[] n = {1,2,4,3,3,32,100};\n\n public static void main(String[] args){\n RecursiveTry maxObject = new RecursiveTry();\n System.out.println(maxObject.Max(maxObject.n, 0));\n }\n\n public int Max(int[] n, int start) {\n if(start == n.length - 1) {\n return n[start];\n } else { \n int maxRest = Max(n, start + 1);\n if(n[start] &gt; maxRest) {\n return n[start];\n }\n return maxRest;\n }\n }\n\n}\n</code></pre>\n\n<p>So now we have a RecursiveTry object named maxObject that does not require the static scope. I'm not sure that finding a maximum is effective using recursion as the number of iterations in the traditional looping method is roughly equivalent, but the amount of stack used is larger using recursion. But for this example, I'd pare it down a lot.</p>\n\n<p>One of the advantages of recursion is that your state doesn't generally need to be persisted during the repeated tests like it does in iteration. Here, I've conceded to the use of a variable to hold the starting point, because it's less CPU intensive that passing a new int[] that contains all the items except for the first one.</p>\n" }, { "answer_id": 245477, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 0, "selected": false, "text": "<p>You are essentially writing an iterative version but using tail recursion for the looping. Also, by making so many variables static, you are essentially using global variables instead of objects. Here is an attempt at something closer to a typical recursive implementation. Of course, in real life if you were using a language like Java that doesn't optimize tail calls, you would implement a \"Max\" function using a loop.</p>\n\n<pre><code>public class RecursiveTry{\n static int[] n;\n\n public static void main(String[] args){\n RecursiveTry t = new RecursiveTry(new int[] {1,2,4,3,3,32,100});\n System.out.println(t.Max());\n } \n\n RecursiveTry(int[] arg) {\n n = arg;\n }\n\n public int Max() {\n return MaxHelper(0);\n }\n\n private int MaxHelper(int index) {\n if(index == n.length-1) {\n return n[index];\n } else {\n int maxrest = MaxHelper(index+1);\n int current = n[index];\n if(current &gt; maxrest)\n return current;\n else\n return maxrest;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 245492, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 2, "selected": false, "text": "<p>\"not-homework\"?</p>\n\n<p>Anyway. First things first. The</p>\n\n<pre><code>static int[] n = new int[] {1,2,4,3,3,32,100};\nstatic int SIZE = n.length;\n</code></pre>\n\n<p>have nothing to do with the parameters of Max() with which they share their names. Move these over to main and lose the \"static\" specifiers. They are used only once, when calling the first instance of Max() from inside main(). Their scope shouldn't extend beyond main().</p>\n\n<p>There is no reason for all invocations of Max() to share a single \"current\" index. \"current\" should be local to Max(). But then how would successive recurrences of Max() know what value of \"current\" to use? (Hint: Max() is already passing other Max()'s lower down the line some data. Add \"current\" to this data.)</p>\n\n<p>The same thing goes for maxValue, though the situation here is a bit more complex. Not only do you need to pass a current \"maxValue\" down the line, but when the recursion finishes, you have to pass it back up all the way to the first Max() function, which will return it to main(). You may need to look at some other examples of recursion and spend some time with this one.</p>\n\n<p>Finally, Max() itself is static. Once you've eliminated the need to refer to external data (the static variables) however; it doesn't really matter. It just means that you can call Max() without having to instantiate an object.</p>\n" }, { "answer_id": 245493, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>Making your function dependent on static variables is not a good idea. Here is possible implementation of recursive Max function:</p>\n\n<pre><code>int Max(int[] array, int currentPos, int maxValue) {\n // Ouch!\n if (currentPos &lt; 0) {\n raise some error\n }\n // We reached the end of the array, return latest maxValue\n if (currentPos &gt;= array.length) {\n return maxValue;\n }\n // Is current value greater then latest maxValue ?\n int currentValue = array[currentPos];\n if (currentValue &gt; maxValue) {\n // currentValue is a new maxValue\n return Max(array, currentPos + 1, currentValue);\n } else {\n // maxValue is still a max value\n return Max(array, currentPos + 1, maxValue);\n }\n}\n...\n\nint[] array = new int[] {...};\nint currentPos = 0;\nint maxValue = array[currentPos] or minimum int value; \n maxValue = Max(array, currentPos, maxValue);\n</code></pre>\n" }, { "answer_id": 245495, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p>As others have observed, there is no <em>need</em> for recursion to implement a Max function, but it can be instructive to use a familiar algorithm to experiment with a new concept. So, here is the simplified code, with an explanation below:</p>\n\n<pre><code>public class RecursiveTry\n{\n public static void main(String[] args)\n {\n System.out.println(Max(new int[] {1,2,4,3,3,32,100}, 0, 0));\n } \n\n public static int Max(int[] n, int current, int maxValue) \n {\n if(current &lt; n.Length)\n {\n if (maxValue &lt;= n[current] || current == 0))\n {\n return Max(n, current+1, n[current]);\n }\n return Max(n, current+1, maxValue);\n }\n return maxValue;\n }\n}\n</code></pre>\n\n<p>all of the static state is gone as unnecessary; instead everything is passed on the stack. the internal logic of the Max function is streamlined, and we recurse in two different ways just for fun</p>\n" }, { "answer_id": 245540, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 0, "selected": false, "text": "<p>In Scheme this can be written very concisely:</p>\n\n<pre><code>(define (max l)\n (if (= (length l) 1)\n (first l)\n (local ([define maxRest (max (rest l))])\n (if (&gt; (first l) maxRest)\n (first l)\n maxRest))))\n</code></pre>\n\n<p>Granted, this uses linked lists and not arrays, which is why I didn't pass it a size element, but I feel this distills the problem to its essence. This is the pseudocode definition:</p>\n\n<pre><code>define max of a list as:\n if the list has one element, return that element\n otherwise, the max of the list will be the max between the first element and the max of the rest of the list\n</code></pre>\n" }, { "answer_id": 245627, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>Here's a Java version for you.</p>\n\n<pre><code>public class Recursion {\n\n public static void main(String[] args) {\n int[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n System.out.println(\"Max: \" + max(0, data));\n }\n\n public static int max(int i, int[] arr) {\n if(i == arr.length-1) {\n return arr[i];\n }\n\n int memo = max(i+1, arr);\n if(arr[i] &gt; memo) {\n return arr[i];\n }\n return memo;\n }\n}\n</code></pre>\n\n<p>The recurrence relation is that the maximum element of an array is either the first element, or the maximum of the rest of the array. The stop condition is reached when you reach the end of the array. Note the use of memoization to reduce the recursive calls (roughly) in half.</p>\n" }, { "answer_id": 245680, "author": "RodeoClown", "author_id": 943, "author_profile": "https://Stackoverflow.com/users/943", "pm_score": 0, "selected": false, "text": "<p>A nicer way of getting the max value of an array recursively would be to implement <a href=\"http://en.wikipedia.org/wiki/Quicksort\" rel=\"nofollow noreferrer\">quicksort</a> (which is a nice, recursive sorting algorithm), and then just return the first value.</p>\n\n<p>Here is some <a href=\"http://www.cs.princeton.edu/introcs/42sort/QuickSort.java.html\" rel=\"nofollow noreferrer\">Java code for quicksort</a>.</p>\n" }, { "answer_id": 245726, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "<p>Smallest codesize I could get:</p>\n\n<pre><code>public class RecursiveTry {\n public static void main(String[] args) {\n int[] x = new int[] {1,2,4,3,3,32,100};\n System.out.println(Max(x, 0));\n } \n\n public static int Max(int[] arr, int currPos) {\n if (arr.length == 0) return -1;\n if (currPos == arr.length) return arr[0];\n int len = Max (arr, currPos + 1);\n if (len &lt; arr[currPos]) return arr[currPos];\n return len;\n }\n}\n</code></pre>\n\n<p>A few things:</p>\n\n<p>1/ If the array is zero-size, it returns a max of -1 (you could have another marker value, say, -MAX_INT, or throw an exception). I've made the assumption for code clarity here to assume all values are zero or more. Otherwise I would have peppered the code with all sorts of unnecessary stuff (in regards to answering the question).</p>\n\n<p>2/ Most recursions are 'cleaner' in my opinion if the terminating case is no-data rather than last-data, hence I return a value guaranteed to be less than or equal to the max when we've finished the array. Others may differ in their opinion but it wouldn't be the first or last time that they've been wrong :-).</p>\n\n<p>3/ The recursive call just gets the max of the rest of the list and compares it to the current element, returning the maximum of the two.</p>\n\n<p>4/ The 'ideal' solution would have been to pass a modified array on each recursive call so that you're only comparing the first element with the rest of the list, removing the need for currPos. But that would have been inefficient and would have bought down the wrath of SO.</p>\n\n<p>5/ This may not necessarily be the best solution. It may be that by gray matter has been compromised from too much use of LISP with its CAR, CDR and those interminable parentheses.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14013/" ]
I'm pretty new to the idea of recursion and this is actually my first attempt at writing a recursive method. I tried to implement a recursive function Max that passes an array, along with a variable that holds the array's size in order to print the largest element. It works, but it just doesn't *feel* right! I have also noticed that I seem to use the static modifier much more than my classmates in general... Can anybody please provide any general tips as well as feedback as to how I can improve my code? ``` public class RecursiveTry{ static int[] n = new int[] {1,2,4,3,3,32,100}; static int current = 0; static int maxValue = 0; static int SIZE = n.length; public static void main(String[] args){ System.out.println(Max(n, SIZE)); } public static int Max(int[] n, int SIZE) { if(current <= SIZE - 1){ if (maxValue <= n[current]) { maxValue = n[current]; current++; Max(n, SIZE); } else { current++; Max(n, SIZE); } } return maxValue; } ``` }
Your use of static variables for holding state outside the function will be a source of difficulty. An example of a recursive implementation of a max() function in pseudocode might be: ``` function Max(data, size) { assert(size > 0) if (size == 1) { return data[0] } maxtail = Max(data[1..size], size-1) if (data[0] > maxtail) { return data[0] } else { return maxtail } } ``` The key here is the recursive call to Max(), where you pass everything *except* the first element, and one less than the size. The general idea is this function says "the maximum value in this data is either the first element, or the maximum of the values in the rest of the array, whichever is larger". This implementation requires no static data outside the function definition. One of the hallmarks of recursive implementations is a so-called "termination condition" which prevents the recursion from going on forever (or, until you get a stack overflow). In the above case, the test for `size == 1` is the termination condition.
245,456
<p>I'm looking for a way to get the name of the main HTML form so I can submit it from JavaScript.</p> <p>The reason I can just set the name of the form is because the JavaScript is on a User Control that could get added to many different sites with different form names.</p> <p>Thanks.</p>
[ { "answer_id": 245489, "author": "Mohamed Faramawi", "author_id": 20006, "author_profile": "https://Stackoverflow.com/users/20006", "pm_score": 2, "selected": false, "text": "<p>I'm not sure , try \"YourUserControl.Page.Form\"</p>\n\n<p>But why do you need the form name, are you going to have more than one form on your .aspx page , if not, you can get the whole post back JS code for the control that will do the post back (submit) using \"Page.ClientScript.GetPostBackEventReference()\" and use it to set the \"OnClick\" attribute of whatever you will use to submit the page.</p>\n" }, { "answer_id": 245491, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": "<p>ASP.NET pages can only have one form, so its safe to just do:</p>\n\n<pre><code> document.forms[0].submit();\n</code></pre>\n" }, { "answer_id": 245500, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>you can't have more than one form control with runat=\"server\" on an aspx page, so you cn use document.forms[0]</p>\n" }, { "answer_id": 245506, "author": "Andrew Theken", "author_id": 32238, "author_profile": "https://Stackoverflow.com/users/32238", "pm_score": 4, "selected": true, "text": "<p>I'm not totally sure that this will address what you're asking for, so please comment on it:</p>\n\n<p>In your script, when the User Control renders, you could have this placed in there. So long as script doesn't have a \"runat\" attribute, you should be good.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n\nvar formname = '&lt;%=this.Page.Form.Name %&gt;';\n\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 73158533, "author": "masoud rafiee", "author_id": 4256602, "author_profile": "https://Stackoverflow.com/users/4256602", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;script type=&quot;text/javascript&quot;&gt;\n\nvar formname = '&lt;%=this.Page.AppRelativeVirtualPath.Replace(this.Page.AppRelativeTemplateSourceDirectory,&quot;&quot;)%&gt;';\n\n&lt;/script&gt;\n \n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10420/" ]
I'm looking for a way to get the name of the main HTML form so I can submit it from JavaScript. The reason I can just set the name of the form is because the JavaScript is on a User Control that could get added to many different sites with different form names. Thanks.
I'm not totally sure that this will address what you're asking for, so please comment on it: In your script, when the User Control renders, you could have this placed in there. So long as script doesn't have a "runat" attribute, you should be good. ``` <script type="text/javascript"> var formname = '<%=this.Page.Form.Name %>'; </script> ```
245,465
<p>How do you connect to a remote server via IP address in the manner that TOAD, SqlDeveloper, are able to connect to databases with just the ip address, username, SID and password?</p> <p>Whenever I try to specify and IP address, it seems to be taking it locally.</p> <p>In other words, how should the string for cx_Oracle.connect() be formatted to a non local database?</p> <p>There was a previous post which listed as an answer connecting to Oracle via cx_Oracle module with the following code:</p> <pre><code>#!/usr/bin/python import cx_Oracle connstr='scott/tiger' conn = cx_Oracle.connect(connstr) curs = conn.cursor() curs.execute('select * from emp') print curs.description for row in curs: print row conn.close() </code></pre>
[ { "answer_id": 1181699, "author": "Jeffrey Kemp", "author_id": 103295, "author_profile": "https://Stackoverflow.com/users/103295", "pm_score": 5, "selected": false, "text": "<p>You can specify the server in the connection string, e.g.:</p>\n\n<pre><code>import cx_Oracle\nconnstr = 'scott/tiger@server:1521/orcl'\nconn = cx_Oracle.connect(connstr)\n</code></pre>\n\n<ul>\n<li>\"server\" is the server, or the IP address if you want.</li>\n<li>\"1521\" is the port that the database is listening on.</li>\n<li>\"orcl\" is the name of the instance (or database service).</li>\n</ul>\n" }, { "answer_id": 1870849, "author": "Kevin Horn", "author_id": 134391, "author_profile": "https://Stackoverflow.com/users/134391", "pm_score": 6, "selected": false, "text": "<p>I like to do it this way:</p>\n\n<pre><code>ip = '192.168.0.1'\nport = 1521\nSID = 'YOURSIDHERE'\ndsn_tns = cx_Oracle.makedsn(ip, port, SID)\n\ndb = cx_Oracle.connect('username', 'password', dsn_tns)\n</code></pre>\n\n<p>One of the main reasons I like this method is that I usually have a TNSNAMES.ORA file lying around someplace, and I can check that the <code>dsn_tns</code> object will do the right thing by doing: </p>\n\n<pre><code>print dsn_tns\n</code></pre>\n\n<p>and comparing the output to my TNSNAMES.ORA</p>\n" }, { "answer_id": 39984489, "author": "Gerrat", "author_id": 429982, "author_profile": "https://Stackoverflow.com/users/429982", "pm_score": 2, "selected": false, "text": "<p>Instead of specifying the SID, you can create a dsn and <a href=\"http://cx-oracle.readthedocs.io/en/latest/module.html#cx_Oracle.makedsn\" rel=\"nofollow\">connect via service_name</a> like: </p>\n\n<pre><code>import cx_Oracle\nip = '192.168.0.1'\nport = 1521\nservice_name = 'my_service'\ndsn = cx_Oracle.makedsn(ip, port, service_name=service_name)\n\ndb = cx_Oracle.connect('user', 'password', dsn)\n</code></pre>\n\n<p>The benefit of using the service name instead of the specific instance identifier (SID), is that it will work in a RAC environment as well (using a SID won't). This parameter is available as of <a href=\"https://bitbucket.org/anthony_tuininga/cx_oracle/commits/b81bd10992eb6a4fb2a3e618cfdf865c72148859\" rel=\"nofollow\">cx_Oracle version 5.1.1</a> (Aug 28, 2011)</p>\n" }, { "answer_id": 48919165, "author": "Gank", "author_id": 336175, "author_profile": "https://Stackoverflow.com/users/336175", "pm_score": -1, "selected": false, "text": "<pre><code>import cx_Oracle\nip = '172.30.1.234'\nport = 1524\nSID = 'dev3'\ndsn_tns = cx_Oracle.makedsn(ip, port, SID)\n\nconn = cx_Oracle.connect('dbmylike', 'pass', dsn_tns)\nprint conn.version\nconn.close()\n</code></pre>\n" }, { "answer_id": 50897127, "author": "Vlad Bezden", "author_id": 30038, "author_profile": "https://Stackoverflow.com/users/30038", "pm_score": 3, "selected": false, "text": "<pre><code>import cx_Oracle\n\nCONN_INFO = {\n 'host': 'xxx.xx.xxx.x',\n 'port': 12345,\n 'user': 'user_name',\n 'psw': 'your_password',\n 'service': 'abc.xyz.com',\n}\n\nCONN_STR = '{user}/{psw}@{host}:{port}/{service}'.format(**CONN_INFO)\n\nconnection = cx_Oracle.connect(CONN_STR)\n</code></pre>\n" }, { "answer_id": 57984625, "author": "admin", "author_id": 6489637, "author_profile": "https://Stackoverflow.com/users/6489637", "pm_score": 1, "selected": false, "text": "<pre class=\"lang-py prettyprint-override\"><code>import cx_Oracle\ndsn = cx_Oracle.makedsn(host='127.0.0.1', port=1521, sid='your_sid')\nconn = cx_Oracle.connect(user='your_username', password='your_password', dsn=dsn)\nconn.close()\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do you connect to a remote server via IP address in the manner that TOAD, SqlDeveloper, are able to connect to databases with just the ip address, username, SID and password? Whenever I try to specify and IP address, it seems to be taking it locally. In other words, how should the string for cx\_Oracle.connect() be formatted to a non local database? There was a previous post which listed as an answer connecting to Oracle via cx\_Oracle module with the following code: ``` #!/usr/bin/python import cx_Oracle connstr='scott/tiger' conn = cx_Oracle.connect(connstr) curs = conn.cursor() curs.execute('select * from emp') print curs.description for row in curs: print row conn.close() ```
I like to do it this way: ``` ip = '192.168.0.1' port = 1521 SID = 'YOURSIDHERE' dsn_tns = cx_Oracle.makedsn(ip, port, SID) db = cx_Oracle.connect('username', 'password', dsn_tns) ``` One of the main reasons I like this method is that I usually have a TNSNAMES.ORA file lying around someplace, and I can check that the `dsn_tns` object will do the right thing by doing: ``` print dsn_tns ``` and comparing the output to my TNSNAMES.ORA
245,475
<p>Having a vector containing pointers to objects then using the clear function doesn't call the destructors for the objects in the vector. I made a function to do this manually but I don't know how to make this a generic function for any kind of objects that might be in the vector.</p> <pre><code>void buttonVectorCleanup(vector&lt;Button *&gt; dVector){ Button* tmpClass; for(int i = 0; i &lt; (int)dVector.size(); i++){ tmpClass = dVector[i]; delete tmpClass; } } </code></pre> <p>This is the function I have that works fine for a specific type of object in the vector but I'd like a single function that could take any kind of vector with object pointers.</p>
[ { "answer_id": 245483, "author": "KeithB", "author_id": 2298, "author_profile": "https://Stackoverflow.com/users/2298", "pm_score": 4, "selected": true, "text": "<p>The best thing to do is use smart pointers, such as from <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm\" rel=\"nofollow noreferrer\">Boost</a>. Then the objects will be deleted automatically.</p>\n\n<p>Or you can make a template function</p>\n\n<pre><code>template &lt;class T&gt;\nvoid vectorCleanup(vector&lt;T *&gt;&amp; dVector){\n T* tmpClass;\n for(vector&lt;T*&gt;::size_type i = 0; i &lt; dVector.size(); i++){\n tmpClass = dVector[i];\n\n delete tmpClass;\n }\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 245513, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>A couple of other points - you probably want to pass a reference to the vector, not a copy. tmpClass is not needed - you can delete the pointer directly. You should either resize the vector to 0 or replace the pointers with NULL after deleting - otherwise you could access unallocated memory in the calling function.</p>\n" }, { "answer_id": 245570, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "<p>You might want to use boost's <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/ptr_container.html\" rel=\"nofollow noreferrer\">pointer containers</a>. They are highly efficient and safe.</p>\n" }, { "answer_id": 246035, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 2, "selected": false, "text": "<p>I use a special functor to delete the pointer and set it to NULL:</p>\n\n<pre><code>struct delete_ptr\n{\n template &lt;typename T&gt;\n void operator()(T&amp; p)\n {\n delete p;\n p = 0;\n }\n};\n</code></pre>\n\n<p>Which is used with <code>std::for_each</code> (also don't forget to <code>#include &lt;algorithm&gt;</code>):</p>\n\n<pre><code>int wmain(int, wchar_t*[])\n{\n std::vector&lt;int*&gt; items;\n items.push_back(new int(1));\n items.push_back(new int(2));\n items.push_back(new int(3));\n std::for_each(items.begin(), items.end(), delete_ptr());\n};\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/370/" ]
Having a vector containing pointers to objects then using the clear function doesn't call the destructors for the objects in the vector. I made a function to do this manually but I don't know how to make this a generic function for any kind of objects that might be in the vector. ``` void buttonVectorCleanup(vector<Button *> dVector){ Button* tmpClass; for(int i = 0; i < (int)dVector.size(); i++){ tmpClass = dVector[i]; delete tmpClass; } } ``` This is the function I have that works fine for a specific type of object in the vector but I'd like a single function that could take any kind of vector with object pointers.
The best thing to do is use smart pointers, such as from [Boost](http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm). Then the objects will be deleted automatically. Or you can make a template function ``` template <class T> void vectorCleanup(vector<T *>& dVector){ T* tmpClass; for(vector<T*>::size_type i = 0; i < dVector.size(); i++){ tmpClass = dVector[i]; delete tmpClass; } ``` }
245,482
<p>I have form area in my view. If I click button <kbd>A</kbd>, I want to submit to <code>/Books/1</code> and if I click button <kbd>B</kbd>, I want to submit to <code>/Books/2</code></p> <p>How do I achieve this with MVC?</p>
[ { "answer_id": 245501, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 1, "selected": false, "text": "<p>MVC Views can have multiple forms on a 'page', so just create separate sections and give each one their own form action.</p>\n\n<pre><code>&lt;form id=\"form1\" name=\"form1\" action=\"/Books/1\" method=\"get\"&gt;\n&lt;!--...form fields--&gt;\n&lt;/form&gt;\n\n\n&lt;form id=\"form2\" name=\"form2\" action=\"/Books/2\" method=\"get\"&gt;\n&lt;!--...form fields--&gt;\n&lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 245579, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 0, "selected": false, "text": "<p>I have never seen the ability to have a form field attached to two forms, seems like it wouldn't work. What you can do is put a hidden field in the second form which, on submission, grabs the information from the textbox in the first form. </p>\n" }, { "answer_id": 245679, "author": "mmacaulay", "author_id": 22152, "author_profile": "https://Stackoverflow.com/users/22152", "pm_score": 2, "selected": true, "text": "<p>It sounds like what you want to do is call the Books Controller, with, say, the Search action. So for instance you might want to call /Books/Search/&lt;search expression&gt;/1, or /Books/Search/&lt;search expression&gt;/2, etc. (There's a few different ways you could be formatting these URLs, but it's mostly a matter of personal preference I think) If you want the URLs to appear as you've got them above (without the action in the URL), that can be accomplished with routing, something like this:</p>\n\n<pre><code>routes.MapRoute(\n \"Books\",\n \"Books/{searchExpr}/{pageId}\",\n new { controller = \"Books\", action = \"Search\", searchExpr = \"\", pageId = 1 }\n);\n</code></pre>\n\n<p>I think the main problem is that you're trying to use the WebForms PostBack everything paradigm in a situation where you're probably better off sending the information to the server in the URL or query string. The only time you're actually going to be posting form data here is when the user actually types something into the search box and clicks the <kbd>Search</kbd> button - at that point, the controller will pass the search expression to the appropriate View by stuffing it in ViewData, and from there, the View can pull it out and repopulate that textbox on the results page.</p>\n" }, { "answer_id": 245718, "author": "Corin Blaikie", "author_id": 1736, "author_profile": "https://Stackoverflow.com/users/1736", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;form id=\"form1\" name=\"form1\" action=\"/Books/\" method=\"get\"&gt;\n&lt;input type=\"text\" name=\"search\" value=\"\"&gt;\n&lt;input type=\"submit\" name=\"id\" value=\"1\"&gt;\n&lt;input type=\"submit\" name=\"id\" value=\"2\"&gt;\n&lt;/form&gt;\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5463/" ]
I have form area in my view. If I click button `A`, I want to submit to `/Books/1` and if I click button `B`, I want to submit to `/Books/2` How do I achieve this with MVC?
It sounds like what you want to do is call the Books Controller, with, say, the Search action. So for instance you might want to call /Books/Search/<search expression>/1, or /Books/Search/<search expression>/2, etc. (There's a few different ways you could be formatting these URLs, but it's mostly a matter of personal preference I think) If you want the URLs to appear as you've got them above (without the action in the URL), that can be accomplished with routing, something like this: ``` routes.MapRoute( "Books", "Books/{searchExpr}/{pageId}", new { controller = "Books", action = "Search", searchExpr = "", pageId = 1 } ); ``` I think the main problem is that you're trying to use the WebForms PostBack everything paradigm in a situation where you're probably better off sending the information to the server in the URL or query string. The only time you're actually going to be posting form data here is when the user actually types something into the search box and clicks the `Search` button - at that point, the controller will pass the search expression to the appropriate View by stuffing it in ViewData, and from there, the View can pull it out and repopulate that textbox on the results page.
245,509
<p>What's the best algorithm for comparing two arrays to see if they have the same members?</p> <p>Assume there are no duplicates, the members can be in any order, and that neither is sorted.</p> <pre><code>compare( [a, b, c, d], [b, a, d, c] ) ==&gt; true compare( [a, b, e], [a, b, c] ) ==&gt; false compare( [a, b, c], [a, b] ) ==&gt; false </code></pre>
[ { "answer_id": 245510, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": -1, "selected": false, "text": "<p>The best I can think of is O(n^2), I guess.</p>\n\n<pre><code>function compare($foo, $bar) {\n if (count($foo) != count($bar)) return false;\n\n foreach ($foo as $f) {\n foreach ($bar as $b) {\n if ($f == $b) {\n // $f exists in $bar, skip to the next $foo\n continue 2;\n }\n }\n return false;\n }\n return true;\n}\n</code></pre>\n" }, { "answer_id": 245520, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 3, "selected": false, "text": "<p>You could load one into a hash table, keeping track of how many elements it has. Then, loop over the second one checking to see if every one of its elements is in the hash table, and counting how many elements it has. If every element in the second array is in the hash table, and the two lengths match, they are the same, otherwise they are not. This should be O(N).</p>\n\n<p>To make this work in the presence of duplicates, track how many of each element has been seen. Increment while looping over the first array, and decrement while looping over the second array. During the loop over the second array, if you can't find something in the hash table, or if the counter is already at zero, they are unequal. Also compare total counts.</p>\n\n<p>Another method that would work in the presence of duplicates is to sort both arrays and do a linear compare. This should be O(N*log(N)).</p>\n" }, { "answer_id": 245521, "author": "Mark Bessey", "author_id": 17826, "author_profile": "https://Stackoverflow.com/users/17826", "pm_score": 5, "selected": true, "text": "<p>Obvious answers would be:</p>\n\n<ol>\n<li>Sort both lists, then check each\nelement to see if they're identical</li>\n<li>Add the items from one array to a\nhashtable, then iterate through the\nother array, checking that each item\nis in the hash </li>\n<li>nickf's iterative search algorithm</li>\n</ol>\n\n<p>Which one you'd use would depend on whether you can sort the lists first, and whether you have a good hash algorithm handy.</p>\n" }, { "answer_id": 245523, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 1, "selected": false, "text": "<p>I would suggest using a sort first and sort both first. Then you will compare the first element of each array then the second and so on.</p>\n\n<p>If you find a mismatch you can stop.</p>\n" }, { "answer_id": 245524, "author": "albertb", "author_id": 26715, "author_profile": "https://Stackoverflow.com/users/26715", "pm_score": 1, "selected": false, "text": "<p>If you sort both arrays first, you'd get O(N log(N)).</p>\n" }, { "answer_id": 245529, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 0, "selected": false, "text": "<p>The best way is probably to use hashmaps. Since insertion into a hashmap is O(1), building a hashmap from one array should take O(n). You then have n lookups, which each take O(1), so another O(n) operation. All in all, it's O(n). </p>\n\n<p>In python:</p>\n\n<pre><code>def comparray(a, b): \n sa = set(a)\n return len(sa)==len(b) and all(el in sa for el in b)\n</code></pre>\n" }, { "answer_id": 245544, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>Ignoring the built in ways to do this in C#, you could do something like this:</p>\n\n<p>Its O(1) in the best case, O(N) (per list) in worst case.</p>\n\n<pre><code>public bool MatchArrays(object[] array1, object[] array2)\n{\n if (array1.length != array2.length)\n return false;\n\n bool retValue = true;\n\n HashTable ht = new HashTable();\n\n for (int i = 0; i &lt; array1.length; i++)\n {\n ht.Add(array1[i]);\n }\n\n for (int i = 0; i &lt; array2.length; i++)\n {\n if (ht.Contains(array2[i])\n {\n retValue = false;\n break;\n }\n }\n\n return retValue;\n}\n</code></pre>\n" }, { "answer_id": 245549, "author": "Frentos", "author_id": 23978, "author_profile": "https://Stackoverflow.com/users/23978", "pm_score": 3, "selected": false, "text": "<p>Assuming you don't want to disturb the original arrays and space is a consideration, another O(n.log(n)) solution that uses less space than sorting both arrays is:</p>\n\n<ol>\n<li>Return FALSE if arrays differ in size</li>\n<li>Sort the first array -- O(n.log(n)) time, extra space required is the size of one array</li>\n<li>For each element in the 2nd array, check if it's in the sorted copy of\n the first array using a binary search -- O(n.log(n)) time</li>\n</ol>\n\n<p>If you use this approach, please use a library routine to do the binary search. Binary search is surprisingly error-prone to hand-code.</p>\n\n<p>[Added after reviewing solutions suggesting dictionary/set/hash lookups:]</p>\n\n<p>In practice I'd use a hash. Several people have asserted O(1) behaviour for hashes, leading them to conclude a hash-based solution is O(N). Typical inserts/lookups may be close to O(1), and some hashing schemes guarantee worst-case O(1) lookup, but worst-case insertion -- in constructing the hash -- isn't O(1). Given any particular hashing data structure, there would be some set of inputs which would produce pathological behaviour. I suspect there exist hashing data structures with the combined worst-case to [insert-N-elements then lookup-N-elements] of O(N.log(N)) time and O(N) space.</p>\n" }, { "answer_id": 245603, "author": "Jimmy", "author_id": 25071, "author_profile": "https://Stackoverflow.com/users/25071", "pm_score": 1, "selected": false, "text": "<p>What is the \"best\" solution obviously depends on what constraints you have. If it's a small data set, the sorting, hashing, or brute force comparison (like <a href=\"https://stackoverflow.com/questions/245509/algorithm-to-tell-if-two-arrays-have-identical-members#245510\">nickf</a> posted) will all be pretty similar. Because you know that you're dealing with integer values, you can get O(n) sort times (e.g. radix sort), and the hash table will also use O(n) time. As always, there are drawbacks to each approach: sorting will either require you to duplicate the data or destructively sort your array (losing the current ordering) if you want to save space. A hash table will obviously have memory overhead to for creating the hash table. If you use nickf's method, you can do it with little-to-no memory overhead, but you have to deal with the O(n<sup>2</sup>) runtime. You can choose which is best for your purposes.</p>\n" }, { "answer_id": 245651, "author": "Hugo", "author_id": 972, "author_profile": "https://Stackoverflow.com/users/972", "pm_score": 1, "selected": false, "text": "<p>Going on deep waters here, but:</p>\n\n<p><strong>Sorted lists</strong>\nsorting can be <code>O(nlogn)</code> as pointed out. just to clarify, it doesn't matter that there is two lists, because: <code>O(2*nlogn) == O(nlogn)</code>, then comparing each elements is another O(n), so sorting both then comparing each element is O(n)+O(nlogn) which is: <strong><code>O(nlogn)</code></strong></p>\n\n<p><strong>Hash-tables:</strong>\nConverting the first list to a hash table is O(n) for reading + the cost of storing in the hash table, which i guess can be estimated as O(n), gives O(n). Then you'll have to check the existence of each element in the other list in the produced hash table, which is (at least?) O(n) (assuming that checking existance of an element the hash-table is constant). All-in-all, we end up with <strong><code>O(n)</code></strong> for the check.</p>\n\n<p>The Java List interface <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/List.html#equals(java.lang.Object)\" rel=\"nofollow noreferrer\">defines equals</a> as each <strong>corresponding</strong> element being equal.</p>\n\n<p>Interestingly, the Java Collection interface definition <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.html#equals(java.lang.Object)\" rel=\"nofollow noreferrer\">almost discourages implementing the equals()</a> function.</p>\n\n<p>Finally, the Java <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/Set.html#equals(java.lang.Object)\" rel=\"nofollow noreferrer\">Set interface per documentation implements</a> this very behaviour. The implementation is should be very efficient, but the documentation makes no mention of performance. (Couldn't find a link to the source, it's probably to strictly licensed. Download and look at it yourself. It comes with the JDK) Looking at the source, the HashSet (which is a commonly used implementation of Set) delegates the equals() implementation to the AbstractSet, which uses the containsAll() function of AbstractCollection using the contains() function again from hashSet. So HashSet.equals() runs in O(n) as expected. (looping through all elements and looking them up in constant time in the hash-table.)</p>\n\n<p>Please edit if you know better to spare me the embarrasment.</p>\n" }, { "answer_id": 246283, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 0, "selected": false, "text": "<p>Upon collisions a hashmap is O(n) in most cases because it uses a linked list to store the collisions. However, there are better approaches and you should hardly have collisions anyway because if you did the hashmap would be useless. In all regular cases it's simply O(1). Besides that, it's not likely to have more than a small n of collisions in a single hashmap so performance wouldn't suck that bad; you can safely say that it's O(1) or <i>almost</i> O(1) because the n is so small it's can be ignored.</p>\n" }, { "answer_id": 373356, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This can be done in different ways:</p>\n\n<p>1 - Brute force: for each element in array1 check that element exists in array2. Note this would require to note the position/index so that duplicates can be handled properly. This requires O(n^2) with much complicated code, don't even think of it at all...</p>\n\n<p>2 - Sort both lists, then check each element to see if they're identical. O(n log n) for sorting and O(n) to check so basically O(n log n), sort can be done in-place if messing up the arrays is not a problem, if not you need to have 2n size memory to copy the sorted list.</p>\n\n<p>3 - Add the items and count from one array to a hashtable, then iterate through the other array, checking that each item is in the hashtable and in that case decrement count if it is not zero otherwise remove it from hashtable. O(n) to create a hashtable, and O(n) to check the other array items in the hashtable, so O(n). This introduces a hashtable with memory at most for n elements.</p>\n\n<p>4 - Best of Best (Among the above): Subtract or take difference of each element in the same index of the two arrays and finally sum up the subtacted values. For eg A1={1,2,3}, A2={3,1,2} the Diff={-2,1,1} now sum-up the Diff = 0 that means they have same set of integers. This approach requires an O(n) with no extra memory. A c# code would look like as follows:</p>\n\n<pre><code> public static bool ArrayEqual(int[] list1, int[] list2)\n {\n if (list1 == null || list2 == null)\n {\n throw new Exception(\"Invalid input\");\n }\n\n if (list1.Length != list2.Length)\n {\n return false;\n }\n\n int diff = 0;\n\n for (int i = 0; i &lt; list1.Length; i++)\n {\n diff += list1[i] - list2[i];\n }\n\n return (diff == 0);\n }\n</code></pre>\n\n<p>4 doesn't work at all, it is the worst</p>\n" }, { "answer_id": 373393, "author": "Yaniv", "author_id": 46883, "author_profile": "https://Stackoverflow.com/users/46883", "pm_score": 3, "selected": false, "text": "<p>You can use a signature (a commutative operation over the array members) to further optimize this in the case where the array are usually different, saving the <code>o(n log n)</code> or the memory allocation.\nA signature can be of the form of a bloom filter(s), or even a simple commutative operation like addition or xor.</p>\n\n<p>A simple example (assuming a long as the signature side and gethashcode as a good object identifier; if the objects are, say, ints, then their value is a better identifier; and some signatures will be larger than long)</p>\n\n<pre><code>public bool MatchArrays(object[] array1, object[] array2)\n{\n if (array1.length != array2.length)\n return false;\n long signature1 = 0;\n long signature2 = 0;\n for (i=0;i&lt;array1.length;i++) {\n signature1=CommutativeOperation(signature1,array1[i].getHashCode());\n signature2=CommutativeOperation(signature2,array2[i].getHashCode());\n }\n\n if (signature1 != signature2) \n return false;\n\n return MatchArraysTheLongWay(array1, array2);\n}\n</code></pre>\n\n<p>where (using an addition operation; use a different commutative operation if desired, e.g. bloom filters)</p>\n\n<pre><code>public long CommutativeOperation(long oldValue, long newElement) {\n return oldValue + newElement;\n}\n</code></pre>\n" }, { "answer_id": 2428771, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Here is another option, let me know what you guys think.It should be T(n)=2n*log2n ->O(nLogn) in the worst case.</p>\n\n<pre><code>private boolean compare(List listA, List listB){\n if (listA.size()==0||listA.size()==0) return true;\n List runner = new ArrayList();\n List maxList = listA.size()&gt;listB.size()?listA:listB;\n List minList = listA.size()&gt;listB.size()?listB:listA;\n int macthes = 0;\n List nextList = null;;\n int maxLength = maxList.size();\n for(int i=0;i&lt;maxLength;i++){\n for (int j=0;j&lt;2;j++) {\n nextList = (nextList==null)?maxList:(maxList==nextList)?minList:maList;\n if (i&lt;= nextList.size()) {\n MatchingItem nextItem =new MatchingItem(nextList.get(i),nextList)\n int position = runner.indexOf(nextItem);\n if (position &lt;0){\n runner.add(nextItem);\n }else{\n MatchingItem itemInBag = runner.get(position);\n if (itemInBag.getList != nextList) matches++;\n runner.remove(position);\n }\n }\n }\n }\n return maxLength==macthes;\n}\n\npublic Class MatchingItem{\nprivate Object item;\nprivate List itemList;\npublic MatchingItem(Object item,List itemList){\n this.item=item\n this.itemList = itemList\n}\npublic boolean equals(object other){\n MatchingItem otheritem = (MatchingItem)other;\n return otheritem.item.equals(this.item) and otheritem.itemlist!=this.itemlist\n}\n\npublic Object getItem(){ return this.item}\npublic Object getList(){ return this.itemList}\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 4154365, "author": "Mohammad Mazaz", "author_id": 467782, "author_profile": "https://Stackoverflow.com/users/467782", "pm_score": 1, "selected": false, "text": "<p>Pseudocode :</p>\n\n<pre><code>A:array\nB:array\nC:hashtable\n\nif A.length != B.length then return false;\n\nforeach objA in A\n{\nH = objA;\nif H is not found in C.Keys then\nC.add(H as key,1 as initial value);\nelse\nC.Val[H as key]++;\n}\n\nforeach objB in B\n{\nH = objB;\nif H is not found in C.Keys then\nreturn false;\nelse\nC.Val[H as key]--;\n}\n\nif(C contains non-zero value)\nreturn false;\nelse\nreturn true;\n</code></pre>\n" }, { "answer_id": 25511735, "author": "akashrajkn", "author_id": 3449335, "author_profile": "https://Stackoverflow.com/users/3449335", "pm_score": 2, "selected": false, "text": "<p>If the elements of an array are given as distinct, then XOR ( bitwise XOR ) all the elements of both the arrays, if the answer is zero, then both the arrays have the same set of numbers. The time complexity is O(n)</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
What's the best algorithm for comparing two arrays to see if they have the same members? Assume there are no duplicates, the members can be in any order, and that neither is sorted. ``` compare( [a, b, c, d], [b, a, d, c] ) ==> true compare( [a, b, e], [a, b, c] ) ==> false compare( [a, b, c], [a, b] ) ==> false ```
Obvious answers would be: 1. Sort both lists, then check each element to see if they're identical 2. Add the items from one array to a hashtable, then iterate through the other array, checking that each item is in the hash 3. nickf's iterative search algorithm Which one you'd use would depend on whether you can sort the lists first, and whether you have a good hash algorithm handy.
245,532
<p>I have a web application that has many faces and so far I've implemented this through creating themes. A theme is a set of html, css and images to be used with the common back end.</p> <p>Things are laid out like so:</p> <pre><code>code/ themes/theme1 themes/theme2 </code></pre> <p>And each instance of the web application has a configuration file that states which theme should be used. Example:</p> <pre><code>theme="theme1" </code></pre> <p>Now new business rules are asking me to make changes to certain themes that can't be achieved through simply change the html/css/images and require changing the backend. In some cases these changes need to be applied to a group of themes.</p> <p>I'm wondering how to best lay this out on disk, and also how to handle it in code. I'm sure someone else must have come up against this.</p> <p>One idea is to have:</p> <pre><code>code/common code/theme1 code/theme2 themes/theme1 themes/theme2 </code></pre> <p>Then have my common code set the <code>include_path</code> such that <code>code/theme1</code> is searched first, then <code>code/common</code>.</p> <p>Then if I want to specialize say the <code>LogoutPage</code> class for <code>theme2</code>, I can simply copy the page from <code>code/common</code> to the same path under <code>code/theme2</code> and it will pick up the specialized version.</p> <p>One problem with this idea is that there'll be multiple classes with the same name. Although in theory they would never be included in the same execution, I wouldn't be able to extend the original base class.</p> <p>So what if I was to make a unique name for the base class? e.g. <code>Theme1LogoutPage extends LogoutPage</code>. One problem I can foresee with that is when some common code (say the Dispatcher) references <code>LogoutPage</code>. I can add conditions to the dispatcher, but I wonder if there's a more transparent way to handle this?</p> <p>Another option I can think of is to maintain separate branches for each theme, but I think this could be a lot of work.</p> <p>One final thing to consider is that features might originate in one theme and then require merging into the common codebase.</p> <p>Any input greatly appreciated. If it makes any difference, it's a LAMP environment.</p>
[ { "answer_id": 245622, "author": "Hapkido", "author_id": 27646, "author_profile": "https://Stackoverflow.com/users/27646", "pm_score": 1, "selected": false, "text": "<p>I don't have a specific recommendation. However, I strongly suggest to <strong>NOT</strong> take shortcut... Use the solution that will you will find comfortable to add a third theme or to change something next year.<br>\nDuplication is the enemy of maintainability.</p>\n" }, { "answer_id": 245707, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>I'd investigate using the Strategy pattern as a means to implement different functionality in different versions of the site. Have a Factory that takes in your configuration and supplies the appropriate code strategy based on it. Each strategy can implement some common interface so that they are interchangeable from the calling class' point of view. This will isolate your changes to implement new strategies to the Factory class, Configuration class, and any new strategy classes that you need to implement to make the change. You could do the same (or similar) with any user controls that need to differ between the different versions.</p>\n\n<p>I'll illustrate with pseudocode (that may look suspiciously like C#)</p>\n\n<pre><code>public interface ILogoutStrategy\n{\n void Logout();\n}\n\npublic abstract class AbstractLogoutStrategy : ILogoutStrategy\n{\n public virtual void Logout()\n {\n // kill the sesssion\n }\n}\n\npublic class SingleSiteLogoutStrategy : AbstractLogoutStrategy\n{\n public void Logout()\n {\n base.Logout();\n // redirect somewhere\n }\n}\n\npublic class CentralAuthenticationSystemLogoutStrategy : AbstractLogoutStrategy\n{\n public void Logout()\n {\n base.Logout();\n // send a logout request to the CAS\n // redirect somewhere\n }\n}\n\npublic static class StrategyFactory\n{\n public ILogoutStrategy GetLogoutStrategy(Configuration config)\n {\n switch (config.Mode)\n {\n case Mode.CAS:\n return new CentralAuthenticationSystemLogoutStrategy();\n break;\n default:\n case Mode.SingleSite:\n return new SingleSiteLogoutStrategy();\n break;\n\n }\n }\n}\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>ILogoutStrategy logoutStrategy = StrategyFactory.GetLogoutStrategy( config );\nlogoutStrategy.Logout();\n</code></pre>\n" }, { "answer_id": 245756, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 0, "selected": false, "text": "<p>Are you using Master Pages? If you need different layout and UI stuff you could just have a different set of master pages for each of your instances. If you need custom behavior then you might want to look into Dependency Injection. Spring.NET, etc.</p>\n" }, { "answer_id": 279891, "author": "Bingy", "author_id": 69518, "author_profile": "https://Stackoverflow.com/users/69518", "pm_score": 0, "selected": false, "text": "<p>What you need are templates.</p>\n\n<p>Thence you can separate your code from your presentation.</p>\n\n<p>I highly recommend smarty templates. Also PEAR template_it.</p>\n\n<p><a href=\"http://www.smarty.net/\" rel=\"nofollow noreferrer\">http://www.smarty.net/</a></p>\n\n<p>This also make your code far more maintainable. The aim is to have no html in your php, and to have no php in your html.</p>\n\n<p>then all you will need to do is change the html template that is being used for each theme. or folder of templates.</p>\n" }, { "answer_id": 840824, "author": "lo_fye", "author_id": 3407, "author_profile": "https://Stackoverflow.com/users/3407", "pm_score": 0, "selected": false, "text": "<p>You could have:\n /common/code</p>\n\n<p>And: \n /sitename/code</p>\n\n<p>All files in /common/code are abstract classes.\nFor every file in /common/code, just create a corresponding non-abstract class file in /sitename/code that INHERITS from the abstract class in /common/code.</p>\n\n<p>This way you only need to implement CHANGES in the /sitename/code\nEverything else is core functionality that exists only in /common/code</p>\n\n<p>The important thing to do here is ensure that you only add <strong>public</strong> methods to the abstract classes. This way the methods are available to all sites, and classes from all sites can be treated/worked with identically.</p>\n" }, { "answer_id": 842519, "author": "Four", "author_id": 103887, "author_profile": "https://Stackoverflow.com/users/103887", "pm_score": 0, "selected": false, "text": "<p>I would do:</p>\n\n<p>[theme name]/[subfolder]\ndefault/common\ndefault/common/html\ndefault/common/css\nred/code\nred/common\nred/common/html\nred/common/css\nred/code\ngreen/common\ngreen/common/html</p>\n\n<p>So if the code or any other component doesn't exist it will fall back to default.</p>\n\n<p>But in fact I would branch the website in svn, so common code if it evolves I can merge it, etc.. see Subversion at: <a href=\"http://subversion.tigris.org/\" rel=\"nofollow noreferrer\">http://subversion.tigris.org/</a></p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a web application that has many faces and so far I've implemented this through creating themes. A theme is a set of html, css and images to be used with the common back end. Things are laid out like so: ``` code/ themes/theme1 themes/theme2 ``` And each instance of the web application has a configuration file that states which theme should be used. Example: ``` theme="theme1" ``` Now new business rules are asking me to make changes to certain themes that can't be achieved through simply change the html/css/images and require changing the backend. In some cases these changes need to be applied to a group of themes. I'm wondering how to best lay this out on disk, and also how to handle it in code. I'm sure someone else must have come up against this. One idea is to have: ``` code/common code/theme1 code/theme2 themes/theme1 themes/theme2 ``` Then have my common code set the `include_path` such that `code/theme1` is searched first, then `code/common`. Then if I want to specialize say the `LogoutPage` class for `theme2`, I can simply copy the page from `code/common` to the same path under `code/theme2` and it will pick up the specialized version. One problem with this idea is that there'll be multiple classes with the same name. Although in theory they would never be included in the same execution, I wouldn't be able to extend the original base class. So what if I was to make a unique name for the base class? e.g. `Theme1LogoutPage extends LogoutPage`. One problem I can foresee with that is when some common code (say the Dispatcher) references `LogoutPage`. I can add conditions to the dispatcher, but I wonder if there's a more transparent way to handle this? Another option I can think of is to maintain separate branches for each theme, but I think this could be a lot of work. One final thing to consider is that features might originate in one theme and then require merging into the common codebase. Any input greatly appreciated. If it makes any difference, it's a LAMP environment.
I don't have a specific recommendation. However, I strongly suggest to **NOT** take shortcut... Use the solution that will you will find comfortable to add a third theme or to change something next year. Duplication is the enemy of maintainability.
245,557
<p>Let's say I have two arrays:</p> <blockquote> <p>int ArrayA[] = {5, 17, 150, 230, 285};</p> <p>int ArrayB[] = {7, 11, 57, 110, 230, 250};</p> </blockquote> <p>Both arrays are sorted and can be any size. I am looking for an efficient algorithm to find if the arrays contain any duplicated elements between them. I just want a true/false answer, I don't care which element is shared or how many.</p> <p>The naive solution is to loop through each item in ArrayA, and do a <a href="http://en.wikipedia.org/wiki/Binary_search" rel="noreferrer">binary search</a> for it in ArrayB. I believe this complexity is O(m * log n).</p> <p>Because both arrays are sorted, it seems like there should be a more efficient algorithm.</p> <p>I would also like a generic solution that doesn't assume that the arrays hold numbers (i.e. the solution should also work for strings). However, the comparison operators are well defined and both arrays are sorted from least to greatest.</p>
[ { "answer_id": 245563, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 6, "selected": true, "text": "<p>Pretend that you are doing a mergesort, but don't send the results anywhere. If you get to the end of either source, there is no intersection. Each time you compare the next element of each, if they are equal, there is an intersection.</p>\n\n<p>For example:</p>\n\n<pre><code>counterA = 0;\ncounterB = 0;\nfor(;;) {\n if(counterA == ArrayA.length || counterB == ArrayB.length)\n return false;\n else if(ArrayA[counterA] == ArrayB[counterB])\n return true;\n else if(ArrayA[counterA] &lt; ArrayB[counterB])\n counterA++;\n else if(ArrayA[counterA] &gt; ArrayB[counterB])\n counterB++;\n else\n halt_and_catch_fire();\n}\n</code></pre>\n" }, { "answer_id": 245564, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>If you don't care about memory consumption, you can achieve good performance by using hash, i.e. create hash with keys = values of one array, and test values of second array against this hash</p>\n" }, { "answer_id": 245568, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 0, "selected": false, "text": "<p>If the range of values is small, you could build a lookup table for one of them (time cost = O(N)) and then check if the bit is set from the other list (time cost = O(N)). If the range is large, you could do something similar with a hash table.</p>\n\n<p>The mergesort trick from Glomek is an even better idea.</p>\n" }, { "answer_id": 245575, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>Glomek is on the right track, but kinda glossed over the algorithm.</p>\n\n<p>Start by comparing ArrayA[0] to ArrayB[0]. if they are equal, you're done.\nIf ArrayA[0] is less than ArrayB[0], then move to ArrayA[1].\nIf ArrayA[0] is more than ArrayB[0], then move to ArrayB[1].</p>\n\n<p>Keeping stepping through till you reach the end of one array or find a match.</p>\n" }, { "answer_id": 245877, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 1, "selected": false, "text": "<p>If you are using C# 3.0 then why not take advantage of LINQ here?</p>\n\n<pre><code>ArrayA.Intersect(ArrayB).Any()\n</code></pre>\n\n<p>Not only is this generic (works for any comparable type) the implementation under the hood is pretty efficient (uses a hashing algorithm). </p>\n" }, { "answer_id": 248229, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 3, "selected": false, "text": "<p>Since someone wondered about stl. Out-of-the-box, the set_intersection algorithm would do more than you want: it would find all the common values.</p>\n\n<pre><code> #include &lt;vector&gt;\n #include &lt;algorithm&gt;\n #include &lt;iterator&gt;\n using namespace std;\n// ... \n int ArrayA[] = {5, 17, 150, 230, 285};\n int ArrayB[] = {7, 11, 57, 110, 230, 250};\n vector&lt;int&gt; intersection;\n ThrowWhenWritten output_iterator;\n set_intersection(ArrayA, ArrayA + sizeof(ArrayA)/sizeof(int),\n ArrayB, ArrayB + sizeof(ArrayB)/sizeof(int),\n back_insert_iterator&lt;vector&lt;int&gt; &gt;(intersection));\n\n return !intersection.empty();\n</code></pre>\n\n<p>this runs in O(m+n) time, but it requires storing all the duplicates and doesn't stop when it finds the first dup. </p>\n\n<p>Now, modifying the code from the gnu <a href=\"http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/\" rel=\"noreferrer\">implementation</a> of the stl, we can get more precisely what you want.</p>\n\n<pre><code> template&lt;typename InputIterator1, typename InputIterator2&gt;\n bool \n has_intersection(InputIterator1 first1, InputIterator1 last1,\n InputIterator2 first2, InputIterator2 last2)\n {\n while (first1 != last1 &amp;&amp; first2 != last2) \n {\n if (*first1 &lt; *first2)\n ++first1;\n else if (*first2 &lt; *first1)\n ++first2;\n else\n return true;\n }\n return false;\n}\n</code></pre>\n" }, { "answer_id": 253655, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>If one list is much much shorter than the other, binary search is the way to go. If the lists are of similar length and you're happy with O(m+n), a standard \"merge\" would work. There are fancier algorithms that are more flexible. One paper I've come across in my own searches is:</p>\n\n<p><a href=\"http://www.cs.uwaterloo.ca/~ajsaling/papers/paper-spire.pdf\" rel=\"nofollow noreferrer\">http://www.cs.uwaterloo.ca/~ajsaling/papers/paper-spire.pdf</a></p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3175/" ]
Let's say I have two arrays: > > int ArrayA[] = {5, 17, 150, 230, 285}; > > > int ArrayB[] = {7, 11, 57, 110, 230, 250}; > > > Both arrays are sorted and can be any size. I am looking for an efficient algorithm to find if the arrays contain any duplicated elements between them. I just want a true/false answer, I don't care which element is shared or how many. The naive solution is to loop through each item in ArrayA, and do a [binary search](http://en.wikipedia.org/wiki/Binary_search) for it in ArrayB. I believe this complexity is O(m \* log n). Because both arrays are sorted, it seems like there should be a more efficient algorithm. I would also like a generic solution that doesn't assume that the arrays hold numbers (i.e. the solution should also work for strings). However, the comparison operators are well defined and both arrays are sorted from least to greatest.
Pretend that you are doing a mergesort, but don't send the results anywhere. If you get to the end of either source, there is no intersection. Each time you compare the next element of each, if they are equal, there is an intersection. For example: ``` counterA = 0; counterB = 0; for(;;) { if(counterA == ArrayA.length || counterB == ArrayB.length) return false; else if(ArrayA[counterA] == ArrayB[counterB]) return true; else if(ArrayA[counterA] < ArrayB[counterB]) counterA++; else if(ArrayA[counterA] > ArrayB[counterB]) counterB++; else halt_and_catch_fire(); } ```
245,592
<p>In DB2, you can name a column ORDER and write SQL like</p> <pre><code>SELECT ORDER FROM tblWHATEVER ORDER BY ORDER </code></pre> <p>without even needing to put any special characters around the column name. This is causing me pain that I won't get into, but my question is: why do databases allow the use of SQL keywords for object names? Surely it would make more sense to just not allow this?</p>
[ { "answer_id": 245595, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "<p>Many SQL parsers (expecially DB2/z, which I use) are smarter than some of the regular parsers which sometimes separate lexical and semantic analysis totally (this separation is mostly a good thing).</p>\n\n<p>The SQL parsers can figure out based on context whether a keyword is valid or should be treated as an identifier.</p>\n\n<p>Hence you can get columns called ORDER or GROUP or DATE (that's a particularly common one).</p>\n\n<p>It does annoy me with some of the syntax coloring editors when they brand an identifier with the keyword color. Their parsers aren't as 'smart' as the ones in DB2.</p>\n" }, { "answer_id": 245598, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 1, "selected": false, "text": "<p>Because object names are ... <em>names</em>. All database systems let you use quoted names to stop you from running into trouble.</p>\n\n<p>If you are running into issues, the fault lies not with the practice of permitting object names to be <em>names</em>, but with faulty implementations, or with faulty code libraries which don't automatically quote everything or cannot be made to quote names as-needed.</p>\n" }, { "answer_id": 247443, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>I largely agree with the sentiment that keywords shouldn't be allowed as identifiers. Most modern computing languages have 20 or maybe 30 keywords, in which case imposing a moratorium on their use as identifiers is entirely reasonable. Unfortunately, SQL comes from the old COBOL school of languages (\"computing languages should be as similar to English as possible\"). Hence, SQL (like COBOL) has several <a href=\"http://publib.boulder.ibm.com/infocenter/db2luw/v9r5/topic/com.ibm.db2.luw.sql.ref.doc/doc/r0001095.html\" rel=\"noreferrer\">hundred keywords</a>.</p>\n\n<p>I don't recall if the SQL standard says anything about whether reserved words <em>must</em> be permitted as identifiers, but given the extensive (excessive!) vocabulary it's unsurprising that several SQL implementations permit it.</p>\n\n<p>Having said that, using keywords as identifiers isn't half as silly as the whole concept of quoted identifiers in SQL (and these aren't DB2 specific). Permitting case sensitive identifiers is one thing, but quoted identifiers permit all sorts of nonsense including spaces, diacriticals and in some implementations (yes, including DB2), control characters! Try the following for example:</p>\n\n<pre>\nCREATE TABLE \"My\nTablé\" ( A INTEGER NOT NULL );\n</pre>\n\n<p>Yes, that's a line break in the middle of an identifier along with an e-acute at the end... (which leads to interesting speculation on what encoding is used for database meta-data and hence whether a non-Unicode database would permit, say, a table definition containing Japanese column names).</p>\n" }, { "answer_id": 247503, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 1, "selected": false, "text": "<p>Interestingly you can use keywords as field names in SqlServer as well. The only differenc eis that you would need to use parenthesis with the name of the field</p>\n\n<p>so you can do something like</p>\n\n<pre><code>create table [order](\nid int,\n[order] varchar(50) )\n</code></pre>\n\n<p>and then :)</p>\n\n<pre><code>select \n [order] \nfrom \n [order]\norder by [order]\n</code></pre>\n\n<p>That is of course a bit extreme example but at least with the use of parenthesis you can see that [order] is not a keyword.</p>\n\n<p>The reason I would see people using names already reserved by keywords is when there is a direct mapping between column names, or names of the tables and the data presentation. You can call that being lazy or convenient.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14606/" ]
In DB2, you can name a column ORDER and write SQL like ``` SELECT ORDER FROM tblWHATEVER ORDER BY ORDER ``` without even needing to put any special characters around the column name. This is causing me pain that I won't get into, but my question is: why do databases allow the use of SQL keywords for object names? Surely it would make more sense to just not allow this?
I largely agree with the sentiment that keywords shouldn't be allowed as identifiers. Most modern computing languages have 20 or maybe 30 keywords, in which case imposing a moratorium on their use as identifiers is entirely reasonable. Unfortunately, SQL comes from the old COBOL school of languages ("computing languages should be as similar to English as possible"). Hence, SQL (like COBOL) has several [hundred keywords](http://publib.boulder.ibm.com/infocenter/db2luw/v9r5/topic/com.ibm.db2.luw.sql.ref.doc/doc/r0001095.html). I don't recall if the SQL standard says anything about whether reserved words *must* be permitted as identifiers, but given the extensive (excessive!) vocabulary it's unsurprising that several SQL implementations permit it. Having said that, using keywords as identifiers isn't half as silly as the whole concept of quoted identifiers in SQL (and these aren't DB2 specific). Permitting case sensitive identifiers is one thing, but quoted identifiers permit all sorts of nonsense including spaces, diacriticals and in some implementations (yes, including DB2), control characters! Try the following for example: ``` CREATE TABLE "My Tablé" ( A INTEGER NOT NULL ); ``` Yes, that's a line break in the middle of an identifier along with an e-acute at the end... (which leads to interesting speculation on what encoding is used for database meta-data and hence whether a non-Unicode database would permit, say, a table definition containing Japanese column names).
245,600
<p>In an information security lab I'm working on, I've been tasked with executing multiple commands with a single call to "system()" (written in C, running on Fedora). What is the syntax that will allow me to execute more than command through system()? (The idea being you could execute arbitrary commands through a program running on a remote computer, if the program interacts with the OS through the system() call.)</p> <p>I.e.:</p> <pre><code>char command[] = "????? \r\n"; system(command); </code></pre>
[ { "answer_id": 245608, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 5, "selected": true, "text": "<p>That depends on the shell being invoked to execute the commands, but in general most shells use <code>;</code> to separate commands so something like this should work:</p>\n\n<pre><code>command1; command2; command3\n</code></pre>\n\n<p>[EDIT]</p>\n\n<p>As @dicroce mentioned, you can use <code>&amp;&amp;</code> instead of <code>;</code> which will stop execution at the first command that returns a non-zero value. This may or may not be desired (and some commands may return non-zero on success) but if you are trying to handle commands that can fail you should probably not string multiple commands together in a system() call as you don't have any way of determining where the failure occured. In this case your best bet would either be to execute one command at a time or create a shell script that performs the appropriate error handling and call that instead.</p>\n" }, { "answer_id": 245609, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 1, "selected": false, "text": "<p>One possibility comes immediately to mind. You could write all the commands to a script then run it with:</p>\n\n<pre><code>system (\"cmd.exe /c \\\"x.cmd\\\"\");\n</code></pre>\n\n<p>or, now that I've noticed you're running on Fedora:</p>\n\n<pre><code>system (\"x.sh\");\n</code></pre>\n" }, { "answer_id": 245631, "author": "dicroce", "author_id": 3886, "author_profile": "https://Stackoverflow.com/users/3886", "pm_score": 3, "selected": false, "text": "<p>Use &amp;&amp; between your commands. It has the advantage that it only continues executing commands as long as they return successful error codes. Example:</p>\n\n<p>\"cd /proc &amp;&amp; cat cpuinfo\"</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28076/" ]
In an information security lab I'm working on, I've been tasked with executing multiple commands with a single call to "system()" (written in C, running on Fedora). What is the syntax that will allow me to execute more than command through system()? (The idea being you could execute arbitrary commands through a program running on a remote computer, if the program interacts with the OS through the system() call.) I.e.: ``` char command[] = "????? \r\n"; system(command); ```
That depends on the shell being invoked to execute the commands, but in general most shells use `;` to separate commands so something like this should work: ``` command1; command2; command3 ``` [EDIT] As @dicroce mentioned, you can use `&&` instead of `;` which will stop execution at the first command that returns a non-zero value. This may or may not be desired (and some commands may return non-zero on success) but if you are trying to handle commands that can fail you should probably not string multiple commands together in a system() call as you don't have any way of determining where the failure occured. In this case your best bet would either be to execute one command at a time or create a shell script that performs the appropriate error handling and call that instead.
245,614
<p>Okay still fighting with doing some SqlCacheDependecy in my Asp.net MVC application</p> <p>I got this piece of code from Microsoft to cache LINQtoSQL, basically what it does is it gets the SqlCommand text from the LINQ query and executes that via the System.Data.SqlClient.SqlCommand which SqlDependecy needs...</p> <p>However there is one slight problem with this and that is whenever you do a where clause in LINQ the SQL generated is like so</p> <pre><code>SELECT [t0].[MemberID], [t0].[Aspnetusername], [t0].[Aspnetpassword], [t0].[EmailAddr], [t0].[DateCreated], [t0].[Location], [t0].[DaimokuGoal], [t0].[PreviewImageID], [t0].[LastDaimoku] AS [LastDaimoku], [t0].[LastNotefied] AS [LastNotefied], [t0].[LastActivityDate] AS [LastActivityDate], [t0].[IsActivated] FROM [dbo].[Members] AS [t0] INNER JOIN [dbo].[MemberStats] AS [t1] ON [t0].[MemberID] = [t1].[MemberID] WHERE [t1].[TotalDeterminations] &gt; @p0 </code></pre> <p>Notice the where [t1].[TotalDeterminations] > @p0, the SqlCommand yells at me because it wants me to declare a scalar variable of @p0... which obviously I can't</p> <p>So how the heck does Microsoft which provides this code to cache Linq queries expect people to use where clauses? Anyone have any ideas around this?</p> <p><strong>Edit</strong> Plus how the heck does SQL know what @p is anyhow when just executing the LINQ like normal the above query is whats getting passed in no matter what to the database?</p>
[ { "answer_id": 245637, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>Why can't you just add SqlParameter objects to the Parameters collection of SqlCommand object before adding them to the SqlDependecy?</p>\n" }, { "answer_id": 245665, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 2, "selected": true, "text": "<p><code>@something</code> is a SQL Parameter, which .NET handles by adding to the SqlParameter collection of the SqlCommand object.</p>\n\n<p>You can create parameters with any name, Linq to SQL just generates them named <code>p#</code>, where <code>#</code> represents its position on the collection.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22093/" ]
Okay still fighting with doing some SqlCacheDependecy in my Asp.net MVC application I got this piece of code from Microsoft to cache LINQtoSQL, basically what it does is it gets the SqlCommand text from the LINQ query and executes that via the System.Data.SqlClient.SqlCommand which SqlDependecy needs... However there is one slight problem with this and that is whenever you do a where clause in LINQ the SQL generated is like so ``` SELECT [t0].[MemberID], [t0].[Aspnetusername], [t0].[Aspnetpassword], [t0].[EmailAddr], [t0].[DateCreated], [t0].[Location], [t0].[DaimokuGoal], [t0].[PreviewImageID], [t0].[LastDaimoku] AS [LastDaimoku], [t0].[LastNotefied] AS [LastNotefied], [t0].[LastActivityDate] AS [LastActivityDate], [t0].[IsActivated] FROM [dbo].[Members] AS [t0] INNER JOIN [dbo].[MemberStats] AS [t1] ON [t0].[MemberID] = [t1].[MemberID] WHERE [t1].[TotalDeterminations] > @p0 ``` Notice the where [t1].[TotalDeterminations] > @p0, the SqlCommand yells at me because it wants me to declare a scalar variable of @p0... which obviously I can't So how the heck does Microsoft which provides this code to cache Linq queries expect people to use where clauses? Anyone have any ideas around this? **Edit** Plus how the heck does SQL know what @p is anyhow when just executing the LINQ like normal the above query is whats getting passed in no matter what to the database?
`@something` is a SQL Parameter, which .NET handles by adding to the SqlParameter collection of the SqlCommand object. You can create parameters with any name, Linq to SQL just generates them named `p#`, where `#` represents its position on the collection.
245,624
<p>Are there any 'standard' plugins for detecting the CPU architecture in <strong>scons</strong>? </p> <p>BTW, this question was asked already <a href="https://stackoverflow.com/questions/152016/detecting-cpu-architecture-compile-time">here</a> in a more general form... just wondering if anyone has already taken the time to incorporate this information into scons. </p>
[ { "answer_id": 418719, "author": "dsvensson", "author_id": 5962, "author_profile": "https://Stackoverflow.com/users/5962", "pm_score": 2, "selected": false, "text": "<p>Something like this?</p>\n\n<pre><code>env = Environment()\nconf = Configure(env)\nif conf.CheckDeclaration(\"__i386__\"):\n conf.Define(\"MY_ARCH\", \"blahblablah\")\nenv = conf.Finish()\n</code></pre>\n" }, { "answer_id": 510888, "author": "David Cournapeau", "author_id": 11465, "author_profile": "https://Stackoverflow.com/users/11465", "pm_score": 3, "selected": false, "text": "<p>Using <strong>i386</strong> is rather compiler dependant, and won't detect non x86 32 bits archs. Assuming the python interpreter used by scons runs on the CPU you are interested in (not always the case - think cross compilation), you can just use python itself.</p>\n\n<pre><code>import platform\nprint platform.machine()\nprint platform.architecture()\n</code></pre>\n\n<p>If you need something more sophisticated, then maybe you will have to write your own configure function - but it may be better to deal with it in your code directly.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14069/" ]
Are there any 'standard' plugins for detecting the CPU architecture in **scons**? BTW, this question was asked already [here](https://stackoverflow.com/questions/152016/detecting-cpu-architecture-compile-time) in a more general form... just wondering if anyone has already taken the time to incorporate this information into scons.
Using **i386** is rather compiler dependant, and won't detect non x86 32 bits archs. Assuming the python interpreter used by scons runs on the CPU you are interested in (not always the case - think cross compilation), you can just use python itself. ``` import platform print platform.machine() print platform.architecture() ``` If you need something more sophisticated, then maybe you will have to write your own configure function - but it may be better to deal with it in your code directly.
245,628
<pre><code>template &lt;class T&gt; bool BST&lt;T&gt;::search(const T&amp; x, int&amp; len) const { return search(BT&lt;T&gt;::root, x); } template &lt;class T&gt; bool BST&lt;T&gt;::search(struct Node&lt;T&gt;*&amp; root, const T&amp; x) { if (root == NULL) return false; else { if (root-&gt;data == x) return true; else if(root-&gt;data &lt; x) search(root-&gt;left, x); else search(root-&gt;right, x); } } </code></pre> <p>So this is my search function for my BST class with a T node. x is the data being searched for within the tree, len is just the amount of nodes it has to travel to come up with the matching node if it exists. I have not implented that yet, I'm just incrementally developing my assignment. I'm calling it by doing this:</p> <pre><code>if(t.search(v[1], len) == true) cout &lt;&lt; endl &lt;&lt; "true"; </code></pre> <p>v is just a vector I had to create to compare it to, and so this is just supplying it with an int. The error I'm getting:</p> <pre><code>BST.h: In member function âbool BST&lt;T&gt;::search(const T&amp;, int&amp;) const [with T = int]â: prog5.cc:24: instantiated from here BST.h:78: error: no matching function for call to âBST&lt;int&gt;::search(Node&lt;int&gt;* const&amp;, const int&amp;) constâ BST.h:76: note: candidates are: bool BST&lt;T&gt;::search(const T&amp;, int&amp;) const [with T = int] BST.h:83: note: bool BST&lt;T&gt;::search(Node&lt;T&gt;*&amp;, const T&amp;) [with T = int] </code></pre> <p>So I'm not sure what I'm doing wrong or where I'm doing wrong. </p>
[ { "answer_id": 245636, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 3, "selected": true, "text": "<p>Okay, <code>bool BST&lt;T&gt;::search(struct Node&lt;T&gt;*&amp; root, const T&amp; x)</code> should probably have const after it like so: <code>bool BST&lt;T&gt;::search(struct Node&lt;T&gt;*&amp; root, const T&amp; x) const</code>. Basically, you've called a non-const function from a const function and this is a no-no.</p>\n\n<p>BTW, this looks suspect to me \"<code>struct Node&lt;T&gt;*&amp;</code>\"... I'd probably drop the &amp; and work with <code>Node&lt;T&gt;*</code>... but maybe you need that because of the <em>struct</em>? </p>\n\n<p>Also, this is C++, there is no reason to leave Node as a struct... needing to have <strong>struct</strong> in the parameter definition just looks bad, IMHO. Why not make Node a class?</p>\n" }, { "answer_id": 39881290, "author": "rashedcs", "author_id": 6714430, "author_profile": "https://Stackoverflow.com/users/6714430", "pm_score": 0, "selected": false, "text": "<p><strong>Algorithm :</strong></p>\n\n<ol>\n<li>Take node value data;</li>\n<li>Repeat step 3 to step 5 until we find the value or we go beyond the tree.</li>\n<li>If data is equal to root node value , searching is successful and terminate the algorithm.</li>\n<li>If data is less than root node value , we have to search the left sub tree.</li>\n<li>Else data is less than root node value , we have to search the left sub tree.</li>\n<li>Output Print message \"Found\" or \"Not Found\".</li>\n</ol>\n\n<hr>\n\n<h2>C++ implementation</h2>\n\n<pre><code> node* search(node* root, int data)\n {\n if (root==NULL || root-&gt;data==data) return root;\n\n if (root-&gt;data &lt; data) return search(root-&gt;right, data);\n\n return search(root-&gt;left, data);\n }\n</code></pre>\n" }, { "answer_id": 40349944, "author": "chqrlie", "author_id": 4593267, "author_profile": "https://Stackoverflow.com/users/4593267", "pm_score": 1, "selected": false, "text": "<p>There are multiple problems in your search code:</p>\n\n<ul>\n<li><p>The sort order is backwards, if the node data is less than what you search, you should search in the right branch, not the left branch.</p></li>\n<li><p>You should return the result of the recursive call</p></li>\n<li><p>It is also unclear why you pass <code>root</code> by reference. it should instead be passed as a <code>const</code> qualified pointer and the method body should be <code>const</code> qualified too.</p></li>\n</ul>\n\n<p>Here is a alternative:</p>\n\n<pre><code>template &lt;class T&gt;\nbool BST&lt;T&gt;::search(const struct Node&lt;T&gt; *root, const T&amp; x) const {\n if (root == NULL)\n return false;\n else\n if (root-&gt;data == x)\n return true;\n else\n if (root-&gt;data &lt; x)\n return search(root-&gt;right, x);\n else \n return search(root-&gt;left, x);\n}\n</code></pre>\n\n<p>And here is a simpler non recursive implementation:</p>\n\n<pre><code>template &lt;class T&gt;\nbool BST&lt;T&gt;::search(const struct Node&lt;T&gt; *root, const T&amp; x) const {\n while (root != NULL) {\n if (root-&gt;data == x)\n return true;\n if (root-&gt;data &lt; x)\n root = root-&gt;right;\n else \n root = root-&gt;left;\n }\n return false;\n}\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28392/" ]
``` template <class T> bool BST<T>::search(const T& x, int& len) const { return search(BT<T>::root, x); } template <class T> bool BST<T>::search(struct Node<T>*& root, const T& x) { if (root == NULL) return false; else { if (root->data == x) return true; else if(root->data < x) search(root->left, x); else search(root->right, x); } } ``` So this is my search function for my BST class with a T node. x is the data being searched for within the tree, len is just the amount of nodes it has to travel to come up with the matching node if it exists. I have not implented that yet, I'm just incrementally developing my assignment. I'm calling it by doing this: ``` if(t.search(v[1], len) == true) cout << endl << "true"; ``` v is just a vector I had to create to compare it to, and so this is just supplying it with an int. The error I'm getting: ``` BST.h: In member function âbool BST<T>::search(const T&, int&) const [with T = int]â: prog5.cc:24: instantiated from here BST.h:78: error: no matching function for call to âBST<int>::search(Node<int>* const&, const int&) constâ BST.h:76: note: candidates are: bool BST<T>::search(const T&, int&) const [with T = int] BST.h:83: note: bool BST<T>::search(Node<T>*&, const T&) [with T = int] ``` So I'm not sure what I'm doing wrong or where I'm doing wrong.
Okay, `bool BST<T>::search(struct Node<T>*& root, const T& x)` should probably have const after it like so: `bool BST<T>::search(struct Node<T>*& root, const T& x) const`. Basically, you've called a non-const function from a const function and this is a no-no. BTW, this looks suspect to me "`struct Node<T>*&`"... I'd probably drop the & and work with `Node<T>*`... but maybe you need that because of the *struct*? Also, this is C++, there is no reason to leave Node as a struct... needing to have **struct** in the parameter definition just looks bad, IMHO. Why not make Node a class?
245,654
<p>My database consists of 3 tables (one for storing all items, one for the tags, and one for the relation between the two):</p> <p>Table: Post Columns: PostID, Name, Desc</p> <p>Table: Tag Columns: TagID, Name</p> <p>Table: PostTag Columns: PostID, TagID</p> <p>What is the best way to save a space separated string (e.g. "smart funny wonderful") into the 3 database tables shown above? </p> <p>Ultimately I would also need to retrieve the tags and display it as a string again. Thanks!</p>
[ { "answer_id": 245757, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 1, "selected": false, "text": "<p>If you have a Tag Table, wouldn't you have a row for each Tag?</p>\n\n<pre><code>tag.id = 1; tag.name = 'smart'\ntag.id = 2; tag.name = 'funny'\ntag.id = 3; tag.name = 'wonderful'\n</code></pre>\n\n<p>In Groovy/Grails, you'd retrieve them as a list, possibly concatenating them into a space separated list for display.</p>\n\n<p>Unless I'm really misunderstanding the question, Groovy/Grails/GORM will handle this with little or no code with the default scaffolding, no real coding required.</p>\n" }, { "answer_id": 248488, "author": "Hates_", "author_id": 3410, "author_profile": "https://Stackoverflow.com/users/3410", "pm_score": 3, "selected": true, "text": "<p>Roughly, something like this:</p>\n\n<pre><code>class Post {\n static hasMany [tags:Tag]\n}\n\nclass Tag {\n static belongsTo = Post\n static hasMany [posts:Post]\n}\n\nclass someService {\n\n def createPostWithTags(name, desc, tags) { \n def post = new Post(name: name, desc: desc).save()\n tags.split(' ').each { tagName -&gt;\n def tag = Tag.findByName(tag) ?: new Tag(name: tagName)\n post.addToTags(tag).save()\n } \n }\n\n}\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27163/" ]
My database consists of 3 tables (one for storing all items, one for the tags, and one for the relation between the two): Table: Post Columns: PostID, Name, Desc Table: Tag Columns: TagID, Name Table: PostTag Columns: PostID, TagID What is the best way to save a space separated string (e.g. "smart funny wonderful") into the 3 database tables shown above? Ultimately I would also need to retrieve the tags and display it as a string again. Thanks!
Roughly, something like this: ``` class Post { static hasMany [tags:Tag] } class Tag { static belongsTo = Post static hasMany [posts:Post] } class someService { def createPostWithTags(name, desc, tags) { def post = new Post(name: name, desc: desc).save() tags.split(' ').each { tagName -> def tag = Tag.findByName(tag) ?: new Tag(name: tagName) post.addToTags(tag).save() } } } ```
245,666
<p>When I'm using an If statement and I want to check if a boolean is false should I use the "Not" keyword or just = false, like so</p> <pre><code>If (Not myboolean) then </code></pre> <p>vs</p> <pre><code>If (myboolean = False) then </code></pre> <p>Which is better practice and more readable?</p>
[ { "answer_id": 245673, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 3, "selected": false, "text": "<p>Since there's no functional difference between either style, this is one of those things that just comes down to personal preference. </p>\n\n<p>If you're working on a codebase where a standard has already been set, then stick to that. </p>\n" }, { "answer_id": 245674, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 6, "selected": true, "text": "<p>Definitely, use \"Not\". And for the alternately, use \"If (myboolean)\" instead of \"If (myboolean = true)\"</p>\n\n<p>The works best if you give the boolean a readable name:</p>\n\n<pre><code> if (node.HasChildren)\n</code></pre>\n" }, { "answer_id": 245736, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 1, "selected": false, "text": "<p>! condition</p>\n\n<p>In C and pre-STL C++, \"!condition\" means condition evaluates to a false truth value, whereas \"condition == FALSE\" meant that the value of condition had to equal what the system designed as FALSE. Since different implementations defined it in different ways, it was deemed better practice to use !condition.</p>\n\n<p>UPDATE: As pointed out in the comment -- FALSE is always 0, it's TRUE that can be dangerous.</p>\n" }, { "answer_id": 245805, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 1, "selected": false, "text": "<p>Definitely use \"Not\", consider reading it aloud.</p>\n\n<p>If you read aloud: </p>\n\n<p>If X is false Then Do Y\n Do Y</p>\n\n<p>Versus</p>\n\n<p>If Not X Then Do Y</p>\n\n<p>I think you'll find the \"Not\" route is more natural. Especially if you pick good variable names or functions.</p>\n\n<p>Code Complete has some good rules on variable names. <a href=\"http://cc2e.com/Page.aspx?hid=225\" rel=\"nofollow noreferrer\">http://cc2e.com/Page.aspx?hid=225</a> (login is probably required)</p>\n" }, { "answer_id": 245890, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 2, "selected": false, "text": "<p>Use <code>True</code> and <code>False</code> to <em>set</em> variables, not to test them. This improves readability as described in the other answers, but it also improves portability, particularly when best practices aren't followed.</p>\n\n<p>Some languages allow you to interchange <code>bool</code> and integer types. Consider the contrived example:</p>\n\n<pre>\nint differentInts(int i, int j)\n{\n return i-j; // Returns non-zero (true) if ints are different.\n}\n\n. . .\nif (differentInts(4, 8) == TRUE)\n printf(\"Four and Eight are different!\\n\");\nelse\n printf(\"Four and Eight are equal!\\n\");\n</pre>\n\n<p>Horrible style, but I've seen worse sneak into production. On <em>other</em> people's watches, of course. :-)</p>\n" }, { "answer_id": 275813, "author": "Ted", "author_id": 7972, "author_profile": "https://Stackoverflow.com/users/7972", "pm_score": 2, "selected": false, "text": "<p>Additionally to the consensus, when there is both a true case and a false case please use</p>\n\n<pre><code>if (condition)\n // true case\nelse\n // false case\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>if (not condition)\n // false case\nelse\n // true case\n</code></pre>\n\n<p>(But then I am never sure if python's <code>x is not None</code> is the true-case or the false case.)</p>\n" }, { "answer_id": 275844, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<p>Something else: Omit the parentheses, they’re redundant in VB and as such, constitute syntactic garbage.</p>\n\n<p>Also, I'm slightly bothered by how many people argue by giving technical examples in other languages that simply <em>do not apply</em> in VB. In VB, the only reasons to use <code>If Not x</code> instead of <code>If x = False</code> is readability and logic. Not that you’d need other reasons.</p>\n\n<p>Completely different reasons apply in C(++), true. Even more true due to the existence of frameworks that really handle this differently. But <em>misleading</em> in the context of VB!</p>\n" }, { "answer_id": 17598007, "author": "yoel halb", "author_id": 640195, "author_profile": "https://Stackoverflow.com/users/640195", "pm_score": 1, "selected": false, "text": "<p>It does not make any difference as long you are dealing with VB only, however if you happen to use C functions such as the Win32 API, definitely do not use \"NOT\" just \"==False\" when testing for false, but when testing for true do not use \"==True\" instead use \"if(function())\".</p>\n\n<p>The reason for that is the difference between C and VB in how boolean is defined.</p>\n\n<ol>\n<li><p>In C true == 1 while in VB true == -1 (therefore you should not compare the output of a C function to true, as you are trying to compare -1 to 1)</p></li>\n<li><p>Not in Vb is a bitwise NOT (equal to C's ~ operator not the ! operator), and thus it negates each bit, and as a result negating 1 (true in C) will result in a non zero value which is true, NOT only works on VB true which is -1 (which in bit format is all one's according to the two's complement rule [111111111]) and negating all bits [0000000000] equals zero. </p></li>\n</ol>\n\n<p>For a better understanding see my answer on <a href=\"https://stackoverflow.com/questions/279208/is-there-a-vb-net-equivalent-for-cs-operator/17580187#17580187\">Is there a VB.net equivalent for C#&#39;s ! operator?</a></p>\n" }, { "answer_id": 25513534, "author": "Jay", "author_id": 3980399, "author_profile": "https://Stackoverflow.com/users/3980399", "pm_score": 0, "selected": false, "text": "<p>Made a difference with these lines in vb 2010/12\nWith the top line, Option Strict had to be turned off.</p>\n\n<pre><code>If InStr(strLine, \"=\") = False Then _\nIf Not CBool(InStr(strLine, \"=\")) Then\n</code></pre>\n\n<p>Thanks for answering the question for me. (I'm learning)</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
When I'm using an If statement and I want to check if a boolean is false should I use the "Not" keyword or just = false, like so ``` If (Not myboolean) then ``` vs ``` If (myboolean = False) then ``` Which is better practice and more readable?
Definitely, use "Not". And for the alternately, use "If (myboolean)" instead of "If (myboolean = true)" The works best if you give the boolean a readable name: ``` if (node.HasChildren) ```
245,677
<p>Many examples of macros seem to be about hiding lambdas, e.g. with-open-file in CL. I'm looking for some more exotic uses of macros, particularly in PLT Scheme. I'd like to get a feel for when to consider using a macro vs. using functions.</p>
[ { "answer_id": 246065, "author": "pupeno", "author_id": 6068, "author_profile": "https://Stackoverflow.com/users/6068", "pm_score": 3, "selected": false, "text": "<p>I'll start answering the last question. When to use a macro instead of a function. The macros do things the functions can't, and the functions do thing the macros can't, so it'll be hard to mix them, but let's go deeper.</p>\n\n<p>You use functions when you want the arguments evaluated and macros when you want the arguments un-evaluated. That's not very useful, is it? You use macros when you want to write something in a different way, when you see a pattern and you want to abstract. For example: I define three functions called foo-create, foo-process and foo-destroy for different values of foo and with similar bodies where the only change is foo. There's a pattern but a too-high level for a function, so you create a macro.</p>\n\n<p>In my humble experience, macros in Scheme are to used as much as in other Lisps, like Common Lisp or <a href=\"http://clojure.org\" rel=\"noreferrer\">Clojure</a>. I suppose it's proof that maybe hygienic macros are not such a good idea, and here I would disagree with Paul Graham about why. It's not because sometimes you want to be dirty (un-hygienic) but because hygienic macros end up being complex or convoluted.</p>\n" }, { "answer_id": 246461, "author": "Luís Oliveira", "author_id": 2967, "author_profile": "https://Stackoverflow.com/users/2967", "pm_score": 2, "selected": false, "text": "<p>Practical Common Lisp, by Peter Seibel, has a good introduction to macros. On Lisp, by Paul Graham, might be a good source of more complicated examples. Also, have look at the built-in macros in, say, Common Lisp.</p>\n" }, { "answer_id": 247229, "author": "Nathan Shively-Sanders", "author_id": 7851, "author_profile": "https://Stackoverflow.com/users/7851", "pm_score": 4, "selected": true, "text": "<p>I only use Scheme macros (<code>define-syntax</code>) for tiny things like better lambda syntax:</p>\n\n<pre><code>(define-syntax [: x]\n (syntax-case x ()\n ([src-: e es ...]\n (syntax-case (datum-&gt;syntax-object #'src-: '_) ()\n (_ #'(lambda (_) (e es ...)))))))\n</code></pre>\n\n<p>Which lets you write</p>\n\n<pre><code>[: / _ 2] ; &lt;-- much better than (lambda (x) (/ x 2))\n</code></pre>\n\n<p>Dan Friedman has a mind-bending implementation of OO using macros: <a href=\"http://www.cs.indiana.edu/~dfried/ooo.pdf\" rel=\"noreferrer\">http://www.cs.indiana.edu/~dfried/ooo.pdf</a></p>\n\n<p>But honestly, all the <em>useful</em> macros I've defined are stolen from <a href=\"http://paulgraham.com/onlisp.html\" rel=\"noreferrer\">Paul Graham's On Lisp</a> and are generally easier to write with <code>defmacro</code> (<code>define-macro</code> in PLT Scheme). For example, <code>aif</code> is pretty ugly with <code>define-syntax</code>.</p>\n\n<pre><code>(define-syntax (aif x)\n (syntax-case x ()\n [(src-aif test then else)\n (syntax-case (datum-&gt;syntax-object (syntax src-aif) '_) ()\n [_ (syntax (let ([_ test]) (if (and _ (not (null? _))) then else)))])]))\n</code></pre>\n\n<p><code>define-syntax</code> is odd in that it's only easy to use for very simple macros, where you are glad of the inability to capture variables; and very complicated macro DSLs, where you are glad of the inability to capture variables <em>easily</em>. In the first case you want to write the code without thinking about it, and in the second case you have thought enough about the DSL that you are willing to write part of it in the <code>syntax-rules</code>/<code>syntax-case</code> language which is not Scheme in order to avoid mystifying bugs.</p>\n\n<hr>\n\n<p>But I don't use macros that much in Scheme. Idiomatic Scheme is so functional that many times you just want to write a functional program and then hide a few lambdas. I got on the functional train and now believe that if you have a lazy language or a good syntax for lambda, even that isn't necessary, so macros are not all that useful in a purely functional style.</p>\n\n<p>So I'd recommend <a href=\"http://gigamonkeys.com/book/\" rel=\"noreferrer\">Practical Common Lisp</a> and <a href=\"http://paulgraham.com/onlisp.html\" rel=\"noreferrer\">On Lisp</a>. If you want to use PLT Scheme, I think most of their <code>defmacro</code> macros will work with <code>define-macro</code>. Or just use Common Lisp.</p>\n" }, { "answer_id": 247912, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 1, "selected": false, "text": "<p>An example of a more advanced macro that is not a lambda form in disguise is Common Lisp's macro <strong>with-slots</strong>, which makes object slot access look like ordinary variable access:</p>\n\n<pre><code>(with-slots (state door) car\n (when (eq state :stopped)\n (setq state :driving-around)\n (setq door :closed)))\n</code></pre>\n\n<p>Note that this is not the same as binding the slot values to local variables and accessing those, as <strong>with-slots</strong> allows you to alter slots by way of SETQ and see external changes immediately.</p>\n" }, { "answer_id": 262954, "author": "soegaard", "author_id": 23567, "author_profile": "https://Stackoverflow.com/users/23567", "pm_score": 3, "selected": false, "text": "<p>Macros are needed in order to implement new control structures and new binding constructs.</p>\n\n<p>Thus look for these kinds of constructs at <a href=\"http://planet.plt-scheme.org\" rel=\"noreferrer\">http://planet.plt-scheme.org</a>.\nAt PLaneT you both browse the documentation and the code.</p>\n\n<p>Examples for new control structures:</p>\n\n<p><a href=\"http://planet.plt-scheme.org/package-source/soegaard/control.plt/2/0/planet-docs/manual/index.html\" rel=\"noreferrer\">http://planet.plt-scheme.org/package-source/soegaard/control.plt/2/0/planet-docs/manual/index.html</a></p>\n\n<p>To find examples of new binding forms, look for macros that begin with \"with-\".\nOne useful example is found in math.plt also from PLaneT.</p>\n\n<pre><code> ; Within a (with-modulus n form1 ...) the return values of\n ; the arithmetival operations +, -, * and ^ are automatically\n ; reduced modulo n. Furthermore (mod x)=(modulo x n) and\n ; (inv x)=(inverse x n).\n\n ; Example: (with-modulus 3 (^ 2 4)) ==&gt; 1\n\n (define-syntax (with-modulus stx)\n (syntax-case stx ()\n [(with-modulus e form ...)\n (with-syntax ([+ (datum-&gt;syntax-object (syntax with-modulus) '+)]\n [- (datum-&gt;syntax-object (syntax with-modulus) '-)]\n [* (datum-&gt;syntax-object (syntax with-modulus) '*)]\n [^ (datum-&gt;syntax-object (syntax with-modulus) '^)]\n [mod (datum-&gt;syntax-object (syntax with-modulus) 'mod)]\n [inv (datum-&gt;syntax-object (syntax with-modulus) 'inv)])\n (syntax (let* ([n e]\n [mod (lambda (x) (modulo x n))]\n [inv (lambda (x) (inverse x n))]\n [+ (compose mod +)]\n [- (compose mod -)]\n [* (compose mod *)]\n [square (lambda (x) (* x x))]\n [^ (rec ^ (lambda (a b)\n (cond\n [(= b 0) 1]\n [(even? b) (square (^ a (/ b 2)))]\n [else (* a (^ a (sub1 b)))])))])\n form ...)))]))\n</code></pre>\n" }, { "answer_id": 330226, "author": "namin", "author_id": 34596, "author_profile": "https://Stackoverflow.com/users/34596", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://www.cs.brown.edu/~sk/Publications/Papers/Published/sk-automata-macros/\" rel=\"nofollow noreferrer\">Automata via Macros</a> paper presents a functional programming pearl on implementing finite state machines via macros in Scheme.</p>\n\n<p>The book <a href=\"http://www.amazon.com/exec/obidos/tg/detail/-/0262562146/\" rel=\"nofollow noreferrer\">The Reasoned Schemer</a> ends with a full macro-based implementation of miniKanren, the logic programming language used in the book. <a href=\"http://scheme2006.cs.uchicago.edu/12-byrd.pdf\" rel=\"nofollow noreferrer\">This paper</a> presents miniKanren and its implementation more formally and concisely than in the book.</p>\n" }, { "answer_id": 330257, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 0, "selected": false, "text": "<p>I use them when procedures do not suffice. </p>\n" }, { "answer_id": 330265, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 1, "selected": false, "text": "<p>I had a <code>curry</code> macro when I used to do a lot of scheme on my palm. It was pretty handy.</p>\n" }, { "answer_id": 357501, "author": "grettke", "author_id": 121526, "author_profile": "https://Stackoverflow.com/users/121526", "pm_score": 1, "selected": false, "text": "<p>Scheme macros let you add features that the original language authors did not include themselves; that is the whole philosophy behind macros.</p>\n\n<p>Here is a tiny example: PLT Scheme provides a language for writing presentations called Slideshow. I used macros to associate a slide number with a slide so that I could more easily manage them.</p>\n" }, { "answer_id": 3153235, "author": "Robert Fisher", "author_id": 103785, "author_profile": "https://Stackoverflow.com/users/103785", "pm_score": 1, "selected": false, "text": "<p>I’ve written a macro that provides infix syntax. Nothing too fancy; no precedence. While I’m generally fine with prefix syntax, I prefer infix for &lt; and >.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28604/" ]
Many examples of macros seem to be about hiding lambdas, e.g. with-open-file in CL. I'm looking for some more exotic uses of macros, particularly in PLT Scheme. I'd like to get a feel for when to consider using a macro vs. using functions.
I only use Scheme macros (`define-syntax`) for tiny things like better lambda syntax: ``` (define-syntax [: x] (syntax-case x () ([src-: e es ...] (syntax-case (datum->syntax-object #'src-: '_) () (_ #'(lambda (_) (e es ...))))))) ``` Which lets you write ``` [: / _ 2] ; <-- much better than (lambda (x) (/ x 2)) ``` Dan Friedman has a mind-bending implementation of OO using macros: <http://www.cs.indiana.edu/~dfried/ooo.pdf> But honestly, all the *useful* macros I've defined are stolen from [Paul Graham's On Lisp](http://paulgraham.com/onlisp.html) and are generally easier to write with `defmacro` (`define-macro` in PLT Scheme). For example, `aif` is pretty ugly with `define-syntax`. ``` (define-syntax (aif x) (syntax-case x () [(src-aif test then else) (syntax-case (datum->syntax-object (syntax src-aif) '_) () [_ (syntax (let ([_ test]) (if (and _ (not (null? _))) then else)))])])) ``` `define-syntax` is odd in that it's only easy to use for very simple macros, where you are glad of the inability to capture variables; and very complicated macro DSLs, where you are glad of the inability to capture variables *easily*. In the first case you want to write the code without thinking about it, and in the second case you have thought enough about the DSL that you are willing to write part of it in the `syntax-rules`/`syntax-case` language which is not Scheme in order to avoid mystifying bugs. --- But I don't use macros that much in Scheme. Idiomatic Scheme is so functional that many times you just want to write a functional program and then hide a few lambdas. I got on the functional train and now believe that if you have a lazy language or a good syntax for lambda, even that isn't necessary, so macros are not all that useful in a purely functional style. So I'd recommend [Practical Common Lisp](http://gigamonkeys.com/book/) and [On Lisp](http://paulgraham.com/onlisp.html). If you want to use PLT Scheme, I think most of their `defmacro` macros will work with `define-macro`. Or just use Common Lisp.
245,698
<p>This is similar to <a href="https://stackoverflow.com/questions/105212/linux-recursively-list-all-files-in-a-directory-including-files-in-symlink-dire">this question</a>, but I want to include the path relative to the current directory in unix. If I do the following:</p> <pre><code>ls -LR | grep .txt </code></pre> <p>It doesn't include the full paths. For example, I have the following directory structure:</p> <pre><code>test1/file.txt test2/file1.txt test2/file2.txt </code></pre> <p>The code above will return:</p> <pre><code>file.txt file1.txt file2.txt </code></pre> <p>How can I get it to include the paths relative to the current directory using standard Unix commands?</p>
[ { "answer_id": 245710, "author": "Jonathan Adelson", "author_id": 8092, "author_profile": "https://Stackoverflow.com/users/8092", "pm_score": 5, "selected": false, "text": "<p>Try <code>find</code>. You can look it up exactly in the man page, but it's sorta like this:</p>\n\n<p><code>find [start directory] -name [what to find]</code></p>\n\n<p>so for your example</p>\n\n<p><code>find . -name \"*.txt\"</code></p>\n\n<p>should give you what you want.</p>\n" }, { "answer_id": 245712, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 9, "selected": true, "text": "<p>Use find:</p>\n\n<pre><code>find . -name \\*.txt -print\n</code></pre>\n\n<p>On systems that use GNU find, like most GNU/Linux distributions, you can leave out the -print.</p>\n" }, { "answer_id": 245716, "author": "Sherm Pendley", "author_id": 27631, "author_profile": "https://Stackoverflow.com/users/27631", "pm_score": 4, "selected": false, "text": "<p>You could use find instead:</p>\n\n<pre><code>find . -name '*.txt'\n</code></pre>\n" }, { "answer_id": 1571652, "author": "h-dima", "author_id": 190533, "author_profile": "https://Stackoverflow.com/users/190533", "pm_score": 2, "selected": false, "text": "<pre><code>DIR=your_path\nfind $DIR | sed 's:\"\"$DIR\"\"::'\n</code></pre>\n\n<p>'sed' will erase 'your_path' from all 'find' results. And you recieve relative to 'DIR' path.</p>\n" }, { "answer_id": 1807738, "author": "Eric Keller", "author_id": 219940, "author_profile": "https://Stackoverflow.com/users/219940", "pm_score": 1, "selected": false, "text": "<p>Here is a Perl script:</p>\n\n<pre class=\"lang-pl prettyprint-override\"><code>sub format_lines($)\n{\n my $refonlines = shift;\n my @lines = @{$refonlines};\n my $tmppath = \"-\";\n\n foreach (@lines)\n {\n next if ($_ =~ /^\\s+/);\n if ($_ =~ /(^\\w+(\\/\\w*)*):/)\n {\n $tmppath = $1 if defined $1; \n next;\n }\n print \"$tmppath/$_\";\n }\n}\n\nsub main()\n{\n my @lines = ();\n\n while (&lt;&gt;) \n {\n push (@lines, $_);\n }\n format_lines(\\@lines);\n}\n\nmain();\n</code></pre>\n\n<p>usage:</p>\n\n<pre><code>ls -LR | perl format_ls-LR.pl\n</code></pre>\n" }, { "answer_id": 2726134, "author": "Stephen Irons", "author_id": 327388, "author_profile": "https://Stackoverflow.com/users/327388", "pm_score": 6, "selected": false, "text": "<p>Use <code>tree</code>, with <code>-f</code> (full path) and <code>-i</code> (no indentation lines):</p>\n\n<pre><code>tree -if --noreport .\ntree -if --noreport directory/\n</code></pre>\n\n<p>You can then use <code>grep</code> to filter out the ones you want.</p>\n\n<hr>\n\n<p>If the command is not found, you can install it:</p>\n\n<p>Type following command to install tree command on RHEL/CentOS and Fedora linux:</p>\n\n<pre><code># yum install tree -y\n</code></pre>\n\n<p>If you are using Debian/Ubuntu, Mint Linux type following command in your terminal:</p>\n\n<pre><code>$ sudo apt-get install tree -y\n</code></pre>\n" }, { "answer_id": 5490765, "author": "rxw", "author_id": 220472, "author_profile": "https://Stackoverflow.com/users/220472", "pm_score": 1, "selected": false, "text": "<p>You could create a shell function, e.g. in your <code>.zshrc</code> or <code>.bashrc</code>:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>filepath() {\n echo $PWD/$1\n}\n\nfilepath2() {\n for i in $@; do\n echo $PWD/$i\n done\n}\n</code></pre>\n\n<p>The first one would work on single files only, obviously.</p>\n" }, { "answer_id": 8676573, "author": "ZaSter", "author_id": 552857, "author_profile": "https://Stackoverflow.com/users/552857", "pm_score": 3, "selected": false, "text": "<p>To get the actual full path file names of the desired files using the find command, use it with the pwd command:</p>\n\n<pre><code>find $(pwd) -name \\*.txt -print\n</code></pre>\n" }, { "answer_id": 15036235, "author": "user2101432", "author_id": 2101432, "author_profile": "https://Stackoverflow.com/users/2101432", "pm_score": 1, "selected": false, "text": "<p>Find the file called \"filename\" on your filesystem starting the search from the root directory \"/\". The \"filename\" </p>\n\n<pre><code>find / -name \"filename\" \n</code></pre>\n" }, { "answer_id": 18360502, "author": "rajeshk", "author_id": 2148088, "author_profile": "https://Stackoverflow.com/users/2148088", "pm_score": 1, "selected": false, "text": "<p>If you want to preserve the details come with ls like file size etc in your output then this should work.</p>\n\n<pre><code>sed \"s|&lt;OLDPATH&gt;|&lt;NEWPATH&gt;|g\" input_file &gt; output_file\n</code></pre>\n" }, { "answer_id": 23039612, "author": "Sireesh Yarlagadda", "author_id": 2057902, "author_profile": "https://Stackoverflow.com/users/2057902", "pm_score": 0, "selected": false, "text": "<p>You can implement this functionality like this<br>\nFirstly, using the ls command pointed to the targeted directory. Later using find command filter the result from it.\nFrom your case, it sounds like - always the filename starts with a word \n<code>file***.txt</code></p>\n\n<pre><code>ls /some/path/here | find . -name 'file*.txt' (* represents some wild card search)\n</code></pre>\n" }, { "answer_id": 35998640, "author": "El Guesto", "author_id": 5233249, "author_profile": "https://Stackoverflow.com/users/5233249", "pm_score": 3, "selected": false, "text": "<p>That does the trick:</p>\n\n<p><code>ls -R1 $PWD | while read l; do case $l in *:) d=${l%:};; \"\") d=;; *) echo \"$d/$l\";; esac; done | grep -i \".txt\"</code></p>\n\n<p>But it does that by \"sinning\" with the parsing of <code>ls</code>, though, which is considered bad form by the GNU and Ghostscript communities.</p>\n" }, { "answer_id": 55816586, "author": "rien333", "author_id": 1657933, "author_profile": "https://Stackoverflow.com/users/1657933", "pm_score": 1, "selected": false, "text": "<p>In the <a href=\"https://fishshell.com/\" rel=\"nofollow noreferrer\">fish</a> shell, you can do this to list all pdfs recursively, including the ones in the current directory:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ ls **pdf\n</code></pre>\n\n<p>Just remove 'pdf' if you want files of any type. </p>\n" }, { "answer_id": 60542090, "author": "kazuwombat", "author_id": 5992952, "author_profile": "https://Stackoverflow.com/users/5992952", "pm_score": 0, "selected": false, "text": "<p>In mycase, with tree command</p>\n\n<p>Relative path</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>tree -ifF ./dir | grep -v '^./dir$' | grep -v '.*/$' | grep '\\./.*' | while read file; do\n echo $file\ndone\n</code></pre>\n\n<p>Absolute path</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>tree -ifF ./dir | grep -v '^./dir$' | grep -v '.*/$' | grep '\\./.*' | while read file; do\n echo $file | sed -e \"s|^.|$PWD|g\"\ndone\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
This is similar to [this question](https://stackoverflow.com/questions/105212/linux-recursively-list-all-files-in-a-directory-including-files-in-symlink-dire), but I want to include the path relative to the current directory in unix. If I do the following: ``` ls -LR | grep .txt ``` It doesn't include the full paths. For example, I have the following directory structure: ``` test1/file.txt test2/file1.txt test2/file2.txt ``` The code above will return: ``` file.txt file1.txt file2.txt ``` How can I get it to include the paths relative to the current directory using standard Unix commands?
Use find: ``` find . -name \*.txt -print ``` On systems that use GNU find, like most GNU/Linux distributions, you can leave out the -print.
245,705
<p>I'm trying to decide what to put in a dialog box that tells the user their login doesn't work, there is probably a duplicate. The system uses email addresses as user names, then requires a password.</p> <p>Right now, I'm using "Email Login" but that just sounds stupid.</p> <p>For instance:</p> <p>1) Application Starts, recognizes that it has never been run. 2) Prompts user to create a new account. 3) User puts in an email address and password to use as their new credentials. 4) Well, looks like they've already got an account probably. (This is the most likely case the account creation would fail but I'm using an API and I can't be 100% this is why it failed) 5) I ask them to try again with a different "email login".</p> <pre><code>Could not create account - try a different email login ! </code></pre> <p>After I check with the API provider, I'll probably try to detect that it is in fact a duplicate account and ask them to try to authenticate that account with a password.</p>
[ { "answer_id": 245713, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 4, "selected": true, "text": "<p>Tell them explicitly that their email address is already in use.</p>\n\n<p>Call it an email address, thats what the user thinks of it as. The fact that you are using it as an id or a database primary key or a hash key is irrelevant to them.</p>\n" }, { "answer_id": 245719, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>I would just call it what it is: an email address. I wouldn't suggest that they try a different one, though. Just ask them if they already have an account and, if so, to try logging in with the address/password. If they continue to have problems, give them a contact that they can use to get help.</p>\n" }, { "answer_id": 245739, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 2, "selected": false, "text": "<p>Perhaps: <em>An account already exists for this email address. If you already have an account but forgot your password, please click <strong>[here]</strong>, otherwise please choose a different email address.</em></p>\n\n<p>I agree with mgb that the best choice is to explain the problem and how the user should proceed.</p>\n" }, { "answer_id": 5869110, "author": "JohnathonMe", "author_id": 3764103, "author_profile": "https://Stackoverflow.com/users/3764103", "pm_score": 0, "selected": false, "text": "<p>There is a distinction between the process of authenticating ie logging-on/login and the options a user can use ie. username, userid or email address. </p>\n\n<p>As more websites are having allowing users to login with email address it doesn't pay to be ambiguous, do your users a favour and label the field 'Email Address:'. This way your users are clear on what is expected in the field. If you label it \"login:\" or something else vague they'll be subtly fooled into thinking they might have created a username when creating their account and try all the usernames they usually use before trying email addresses.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22917/" ]
I'm trying to decide what to put in a dialog box that tells the user their login doesn't work, there is probably a duplicate. The system uses email addresses as user names, then requires a password. Right now, I'm using "Email Login" but that just sounds stupid. For instance: 1) Application Starts, recognizes that it has never been run. 2) Prompts user to create a new account. 3) User puts in an email address and password to use as their new credentials. 4) Well, looks like they've already got an account probably. (This is the most likely case the account creation would fail but I'm using an API and I can't be 100% this is why it failed) 5) I ask them to try again with a different "email login". ``` Could not create account - try a different email login ! ``` After I check with the API provider, I'll probably try to detect that it is in fact a duplicate account and ask them to try to authenticate that account with a password.
Tell them explicitly that their email address is already in use. Call it an email address, thats what the user thinks of it as. The fact that you are using it as an id or a database primary key or a hash key is irrelevant to them.
245,727
<p>I have one website on my server, and my IIS Worker Process is using 4GB RAM consistently. What should I be checking?</p> <pre><code>c:\windows\system32\inetsrv\w3wp.exe </code></pre>
[ { "answer_id": 245731, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 3, "selected": false, "text": "<p>check the section on troubleshooting memory bottlenecks in <a href=\"http://msdn.microsoft.com/en-us/library/ms998583.aspx#scalenetchapt17_topic9\" rel=\"noreferrer\">Tuning .NET Application Performance</a></p>\n" }, { "answer_id": 245758, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>If you have access to the source code, you may want to check that any objects that implement IDisposable are being referenced inside <code>using</code> statements or being properly disposed of when you are done with them.</p>\n\n<p><code>Using</code> is a C# construct, but the basic idea is that you are freeing up resources when you are done.</p>\n\n<p>Another thing to check on is large objects getting put in the \"in process\" session state or cache.</p>\n" }, { "answer_id": 245779, "author": "Maxam", "author_id": 15310, "author_profile": "https://Stackoverflow.com/users/15310", "pm_score": 2, "selected": false, "text": "<p>More details would definitely help. How many applications are running inside the application pool? Are there ASP.NET applications in the pool?</p>\n\n<p>If you're running ASP.NET, take a good look at what you're storing in the session and cache variables. Use PerfMon to check how many Generation 0, 1 and 2 collections are occurring. Be wary of storing UI elements in the session state or cache since this will prevent the entire page instance and all of the page instance's children from being collected as well. Finally, check to see if you're doing lots of string concatenation. This can cause lots of object instantiations since .NET strings are immutable. Look into using StringBuilder instead.</p>\n" }, { "answer_id": 245876, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 5, "selected": true, "text": "<p>I would check the CLR Tuning Section in the <a href=\"http://msdn.microsoft.com/en-us/library/ms998583.aspx#scalenetchapt17_topic9\" rel=\"noreferrer\">document</a> Gulzar mentioned.</p>\n<p>As the other posters pointed out, any object that implements <code>IDispose</code> should have <code>Dispose()</code> called on it when it's finished with, preferably using the <code>using</code> construct.</p>\n<p>Fire up <code>perfmon.exe</code> and add these counters:</p>\n<blockquote>\n<ul>\n<li>Process\\Private Bytes</li>\n<li>.NET CLR Memory# Bytes in all Heaps</li>\n<li>Process\\Working Set</li>\n<li>.NET CLR Memory\\Large Object Heap size</li>\n</ul>\n<p>An increase in Private Bytes while the\nnumber of Bytes in all Heaps counter remains the same indicates unmanaged\nmemory consumption.</p>\n<p>An increase in\nboth counters indicates managed memory\nconsumption</p>\n</blockquote>\n" }, { "answer_id": 245904, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "<p>As other people noted common cause of this problem is resource leaking, also there is a known issue with win2k3 server and IIS6 <a href=\"http://support.microsoft.com/kb/916984\" rel=\"nofollow noreferrer\">KB916984</a></p>\n" }, { "answer_id": 246140, "author": "jwanagel", "author_id": 15118, "author_profile": "https://Stackoverflow.com/users/15118", "pm_score": 2, "selected": false, "text": "<p>Create a mini-dump of the w3wp process and use WinDbg to see what objects are in memory. This is what the IIS support team at Microsoft does whenever they get questions like this.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16794/" ]
I have one website on my server, and my IIS Worker Process is using 4GB RAM consistently. What should I be checking? ``` c:\windows\system32\inetsrv\w3wp.exe ```
I would check the CLR Tuning Section in the [document](http://msdn.microsoft.com/en-us/library/ms998583.aspx#scalenetchapt17_topic9) Gulzar mentioned. As the other posters pointed out, any object that implements `IDispose` should have `Dispose()` called on it when it's finished with, preferably using the `using` construct. Fire up `perfmon.exe` and add these counters: > > * Process\Private Bytes > * .NET CLR Memory# Bytes in all Heaps > * Process\Working Set > * .NET CLR Memory\Large Object Heap size > > > An increase in Private Bytes while the > number of Bytes in all Heaps counter remains the same indicates unmanaged > memory consumption. > > > An increase in > both counters indicates managed memory > consumption > > >
245,735
<p>By which I mean this:</p> <p>Given the input set of numbers: </p> <p>1,2,3,4,5 becomes "1-5".</p> <p>1,2,3,5,7,9,10,11,12,14 becomes "1-3, 5, 7, 9-12, 14"</p> <p>This is the best I managed to come up with: [C#]</p> <p><em>Which feels a little sloppy to me, so the question is, is there somehow more readable and/or elegant solution to this?</em></p> <pre><code>public static string[] FormatInts(int[] ints) { if (ints == null) throw new ArgumentNullException("ints"); // hey what are you doing? if (ints.Length == 0) return new string[] { "" }; // nothing to process if (ints.Length == 1) return new string[] { ints[0].ToString() }; // nothing to process Array.Sort&lt;int&gt;(ints); // need to sort these lil' babies List&lt;string&gt; values = new List&lt;string&gt;(); int lastNumber = ints[0]; // start with the first number int firstNumber = ints[0]; // same as above for (int i = 1; i &lt; ints.Length; i++) { int current = ints[i]; int difference = (lastNumber - current ); // compute difference between last number and current number if (difference == -1) // the numbers are adjacent { if (firstNumber == 0) // this is the first of the adjacent numbers { firstNumber = lastNumber; } else // we're somehow in the middle or at the end of the adjacent number set { lastNumber = current; continue; } } else { if (firstNumber &gt; 0 &amp;&amp; firstNumber != lastNumber) // get ready to print a set of numbers { values.Add(string.Format("{0}-{1}", firstNumber, lastNumber)); firstNumber = 0; // reset } else // print a single value { values.Add(string.Format("{0}", lastNumber)); } } lastNumber = current; } if (firstNumber &gt; 0) // if theres anything left, print it out { values.Add(string.Format("{0}-{1}", firstNumber, lastNumber)); } return values.ToArray(); } </code></pre>
[ { "answer_id": 245743, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 1, "selected": false, "text": "<p>Looks clear and straightforward to me. You can simplify a bit if you either assume the input array is sorted, or sort it yourself before further processing.</p>\n\n<p>The only tweak I'd suggest would be to reverse the subtraction:</p>\n\n<blockquote>\n <p><pre>int difference = (current - lastNumber);</pre></p>\n</blockquote>\n\n<p>... simply because I find it easier to work with positive differences. But your code is a pleasure to read!</p>\n" }, { "answer_id": 245788, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 5, "selected": true, "text": "<p>I've rewritten your code like this:</p>\n\n<pre><code> public static string[] FormatInts(int[] ints)\n {\n Array.Sort&lt;int&gt;(ints);\n List&lt;string&gt; values = new List&lt;string&gt;();\n\n for (int i = 0; i &lt; ints.Length; i++)\n {\n int groupStart = ints[i];\n int groupEnd = groupStart;\n while (i &lt; ints.Length - 1 &amp;&amp; ints[i] - ints[i + 1] == -1)\n {\n groupEnd = ints[i + 1];\n i++;\n }\n values.Add(string.Format(groupEnd == groupStart ? \"{0}\":\"{0} - {1}\", groupStart, groupEnd));\n }\n return values.ToArray();\n }\n</code></pre>\n\n<p>And then:</p>\n\n<pre><code>/////////////////\nint[] myInts = { 1,2,3,5,7,9,10,11,12,14 };\nstring[] result = FormatInts(myInts); // now result haves \"1-3\", \"5\", \"7\", \"9-12\", \"14\"\n</code></pre>\n" }, { "answer_id": 245875, "author": "Robert Krimen", "author_id": 25171, "author_profile": "https://Stackoverflow.com/users/25171", "pm_score": 1, "selected": false, "text": "<h2>Perl</h2>\n\n<p>With input validation/pre-sorting</p>\n\n<p>You can easily get the result as a LoL if you need to do something more fancy than\njust return a string.</p>\n\n<pre><code>#!/usr/bin/perl -w\n\nuse strict;\nuse warnings;\n\nuse Scalar::Util qw/looks_like_number/;\n\nsub adjacenify {\n my @input = @_; \n\n # Validate and sort\n looks_like_number $_ or\n die \"Saw '$_' which doesn't look like a number\" for @input;\n @input = sort { $a &lt;=&gt; $b } @input;\n\n my (@output, @range);\n @range = (shift @input);\n for (@input) {\n if ($_ - $range[-1] &lt;= 1) {\n push @range, $_ unless $range[-1] == $_; # Prevent repetition\n }\n else {\n push @output, [ @range ];\n @range = ($_); \n }\n } \n push @output, [ @range ] if @range;\n\n # Return the result as a string. If a sequence is size 1, then it's just that number.\n # Otherwise, it's the first and last number joined by '-'\n return join ', ', map { 1 == @$_ ? @$_ : join ' - ', $_-&gt;[0], $_-&gt;[-1] } @output;\n}\n\nprint adjacenify( qw/1 2 3 5 7 9 10 11 12 14/ ), \"\\n\";\nprint adjacenify( 1 .. 5 ), \"\\n\";\nprint adjacenify( qw/-10 -9 -8 -1 0 1 2 3 5 7 9 10 11 12 14/ ), \"\\n\";\nprint adjacenify( qw/1 2 4 5 6 7 100 101/), \"\\n\";\nprint adjacenify( qw/1 62/), \"\\n\";\nprint adjacenify( qw/1/), \"\\n\";\nprint adjacenify( qw/1 2/), \"\\n\";\nprint adjacenify( qw/1 62 63/), \"\\n\";\nprint adjacenify( qw/-2 0 0 2/), \"\\n\";\nprint adjacenify( qw/-2 0 0 1/), \"\\n\";\nprint adjacenify( qw/-2 0 0 1 2/), \"\\n\";\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>1 - 3, 5, 7, 9 - 12, 14\n1 - 5\n-10 - -8, -1 - 3, 5, 7, 9 - 12, 14\n1 - 2, 4 - 7, 100 - 101\n1, 62\n1\n1 - 2\n1, 62 - 63\n-2, 0, 2\n-2, 0 - 1\n-2, 0 - 2\n-2, 0 - 2\n</code></pre>\n\n<p>And a nice recursive solution:</p>\n\n<pre><code>sub _recursive_adjacenify($$);\nsub _recursive_adjacenify($$) {\n my ($input, $range) = @_;\n\n return $range if ! @$input;\n\n my $number = shift @$input;\n\n if ($number - $range-&gt;[-1] &lt;= 1) {\n return _recursive_adjacenify $input, [ @$range, $number ];\n }\n else {\n return $range, _recursive_adjacenify $input, [ $number ];\n }\n}\n\nsub recursive_adjacenify {\n my @input = @_;\n\n # Validate and sort\n looks_like_number $_ or\n die \"Saw '$_' which doesn't look like a number\" for @input;\n @input = sort { $a &lt;=&gt; $b } @input;\n\n my @output = _recursive_adjacenify \\@input, [ shift @input ];\n\n # Return the result as a string. If a sequence is size 1, \n # then it's just that number.\n # Otherwise, it's the first and last number joined by '-'\n return join ', ', map { 2 == @$_ &amp;&amp; $_-&gt;[0] == $_-&gt;[1] ? $_-&gt;[0] : \n 1 == @$_ ? @$_ : \n join ' - ', $_-&gt;[0], $_-&gt;[-1] } @output;\n\n}\n</code></pre>\n" }, { "answer_id": 246039, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "<p>As I wrote in comment, I am not fan of the use of value 0 as flag, making firstNumber both a value and a flag.</p>\n\n<p>I did a quick implementation of the algorithm in Java, boldly skipping the validity tests you already correctly covered...</p>\n\n<pre><code>public class IntListToRanges\n{\n // Assumes all numbers are above 0\n public static String[] MakeRanges(int[] numbers)\n {\n ArrayList&lt;String&gt; ranges = new ArrayList&lt;String&gt;();\n\n Arrays.sort(numbers);\n int rangeStart = 0;\n boolean bInRange = false;\n for (int i = 1; i &lt;= numbers.length; i++)\n {\n if (i &lt; numbers.length &amp;&amp; numbers[i] - numbers[i - 1] == 1)\n {\n if (!bInRange)\n {\n rangeStart = numbers[i - 1];\n bInRange = true;\n }\n }\n else\n {\n if (bInRange)\n {\n ranges.add(rangeStart + \"-\" + numbers[i - 1]);\n bInRange = false;\n }\n else\n {\n ranges.add(String.valueOf(numbers[i - 1]));\n }\n }\n }\n return ranges.toArray(new String[ranges.size()]);\n }\n\n public static void ShowRanges(String[] ranges)\n {\n for (String range : ranges)\n {\n System.out.print(range + \",\"); // Inelegant but quickly coded...\n }\n System.out.println();\n }\n\n /**\n * @param args\n */\n public static void main(String[] args)\n {\n int[] an1 = { 1,2,3,5,7,9,10,11,12,14,15,16,22,23,27 };\n int[] an2 = { 1,2 };\n int[] an3 = { 1,3,5,7,8,9,11,12,13,14,15 };\n ShowRanges(MakeRanges(an1));\n ShowRanges(MakeRanges(an2));\n ShowRanges(MakeRanges(an3));\n int L = 100;\n int[] anr = new int[L];\n for (int i = 0, c = 1; i &lt; L; i++)\n {\n int incr = Math.random() &gt; 0.2 ? 1 : (int) Math.random() * 3 + 2;\n c += incr;\n anr[i] = c;\n }\n ShowRanges(MakeRanges(anr));\n }\n}\n</code></pre>\n\n<p>I won't say it is more elegant/efficient than your algorithm, of course... Just something different.</p>\n\n<p>Note that 1,5,6,9 can be written either 1,5-6,9 or 1,5,6,9, not sure what is better (if any).</p>\n\n<p>I remember having done something similar (in C) to group message numbers to Imap ranges, as it is more efficient. A useful algorithm.</p>\n" }, { "answer_id": 246075, "author": "Deestan", "author_id": 6848, "author_profile": "https://Stackoverflow.com/users/6848", "pm_score": 2, "selected": false, "text": "<p>Pure functional Python:</p>\n\n<pre><code>#!/bin/env python\n\ndef group(nums):\n def collect((acc, i_s, i_e), n):\n if n == i_e + 1: return acc, i_s, n\n return acc + [\"%d\"%i_s + (\"-%d\"%i_e)*(i_s!=i_e)], n, n\n s = sorted(nums)+[None]\n acc, _, __ = reduce(collect, s[1:], ([], s[0], s[0]))\n return \", \".join(acc)\n\nassert group([1,2,3,5,7,9,10,11,12,14]) == \"1-3, 5, 7, 9-12, 14\"\n</code></pre>\n" }, { "answer_id": 246093, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "<p>See <a href=\"https://stackoverflow.com/questions/117691/how-would-you-display-an-array-of-integers-as-a-set-of-ranges-algorithm\">How would you display an array of integers as a set of ranges? (algorithm)</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/117691/how-would-you-display-an-array-of-integers-as-a-set-of-ranges-algorithm#233811\">My answer</a> to the above question:</p>\n\n<pre><code>void ranges(int n; int a[n], int n)\n{\n qsort(a, n, sizeof(*a), intcmp);\n for (int i = 0; i &lt; n; ++i) {\n const int start = i;\n while(i &lt; n-1 and a[i] &gt;= a[i+1]-1)\n ++i;\n printf(\"%d\", a[start]);\n if (a[start] != a[i])\n printf(\"-%d\", a[i]);\n if (i &lt; n-1)\n printf(\",\");\n }\n printf(\"\\n\");\n}\n</code></pre>\n" }, { "answer_id": 246259, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 1, "selected": false, "text": "<p>Short and sweet Ruby</p>\n\n<pre><code>def range_to_s(range)\n return range.first.to_s if range.size == 1\n return range.first.to_s + \"-\" + range.last.to_s\nend\n\ndef format_ints(ints)\n range = []\n 0.upto(ints.size-1) do |i|\n range &lt;&lt; ints[i]\n unless (range.first..range.last).to_a == range\n return range_to_s(range[0,range.length-1]) + \",\" + format_ints(ints[i,ints.length-1])\n end\n end\n range_to_s(range) \nend\n</code></pre>\n" }, { "answer_id": 247226, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 1, "selected": false, "text": "<p>My first thought, in Python:</p>\n\n<pre><code>def seq_to_ranges(seq):\n first, last = None, None\n for x in sorted(seq):\n if last != None and last + 1 != x:\n yield (first, last)\n first = x\n if first == None: first = x\n last = x\n if last != None: yield (first, last)\ndef seq_to_ranges_str(seq):\n return \", \".join(\"%d-%d\" % (first, last) if first != last else str(first) for (first, last) in seq_to_ranges(seq))\n</code></pre>\n\n<p>Possibly could be cleaner, but it's still waaay easy.</p>\n\n<p>Plain translation to Haskell:</p>\n\n<pre><code>import Data.List\nseq_to_ranges :: (Enum a, Ord a) =&gt; [a] -&gt; [(a, a)]\nseq_to_ranges = merge . foldl accum (id, Nothing) . sort where\n accum (k, Nothing) x = (k, Just (x, x))\n accum (k, Just (a, b)) x | succ b == x = (k, Just (a, x))\n | otherwise = (k . ((a, b):), Just (x, x))\n merge (k, m) = k $ maybe [] (:[]) m\nseq_to_ranges_str :: (Enum a, Ord a, Show a) =&gt; [a] -&gt; String\nseq_to_ranges_str = drop 2 . concatMap r2s . seq_to_ranges where\n r2s (a, b) | a /= b = \", \" ++ show a ++ \"-\" ++ show b\n | otherwise = \", \" ++ show a\n</code></pre>\n\n<p>About the same.</p>\n" }, { "answer_id": 249173, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 1, "selected": false, "text": "<p>Transcript of an interactive <a href=\"http://www.jsoftware.com/\" rel=\"nofollow noreferrer\">J</a> session (user input is indented 3 spaces, text in ASCII boxes is J output):</p>\n\n<pre><code> g =: 3 : '&lt;@~.\"1((y~:1+({.,}:)y)#y),.(y~:(}.y,{:y)-1)#y'@/:~\"1\n g 1 2 3 4 5\n+---+\n|1 5|\n+---+\n g 1 2 3 5 7 9 10 11 12 14\n+---+-+-+----+--+\n|1 3|5|7|9 12|14|\n+---+-+-+----+--+\n g 12 2 14 9 1 3 10 5 11 7\n+---+-+-+----+--+\n|1 3|5|7|9 12|14|\n+---+-+-+----+--+\n g2 =: 4 : '&lt;(&gt;x),'' '',&gt;y'/@:&gt;@:(4 :'&lt;(&gt;x),''-'',&gt;y'/&amp;.&gt;)@((&lt;@\":)\"0&amp;.&gt;@g)\n g2 12 2 14 9 1 3 10 5 11 7\n+---------------+\n|1-3 5 7 9-12 14|\n+---------------+\n (;g2) 5 1 20 $ (i.100) /: ? 100 $ 100\n+-----------------------------------------------------------+\n|20 39 82 33 72 93 15 30 85 24 97 60 87 44 77 29 58 69 78 43|\n| |\n|67 89 17 63 34 41 53 37 61 18 88 70 91 13 19 65 99 81 3 62|\n| |\n|31 32 6 11 23 94 16 73 76 7 0 75 98 27 66 28 50 9 22 38|\n| |\n|25 42 86 5 55 64 79 35 36 14 52 2 57 12 46 80 83 84 90 56|\n| |\n| 8 96 4 10 49 71 21 54 48 51 26 40 95 1 68 47 59 74 92 45|\n+-----------------------------------------------------------+\n|15 20 24 29-30 33 39 43-44 58 60 69 72 77-78 82 85 87 93 97|\n+-----------------------------------------------------------+\n|3 13 17-19 34 37 41 53 61-63 65 67 70 81 88-89 91 99 |\n+-----------------------------------------------------------+\n|0 6-7 9 11 16 22-23 27-28 31-32 38 50 66 73 75-76 94 98 |\n+-----------------------------------------------------------+\n|2 5 12 14 25 35-36 42 46 52 55-57 64 79-80 83-84 86 90 |\n+-----------------------------------------------------------+\n|1 4 8 10 21 26 40 45 47-49 51 54 59 68 71 74 92 95-96 |\n+-----------------------------------------------------------+\n</code></pre>\n\n<p>Readable and elegant are in the eye of the beholder :D</p>\n\n<p>That was a good exercise! It suggests the following segment of Perl:</p>\n\n<pre><code>sub g {\n my ($i, @r, @s) = 0, local @_ = sort {$a&lt;=&gt;$b} @_;\n $_ &amp;&amp; $_[$_-1]+1 == $_[$_] || push(@r, $_[$_]),\n $_&lt;$#_ &amp;&amp; $_[$_+1]-1 == $_[$_] || push(@s, $_[$_]) for 0..$#_;\n join ' ', map {$_ == $s[$i++] ? $_ : \"$_-$s[$i-1]\"} @r;\n}\n</code></pre>\n\n<h2>Addendum</h2>\n\n<p>In plain English, this algorithm finds all items where the previous item is not one less, uses them for the lower bounds; finds all items where the next item is not one greater, uses them for the upper bounds; and combines the two lists together item-by-item.</p>\n\n<p>Since J is pretty obscure, here's a short explanation of how that code works:</p>\n\n<p><code>x /: y</code> sorts the array <code>x</code> on <code>y</code>. <code>~</code> can make a dyadic verb into a reflexive monad, so <code>/:~</code> means \"sort an array on itself\".</p>\n\n<p><code>3 : '...'</code> declares a monadic verb (J's way of saying \"function taking one argument\"). <code>@</code> means function composition, so <code>g =: 3 : '...' @ /:~</code> means \"<code>g</code> is set to the function we're defining, but with its argument sorted first\". <code>\"1</code> says that we operate on arrays, not tables or anything of higher dimensionality.</p>\n\n<p>Note: <code>y</code> is always the name of the only argument to a monadic verb.</p>\n\n<p><code>{.</code> takes the first element of an array (head) and <code>}:</code> takes all but the last (curtail). <code>({.,}:)y</code> effectively duplicates the first element of <code>y</code> and lops off the last element. <code>1+({.,}:)y</code> adds 1 to it all, and <code>~:</code> compares two arrays, true wherever they are different and false wherever they are the same, so <code>y~:1+({.,}:)y</code> is an array that is true in all the indices of <code>y</code> where an element is not equal to one more than the element that preceded it. <code>(y~:1+({.,}:)y)#y</code> selects all elements of <code>y</code> where the property stated in the previous sentence is true.</p>\n\n<p>Similarly, <code>}.</code> takes all but the first element of an array (behead) and <code>{:</code> takes the last (tail), so <code>}.y,{:y</code> is all but the first element of <code>y</code>, with the last element duplicated. <code>(}.y,{:y)-1</code> subtracts 1 to it all, and again <code>~:</code> compares two arrays item-wise for non-equality while <code>#</code> picks.</p>\n\n<p><code>,.</code> zips the two arrays together, into an array of two-element arrays. <code>~.</code> nubs a list (eliminates duplicates), and is given the <code>\"1</code> rank, so it operates on the inner two-element arrays rather than the top-level array. This is <code>@</code> composed with <code>&lt;</code>, which puts each subarray into a box (otherwise J will extend each subarray again to form a 2D table).</p>\n\n<p><code>g2</code> is a mess of boxing and unboxing (otherwise J will pad strings to equal length), and is pretty uninteresting.</p>\n" }, { "answer_id": 252877, "author": "ja.", "author_id": 15467, "author_profile": "https://Stackoverflow.com/users/15467", "pm_score": 1, "selected": false, "text": "<p>Here's my Haskell entry:</p>\n\n<pre><code>runs lst = map showRun $ runs' lst\n\nruns' l = reverse $ map reverse $ foldl newOrGlue [[]] l \n\nshowRun [s] = show s\nshowRun lst = show (head lst) ++ \"-\" ++ (show $ last lst)\n\nnewOrGlue [[]] e = [[e]]\nnewOrGlue (curr:other) e | e == (1 + (head curr)) = ((e:curr):other)\nnewOrGlue (curr:other) e | otherwise = [e]:(curr:other)\n</code></pre>\n\n<p>and a sample run:</p>\n\n<pre><code>T&gt; runs [1,2,3,5,7,9,10,11,12,14]\n\n[\"1-3\",\"5\",\"7\",\"9-12\",\"14\"]\n</code></pre>\n" }, { "answer_id": 1917673, "author": "Geert Baeyaert", "author_id": 233617, "author_profile": "https://Stackoverflow.com/users/233617", "pm_score": 2, "selected": false, "text": "<p>I'm a bit late to the party, but anyway, here is my version using Linq:</p>\n\n<pre><code>public static string[] FormatInts(IEnumerable&lt;int&gt; ints)\n{\n var intGroups = ints\n .OrderBy(i =&gt; i)\n .Aggregate(new List&lt;List&lt;int&gt;&gt;(), (acc, i) =&gt;\n {\n if (acc.Count &gt; 0 &amp;&amp; acc.Last().Last() == i - 1) acc.Last().Add(i);\n else acc.Add(new List&lt;int&gt; { i });\n\n return acc;\n });\n\n return intGroups\n .Select(g =&gt; g.First().ToString() + (g.Count == 1 ? \"\" : \"-\" + g.Last().ToString()))\n .ToArray();\n}\n</code></pre>\n" }, { "answer_id": 3569459, "author": "emaxt6", "author_id": 431114, "author_profile": "https://Stackoverflow.com/users/431114", "pm_score": 1, "selected": false, "text": "<p>Erlang , perform also sort and unique on input and can generate programmatically reusable pair and also a string representation.</p>\n\n<pre><code>group(List) -&gt;\n [First|_] = USList = lists:usort(List),\n getnext(USList, First, 0).\ngetnext([Head|Tail] = List, First, N) when First+N == Head -&gt;\n getnext(Tail, First, N+1);\ngetnext([Head|Tail] = List, First, N) -&gt;\n [ {First, First+N-1} | getnext(List, Head, 0) ];\ngetnext([], First, N) -&gt; [{First, First+N-1}].\n%%%%%% pretty printer\ngroup_to_string({X,X}) -&gt; integer_to_list(X);\ngroup_to_string({X,Y}) -&gt; integer_to_list(X) ++ \"-\" ++ integer_to_list(Y);\ngroup_to_string(List) -&gt; [group_to_string(X) || X &lt;- group(List)].\n</code></pre>\n\n<p>Test getting programmatically reusable pairs:</p>\n\n<p>shell> testing:group([34,3415,56,58,57,11,12,13,1,2,3,3,4,5]).</p>\n\n<p>result> [{1,5},{11,13},{34,34},{56,58},{3415,3415}]</p>\n\n<p>Test getting \"pretty\" string:</p>\n\n<p>shell> testing:group_to_string([34,3415,56,58,57,11,12,13,1,2,3,3,4,5]).</p>\n\n<p>result> [\"1-5\",\"11-13\",\"34\",\"56-58\",\"3415\"]</p>\n\n<p>hope it helps\nbye</p>\n" }, { "answer_id": 27769172, "author": "Christopher Thomas Nicodemus", "author_id": 1620223, "author_profile": "https://Stackoverflow.com/users/1620223", "pm_score": 1, "selected": false, "text": "<p>VBA</p>\n\n<pre><code>Public Function convertListToRange(lst As String) As String\n Dim splLst() As String\n splLst = Split(lst, \",\")\n Dim x As Long\n For x = 0 To UBound(splLst)\n Dim groupStart As Integer\n groupStart = splLst(x)\n Dim groupEnd As Integer\n groupEnd = groupStart\n Do While (x &lt;= UBound(splLst) - 1)\n If splLst(x) - splLst(x + 1) &lt;&gt; -1 Then Exit Do\n groupEnd = splLst(x + 1)\n x = x + 1\n Loop\n convertListToRange = convertListToRange &amp; IIf(groupStart = groupEnd, groupStart &amp; \",\", groupStart &amp; \"-\" &amp; groupEnd &amp; \",\")\n Next x\n convertListToRange = Left(convertListToRange, Len(convertListToRange) - 1)\nEnd Function\n</code></pre>\n\n<p>convertListToRange(\"1,2,3,7,8,9,11,12,99,100,101\")<br />\nReturn: \"1-3,7-9,11-12,99-101\"</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15409/" ]
By which I mean this: Given the input set of numbers: 1,2,3,4,5 becomes "1-5". 1,2,3,5,7,9,10,11,12,14 becomes "1-3, 5, 7, 9-12, 14" This is the best I managed to come up with: [C#] *Which feels a little sloppy to me, so the question is, is there somehow more readable and/or elegant solution to this?* ``` public static string[] FormatInts(int[] ints) { if (ints == null) throw new ArgumentNullException("ints"); // hey what are you doing? if (ints.Length == 0) return new string[] { "" }; // nothing to process if (ints.Length == 1) return new string[] { ints[0].ToString() }; // nothing to process Array.Sort<int>(ints); // need to sort these lil' babies List<string> values = new List<string>(); int lastNumber = ints[0]; // start with the first number int firstNumber = ints[0]; // same as above for (int i = 1; i < ints.Length; i++) { int current = ints[i]; int difference = (lastNumber - current ); // compute difference between last number and current number if (difference == -1) // the numbers are adjacent { if (firstNumber == 0) // this is the first of the adjacent numbers { firstNumber = lastNumber; } else // we're somehow in the middle or at the end of the adjacent number set { lastNumber = current; continue; } } else { if (firstNumber > 0 && firstNumber != lastNumber) // get ready to print a set of numbers { values.Add(string.Format("{0}-{1}", firstNumber, lastNumber)); firstNumber = 0; // reset } else // print a single value { values.Add(string.Format("{0}", lastNumber)); } } lastNumber = current; } if (firstNumber > 0) // if theres anything left, print it out { values.Add(string.Format("{0}-{1}", firstNumber, lastNumber)); } return values.ToArray(); } ```
I've rewritten your code like this: ``` public static string[] FormatInts(int[] ints) { Array.Sort<int>(ints); List<string> values = new List<string>(); for (int i = 0; i < ints.Length; i++) { int groupStart = ints[i]; int groupEnd = groupStart; while (i < ints.Length - 1 && ints[i] - ints[i + 1] == -1) { groupEnd = ints[i + 1]; i++; } values.Add(string.Format(groupEnd == groupStart ? "{0}":"{0} - {1}", groupStart, groupEnd)); } return values.ToArray(); } ``` And then: ``` ///////////////// int[] myInts = { 1,2,3,5,7,9,10,11,12,14 }; string[] result = FormatInts(myInts); // now result haves "1-3", "5", "7", "9-12", "14" ```
245,740
<p>For example, when I'm dividing two ints and want a float returned, I superstitiously write something like this:</p> <pre><code>int a = 2, b = 3; float c = (float)a / (float)b; </code></pre> <p>If I do not cast <code>a</code> and <code>b</code> to floats, it'll do integer division and return an int.</p> <p>Similarly, if I want to multiply a signed 8-bit number with an unsigned 8-bit number, I will cast them to signed 16-bit numbers before multiplying for fear of overflow:</p> <pre><code>u8 a = 255; s8 b = -127; s16 = (s16)a * (s16)b; </code></pre> <p>How exactly does the compiler behave in these situations when not casting at all or when only casting one of the variables? Do I really need to explicitly cast all of the variables, or just the one on the left, or the one on the right?</p>
[ { "answer_id": 245746, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 2, "selected": false, "text": "<p>Division of integers: cast any one of the operands, no need to cast them both. If both operands are integers the division operation is an integer division, otherwise it is a floating-point division.</p>\n\n<p>As for the overflow question, there is no need to explicitly cast, as the compiler implicitly does that for you:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;limits&gt;\n\nusing namespace std;\nint main()\n{\n signed int a = numeric_limits&lt;signed int&gt;::max();\n unsigned int b = a + 1; // implicit cast, no overflow here\n cout &lt;&lt; a &lt;&lt; ' ' &lt;&lt; b &lt;&lt; endl;\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 245750, "author": "Matthew Crumley", "author_id": 2214, "author_profile": "https://Stackoverflow.com/users/2214", "pm_score": 3, "selected": false, "text": "<p>You can just cast one of them. It doesn't matter which one though.</p>\n\n<p>Whenever the types don't match, the \"smaller\" type is automatically promoted to the \"larger\" type, with floating point being \"larger\" than integer types.</p>\n" }, { "answer_id": 245752, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 1, "selected": false, "text": "<p>In the case of the floating-point division, as long as one variable is of a floating-point datatype (float or double), then the other variable should be widened to a floating-point type, and floating-point division should occur; so there's no need to cast both to a float.</p>\n\n<p>Having said that, I always cast both to a float, anyway.</p>\n" }, { "answer_id": 245753, "author": "user21785", "author_id": 21785, "author_profile": "https://Stackoverflow.com/users/21785", "pm_score": 1, "selected": false, "text": "<p>I think as long as you are casting just one of the two variables the compiler will behave properly (At least on the compilers that I know).</p>\n\n<p>So all of:</p>\n\n<p>float c = (float)a / b;</p>\n\n<p>float c = a / (float)b;</p>\n\n<p>float c = (float)a / (float)b;</p>\n\n<p>will have the same result.</p>\n" }, { "answer_id": 245793, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 4, "selected": false, "text": "<p>In general, if operands are of different types, the compiler will promote all to the largest or most precise type:</p>\n\n<pre>\nIf one number is... And the other is... The compiler will promote to...\n------------------- ------------------- -------------------------------\nchar int int\nsigned unsigned unsigned\nchar or int float float\nfloat double double\n</pre>\n\n<p>Examples:</p>\n\n<pre>\nchar + int ==> int\nsigned int + unsigned char ==> unsigned int\nfloat + int ==> float\n</pre>\n\n<p>Beware, though, that promotion occurs only as required for each intermediate calculation, so:</p>\n\n<pre>4.0 + 5/3 = 4.0 + 1 = 5.0</pre>\n\n<p>This is because the integer division is performed first, then the result is promoted to float for the addition.</p>\n" }, { "answer_id": 245908, "author": "DarenW", "author_id": 10468, "author_profile": "https://Stackoverflow.com/users/10468", "pm_score": 1, "selected": false, "text": "<p>Then there are older brain-damaged types like me who, having to use old-fashioned languages, just unthinkingly write stuff like</p>\n\n<pre><code>int a;\nint b;\nfloat z;\n\nz = a*1.0*b;\n</code></pre>\n\n<p>Of course this isn't universal, good only for pretty much just this case.</p>\n" }, { "answer_id": 245911, "author": "DarenW", "author_id": 10468, "author_profile": "https://Stackoverflow.com/users/10468", "pm_score": 1, "selected": false, "text": "<p>Having worked on safety-critical systems, i tend to be paranoid and always cast both factors: float(a)/float(b) - just in case some subtle gotcha is planning to bite me later. No matter how good the compiler is said to be, no matter how well-defined the details are in the official language specs. Paranoia: a programmer's best friend!</p>\n" }, { "answer_id": 245986, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 5, "selected": false, "text": "<h3>Question 1: Float division</h3>\n\n<pre><code>int a = 2, b = 3;\nfloat c = static_cast&lt;float&gt;(a) / b; // need to convert 1 operand to a float\n</code></pre>\n\n<h3>Question 2: How the compiler works</h3>\n\n<p>Five rules of thumb to remember:</p>\n\n<ul>\n<li>Arithmetic operations are always performed on values of the same type.</li>\n<li>The result type is the same as the operands (after promotion)</li>\n<li>The smallest type arithmetic operations are performed on is int.</li>\n<li>ANSCI C (and thus C++) use value preserving integer promotion.</li>\n<li><b>Each operation is done in isolation</b>.</li>\n</ul>\n\n<p>The ANSI C rules are as follows:<br>\nMost of these rules also apply to C++ though not all types are officially supported (yet).</p>\n\n<ul>\n<li>If either operand is a <b>long double</b> the other is converted to a <b>long double</b>.</li>\n<li>If either operand is a <b>double</b> the other is converted to a <b>double</b>.</li>\n<li>If either operand is a <b>float</b> the other is converted to a <b>float</b>.</li>\n<li>If either operand is a <b>unsigned long long</b> the other is converted to <b>unsigned long long</b>.</li>\n<li>If either operand is a <b>long long</b> the other is converted to <b>long long</b>.</li>\n<li>If either operand is a <b>unsigned long</b> the other is converted to <b>unsigned long</b>.</li>\n<li>If either operand is a <b>long</b> the other is converted to <b>long</b>.</li>\n<li>If either operand is a <b>unsigned int</b> the other is converted to <b>unsigned int</b>.</li>\n<li><b>Otherwise both</b> operands are converted to <b>int</b>.</li>\n</ul>\n\n<h3>Overflow</h3>\n\n<p>Overflow is always a problem. Note. The type of the result is the same as the input operands so all the operations can overflow, so yes you do need to worry about it (though the language does not provide any explicit way to catch this happening.</p>\n\n<p>As a side note:<br>\nUnsigned division can not overflow but signed division can.<br></p>\n\n<pre><code>std::numeric_limits&lt;int&gt;::max() / -1 // No Overflow\nstd::numeric_limits&lt;int&gt;::min() / -1 // Will Overflow\n</code></pre>\n" }, { "answer_id": 246476, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "<p>Do you need to cast one or two sides? The answer isn't dictated by the compiler. It has to know the exact, precse rules. Instead, the answer should be dictated by the person who will read the code later. For that reason alone, cast both sides to the same type. Implicit truncation might be visible enough, so that cast could be redundant.</p>\n\n<p>e.g. this cast float->int is obvious.</p>\n\n<pre><code>int a = float(foo()) * float(c); \n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813/" ]
For example, when I'm dividing two ints and want a float returned, I superstitiously write something like this: ``` int a = 2, b = 3; float c = (float)a / (float)b; ``` If I do not cast `a` and `b` to floats, it'll do integer division and return an int. Similarly, if I want to multiply a signed 8-bit number with an unsigned 8-bit number, I will cast them to signed 16-bit numbers before multiplying for fear of overflow: ``` u8 a = 255; s8 b = -127; s16 = (s16)a * (s16)b; ``` How exactly does the compiler behave in these situations when not casting at all or when only casting one of the variables? Do I really need to explicitly cast all of the variables, or just the one on the left, or the one on the right?
### Question 1: Float division ``` int a = 2, b = 3; float c = static_cast<float>(a) / b; // need to convert 1 operand to a float ``` ### Question 2: How the compiler works Five rules of thumb to remember: * Arithmetic operations are always performed on values of the same type. * The result type is the same as the operands (after promotion) * The smallest type arithmetic operations are performed on is int. * ANSCI C (and thus C++) use value preserving integer promotion. * **Each operation is done in isolation**. The ANSI C rules are as follows: Most of these rules also apply to C++ though not all types are officially supported (yet). * If either operand is a **long double** the other is converted to a **long double**. * If either operand is a **double** the other is converted to a **double**. * If either operand is a **float** the other is converted to a **float**. * If either operand is a **unsigned long long** the other is converted to **unsigned long long**. * If either operand is a **long long** the other is converted to **long long**. * If either operand is a **unsigned long** the other is converted to **unsigned long**. * If either operand is a **long** the other is converted to **long**. * If either operand is a **unsigned int** the other is converted to **unsigned int**. * **Otherwise both** operands are converted to **int**. ### Overflow Overflow is always a problem. Note. The type of the result is the same as the input operands so all the operations can overflow, so yes you do need to worry about it (though the language does not provide any explicit way to catch this happening. As a side note: Unsigned division can not overflow but signed division can. ``` std::numeric_limits<int>::max() / -1 // No Overflow std::numeric_limits<int>::min() / -1 // Will Overflow ```
245,742
<p>In this thread, we look at examples of good uses of <code>goto</code> in C or C++. It's inspired by <a href="https://stackoverflow.com/questions/244445/best-refactoring-for-the-dreaded-while-true-loop#244644">an answer</a> which people voted up because they thought I was joking.</p> <p>Summary (label changed from original to make intent even clearer):</p> <pre><code>infinite_loop: // code goes here goto infinite_loop; </code></pre> <p>Why it's better than the alternatives:</p> <ul> <li>It's specific. <code>goto</code> is the language construct which causes an unconditional branch. Alternatives depend on using structures supporting conditional branches, with a degenerate always-true condition.</li> <li>The label documents the intent without extra comments.</li> <li>The reader doesn't have to scan the intervening code for early <code>break</code>s (although it's still possible for an unprincipled hacker to simulate <code>continue</code> with an early <code>goto</code>).</li> </ul> <p><strong>Rules:</strong></p> <ul> <li>Pretend that the gotophobes didn't win. It's understood that the above can't be used in real code because it goes against established idiom.</li> <li>Assume that we have all heard of 'Goto considered harmful' and know that goto can be used to write spaghetti code.</li> <li>If you disagree with an example, criticize it on technical merit alone ('Because people don't like goto' is not a technical reason).</li> </ul> <p>Let's see if we can talk about this like grown ups.</p> <p><strong>Edit</strong></p> <p>This question seems finished now. It generated some high quality answers. Thanks to everyone, especially those who took my little loop example seriously. Most skeptics were concerned by the lack of block scope. As @quinmars pointed out in a comment, you can always put braces around the loop body. I note in passing that <code>for(;;)</code> and <code>while(true)</code> don't give you the braces for free either (and omitting them can cause vexing bugs). Anyway, I won't waste any more of your brain power on this trifle - I can live with the harmless and idiomatic <code>for(;;)</code> and <code>while(true)</code> (just as well if I want to keep my job). </p> <p>Considering the other responses, I see that many people view <code>goto</code> as something you always have to rewrite in another way. Of course you can avoid a <code>goto</code> by introducing a loop, an extra flag, a stack of nested <code>if</code>s, or whatever, but why not consider whether <code>goto</code> is perhaps the best tool for the job? Put another way, how much ugliness are people prepared to endure to avoid using a built-in language feature for its intended purpose? My take is that even adding a flag is too high a price to pay. I like my variables to represent things in the problem or solution domains. 'Solely to avoid a <code>goto</code>' doesn't cut it.</p> <p>I'll accept the first answer which gave the C pattern for branching to a cleanup block. IMO, this makes the strongest case for a <code>goto</code> of all the posted answers, certainly if you measure it by the contortions a hater has to go through to avoid it.</p>
[ { "answer_id": 245745, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "<p>Here is an example of a good goto:</p>\n\n<pre><code>// No Code\n</code></pre>\n" }, { "answer_id": 245749, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 4, "selected": false, "text": "<p>I have nothing against gotos in general, but I can think of several reasons why you wouldn't want to use them for a loop like you mentioned:</p>\n\n<ul>\n<li>It does not limit scope hence any temp variables you use inside won't be freed until later.</li>\n<li>It does not limit scope hence it could lead to bugs.</li>\n<li>It does not limit scope hence you cannot re-use the same variable names later in future code in the same scope. </li>\n<li>It does not limit scope hence you have the chance of skipping over a variable declaration.</li>\n<li>People are not accustomed to it and it will make your code harder to read.</li>\n<li>Nested loops of this type can lead to spaghetti code, normals loops will not lead to spaghetti code.</li>\n</ul>\n" }, { "answer_id": 245759, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 5, "selected": false, "text": "<p>Here's my non-silly example, (from Stevens APITUE) for Unix system calls which may be interrupted by a signal.</p>\n\n<pre><code>restart:\n if (system_call() == -1) {\n if (errno == EINTR) goto restart;\n\n // handle real errors\n }\n</code></pre>\n\n<p>The alternative is a degenerate loop. This version reads like English \"if the system call was interrupted by a signal, restart it\".</p>\n" }, { "answer_id": 245760, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 4, "selected": false, "text": "<p>If Duff's device doesn't need a goto, then neither should you! ;)</p>\n\n<pre><code>void dsend(int count) {\n int n;\n if (!count) return;\n n = (count + 7) / 8;\n switch (count % 8) {\n case 0: do { puts(\"case 0\");\n case 7: puts(\"case 7\");\n case 6: puts(\"case 6\");\n case 5: puts(\"case 5\");\n case 4: puts(\"case 4\");\n case 3: puts(\"case 3\");\n case 2: puts(\"case 2\");\n case 1: puts(\"case 1\");\n } while (--n &gt; 0);\n }\n}\n</code></pre>\n\n<p>code above from Wikipedia <a href=\"http://en.wikipedia.org/wiki/Duffs_device\" rel=\"noreferrer\">entry</a>.</p>\n" }, { "answer_id": 245761, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 7, "selected": true, "text": "<p>Heres one trick I've heard of people using. I've never seen it in the wild though. And it only applies to C because C++ has RAII to do this more idiomatically. </p>\n\n<pre><code>void foo()\n{\n if (!doA())\n goto exit;\n if (!doB())\n goto cleanupA;\n if (!doC())\n goto cleanupB;\n\n /* everything has succeeded */\n return;\n\ncleanupB:\n undoB();\ncleanupA:\n undoA();\nexit:\n return;\n}\n</code></pre>\n" }, { "answer_id": 245763, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 3, "selected": false, "text": "<p>One good place to use a goto is in a procedure that can abort at several points, each of which requires various levels of cleanup. Gotophobes can always replace the gotos with structured code and a series of tests, but I think this is more straightforward because it eliminates excessive indentation:</p>\n\n<pre>\nif (!openDataFile())\n goto quit;\n\nif (!getDataFromFile())\n goto closeFileAndQuit;\n\nif (!allocateSomeResources)\n goto freeResourcesAndQuit;\n\n// Do more work here....\n\nfreeResourcesAndQuit:\n // free resources\ncloseFileAndQuit:\n // close file\nquit:\n // quit!\n</pre>\n" }, { "answer_id": 245771, "author": "Jim Nelson", "author_id": 32168, "author_profile": "https://Stackoverflow.com/users/32168", "pm_score": 0, "selected": false, "text": "<p>My gripe about this is that you lose block scoping; any local variables declared between the gotos remains in force if the loop is ever broken out of. (Maybe you're assuming the loop runs forever; I don't think that's what the original question writer was asking, though.)</p>\n\n<p>The problem of scoping is more of an issue with C++, as some objects may be depending on their dtor being called at appropriate times.</p>\n\n<p>For me, the best reason to use goto is during a multi-step initialization process where the it's vital that all inits are backed out of if one fails, a la:</p>\n\n<pre><code>if(!foo_init())\n goto bye;\n\nif(!bar_init())\n goto foo_bye;\n\nif(!xyzzy_init())\n goto bar_bye;\n\nreturn TRUE;\n\nbar_bye:\n bar_terminate();\n\nfoo_bye:\n foo_terminate();\n\nbye:\n return FALSE;\n</code></pre>\n" }, { "answer_id": 245775, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": "<p>@Greg:</p>\n\n<p>Why not do your example like this:</p>\n\n<pre><code>void foo()\n{\n if (doA())\n { \n if (doB())\n {\n if (!doC())\n {\n UndoA();\n UndoB();\n }\n }\n else\n {\n UndoA();\n }\n }\n return;\n}\n</code></pre>\n" }, { "answer_id": 245780, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 3, "selected": false, "text": "<p>@fizzer.myopenid.com: your posted code snippet is equivalent to the following:</p>\n\n<pre><code> while (system_call() == -1)\n {\n if (errno != EINTR)\n {\n // handle real errors\n\n break;\n }\n }\n</code></pre>\n\n<p>I definitely prefer this form.</p>\n" }, { "answer_id": 245781, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "<p>Very common.</p>\n\n<pre><code>do_stuff(thingy) {\n lock(thingy);\n\n foo;\n if (foo failed) {\n status = -EFOO;\n goto OUT;\n }\n\n bar;\n if (bar failed) {\n status = -EBAR;\n goto OUT;\n }\n\n do_stuff_to(thingy);\n\nOUT:\n unlock(thingy);\n return status;\n}\n</code></pre>\n\n<p>The only case I ever use <code>goto</code> is for jumping forwards, usually out of blocks, and never into blocks. This avoids abuse of <code>do{}while(0)</code> and other constructs which increase nesting, while still maintaining readable, structured code.</p>\n" }, { "answer_id": 245801, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 6, "selected": false, "text": "<p>The classic need for GOTO in C is as follows</p>\n\n<pre><code>for ...\n for ...\n if(breakout_condition) \n goto final;\n\nfinal:\n</code></pre>\n\n<p>There is no straightforward way to break out of nested loops without a goto.</p>\n" }, { "answer_id": 245848, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 3, "selected": false, "text": "<p>Even though I've grown to hate this pattern over time, it's in-grained into COM programming. </p>\n\n<pre><code>#define IfFailGo(x) {hr = (x); if (FAILED(hr)) goto Error}\n...\nHRESULT SomeMethod(IFoo* pFoo) {\n HRESULT hr = S_OK;\n IfFailGo( pFoo-&gt;PerformAction() );\n IfFailGo( pFoo-&gt;SomeOtherAction() );\nError:\n return hr;\n}\n</code></pre>\n" }, { "answer_id": 245922, "author": "user25306", "author_id": 25306, "author_profile": "https://Stackoverflow.com/users/25306", "pm_score": 0, "selected": false, "text": "<p>I don't use goto's myself, however I did work with a person once that would use them in specific cases. If I remember correctly, his rationale was around performance issues - he also had specific rules for <em>how</em>. Always in the same function, and the label was always BELOW the goto statement.</p>\n" }, { "answer_id": 246027, "author": "zvrba", "author_id": 2583, "author_profile": "https://Stackoverflow.com/users/2583", "pm_score": 4, "selected": false, "text": "<p>Knuth has written a paper \"Structured programming with GOTO statements\", you can get it e.g. from <a href=\"http://pplab.snu.ac.kr/courses/adv_pl05/papers/p261-knuth.pdf\" rel=\"noreferrer\">here</a>. You'll find many examples there.</p>\n" }, { "answer_id": 246431, "author": "Charles Beattie", "author_id": 97554, "author_profile": "https://Stackoverflow.com/users/97554", "pm_score": 1, "selected": false, "text": "<p>I've seen goto used correctly but the situations are normaly ugly. It is only when the use of <code>goto</code> itself is so much less worse than the original.\n@Johnathon Holland the poblem is you're version is less clear. people seem to be scared of local variables:</p>\n\n<pre><code>void foo()\n{\n bool doAsuccess = doA();\n bool doBsuccess = doAsuccess &amp;&amp; doB();\n bool doCsuccess = doBsuccess &amp;&amp; doC();\n\n if (!doCsuccess)\n {\n if (doBsuccess)\n undoB();\n if (doAsuccess)\n undoA();\n }\n}\n</code></pre>\n\n<p>And I prefer loops like this but some people prefer <code>while(true)</code>.</p>\n\n<pre><code>for (;;)\n{\n //code goes here\n}\n</code></pre>\n" }, { "answer_id": 21032091, "author": "StrifeSephiroth", "author_id": 3015167, "author_profile": "https://Stackoverflow.com/users/3015167", "pm_score": 0, "selected": false, "text": "<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nint main()\n{\n char name[64];\n char url[80]; /*The final url name with http://www..com*/\n char *pName;\n int x;\n\n pName = name;\n\n INPUT:\n printf(\"\\nWrite the name of a web page (Without www, http, .com) \");\n gets(name);\n\n for(x=0;x&lt;=(strlen(name));x++)\n if(*(pName+0) == '\\0' || *(pName+x) == ' ')\n {\n printf(\"Name blank or with spaces!\");\n getch();\n system(\"cls\");\n goto INPUT;\n }\n\n strcpy(url,\"http://www.\");\n strcat(url,name);\n strcat(url,\".com\");\n\n printf(\"%s\",url);\n return(0);\n}\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18167/" ]
In this thread, we look at examples of good uses of `goto` in C or C++. It's inspired by [an answer](https://stackoverflow.com/questions/244445/best-refactoring-for-the-dreaded-while-true-loop#244644) which people voted up because they thought I was joking. Summary (label changed from original to make intent even clearer): ``` infinite_loop: // code goes here goto infinite_loop; ``` Why it's better than the alternatives: * It's specific. `goto` is the language construct which causes an unconditional branch. Alternatives depend on using structures supporting conditional branches, with a degenerate always-true condition. * The label documents the intent without extra comments. * The reader doesn't have to scan the intervening code for early `break`s (although it's still possible for an unprincipled hacker to simulate `continue` with an early `goto`). **Rules:** * Pretend that the gotophobes didn't win. It's understood that the above can't be used in real code because it goes against established idiom. * Assume that we have all heard of 'Goto considered harmful' and know that goto can be used to write spaghetti code. * If you disagree with an example, criticize it on technical merit alone ('Because people don't like goto' is not a technical reason). Let's see if we can talk about this like grown ups. **Edit** This question seems finished now. It generated some high quality answers. Thanks to everyone, especially those who took my little loop example seriously. Most skeptics were concerned by the lack of block scope. As @quinmars pointed out in a comment, you can always put braces around the loop body. I note in passing that `for(;;)` and `while(true)` don't give you the braces for free either (and omitting them can cause vexing bugs). Anyway, I won't waste any more of your brain power on this trifle - I can live with the harmless and idiomatic `for(;;)` and `while(true)` (just as well if I want to keep my job). Considering the other responses, I see that many people view `goto` as something you always have to rewrite in another way. Of course you can avoid a `goto` by introducing a loop, an extra flag, a stack of nested `if`s, or whatever, but why not consider whether `goto` is perhaps the best tool for the job? Put another way, how much ugliness are people prepared to endure to avoid using a built-in language feature for its intended purpose? My take is that even adding a flag is too high a price to pay. I like my variables to represent things in the problem or solution domains. 'Solely to avoid a `goto`' doesn't cut it. I'll accept the first answer which gave the C pattern for branching to a cleanup block. IMO, this makes the strongest case for a `goto` of all the posted answers, certainly if you measure it by the contortions a hater has to go through to avoid it.
Heres one trick I've heard of people using. I've never seen it in the wild though. And it only applies to C because C++ has RAII to do this more idiomatically. ``` void foo() { if (!doA()) goto exit; if (!doB()) goto cleanupA; if (!doC()) goto cleanupB; /* everything has succeeded */ return; cleanupB: undoB(); cleanupA: undoA(); exit: return; } ```
245,747
<p>In SQL Server given a Table/View how can you generate a definition of the Table/View in the form:</p> <blockquote> <p>C1 int,<br> C2 varchar(20),<br> C3 double</p> </blockquote> <p>The information required to do it is contained in the meta-tables of SQL Server but is there a standard script / IDE faciltity to output the data contained there in the form described above ?. </p> <p>For the curious I want this as I have to maintain a number of SP's which contain Table objects (that is a form of temporary table used by SQL Server). The Table objects need to match the definition of Tables or Views already in the database - it would make life a lot easier if these definitions could be generated automatically.</p>
[ { "answer_id": 245935, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 0, "selected": false, "text": "<p>If you want to duplpicate a table definition you could use:</p>\n\n<pre><code>select top 0\n *\ninto\n newtable\nfrom\n mytable\n</code></pre>\n\n<p>Edit: Sorry, just re-read your question, and realised this might not answer it. Could you be clear on what you are after, do you want an exact duplicate of the table definition, or a table that contains information about the tables definition?</p>\n" }, { "answer_id": 246435, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 1, "selected": false, "text": "<p>Here is an example of listing the names and types of columns in a table:</p>\n\n<pre><code>select \n COLUMN_NAME, \n COLUMN_DEFAULT, \n IS_NULLABLE, \n DATA_TYPE, \n CHARACTER_MAXIMUM_LENGTH, \n NUMERIC_PRECISION, \n NUMERIC_SCALE\nfrom \n INFORMATION_SCHEMA.COLUMNS\nwhere \n TABLE_NAME = 'YOUR_TABLE_NAME_HERE' \norder by \n Ordinal_Position\n</code></pre>\n\n<p>Generating DDL from that information is more difficult. There seems to be some suggestions at <a href=\"http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=53007\" rel=\"nofollow noreferrer\">SQLTeam</a></p>\n" }, { "answer_id": 248665, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Thanks for your replies. Yes I do want an exact duplicate of the DDL but I've realised I misstated exactly what I needed. It's DDL which will create a temporary table which will match the columns of a view.</p>\n\n<p>I realised this in looking at Duckworths suggestion - which is good but unfortunately doesn't cover the case of a view.</p>\n\n<blockquote>\n <p>SELECT VIEWDEFINITION FROM\n INFORMATIONSCHEMA.VIEWS</p>\n</blockquote>\n\n<p>... will give you a list of columns in a view and (assuming that all columns in the view are derived directly from a table) it should then be possible to use an amended version of Duckworths suggestion to pull together the relevant DLL.</p>\n\n<p>I'm just amazed it's not easier ! I was expecting someone to tell me that there was a well established routine to do this given the TABLE objects need to have all columns full defined (rather than the way Oracle does it which is to say - \"give me something which looks like table X\".</p>\n\n<p>Anyway thanks again for help and any further suggestions welcomed.</p>\n" }, { "answer_id": 248711, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 0, "selected": false, "text": "<p>In <a href=\"https://stackoverflow.com/questions/181909/tool-for-scripting-table-data#181942\">this posting</a> to another question I've got a DB reverse engineering script that will do tables, views, PK, UK and index definitions and foreign keys. This one is for SQL Server 2005 and is a port of one I originally wrote for SQL Server 2000. If you need a SQL Server 2000 version add a comment to this post and I'll post it up here.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In SQL Server given a Table/View how can you generate a definition of the Table/View in the form: > > C1 int, > > C2 varchar(20), > > C3 double > > > The information required to do it is contained in the meta-tables of SQL Server but is there a standard script / IDE faciltity to output the data contained there in the form described above ?. For the curious I want this as I have to maintain a number of SP's which contain Table objects (that is a form of temporary table used by SQL Server). The Table objects need to match the definition of Tables or Views already in the database - it would make life a lot easier if these definitions could be generated automatically.
Here is an example of listing the names and types of columns in a table: ``` select COLUMN_NAME, COLUMN_DEFAULT, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'YOUR_TABLE_NAME_HERE' order by Ordinal_Position ``` Generating DDL from that information is more difficult. There seems to be some suggestions at [SQLTeam](http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=53007)
245,765
<p>For example, using the answer for this question: </p> <p><a href="https://stackoverflow.com/questions/152024/how-to-select-all-users-who-made-more-than-10-submissions">How to select all users who made more than 10 submissions</a> "How to select all users who made more than 10 submissions."</p> <pre><code>select userId from submission group by userId having count(submissionGuid) &gt; 10 </code></pre> <p>Let's say now I want to know many rows this sql statement outputted. How scalable is the solution for counting the rows of counting the rows?</p>
[ { "answer_id": 245769, "author": "Dave Neeley", "author_id": 9660, "author_profile": "https://Stackoverflow.com/users/9660", "pm_score": 2, "selected": false, "text": "<p>In SQL Server you could do</p>\n\n<pre><code>select @@ROWCOUNT \n</code></pre>\n\n<p>immediately following the query you posted.</p>\n" }, { "answer_id": 245776, "author": "BQ.", "author_id": 4632, "author_profile": "https://Stackoverflow.com/users/4632", "pm_score": 3, "selected": false, "text": "<p>Nested queries:</p>\n\n<pre><code>select count(*) from\n (select userId\n from submission \n group by userId\n having count(submissionGuid) &gt; 10) n\n</code></pre>\n\n<p>Edited to incorporate mbrierst's comment about needing an alias (the \"n\" at the end) for the nested subquery. Oracle does not require this, but SQL Server does. Feel free to add a comment regarding usage on other database platforms.</p>\n" }, { "answer_id": 245786, "author": "user12861", "author_id": 12861, "author_profile": "https://Stackoverflow.com/users/12861", "pm_score": 4, "selected": false, "text": "<p>Slight error in previously posted example, need an alias for a table name for the subquery:<p></p>\n\n<pre><code>\nselect count(*) from\n (select userId\n from submission \n group by userId\n having count(submissionGuid) > 10) t\n</code></pre>\n\n<p>I'm not sure about scalability, but this is the solution. If this isn't scaling well enough for you, you need to consider major design changes, like perhaps tracking those who submitted more than 10 submissions in a separate table that you update through applications that populate the submissions. Or many other possible solutions.</p>\n" }, { "answer_id": 61674782, "author": "Apple Yellow", "author_id": 10770048, "author_profile": "https://Stackoverflow.com/users/10770048", "pm_score": 0, "selected": false, "text": "<p>You can try way this:\nI hope to help you.</p>\n<pre><code>select top(1) row_number() over(partition by count(userId) order by count(userId)) as RowNumber\nfrom submission\ngroup by userId\nhaving count(submissionGuid) &gt; 10\norder by userId desc \n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
For example, using the answer for this question: [How to select all users who made more than 10 submissions](https://stackoverflow.com/questions/152024/how-to-select-all-users-who-made-more-than-10-submissions) "How to select all users who made more than 10 submissions." ``` select userId from submission group by userId having count(submissionGuid) > 10 ``` Let's say now I want to know many rows this sql statement outputted. How scalable is the solution for counting the rows of counting the rows?
Slight error in previously posted example, need an alias for a table name for the subquery: ``` select count(*) from (select userId from submission group by userId having count(submissionGuid) > 10) t ``` I'm not sure about scalability, but this is the solution. If this isn't scaling well enough for you, you need to consider major design changes, like perhaps tracking those who submitted more than 10 submissions in a separate table that you update through applications that populate the submissions. Or many other possible solutions.
245,766
<p>In a fictitious web application ...</p> <ol> <li>The user clicks a link </li> <li>The server starts to prepare the response, but it takes several seconds</li> <li>The user cancels the page load</li> </ol> <p>What happens to the request? Does the server continue to prepare the response? Does the response arrive to the browser?</p>
[ { "answer_id": 245782, "author": "dreamlax", "author_id": 10320, "author_profile": "https://Stackoverflow.com/users/10320", "pm_score": 0, "selected": false, "text": "<p>I would think that the actual TCP connection is closed by the browser and therefore the web-server will be unable to send data, and unless it is specifically programmed to detect broken connections whilst preparing the data, then the page will be fully processed even if the user cancels.</p>\n\n<p>I have little knowledge on these things though, but that would be my guess.</p>\n" }, { "answer_id": 245795, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 4, "selected": true, "text": "<p>The server will continue to prepare the response. When it tries to send the response to the client, it'll fail. When this actually happens will probably depend on the actual application server implementation, whether the response is buffered etc.</p>\n\n<p>In Java EE app servers (Tomcat and WebLogic, probably others as well), you'll get the following exception:</p>\n\n<pre><code>java.net.SocketException: Connection reset by peer: socket write error\n</code></pre>\n" }, { "answer_id": 245804, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 1, "selected": false, "text": "<p>PHP understands three states of connection: NORMAL, ABORTED and TIMEOUT. You can change PHP's policy on ABORTED connections (by default, the script is terminated) with the <a href=\"http://www.php.net/ignore_user_abort\" rel=\"nofollow noreferrer\">ignore_user_abort()</a> function. From the <strong>notes</strong> section:</p>\n\n<p>\"PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client.\"</p>\n\n<p>Note that if your server's output is buffered, a send may not occur immediately.</p>\n\n<p>See <a href=\"http://au.php.net/manual/en/features.connection-handling.php\" rel=\"nofollow noreferrer\">PHP's page on connection handling</a> for more details.</p>\n" }, { "answer_id": 245829, "author": "Maxam", "author_id": 15310, "author_profile": "https://Stackoverflow.com/users/15310", "pm_score": 1, "selected": false, "text": "<p>If the connection was broken before the request was completely sent to the server, the response processing won't occur.</p>\n\n<p>If the request was sent completely, this triggers the server-side processing, and the response generation will continue despite the broken connection. </p>\n\n<p>In ASP.NET, you can detect this by using Response.IsClientConnected to halt the processing if the client is not connected anymore, saving CPU time and returning the thread immediately to the thread pool.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14755/" ]
In a fictitious web application ... 1. The user clicks a link 2. The server starts to prepare the response, but it takes several seconds 3. The user cancels the page load What happens to the request? Does the server continue to prepare the response? Does the response arrive to the browser?
The server will continue to prepare the response. When it tries to send the response to the client, it'll fail. When this actually happens will probably depend on the actual application server implementation, whether the response is buffered etc. In Java EE app servers (Tomcat and WebLogic, probably others as well), you'll get the following exception: ``` java.net.SocketException: Connection reset by peer: socket write error ```
245,787
<p>Whenever I run any jython program in Eclipse, I got the following error in the beginning of the output: </p> <blockquote> <p>" Failed to get environment, environ will be empty: (0, 'Failed to execute command ([\'sh\', \'-c\', \'env\']): java.io.IOException: Cannot run program "sh": Crea teProcess error=2, The system cannot find the file specified')</p> </blockquote> <p>First, my environment is:</p> <p>Windows 2008</p> <p>JDK 1.6.0u10</p> <p>jython 2.2.1</p> <p>I did some digging, and I realized that this message is produced in the function javaos.getenv(). Whenever I call the javaos.getenv() function, it throws the following error:</p> <p>C:\jython2.2.1>java -jar jython.jar</p> <blockquote> <blockquote> <blockquote> <p>import javaos</p> <p>print javaos.getenv("user.name")</p> </blockquote> </blockquote> <p>Failed to get environment, environ will be empty: (0, 'Failed to execute command ([\'sh\', \'-c\', \'env\']): java.io.IOException: Cannot run program "sh": Crea teProcess error=2, The system cannot find the file specified')</p> </blockquote> <p>This is strange, because I'm currently using a Windows machine, not an Unix.</p>
[ { "answer_id": 245871, "author": "user12861", "author_id": 12861, "author_profile": "https://Stackoverflow.com/users/12861", "pm_score": 2, "selected": false, "text": "<p>Interesting. Well, I seem to have found the relevant code here:\n<a href=\"http://www.koders.com/python/fid4B7C33153C1427D2CE19CE361EA9519D1652F802.aspx?s=self\" rel=\"nofollow noreferrer\"><a href=\"http://www.koders.com/python/fid4B7C33153C1427D2CE19CE361EA9519D1652F802.aspx?s=self\" rel=\"nofollow noreferrer\">http://www.koders.com/python/fid4B7C33153C1427D2CE19CE361EA9519D1652F802.aspx?s=self</a></a></p>\n\n<p>If you look towards the bottom, it seems when setting the environment command jython thinks your os is posix. You say you're using \"Windows 2008\". I'm not sure what that is. Do you mean Windows Server 2008? If so, it's quite new and if you look at the _getOsType function in the same module, it looks like it might be too new for that module. You may need to upgrade to the most recent version of jython or Eclipse. But it's quite possible they haven't yet released a version that supports this OS. If that's the case, you may need to just report the bug to them.</p>\n" }, { "answer_id": 246176, "author": "Blauohr", "author_id": 22176, "author_profile": "https://Stackoverflow.com/users/22176", "pm_score": 3, "selected": true, "text": "<p>Try to uncomment and change the os setting in the 'registry' file </p>\n\n<p>(it is in the same directory as your jython.jar / i hope)</p>\n\n<pre><code># python.os determines operating-specific features, similar to and overriding the\n# Java property \"os.name\".\n# Some generic values are also supported: 'nt', 'ce' and 'posix'.\n# Uncomment the following line for the most generic OS behavior available.\n#python.os=None\npython.os=nt\n# try nt or dos\n</code></pre>\n" }, { "answer_id": 2336254, "author": "deeeptext", "author_id": 173954, "author_profile": "https://Stackoverflow.com/users/173954", "pm_score": 0, "selected": false, "text": "<p>I ran into the same error, using Windows Vista, and Jython 2.5.1, under Eclipse/PyDev By editing javaos.py, to include \"Windows Vista\" in the OR statement in getOsType,;\nI fixed the error. (I've filed a bug with the fix under the PyDev Tracker at SourceForge.)</p>\n\n<p>Details:</p>\n\n<p>I installed the full version of Jython, and that did not help.\nI also tried editing the \"registry\" file in the Jython tree. That did not help either.</p>\n\n<p>Then I looked at the files in:</p>\n\n<p><code>C:\\eclipse-platform-3.5-win32\\eclipse\\plugins\\org.python.pydev.jython_1.4.8.2881\\Lib</code></p>\n\n<p>to find \"javaos.py\" and added a bit of code to read:</p>\n\n<pre><code>def _getOsType( os=None ):\n os = os or sys.registry.getProperty( \"python.os\" ) or \\\n java.lang.System.getProperty( \"os.name\" )\n\n_osTypeMap = (\n ( \"nt\", r\"(nt)|(Windows NT)|(Windows NT 4.0)|(WindowsNT)|\"\n r\"(Windows 2000)|(Windows XP)|(Windows CE)|(Windows Vista)\" ),\n ( \"dos\", r\"(dos)|(Windows 95)|(Windows 98)|(Windows ME)\" ),\n ( \"mac\", r\"(mac)|(MacOS.*)|(Darwin)\" ),\n ( \"None\", r\"(None)\" ),\n ( \"posix\", r\"(.*)\" ), # default - posix seems to vary mast widely\n )\nfor osType, pattern in _osTypeMap:\n if re.match( pattern, os ):\n break\nreturn osType\n</code></pre>\n" }, { "answer_id": 5122793, "author": "Rob", "author_id": 634897, "author_profile": "https://Stackoverflow.com/users/634897", "pm_score": 2, "selected": false, "text": "<p>I'm running on Windows 7.\nI'm running Jython as a script in the Websphere wsadmin tool.\nI encountered this same error.\nI cut-n-pasted these lines from javaos.py into my script:\n os or sys.registry.getProperty( \"python.os\" ) or \\ java.lang.System.getProperty( \"os.name\" )\nand it returned \"Windows Vista\".\nSo I performed the same surgery as suggested above, ie., add Windows Vista to javaos.py and that solved my problem.</p>\n" }, { "answer_id": 8359361, "author": "Dave Patterson", "author_id": 88556, "author_profile": "https://Stackoverflow.com/users/88556", "pm_score": 0, "selected": false, "text": "<p>I've used this hack from Dave Brands blog: <a href=\"http://dbrand666.wordpress.com/2010/04/08/fix1/\" rel=\"nofollow\">http://dbrand666.wordpress.com/2010/04/08/fix1/</a></p>\n\n<pre><code>try:\n import javaos\n if javaos._osType == 'posix' and \\\n java.lang.System.getProperty('os.name').startswith('Windows'):\n sys.registry.setProperty('python.os', 'nt')\n reload(javaos)\nexcept:\n pass\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32267/" ]
Whenever I run any jython program in Eclipse, I got the following error in the beginning of the output: > > " Failed to > get environment, environ will be > empty: (0, 'Failed to execute command > ([\'sh\', \'-c\', \'env\']): > java.io.IOException: Cannot run > program "sh": Crea teProcess error=2, > The system cannot find the file > specified') > > > First, my environment is: Windows 2008 JDK 1.6.0u10 jython 2.2.1 I did some digging, and I realized that this message is produced in the function javaos.getenv(). Whenever I call the javaos.getenv() function, it throws the following error: C:\jython2.2.1>java -jar jython.jar > > > > > > > > > > > > import javaos > > > > > > > > > print javaos.getenv("user.name") > > > > > > > > > > > > > > > > > > Failed to get environment, environ > will be empty: (0, 'Failed to execute > command ([\'sh\', \'-c\', \'env\']): > java.io.IOException: Cannot run > program "sh": Crea teProcess error=2, > The system cannot find the file > specified') > > > This is strange, because I'm currently using a Windows machine, not an Unix.
Try to uncomment and change the os setting in the 'registry' file (it is in the same directory as your jython.jar / i hope) ``` # python.os determines operating-specific features, similar to and overriding the # Java property "os.name". # Some generic values are also supported: 'nt', 'ce' and 'posix'. # Uncomment the following line for the most generic OS behavior available. #python.os=None python.os=nt # try nt or dos ```
245,792
<p>This is rather the inverse of <a href="https://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for">What can you use Python generator functions for?</a>: python generators, generator expressions, and the <code>itertools</code> module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files.</p> <p><strong>So when is it <em>not</em> a good time to use a generator, or a generator expression, or an <code>itertools</code> function?</strong></p> <ul> <li>When should I prefer <code>zip()</code> over <code>itertools.izip()</code>, or</li> <li><code>range()</code> over <code>xrange()</code>, or</li> <li><code>[x for x in foo]</code> over <code>(x for x in foo)</code>?</li> </ul> <p>Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking.</p> <p>We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off?</p> <p>I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of <a href="http://www.gossamer-threads.com/lists/python/python/76267" rel="noreferrer">list comprehension performance vs. map() and filter()</a>. (<a href="https://mail.python.org/pipermail//python-list/2001-December/096256.html" rel="noreferrer">alt link</a>)</p>
[ { "answer_id": 245797, "author": "Steven Huwig", "author_id": 28604, "author_profile": "https://Stackoverflow.com/users/28604", "pm_score": 4, "selected": false, "text": "<p>You should never favor <a href=\"http://docs.python.org/2/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip</code></a> over <a href=\"http://docs.python.org/2/library/itertools.html#itertools.izip\" rel=\"nofollow noreferrer\"><code>izip</code></a>, <code>range</code> over <code>xrange</code>, or list comprehensions over generator comprehensions. In Python 3.0 <code>range</code> has <code>xrange</code>-like semantics and <code>zip</code> has <code>izip</code>-like semantics.</p>\n\n<p>List comprehensions are actually clearer like <code>list(frob(x) for x in foo)</code> for those times you need an actual list.</p>\n" }, { "answer_id": 245816, "author": "Ryan Ginstrom", "author_id": 10658, "author_profile": "https://Stackoverflow.com/users/10658", "pm_score": 5, "selected": false, "text": "<p>In general, don't use a generator when you need list operations, like len(), reversed(), and so on.</p>\n\n<p>There may also be times when you don't want lazy evaluation (e.g. to do all the calculation up front so you can release a resource). In that case, a list expression might be better.</p>\n" }, { "answer_id": 246155, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 3, "selected": false, "text": "<p>As you mention, \"This especially makes sense for large datasets\", I think this answers your question.</p>\n\n<p>If your not hitting any walls, performance-wise, you can still stick to lists and standard functions. Then when you run into problems with performance make the switch.</p>\n\n<p>As mentioned by @u0b34a0f6ae in the comments, however, using generators at the start can make it easier for you to scale to larger datasets.</p>\n" }, { "answer_id": 246481, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 5, "selected": false, "text": "<p>Profile, Profile, Profile.</p>\n\n<p>Profiling your code is the only way to know if what you're doing has any effect at all.</p>\n\n<p>Most usages of xrange, generators, etc are over static size, small datasets. It's only when you get to large datasets that it really makes a difference. range() vs. xrange() is mostly just a matter of making the code look a tiny little bit more ugly, and not losing anything, and maybe gaining something.</p>\n\n<p>Profile, Profile, Profile.</p>\n" }, { "answer_id": 246494, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 2, "selected": false, "text": "<p>As far as performance is concerned, I can't think of any times that you would want to use a list over a generator.</p>\n" }, { "answer_id": 247527, "author": "Jeremy Cantrell", "author_id": 18866, "author_profile": "https://Stackoverflow.com/users/18866", "pm_score": 2, "selected": false, "text": "<p>I've never found a situation where generators would hinder what you're trying to do. There are, however, plenty of instances where using generators would not help you any more than not using them.</p>\n\n<p>For example:</p>\n\n<pre><code>sorted(xrange(5))\n</code></pre>\n\n<p>Does not offer any improvement over:</p>\n\n<pre><code>sorted(range(5))\n</code></pre>\n" }, { "answer_id": 255570, "author": "Ryan Ginstrom", "author_id": 10658, "author_profile": "https://Stackoverflow.com/users/10658", "pm_score": 3, "selected": false, "text": "<p>Regarding performance: if using psyco, lists can be quite a bit faster than generators. In the example below, lists are almost 50% faster when using psyco.full()</p>\n\n<pre><code>import psyco\nimport time\nimport cStringIO\n\ndef time_func(func):\n \"\"\"The amount of time it requires func to run\"\"\"\n start = time.clock()\n func()\n return time.clock() - start\n\ndef fizzbuzz(num):\n \"\"\"That algorithm we all know and love\"\"\"\n if not num % 3 and not num % 5:\n return \"%d fizz buzz\" % num\n elif not num % 3:\n return \"%d fizz\" % num\n elif not num % 5:\n return \"%d buzz\" % num\n return None\n\ndef with_list(num):\n \"\"\"Try getting fizzbuzz with a list comprehension and range\"\"\"\n out = cStringIO.StringIO()\n for fibby in [fizzbuzz(x) for x in range(1, num) if fizzbuzz(x)]:\n print &gt;&gt; out, fibby\n return out.getvalue()\n\ndef with_genx(num):\n \"\"\"Try getting fizzbuzz with generator expression and xrange\"\"\"\n out = cStringIO.StringIO()\n for fibby in (fizzbuzz(x) for x in xrange(1, num) if fizzbuzz(x)):\n print &gt;&gt; out, fibby\n return out.getvalue()\n\ndef main():\n \"\"\"\n Test speed of generator expressions versus list comprehensions,\n with and without psyco.\n \"\"\"\n\n #our variables\n nums = [10000, 100000]\n funcs = [with_list, with_genx]\n\n # try without psyco 1st\n print \"without psyco\"\n for num in nums:\n print \" number:\", num\n for func in funcs:\n print func.__name__, time_func(lambda : func(num)), \"seconds\"\n print\n\n # now with psyco\n print \"with psyco\"\n psyco.full()\n for num in nums:\n print \" number:\", num\n for func in funcs:\n print func.__name__, time_func(lambda : func(num)), \"seconds\"\n print\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>without psyco\n number: 10000\nwith_list 0.0519102208309 seconds\nwith_genx 0.0535933367509 seconds\n\n number: 100000\nwith_list 0.542204280744 seconds\nwith_genx 0.557837353115 seconds\n\nwith psyco\n number: 10000\nwith_list 0.0286369007033 seconds\nwith_genx 0.0513424889137 seconds\n\n number: 100000\nwith_list 0.335414877839 seconds\nwith_genx 0.580363490491 seconds\n</code></pre>\n" }, { "answer_id": 256272, "author": "minty", "author_id": 4491, "author_profile": "https://Stackoverflow.com/users/4491", "pm_score": 2, "selected": false, "text": "<p>You should prefer list comprehensions if you need to keep the values around for something else later and the size of your set is not too large.</p>\n\n<p>For example:\n you are creating a list that you will loop over several times later in your program. </p>\n\n<p>To some extent you can think of generators as a replacement for iteration (loops) vs. list comprehensions as a type of data structure initialization. If you want to keep the data structure then use list comprehensions.</p>\n" }, { "answer_id": 26635939, "author": "Raymond Hettinger", "author_id": 424499, "author_profile": "https://Stackoverflow.com/users/424499", "pm_score": 7, "selected": true, "text": "<p><strong>Use a list instead of a generator when:</strong></p>\n\n<p>1) You need to access the data <strong>multiple</strong> times (i.e. cache the results instead of recomputing them):</p>\n\n<pre><code>for i in outer: # used once, okay to be a generator or return a list\n for j in inner: # used multiple times, reusing a list is better\n ...\n</code></pre>\n\n<p>2) You need <strong>random access</strong> (or any access other than forward sequential order):</p>\n\n<pre><code>for i in reversed(data): ... # generators aren't reversible\n\ns[i], s[j] = s[j], s[i] # generators aren't indexable\n</code></pre>\n\n<p>3) You need to <strong>join</strong> strings (which requires two passes over the data):</p>\n\n<pre><code>s = ''.join(data) # lists are faster than generators in this use case\n</code></pre>\n\n<p>4) You are using <strong>PyPy</strong> which sometimes can't optimize generator code as much as it can with normal function calls and list manipulations.</p>\n" }, { "answer_id": 67727282, "author": "Golden Lion", "author_id": 4001177, "author_profile": "https://Stackoverflow.com/users/4001177", "pm_score": 0, "selected": false, "text": "<p>A generator builds and enumerable list of values. enumerables are useful when iterative process can use the values on demand. It takes time to build your generator, so if the list is millions of records in size, it may be more useful to use sql server to process the data in sql.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18950/" ]
This is rather the inverse of [What can you use Python generator functions for?](https://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for): python generators, generator expressions, and the `itertools` module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files. **So when is it *not* a good time to use a generator, or a generator expression, or an `itertools` function?** * When should I prefer `zip()` over `itertools.izip()`, or * `range()` over `xrange()`, or * `[x for x in foo]` over `(x for x in foo)`? Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking. We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off? I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of [list comprehension performance vs. map() and filter()](http://www.gossamer-threads.com/lists/python/python/76267). ([alt link](https://mail.python.org/pipermail//python-list/2001-December/096256.html))
**Use a list instead of a generator when:** 1) You need to access the data **multiple** times (i.e. cache the results instead of recomputing them): ``` for i in outer: # used once, okay to be a generator or return a list for j in inner: # used multiple times, reusing a list is better ... ``` 2) You need **random access** (or any access other than forward sequential order): ``` for i in reversed(data): ... # generators aren't reversible s[i], s[j] = s[j], s[i] # generators aren't indexable ``` 3) You need to **join** strings (which requires two passes over the data): ``` s = ''.join(data) # lists are faster than generators in this use case ``` 4) You are using **PyPy** which sometimes can't optimize generator code as much as it can with normal function calls and list manipulations.
245,798
<p>I use screen to persist my work session and connect to the same session from multiple machines. How can I setup SSH and screen such that the XDISPLAY variable <em>inside</em> my persistent screen session is always set to the machine I am currently connecting from?</p> <p>ie. I start the screen session at work and use gvim, which uses the X server running on my work machine. Later, I connect to the same session from home and also want to use gvim. But this time, I want gvim to use the X server on my home machine. I realize I could manually update XDISPLAY every time I connect from a different machine but I'd rather have an automated system.</p> <p>Bonus points if I can actually <em>move</em> gvim from my work machine to my home machine while it is running. I tried <a href="http://manpages.ubuntu.com/manpages/hardy/man1/xmove.html" rel="nofollow noreferrer">xmove</a> but could never get it to play nice.</p>
[ { "answer_id": 246046, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 2, "selected": false, "text": "<p>There is no \"trivial\" way to change environment variables in foreign processes.</p>\n\n<p>A straightforward solution might be to persist your <code>XDISPLAY</code> into a file on login and use a <code>PROMPT_COMMAND</code> to read this file before printing the next prompt.</p>\n\n<hr>\n\n<p>For moving X applications around look at something like <a href=\"http://en.wikipedia.org/wiki/X11vnc\" rel=\"nofollow noreferrer\"><code>X11vnc</code></a> or <a href=\"http://www.realvnc.com/products/free/4.1/man/Xvnc.html\" rel=\"nofollow noreferrer\"><code>Xvnc</code></a>.</p>\n" }, { "answer_id": 670984, "author": "rampion", "author_id": 9859, "author_profile": "https://Stackoverflow.com/users/9859", "pm_score": 4, "selected": true, "text": "<p>The following is a manual solution, but there's no reason you couldn't\nuse an alias or a script to have it done automagically when you remotely log in.</p>\n\n<p>Assuming that your local shell sets the DISPLAY variable appropriately,\nyou could use <code>screen -X</code> to send the following commads to your remote screen before\nconnecting.</p>\n\n<pre><code># set future remote shells started by screen to have the correct XDISPLAY\n% screen -X \"setenv XDISPLAY $DISPLAY\" #...\n\n# set up the keystroke F1 to update the XDISPLAY in current shells\n% screen -X \"bindkey -k k1 stuff export XDISPLAY=$DISPLAY\\015\" #...\n</code></pre>\n\n<p>If you know that all your windows were left in a shell (not a running editor or some such), you could use <code>:at</code> to change the <code>XDISPLAY</code> rather than a key binding:</p>\n\n<pre><code># update the XDISPLAY in all current windows\n% screen -X \"at % stuff export XDISPLAY=$DISPLAY\\015\" #...\n</code></pre>\n\n<p>Alternately, if you know some way of grabbing a parent process's environment variable value, then you could use that together with your shell's prompt hook to grab SCREEN's value of XDISPLAY (as set by setenv) and update it for the shell.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26715/" ]
I use screen to persist my work session and connect to the same session from multiple machines. How can I setup SSH and screen such that the XDISPLAY variable *inside* my persistent screen session is always set to the machine I am currently connecting from? ie. I start the screen session at work and use gvim, which uses the X server running on my work machine. Later, I connect to the same session from home and also want to use gvim. But this time, I want gvim to use the X server on my home machine. I realize I could manually update XDISPLAY every time I connect from a different machine but I'd rather have an automated system. Bonus points if I can actually *move* gvim from my work machine to my home machine while it is running. I tried [xmove](http://manpages.ubuntu.com/manpages/hardy/man1/xmove.html) but could never get it to play nice.
The following is a manual solution, but there's no reason you couldn't use an alias or a script to have it done automagically when you remotely log in. Assuming that your local shell sets the DISPLAY variable appropriately, you could use `screen -X` to send the following commads to your remote screen before connecting. ``` # set future remote shells started by screen to have the correct XDISPLAY % screen -X "setenv XDISPLAY $DISPLAY" #... # set up the keystroke F1 to update the XDISPLAY in current shells % screen -X "bindkey -k k1 stuff export XDISPLAY=$DISPLAY\015" #... ``` If you know that all your windows were left in a shell (not a running editor or some such), you could use `:at` to change the `XDISPLAY` rather than a key binding: ``` # update the XDISPLAY in all current windows % screen -X "at % stuff export XDISPLAY=$DISPLAY\015" #... ``` Alternately, if you know some way of grabbing a parent process's environment variable value, then you could use that together with your shell's prompt hook to grab SCREEN's value of XDISPLAY (as set by setenv) and update it for the shell.
245,802
<p>I am using fscanf to read a file which has lines like<br> Number &lt;-whitespace-> string &lt;-whitespace-> optional_3rd_column </p> <p>I wish to extract the number and string out of each column, but ignore the 3rd_column if it exists</p> <p>Example Data:<br> 12 foo something<br> 03 bar<br> 24 something #randomcomment</p> <p>I would want to extract 12,foo; 03,bar; 24, something while ignoring "something" and "#randomcomment"</p> <p>I currently have something like</p> <pre><code>while(scanf("%d %s %*s",&amp;num,&amp;word)&gt;=2) { assign stuff } </code></pre> <p>However this does not work with lines with no 3rd column. How can I make it ignore everything after the 2nd string?</p>
[ { "answer_id": 245806, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 2, "selected": false, "text": "<p>Use fgets() to read a line at a time and then use sscanf() to look for the two columns you are interested in, more robust and you don't have to do anything special to ignore trailing data.</p>\n" }, { "answer_id": 245809, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 0, "selected": false, "text": "<p>I often use gets() followed by an sscanf() on the string you just, er, gots.</p>\n\n<p>Bonus: you can separate the test for end-of-input from the parsing.</p>\n" }, { "answer_id": 245820, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 3, "selected": true, "text": "<p>It would appear to me that the simplest solution is to scanf(\"%d %s\", &amp;num, &amp;word) and then fgets() to eat the rest of the line.</p>\n" }, { "answer_id": 245845, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 4, "selected": false, "text": "<p>The problem is that the <code>%*s</code> is eating the number on the next line when there's no third column, and then the next <code>%d</code> is failing because the next token is not a number. To fix it without using <code>gets()</code> followed by <code>sscanf()</code>, you can use the character class specified:</p>\n\n<pre><code>while(scanf(\"%d %s%*[^\\n]\", &num, &word) == 2)\n{ \n assign stuff \n}</code></pre>\n\n<p>The <code>[^\\n]</code> says to match as many characters as possible that aren't newlines, and the <code>*</code> suppresses assignment as before. Also note that you can't put a space between the <code>%s</code> and the <code>%*[\\n]</code>, because otherwise that space in the format string would match the newline, causing the <code>%*[\\n]</code> to match the entire subsequent line, which is not what you want.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25990/" ]
I am using fscanf to read a file which has lines like Number <-whitespace-> string <-whitespace-> optional\_3rd\_column I wish to extract the number and string out of each column, but ignore the 3rd\_column if it exists Example Data: 12 foo something 03 bar 24 something #randomcomment I would want to extract 12,foo; 03,bar; 24, something while ignoring "something" and "#randomcomment" I currently have something like ``` while(scanf("%d %s %*s",&num,&word)>=2) { assign stuff } ``` However this does not work with lines with no 3rd column. How can I make it ignore everything after the 2nd string?
It would appear to me that the simplest solution is to scanf("%d %s", &num, &word) and then fgets() to eat the rest of the line.
245,803
<p>I have recently discovered the incredibly useful <a href="http://www.eclipse.org/mat/" rel="nofollow noreferrer">Eclipse Memory Analysis Tool</a>, which makes quick work of finding memory leaks in Java applications. Unfortunately, after switching my JDK to 1.6 (under Mac OS 10.5), the JVM terminates immediately upon startup. All that appears is a dialog stating "JVM terminated" with "Exit code = -1".</p> <p>Anyone else encounter this one? Perhaps there is a way to configure it to use a different JDK? (such as 1.5: which it was shown to be compatible with)</p>
[ { "answer_id": 246197, "author": "Guðmundur Bjarni", "author_id": 27349, "author_profile": "https://Stackoverflow.com/users/27349", "pm_score": 1, "selected": false, "text": "<p>The official Java 6 for the Mac only has a 64 bit data model. Unfortunately, Eclipse uses Carbon on the Mac which is only available in 32 bits. In short, it is impossible to run Eclipse with the official Java 6 distribution.</p>\n\n<p>The classical solution to this is to set the default VM to Java 5, and then choose Java 6 as the JRE/JDK within Eclipse.</p>\n\n<p>If you really need to run Eclipse with Java 6, then you could take a look at <a href=\"http://landonf.bikemonkey.org/static/soylatte/\" rel=\"nofollow noreferrer\">SoyLatte</a> which is a build of OpenJDK which both supports 32 and 64 bit modes.</p>\n" }, { "answer_id": 246883, "author": "Turismo", "author_id": 5271, "author_profile": "https://Stackoverflow.com/users/5271", "pm_score": 3, "selected": true, "text": "<p>To configure Eclipse to use another VM use this command line:</p>\n\n<pre><code>eclipse -vm &lt;path to java&gt;\n</code></pre>\n\n<p>You can also specify the path in Eclipse.app/Contents/Info.plist. There is a section like this:</p>\n\n<pre><code>&lt;!-- to use a specific Java version (instead of the platform's default) uncomment one of the following options:\n &lt;string&gt;-vm&lt;/string&gt;&lt;string&gt;/System/Library/Frameworks/JavaVM.framework/Versions/1.4.2/Commands/java&lt;/string&gt;\n &lt;string&gt;-vm&lt;/string&gt;&lt;string&gt;/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Commands/java&lt;/string&gt;\n--&gt;\n</code></pre>\n\n<p>For the Memory Analyzer the you can find the Info.plist file under MemoryAnalyzer.app/Contents.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9931/" ]
I have recently discovered the incredibly useful [Eclipse Memory Analysis Tool](http://www.eclipse.org/mat/), which makes quick work of finding memory leaks in Java applications. Unfortunately, after switching my JDK to 1.6 (under Mac OS 10.5), the JVM terminates immediately upon startup. All that appears is a dialog stating "JVM terminated" with "Exit code = -1". Anyone else encounter this one? Perhaps there is a way to configure it to use a different JDK? (such as 1.5: which it was shown to be compatible with)
To configure Eclipse to use another VM use this command line: ``` eclipse -vm <path to java> ``` You can also specify the path in Eclipse.app/Contents/Info.plist. There is a section like this: ``` <!-- to use a specific Java version (instead of the platform's default) uncomment one of the following options: <string>-vm</string><string>/System/Library/Frameworks/JavaVM.framework/Versions/1.4.2/Commands/java</string> <string>-vm</string><string>/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Commands/java</string> --> ``` For the Memory Analyzer the you can find the Info.plist file under MemoryAnalyzer.app/Contents.
245,827
<p>I have a legacy app where it reads message from a client program from file descriptor 3. This is an external app so I cannot change this. The client is written in C#. How can we open a connection to a specific file descriptor in C#? Can we use something like AnonymousPipeClientStream()? But how do we specify the file descriptor to connect to?</p>
[ { "answer_id": 493768, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 3, "selected": false, "text": "<p>Unfortunately, you won't be able to do that without P/Invoking to the native Windows API first.</p>\n\n<p>First, you will need to open your file descriptor with a native P/Invoke call. This is done by the OpenFileById WINAPI function. <a href=\"http://msdn.microsoft.com/en-us/library/aa365432(VS.85).aspx\" rel=\"noreferrer\">Here's how to use it</a> on MSDN, <a href=\"http://social.msdn.microsoft.com/forums/en-US/windowssearch/thread/4b71fcb3-bea9-4cfb-bdb7-2f1a91522ea6/\" rel=\"noreferrer\">here's an other link</a> explaining it in detail on the MSDN forums, and <a href=\"http://www.pinvoke.net/\" rel=\"noreferrer\">here's some help (pinvoke.net)</a> on how to construct your P/Invoke call.</p>\n\n<p>Once you got the file handle, you need to wrap it in a SafeFileHandle, this time in safe, managed C#:</p>\n\n<pre><code>// nativeHandle is the WINAPI handle you have acquired with the P/Invoke call\nSafeFileHandle safeHandle = new SafeFileHandle(nativeHandle, true);\n</code></pre>\n\n<p>Now you can open the file stream directly:</p>\n\n<pre><code>Stream stream = new FileStream(safeHandle, FileAccess.ReadWrite);\n</code></pre>\n\n<p>And from this point you can use it as any other file or stream in C#. Don't forget to dispose your objects once you're done.</p>\n" }, { "answer_id": 43494635, "author": "Tim Cooper", "author_id": 142162, "author_profile": "https://Stackoverflow.com/users/142162", "pm_score": 2, "selected": false, "text": "<p>I was able to solve the same issue by using <a href=\"https://msdn.microsoft.com/en-us/library/ks2530z6.aspx\" rel=\"nofollow noreferrer\"><code>_get_osfhandle</code></a>. Example:</p>\n\n<pre><code>using System;\nusing System.IO;\nusing Microsoft.Win32.SafeHandles;\nusing System.Runtime.InteropServices;\n\nclass Comm : IDisposable\n{\n [DllImport(\"MSVCRT.DLL\", CallingConvention = CallingConvention.Cdecl)]\n extern static IntPtr _get_osfhandle(int fd);\n\n public readonly Stream Stream;\n\n public Comm(int fd)\n {\n var handle = _get_osfhandle(fd);\n if (handle == IntPtr.Zero || handle == (IntPtr)(-1) || handle == (IntPtr)(-2))\n {\n throw new ApplicationException(\"invalid handle\");\n }\n\n var fileHandle = new SafeFileHandle(handle, true);\n Stream = new FileStream(fileHandle, FileAccess.ReadWrite);\n }\n\n public void Dispose()\n {\n Stream.Dispose();\n } \n}\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a legacy app where it reads message from a client program from file descriptor 3. This is an external app so I cannot change this. The client is written in C#. How can we open a connection to a specific file descriptor in C#? Can we use something like AnonymousPipeClientStream()? But how do we specify the file descriptor to connect to?
Unfortunately, you won't be able to do that without P/Invoking to the native Windows API first. First, you will need to open your file descriptor with a native P/Invoke call. This is done by the OpenFileById WINAPI function. [Here's how to use it](http://msdn.microsoft.com/en-us/library/aa365432(VS.85).aspx) on MSDN, [here's an other link](http://social.msdn.microsoft.com/forums/en-US/windowssearch/thread/4b71fcb3-bea9-4cfb-bdb7-2f1a91522ea6/) explaining it in detail on the MSDN forums, and [here's some help (pinvoke.net)](http://www.pinvoke.net/) on how to construct your P/Invoke call. Once you got the file handle, you need to wrap it in a SafeFileHandle, this time in safe, managed C#: ``` // nativeHandle is the WINAPI handle you have acquired with the P/Invoke call SafeFileHandle safeHandle = new SafeFileHandle(nativeHandle, true); ``` Now you can open the file stream directly: ``` Stream stream = new FileStream(safeHandle, FileAccess.ReadWrite); ``` And from this point you can use it as any other file or stream in C#. Don't forget to dispose your objects once you're done.
245,834
<p>I usually hate posting these types of questions as normally I find that the best way to really learn is to figure out the answer yourself. </p> <p>However, I need an answer to this question really quickly as I have a client who can't run her business due to this problem.</p> <p>Yesterday my ASP.NET host provider moved my application from a server running .NET 1.1 to one running .NET 1.1 and 2.0. My problem is that when I test the move the main site page (Default.aspx) will not load </p> <p><strong>"Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.</strong> </p> <p><strong>Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."</strong></p> <p><strong>[SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.] System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark&amp; stackMark, Boolean isPermSet) +0 System.Security.CodeAccessPermission.Demand() +59 System.Net.HttpWebRequest..ctor(Uri uri, ServicePoint servicePoint) +147 System.Net.HttpRequestCreator.Create(Uri Uri) +26 System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase) +298 System.Net.WebRequest.Create(Uri requestUri) +28 System.Web.Services.Protocols.WebClientProtocol.GetWebRequest(Uri uri) +30 System.Web.Services.Protocols.HttpWebClientProtocol.GetWebRequest(Uri uri) +12 System.Web.Services.Protocols.SoapHttpClientProtocol.GetWebRequest(Uri uri) +4 System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +52 PilatesPlusDublin.PilatesPlusDublinws.PilatesPlus.InsertException(String sModuleName, String sException, Int32 iUserID) +97 PilatesPlusDublin.MainDefault.Page_Load(Object sender, EventArgs e) +144 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +7350 System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +213 System.Web.UI.Page.ProcessRequest() +86 System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +18 System.Web.UI.Page.ProcessRequest(HttpContext context) +49 ASP.maindefault_aspx.ProcessRequest(HttpContext context) +4 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +358 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +64"</strong></p> <p>If WebPermission isn't available at the hosting site, how do I configure my site to allow access to the page? Is there some tags that need to be put into the web.config? Note - we have no access to machine.config or any other IIS settings. </p> <p>I understand that people hate reading and answering these types of question but any help on what I, or my hosting site need to do to fix this would be appreciated enormously </p>
[ { "answer_id": 245843, "author": "Maxam", "author_id": 15310, "author_profile": "https://Stackoverflow.com/users/15310", "pm_score": 1, "selected": false, "text": "<p>Is your web application calling a web service or accessing external web sites? If so, you might need to talk with your hosting provider and ask for the URI to be added to the list of allowed connection endpoints.</p>\n" }, { "answer_id": 248647, "author": "Skittles", "author_id": 26300, "author_profile": "https://Stackoverflow.com/users/26300", "pm_score": 2, "selected": false, "text": "<p>I am posting this in case it helps anyone else. Be warned before they move an existing ASP.NET site hosted by your provider to another sever.</p>\n\n<p><strong>MAKE SURE YOU ASK THEM ABOUT WEBPERMISSIONS AND TRUST LEVELS.</strong></p>\n\n<p>This was my providers reply.... </p>\n\n<p>\"Thank you for your email. </p>\n\n<p>It's failing because WebPermission isn't available in a medium trust environment. </p>\n\n<p>We can't make any changes to these servers at the moment, since we plan to migrate all sites on to a pair of new clusters by the end of this year. I'm confident that the new Windows cluster will have WebPermission available, since it's enabled on the current Namesco Windows cluster. \"</p>\n\n<p>So they expect my client's site to be offline and losing business until the New Year. </p>\n" }, { "answer_id": 270712, "author": "Mario", "author_id": 8426, "author_profile": "https://Stackoverflow.com/users/8426", "pm_score": 2, "selected": false, "text": "<p>Just as an FYI to anyone that might have the same problem - I got this exact error message and couldn't figure out what was wrong since I hadn't changed any settings on my local box. </p>\n\n<p>I realized after a couple minutes that I had accidentally opened the project from a network share on Windows Server 2008. Of course the permissions weren't correct! Really stupid move, but if it helps someone I am willing to be humiliated :)</p>\n" }, { "answer_id": 270736, "author": "Mun", "author_id": 775, "author_profile": "https://Stackoverflow.com/users/775", "pm_score": 3, "selected": false, "text": "<p>Not sure if this will help, but I once had a client with the same type of problem. Their webhosting company made some changes, resulting in their website throwing similar kinds of errors. Managed to get things working again by adding the following just inside the System.Web section in web.config:</p>\n\n<pre><code>&lt;trust level=\"Full\" /&gt;\n</code></pre>\n\n<p>If this doesn't solve your problem and the webhosting can't fix things on their until the new year, I'd seriously consider switching hosting providers.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26300/" ]
I usually hate posting these types of questions as normally I find that the best way to really learn is to figure out the answer yourself. However, I need an answer to this question really quickly as I have a client who can't run her business due to this problem. Yesterday my ASP.NET host provider moved my application from a server running .NET 1.1 to one running .NET 1.1 and 2.0. My problem is that when I test the move the main site page (Default.aspx) will not load **"Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.** **Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."** **[SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.] System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0 System.Security.CodeAccessPermission.Demand() +59 System.Net.HttpWebRequest..ctor(Uri uri, ServicePoint servicePoint) +147 System.Net.HttpRequestCreator.Create(Uri Uri) +26 System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase) +298 System.Net.WebRequest.Create(Uri requestUri) +28 System.Web.Services.Protocols.WebClientProtocol.GetWebRequest(Uri uri) +30 System.Web.Services.Protocols.HttpWebClientProtocol.GetWebRequest(Uri uri) +12 System.Web.Services.Protocols.SoapHttpClientProtocol.GetWebRequest(Uri uri) +4 System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +52 PilatesPlusDublin.PilatesPlusDublinws.PilatesPlus.InsertException(String sModuleName, String sException, Int32 iUserID) +97 PilatesPlusDublin.MainDefault.Page\_Load(Object sender, EventArgs e) +144 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +7350 System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +213 System.Web.UI.Page.ProcessRequest() +86 System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +18 System.Web.UI.Page.ProcessRequest(HttpContext context) +49 ASP.maindefault\_aspx.ProcessRequest(HttpContext context) +4 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +358 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +64"** If WebPermission isn't available at the hosting site, how do I configure my site to allow access to the page? Is there some tags that need to be put into the web.config? Note - we have no access to machine.config or any other IIS settings. I understand that people hate reading and answering these types of question but any help on what I, or my hosting site need to do to fix this would be appreciated enormously
Not sure if this will help, but I once had a client with the same type of problem. Their webhosting company made some changes, resulting in their website throwing similar kinds of errors. Managed to get things working again by adding the following just inside the System.Web section in web.config: ``` <trust level="Full" /> ``` If this doesn't solve your problem and the webhosting can't fix things on their until the new year, I'd seriously consider switching hosting providers.
245,835
<p>I have a site behind basic authentication (IIS6).</p> <p>Part of this site calls a web service that is also part of the site and thus behind basic authentication as well.</p> <p>However, when this happens the calling code receives a 401 Authentication Error.</p> <p>I've tried a couple of things, with the general recommendation being code like this:</p> <pre><code>Service.ServiceName s = new Service.ServiceName(); s.PreAuthenticate = true; s.Credentials = System.Net.CredentialCache.DefaultCredentials; s.Method("Test"); </code></pre> <p>However, this does not seem to resolve my problem.</p> <p>Any advice?</p> <p><strong>Edit</strong></p> <p>This seems to be a not uncommon issue but so far I have found no solutions. Here is <a href="http://forums.iis.net/t/1146546.aspx" rel="nofollow noreferrer">one thread</a> on the topic.</p>
[ { "answer_id": 245946, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 0, "selected": false, "text": "<p>The Line:</p>\n\n<pre><code>s.Credentials = System.Net.CredentialCache.DefaultCredentials();</code></pre>\n\n<p>Maybe you should try :</p>\n\n<pre><code>s.Credentials = HttpContext.Current.User.Identity;</code></pre>\n" }, { "answer_id": 248752, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 3, "selected": true, "text": "<h2>Solution: (I am almost certain this will help someone)</h2>\n\n<p><strong>See <a href=\"http://forums.asp.net/t/1172902.aspx\" rel=\"nofollow noreferrer\">this link</a> for the source of this solution in VB (thanks jshardy!), all I did was convert to C#.</strong></p>\n\n<p><strong>NB:</strong> You must be using ONLY basic authentication on IIS for this to work, but it can probably be adapted. You also need to pass a Page instance in, or at least the Request.ServerVariables property (or use 'this' if called from a Page code-behind directly). I'd tidy this up and probably remove the use of references but this is a faithful translation of the original solution and you can make any amendments necessary.</p>\n\n<pre><code>public static void ServiceCall(Page p)\n{\n LocalServices.ServiceName s = new LocalServices.ServiceName();\n s.PreAuthenticate = true; /* Not sure if required */\n\n string username = \"\";\n string password = \"\";\n string domain = \"\";\n GetBasicCredentials(p, ref username, ref password, ref domain);\n\n s.Credentials = new NetworkCredential(username, password, domain);\n s.ServiceMethod();\n}\n\n\n/* Converted from: http://forums.asp.net/t/1172902.aspx */\nprivate static void GetBasicCredentials(Page p, ref string rstrUser, ref string rstrPassword, ref string rstrDomain)\n{\n if (p == null)\n {\n return;\n }\n\n rstrUser = \"\";\n rstrPassword = \"\";\n rstrDomain = \"\";\n\n rstrUser = p.Request.ServerVariables[\"AUTH_USER\"];\n rstrPassword = p.Request.ServerVariables[\"AUTH_PASSWORD\"];\n\n SplitDomainUserName(rstrUser, ref rstrDomain, ref rstrUser);\n\n /* MSDN KB article 835388\n BUG: The Request.ServerVariables(\"AUTH_PASSWORD\") object does not display certain characters from an ASPX page */\n string lstrHeader = p.Request.ServerVariables[\"HTTP_AUTHORIZATION\"];\n if (!string.IsNullOrEmpty(lstrHeader) &amp;&amp; lstrHeader.StartsWith(\"Basic\"))\n {\n string lstrTicket = lstrHeader.Substring(6);\n lstrTicket = System.Text.Encoding.Default.GetString(Convert.FromBase64String(lstrTicket));\n rstrPassword = lstrTicket.Substring((lstrTicket.IndexOf(\":\") + 1));\n }\n\n /* At least on my XP Pro machine AUTH_USER is not set (probably because we're using Forms authentication \n But if the password is set (either by AUTH_PASSWORD or HTTP_AUTHORIZATION)\n then we can use LOGON_USER*/\n if (string.IsNullOrEmpty(rstrUser) &amp;&amp; !string.IsNullOrEmpty(rstrPassword))\n {\n rstrUser = p.Request.ServerVariables[\"LOGON_USER\"];\n SplitDomainUserName(rstrUser, ref rstrDomain, ref rstrUser);\n }\n}\n\n/* Converted from: http://forums.asp.net/t/1172902.aspx */\nprivate static void SplitDomainUserName(string pstrDomainUserName, ref string rstrDomainName, ref string rstrUserName)\n{\n rstrDomainName = \"\";\n rstrUserName = pstrDomainUserName;\n\n int lnSlashPos = pstrDomainUserName.IndexOf(\"\\\\\");\n if (lnSlashPos &gt; 0)\n {\n rstrDomainName = pstrDomainUserName.Substring(0, lnSlashPos);\n rstrUserName = pstrDomainUserName.Substring(lnSlashPos + 1);\n }\n}\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
I have a site behind basic authentication (IIS6). Part of this site calls a web service that is also part of the site and thus behind basic authentication as well. However, when this happens the calling code receives a 401 Authentication Error. I've tried a couple of things, with the general recommendation being code like this: ``` Service.ServiceName s = new Service.ServiceName(); s.PreAuthenticate = true; s.Credentials = System.Net.CredentialCache.DefaultCredentials; s.Method("Test"); ``` However, this does not seem to resolve my problem. Any advice? **Edit** This seems to be a not uncommon issue but so far I have found no solutions. Here is [one thread](http://forums.iis.net/t/1146546.aspx) on the topic.
Solution: (I am almost certain this will help someone) ------------------------------------------------------ **See [this link](http://forums.asp.net/t/1172902.aspx) for the source of this solution in VB (thanks jshardy!), all I did was convert to C#.** **NB:** You must be using ONLY basic authentication on IIS for this to work, but it can probably be adapted. You also need to pass a Page instance in, or at least the Request.ServerVariables property (or use 'this' if called from a Page code-behind directly). I'd tidy this up and probably remove the use of references but this is a faithful translation of the original solution and you can make any amendments necessary. ``` public static void ServiceCall(Page p) { LocalServices.ServiceName s = new LocalServices.ServiceName(); s.PreAuthenticate = true; /* Not sure if required */ string username = ""; string password = ""; string domain = ""; GetBasicCredentials(p, ref username, ref password, ref domain); s.Credentials = new NetworkCredential(username, password, domain); s.ServiceMethod(); } /* Converted from: http://forums.asp.net/t/1172902.aspx */ private static void GetBasicCredentials(Page p, ref string rstrUser, ref string rstrPassword, ref string rstrDomain) { if (p == null) { return; } rstrUser = ""; rstrPassword = ""; rstrDomain = ""; rstrUser = p.Request.ServerVariables["AUTH_USER"]; rstrPassword = p.Request.ServerVariables["AUTH_PASSWORD"]; SplitDomainUserName(rstrUser, ref rstrDomain, ref rstrUser); /* MSDN KB article 835388 BUG: The Request.ServerVariables("AUTH_PASSWORD") object does not display certain characters from an ASPX page */ string lstrHeader = p.Request.ServerVariables["HTTP_AUTHORIZATION"]; if (!string.IsNullOrEmpty(lstrHeader) && lstrHeader.StartsWith("Basic")) { string lstrTicket = lstrHeader.Substring(6); lstrTicket = System.Text.Encoding.Default.GetString(Convert.FromBase64String(lstrTicket)); rstrPassword = lstrTicket.Substring((lstrTicket.IndexOf(":") + 1)); } /* At least on my XP Pro machine AUTH_USER is not set (probably because we're using Forms authentication But if the password is set (either by AUTH_PASSWORD or HTTP_AUTHORIZATION) then we can use LOGON_USER*/ if (string.IsNullOrEmpty(rstrUser) && !string.IsNullOrEmpty(rstrPassword)) { rstrUser = p.Request.ServerVariables["LOGON_USER"]; SplitDomainUserName(rstrUser, ref rstrDomain, ref rstrUser); } } /* Converted from: http://forums.asp.net/t/1172902.aspx */ private static void SplitDomainUserName(string pstrDomainUserName, ref string rstrDomainName, ref string rstrUserName) { rstrDomainName = ""; rstrUserName = pstrDomainUserName; int lnSlashPos = pstrDomainUserName.IndexOf("\\"); if (lnSlashPos > 0) { rstrDomainName = pstrDomainUserName.Substring(0, lnSlashPos); rstrUserName = pstrDomainUserName.Substring(lnSlashPos + 1); } } ```
245,838
<p>Ok so I thought it was fixed, but I'm getting totally inconsistent results. I rewrote it kind of from scratch to start fresh and here are my results. I get no errors, no crashing, it just doesn't remove them. It just totally messes up the tree and gives me a ton more leaves, and mixes everything up. Not sure where else to go</p> <pre><code>template &lt;class T&gt; void BST&lt;T&gt;::remove(struct Node&lt;T&gt;*&amp; root, const T&amp; x) { Node&lt;T&gt;* ptr = root; bool found = false; Node&lt;T&gt;* parent; while (ptr != NULL &amp;&amp; !found) { if (x &lt; ptr-&gt;data) { parent = ptr; ptr = ptr-&gt;left; } else if (x &gt; ptr-&gt;data) { parent = ptr; ptr = ptr-&gt;right; } else found = true; } if (found == false) return; else { if(ptr-&gt;left != NULL &amp;&amp; ptr-&gt;right != NULL) { Node&lt;T&gt;* inOrderPtr = ptr-&gt;left; parent = ptr; while (inOrderPtr-&gt;right != NULL) { parent = inOrderPtr; inOrderPtr = inOrderPtr-&gt;right; } ptr-&gt;data = inOrderPtr-&gt;data; ptr = inOrderPtr; } Node&lt;T&gt;* subPtr = ptr-&gt;left; if (subPtr == NULL) subPtr = ptr-&gt;right; else if (parent-&gt;left == ptr) parent-&gt;left = subPtr; else parent-&gt;right = subPtr; delete ptr; } </code></pre>
[ { "answer_id": 245883, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "<p>You shouldn't be calling <code>remove()</code> recursively in the third case (where your \"not sure if this is right\" comment is). In the case where the the node to remove has two children, what you want to do is find the right-most child of the left child (as you are doing; the resulting node is stored in <code>parent</code>). This node has no right child - make it so that its right child is the right child of the node to be deleted. Then just change the <code>root</code> variable to be its left child; no need to change the <code>data</code> member in any nodes or to call <code>remove</code> recursively.</p>\n\n<p>In pictures:</p>\n\n<pre>\nBefore:\n r &lt;- root points here\n / \\\n / \\\n a b\n / \\ / \\\n x c y y\n / \\\n x d\n /\n x\n\nAfter:\n a &lt;-- root points here\n / \\\n x c\n / \\\n x d\n / \\\n x b\n / \\\n y y\n</pre>\n" }, { "answer_id": 245928, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 1, "selected": true, "text": "<p>Are each T found in the tree unique? It looks like they are from your code...</p>\n\n<p>It looks like this should work:</p>\n\n<p>In the else case deleting the root node:</p>\n\n<pre><code>Node&lt;T&gt; *tmp_r = root-&gt;left;\nNode&lt;T&gt; *parent = root;\nwhile (tmp_r-&gt;right != NULL)\n{\n parent = tmp_r;\n tmp_r = tmp_r-&gt;right;\n}\nNode&lt;T&gt; *tmp_l = tmp_r;\nwhile (tmp_l-&gt;left != NULL)\n tmp_l = tmp_l-&gt;left;\n\ntmp_l-&gt;left = root-&gt;left;\ntmp_r-&gt;right = root-&gt;right;\nparent-&gt;right = NULL;\n\nparent = root;\nroot = tmp_r;\ndelete parent;\n</code></pre>\n" }, { "answer_id": 246019, "author": "Doug", "author_id": 28392, "author_profile": "https://Stackoverflow.com/users/28392", "pm_score": 1, "selected": false, "text": "<p>What actually was happening is that might searches were reversed so it would actually just keep going right but the data wasn't really matching correctly and so it would hit a wall it seems. </p>\n\n<pre><code>if (root-&gt;data &lt; x)\n remove(root-&gt;left, x);\n else \n remove(root-&gt;right, x);\n</code></pre>\n\n<p>should have been</p>\n\n<pre><code>if(x &lt; root-&gt;data)\nremove(root-&gt;left, x);\nelse\nremove(root-&gt;right, x);\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28392/" ]
Ok so I thought it was fixed, but I'm getting totally inconsistent results. I rewrote it kind of from scratch to start fresh and here are my results. I get no errors, no crashing, it just doesn't remove them. It just totally messes up the tree and gives me a ton more leaves, and mixes everything up. Not sure where else to go ``` template <class T> void BST<T>::remove(struct Node<T>*& root, const T& x) { Node<T>* ptr = root; bool found = false; Node<T>* parent; while (ptr != NULL && !found) { if (x < ptr->data) { parent = ptr; ptr = ptr->left; } else if (x > ptr->data) { parent = ptr; ptr = ptr->right; } else found = true; } if (found == false) return; else { if(ptr->left != NULL && ptr->right != NULL) { Node<T>* inOrderPtr = ptr->left; parent = ptr; while (inOrderPtr->right != NULL) { parent = inOrderPtr; inOrderPtr = inOrderPtr->right; } ptr->data = inOrderPtr->data; ptr = inOrderPtr; } Node<T>* subPtr = ptr->left; if (subPtr == NULL) subPtr = ptr->right; else if (parent->left == ptr) parent->left = subPtr; else parent->right = subPtr; delete ptr; } ```
Are each T found in the tree unique? It looks like they are from your code... It looks like this should work: In the else case deleting the root node: ``` Node<T> *tmp_r = root->left; Node<T> *parent = root; while (tmp_r->right != NULL) { parent = tmp_r; tmp_r = tmp_r->right; } Node<T> *tmp_l = tmp_r; while (tmp_l->left != NULL) tmp_l = tmp_l->left; tmp_l->left = root->left; tmp_r->right = root->right; parent->right = NULL; parent = root; root = tmp_r; delete parent; ```
245,840
<p>Is there any way of batch renaming files in sub directories?</p> <p>For example:</p> <p>Rename <code>*.html</code> to <code>*.htm</code> in a folder which has directories and sub directories.</p>
[ { "answer_id": 245854, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "<p>In Bash, you could do the following:</p>\n\n<pre><code>for x in $(find . -name \\*.html); do\n mv $x $(echo \"$x\" | sed 's/\\.html$/.htm/')\ndone\n</code></pre>\n" }, { "answer_id": 245857, "author": "albertb", "author_id": 26715, "author_profile": "https://Stackoverflow.com/users/26715", "pm_score": 2, "selected": false, "text": "<p>I'm sure there's a more elegant way, but here's the first thing that popped in my head:</p>\n\n<pre><code>for f in $(find . -type f -name '*.html'); do \n mv $f $(echo \"$f\" | sed 's/html$/htm/')\ndone\n</code></pre>\n" }, { "answer_id": 245862, "author": "Anonymous", "author_id": 19650, "author_profile": "https://Stackoverflow.com/users/19650", "pm_score": 8, "selected": true, "text": "<p>Windows command prompt: (If inside a batch file, change %x to %%x)</p>\n\n<pre><code>for /r %x in (*.html) do ren \"%x\" *.htm\n</code></pre>\n\n<p>This also works for renaming the middle of the files</p>\n\n<pre><code>for /r %x in (website*.html) do ren \"%x\" site*.htm\n</code></pre>\n" }, { "answer_id": 245864, "author": "Aditya Mukherji", "author_id": 25990, "author_profile": "https://Stackoverflow.com/users/25990", "pm_score": 3, "selected": false, "text": "<pre><code>find . -regex \".*html$\" | while read line;\n do \n A=`basename ${line} | sed 's/html$/htm/g'`;\n B=`dirname ${line}`;\n mv ${line} \"${B}/${A}\";\n done\n</code></pre>\n" }, { "answer_id": 245874, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 3, "selected": false, "text": "<p>In python</p>\n\n<pre><code>import os\n\ntarget_dir = \".\"\n\nfor path, dirs, files in os.walk(target_dir):\n for file in files:\n filename, ext = os.path.splitext(file)\n new_file = filename + \".htm\"\n\n if ext == '.html':\n old_filepath = os.path.join(path, file)\n new_filepath = os.path.join(path, new_file)\n os.rename(old_filepath, new_filepath)\n</code></pre>\n" }, { "answer_id": 245939, "author": "ayaz", "author_id": 23191, "author_profile": "https://Stackoverflow.com/users/23191", "pm_score": 1, "selected": false, "text": "<p>On Linux, you may use the '<a href=\"http://linux.die.net/man/1/rename\" rel=\"nofollow noreferrer\">rename</a>' command to rename files in batch.</p>\n" }, { "answer_id": 246015, "author": "Alex", "author_id": 30181, "author_profile": "https://Stackoverflow.com/users/30181", "pm_score": 0, "selected": false, "text": "<p>AWK on Linux. For the first directory this is your answer... Extrapolate by recursively calling awk on dir_path perhaps by writing another awk which writes this exact awk below... and so on.</p>\n\n<pre><code>ls dir_path/. | awk -F\".\" '{print \"mv file_name/\"$0\" dir_path/\"$1\".new_extension\"}' |csh\n</code></pre>\n" }, { "answer_id": 248147, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>In bash use command rename :)\n\n rename 's/\\.htm$/.html/' *.htm\n\n # or\n\n find . -name '*.txt' -print0 | xargs -0 rename 's/.txt$/.xml/'\n\n #Obs1: Above I use regex \\. --&gt; literal '.' and $ --&gt; end of line\n #Obs2: Use find -maxdepht 'value' for determine how recursive is\n #Obs3: Use -print0 to avoid 'names spaces asdfa' crash!\n</code></pre>\n" }, { "answer_id": 1783273, "author": "BBX", "author_id": 217038, "author_profile": "https://Stackoverflow.com/users/217038", "pm_score": 3, "selected": false, "text": "<p>If you have forfiles (it comes with Windows XP and 2003 and newer stuff I think) you can run:</p>\n<pre><code>forfiles /S /M *.HTM /C &quot;cmd /c ren @file *.HTML&quot;\n</code></pre>\n" }, { "answer_id": 37085847, "author": "Jahid", "author_id": 3744681, "author_profile": "https://Stackoverflow.com/users/3744681", "pm_score": 0, "selected": false, "text": "<p>On Unix, you can use <a href=\"https://github.com/neurobin/rnm\" rel=\"nofollow\">rnm</a>:</p>\n\n<pre><code>rnm -rs '/\\.html$/.htm/' -fo -dp -1 *\n</code></pre>\n\n<p>Or </p>\n\n<pre><code>rnm -ns '/n/.htm' -ss '\\.html$' -fo -dp -1 *\n</code></pre>\n\n<p>Explanation:</p>\n\n<ol>\n<li><code>-ns</code> : name string (new name). <code>/n/</code> is a name string rule that expands to the filename without the extension.</li>\n<li><code>-ss</code> : search string (regex). Searches for files with match.</li>\n<li><code>-rs</code> : replace string of the form <code>/search_regex/replace_part/modifier</code></li>\n<li><code>-fo</code> : file only mode</li>\n<li><code>-dp</code> : depth of directory (-1 means unlimited).</li>\n</ol>\n" }, { "answer_id": 73785580, "author": "vilem cech", "author_id": 15067478, "author_profile": "https://Stackoverflow.com/users/15067478", "pm_score": 0, "selected": false, "text": "<p>there is pretty powerfull <a href=\"https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/forfiles\" rel=\"nofollow noreferrer\">forfiles</a> command:</p>\n<p><code>forfiles /? </code> gives u hint of what is possible with the command.\nin this case it can be used like:</p>\n<pre><code>forfiles /S /M *.html /C &quot;cmd /c rename @file @fname.htm&quot;\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12178/" ]
Is there any way of batch renaming files in sub directories? For example: Rename `*.html` to `*.htm` in a folder which has directories and sub directories.
Windows command prompt: (If inside a batch file, change %x to %%x) ``` for /r %x in (*.html) do ren "%x" *.htm ``` This also works for renaming the middle of the files ``` for /r %x in (website*.html) do ren "%x" site*.htm ```
245,866
<p>Given a System.Timers.Timer, is there a way from the main thread to tell if the worker thread running the elapsed event code is still running?</p> <p>In other words, how can one make sure the code running in the worker thread is not currently running before stopping the timer or the main app/service thread the timer is running in?</p> <p>Is this a matter of ditching Timer for threading timer using state, or is it just time to use threads directly?</p>
[ { "answer_id": 245926, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 0, "selected": false, "text": "<p>For the out of the box solution, there is no way. The main reason is the thread running the TimerCallback function is in all likelihood still alive even if the code running the callback has completed. The TimerCallback is executed by a Thread out of the ThreadPool. When the task is completed the thread does not die, but instead goes back into the queue for the next thread pool task. </p>\n\n<p>In order to get this to work your going to have to use a manner of thread safe signalling to detect the operation has completed. </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx\" rel=\"nofollow noreferrer\">Timer Documentation</a></p>\n" }, { "answer_id": 246013, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 2, "selected": true, "text": "<p>Look up ManualResetEvent, as it is made to do specifically what you're asking for.</p>\n\n<p>Your threads create a new reset event, and add it to an accessible queue that your main thread can use to see if any threads are still running.</p>\n\n<pre><code>// main thread owns this\nprivate List&lt;ManualResetEvent&gt; _resetEvents;\n...\n// main thread does this to wait for executing threads to finish\nWaitHandle.WaitAll(_resetEvents.ToArray(), 2000, false)\n...\n// worker threads do this to signal the thread is done\nmyResetEvent.Set();\n</code></pre>\n\n<p>I can give you more sample code if you want, but I basically just copied it from the couple articles I read when I had to do this a year ago or so.</p>\n\n<hr>\n\n<p>Forgot to mention, you can't add this functionality to the default threads you'll get when your timer fires. So you should make your timer handler be very lean and do nothing more than prepare and start a new worker thread.</p>\n\n<pre><code>...\nThreadPool.QueueUserWorkItem(new WaitCallback(MyWorkerDelegate),\n myCustomObjectThatContainsAResetEvent);\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91911/" ]
Given a System.Timers.Timer, is there a way from the main thread to tell if the worker thread running the elapsed event code is still running? In other words, how can one make sure the code running in the worker thread is not currently running before stopping the timer or the main app/service thread the timer is running in? Is this a matter of ditching Timer for threading timer using state, or is it just time to use threads directly?
Look up ManualResetEvent, as it is made to do specifically what you're asking for. Your threads create a new reset event, and add it to an accessible queue that your main thread can use to see if any threads are still running. ``` // main thread owns this private List<ManualResetEvent> _resetEvents; ... // main thread does this to wait for executing threads to finish WaitHandle.WaitAll(_resetEvents.ToArray(), 2000, false) ... // worker threads do this to signal the thread is done myResetEvent.Set(); ``` I can give you more sample code if you want, but I basically just copied it from the couple articles I read when I had to do this a year ago or so. --- Forgot to mention, you can't add this functionality to the default threads you'll get when your timer fires. So you should make your timer handler be very lean and do nothing more than prepare and start a new worker thread. ``` ... ThreadPool.QueueUserWorkItem(new WaitCallback(MyWorkerDelegate), myCustomObjectThatContainsAResetEvent); ```
245,868
<p>I have seen the following methods of putting JavaScript code in an <code>&lt;a&gt;</code> tag:</p> <pre><code>function DoSomething() { ... return false; } </code></pre> <ol> <li><code>&lt;a href="javascript:;" onClick="return DoSomething();"&gt;link&lt;/a&gt;</code></li> <li><code>&lt;a href="javascript:DoSomething();"&gt;link&lt;/a&gt;</code></li> <li><code>&lt;a href="javascript:void(0);" onClick="return DoSomething();"&gt;link&lt;/a&gt;</code></li> <li><code>&lt;a href="#" onClick="return DoSomething();"&gt;link&lt;/a&gt;</code></li> </ol> <p>I understand the idea of trying to put a valid URL instead of just JavaScript code, just in case the user doesn't have JavaScript enabled. But for the purpose of this discussion, I need to assume JavaScript is enabled (they can't login without it).</p> <p>I personally like option 2 as it allows you to see what's going to be run&ndash;especially useful when debuging where there are parameters being passed to the function. I have used it quite a bit and haven't found browser issues.</p> <p>I have read that people recommend 4, because it gives the user a real link to follow, but really, # isn't "real". It will go absolutely no where.</p> <p>Is there one that isn't support or is really bad, when you know the user has JavaScript enabled?</p> <p>Related question: <em><a href="https://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0">Href for JavaScript links: “#” or “javascript:void(0)”?</a></em>.</p>
[ { "answer_id": 245886, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": false, "text": "<p>Why would you do this when you can use <code>addEventListener</code>/<code>attachEvent</code>? If there is no <code>href</code>-equivalent, don't use an <code>&lt;a&gt;</code>, use a <code>&lt;button&gt;</code> and style it accordingly.</p>\n" }, { "answer_id": 245888, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 3, "selected": false, "text": "<p>You forgot another method:</p>\n\n<pre><code>5: &lt;a href=\"#\" id=\"myLink\"&gt;Link&lt;/a&gt;\n</code></pre>\n\n<p>With the JavaScript code:</p>\n\n<pre><code>document.getElementById('myLink').onclick = function() {\n // Do stuff.\n};\n</code></pre>\n\n<p>I can't comment on which of the options has the best support or which is semantically the best, but I'll just say that I much prefer this style because it separates your content from your JavaScript code. It keeps all the JavaScript code together, which is much easier to maintain (especially if you are applying this to many links), and you can even put it in an external file which can then be packed to reduce filesize and cached by client browsers.</p>\n" }, { "answer_id": 245889, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;a href=\"#\" onClick=\"DoSomething(); return false;\"&gt;link&lt;/a&gt;\n</code></pre>\n\n<p>I will do this, or:</p>\n\n<pre><code>&lt;a href=\"#\" id = \"Link\"&gt;link&lt;/a&gt;\n(document.getElementById(\"Link\")).onclick = function() {\n DoSomething();\n return false;\n};\n</code></pre>\n\n<p>Depending on the situation. For larger apps, the second one is best because then it consolidates your event code.</p>\n" }, { "answer_id": 245898, "author": "cowgod", "author_id": 6406, "author_profile": "https://Stackoverflow.com/users/6406", "pm_score": 7, "selected": true, "text": "<p>I quite enjoy <a href=\"http://web.archive.org/web/20190822202858/http://www.javascripttoolbox.com/bestpractices/\" rel=\"nofollow noreferrer\">Matt Kruse's Javascript Best Practices article</a>. In it, he states that using the <code>href</code> section to execute JavaScript code is a bad idea. Even though you have stated that your users must have JavaScript enabled, there's no reason you can't have a simple HTML page that all your JavaScript links can point to for their <code>href</code> section in the event that someone happens to turn off JavaScript after logging in. I would highly encourage you to still allow this fallback mechanism. Something like this will adhere to &quot;best practices&quot; and accomplish your goal:</p>\n<pre><code>&lt;a href=&quot;javascript_required.html&quot; onclick=&quot;doSomething(); return false;&quot;&gt;go&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 246031, "author": "Pier Luigi", "author_id": 27789, "author_profile": "https://Stackoverflow.com/users/27789", "pm_score": 1, "selected": false, "text": "<p>Method #2 has a syntax error in FF3 and IE7.\nI prefer methods #1 and #3, because #4 dirty the URI with '#' although causes less typing...\nObviously, as noted by other responses, the best solution is separate html from event handling.</p>\n" }, { "answer_id": 22793173, "author": "JoelFan", "author_id": 16012, "author_profile": "https://Stackoverflow.com/users/16012", "pm_score": 1, "selected": false, "text": "<p>One difference I've noticed between this:</p>\n\n<pre><code>&lt;a class=\"actor\" href=\"javascript:act1()\"&gt;Click me&lt;/a&gt;\n</code></pre>\n\n<p>and this:</p>\n\n<pre><code>&lt;a class=\"actor\" onclick=\"act1();\"&gt;Click me&lt;/a&gt;\n</code></pre>\n\n<p>is that if in either case you have:</p>\n\n<pre><code>&lt;script&gt;$('.actor').click(act2);&lt;/script&gt;\n</code></pre>\n\n<p>then for the first example, <code>act2</code> will run before <code>act1</code> and in the second example, it will be the other way around.</p>\n" }, { "answer_id": 23977642, "author": "Timo Huovinen", "author_id": 175071, "author_profile": "https://Stackoverflow.com/users/175071", "pm_score": 1, "selected": false, "text": "<h2>Modern browsers only</h2>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;script type=\"text/javascript\"&gt;\n(function(doc){\n var hasClass = function(el,className) {\n return (' ' + el.className + ' ').indexOf(' ' + className + ' ') &gt; -1;\n }\n doc.addEventListener('click', function(e){\n if(hasClass(e.target, 'click-me')){\n e.preventDefault();\n doSomething.call(e.target, e);\n }\n });\n})(document);\n\nfunction doSomething(event){\n console.log(this); // this will be the clicked element\n}\n&lt;/script&gt;\n&lt;!--... other head stuff ...--&gt;\n&lt;/head&gt;\n&lt;body&gt;\n\n&lt;!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 --&gt;\n&lt;button class=\"click-me\"&gt;Button 1&lt;/button&gt;\n&lt;input class=\"click-me\" type=\"button\" value=\"Button 2\"&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<h2>Cross-browser</h2>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;script type=\"text/javascript\"&gt;\n(function(doc){\n var cb_addEventListener = function(obj, evt, fnc) {\n // W3C model\n if (obj.addEventListener) {\n obj.addEventListener(evt, fnc, false);\n return true;\n } \n // Microsoft model\n else if (obj.attachEvent) {\n return obj.attachEvent('on' + evt, fnc);\n }\n // Browser don't support W3C or MSFT model, go on with traditional\n else {\n evt = 'on'+evt;\n if(typeof obj[evt] === 'function'){\n // Object already has a function on traditional\n // Let's wrap it with our own function inside another function\n fnc = (function(f1,f2){\n return function(){\n f1.apply(this,arguments);\n f2.apply(this,arguments);\n }\n })(obj[evt], fnc);\n }\n obj[evt] = fnc;\n return true;\n }\n return false;\n };\n var hasClass = function(el,className) {\n return (' ' + el.className + ' ').indexOf(' ' + className + ' ') &gt; -1;\n }\n\n cb_addEventListener(doc, 'click', function(e){\n if(hasClass(e.target, 'click-me')){\n e.preventDefault ? e.preventDefault() : e.returnValue = false;\n doSomething.call(e.target, e);\n }\n });\n})(document);\n\nfunction doSomething(event){\n console.log(this); // this will be the clicked element\n}\n&lt;/script&gt;\n&lt;!--... other head stuff ...--&gt;\n&lt;/head&gt;\n&lt;body&gt;\n\n&lt;!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 --&gt;\n&lt;button class=\"click-me\"&gt;Button 1&lt;/button&gt;\n&lt;input class=\"click-me\" type=\"button\" value=\"Button 2\"&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>You can run this before the document is ready, clicking the buttons will work because we attach the event to the document.</p>\n\n<p>Sources:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/5898656/test-if-an-element-contains-a-class\">Test if an element contains a class?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/1000597/event-preventdefault-function-not-working-in-ie\">event.preventDefault() function not working in IE</a></li>\n<li><a href=\"https://gist.github.com/eduardocereto/955642\" rel=\"nofollow noreferrer\">https://gist.github.com/eduardocereto/955642</a></li>\n</ul>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
I have seen the following methods of putting JavaScript code in an `<a>` tag: ``` function DoSomething() { ... return false; } ``` 1. `<a href="javascript:;" onClick="return DoSomething();">link</a>` 2. `<a href="javascript:DoSomething();">link</a>` 3. `<a href="javascript:void(0);" onClick="return DoSomething();">link</a>` 4. `<a href="#" onClick="return DoSomething();">link</a>` I understand the idea of trying to put a valid URL instead of just JavaScript code, just in case the user doesn't have JavaScript enabled. But for the purpose of this discussion, I need to assume JavaScript is enabled (they can't login without it). I personally like option 2 as it allows you to see what's going to be run–especially useful when debuging where there are parameters being passed to the function. I have used it quite a bit and haven't found browser issues. I have read that people recommend 4, because it gives the user a real link to follow, but really, # isn't "real". It will go absolutely no where. Is there one that isn't support or is really bad, when you know the user has JavaScript enabled? Related question: *[Href for JavaScript links: “#” or “javascript:void(0)”?](https://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0)*.
I quite enjoy [Matt Kruse's Javascript Best Practices article](http://web.archive.org/web/20190822202858/http://www.javascripttoolbox.com/bestpractices/). In it, he states that using the `href` section to execute JavaScript code is a bad idea. Even though you have stated that your users must have JavaScript enabled, there's no reason you can't have a simple HTML page that all your JavaScript links can point to for their `href` section in the event that someone happens to turn off JavaScript after logging in. I would highly encourage you to still allow this fallback mechanism. Something like this will adhere to "best practices" and accomplish your goal: ``` <a href="javascript_required.html" onclick="doSomething(); return false;">go</a> ```
245,916
<p>What is the best way to extract the MAC address from <code>ifconfig</code>'s output?</p> <p>Sample output:</p> <pre><code>bash-3.00# ifconfig eth0 eth0 Link encap:Ethernet HWaddr 1F:2E:19:10:3B:52 inet addr:127.0.0.66 Bcast:127.255.255.255 Mask:255.0.0.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 .... .... </code></pre> <p>Should I use cut, <a href="http://en.wikipedia.org/wiki/AWK" rel="noreferrer">AWK</a> or anything else, and what are the merits and demerits of one method over the other.</p>
[ { "answer_id": 245923, "author": "albertb", "author_id": 26715, "author_profile": "https://Stackoverflow.com/users/26715", "pm_score": 3, "selected": false, "text": "<p>Not sure whether there really are any advantages, but you can simply use awk:</p>\n\n<pre><code>ifconfig eth0 | awk '/HWaddr/ {print $5}'\n</code></pre>\n" }, { "answer_id": 245925, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 6, "selected": false, "text": "<p>I would use:</p>\n\n<pre><code>ifconfig eth0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'\n</code></pre>\n\n<p>The -o will cause grep to only print the part of the line that matches the expression. <code>[[:xdigit:]]{1,2}</code> will match 1 or 2 hexidecimal digits (Solaris doesn't output leading zeros).</p>\n" }, { "answer_id": 246523, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 5, "selected": false, "text": "<p>I like using /sbin/ip for these kind of tasks, because it is far easier to parse:</p>\n\n<pre><code>$ ip link show eth0\n2: eth0: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc pfifo_fast qlen 1000\n link/ether 00:0c:29:30:21:48 brd ff:ff:ff:ff:ff:ff\n</code></pre>\n\n<p>You can trivially get the mac address from this output with awk:</p>\n\n<pre><code>$ ip link show eth0 | awk '/ether/ {print $2}'\n00:0c:29:30:21:48\n</code></pre>\n\n<p>If you want to put a little more effort in, and parse more data out, I recommend using the -online argument to the ip command, which will let you treat every line as a new device:</p>\n\n<pre><code>$ ip -o link \n1: lo: &lt;LOOPBACK,UP,LOWER_UP&gt; mtu 16436 qdisc noqueue \\ link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00\n2: eth0: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc pfifo_fast qlen 1000\\ link/ether 00:0c:29:30:21:48 brd ff:ff:ff:ff:ff:ff\n3: eth1: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc pfifo_fast qlen 1000\\ link/ether 00:0c:29:30:21:52 brd ff:ff:ff:ff:ff:ff\n4: tun0: &lt;POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP&gt; mtu 1500 qdisc pfifo_fast qlen 100\\ link/[65534] \n5: sit0: &lt;NOARP&gt; mtu 1480 qdisc noop \\ link/sit 0.0.0.0 brd 0.0.0.0\n</code></pre>\n" }, { "answer_id": 4986764, "author": "xebeche", "author_id": 196133, "author_profile": "https://Stackoverflow.com/users/196133", "pm_score": 2, "selected": false, "text": "<p>Since the OP's example refers to Bash, here's a way to extract fields such as HWaddr without the use of additional tools:</p>\n\n<pre><code>x=$(ifconfig eth0) &amp;&amp; x=${x#*HWaddr } &amp;&amp; echo ${x%% *}\n</code></pre>\n\n<p>In the 1st step this assigns the ouput of ifconfig to x. The 2nd step removes everything before \"HWaddr \". In the final step everything after \" \" (the space behind the MAC) is removed.</p>\n\n<p>Reference: <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion\" rel=\"nofollow\">http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion</a></p>\n" }, { "answer_id": 5959167, "author": "phoxis", "author_id": 702361, "author_profile": "https://Stackoverflow.com/users/702361", "pm_score": 1, "selected": false, "text": "<p>How about this one:</p>\n\n<pre><code>ifconfig eth0 | grep -Eo ..\\(\\:..\\){5}\n</code></pre>\n\n<p>or more specifically </p>\n\n<pre><code>ifconfig eth0 | grep -Eo [:0-9A-F:]{2}\\(\\:[:0-9A-F:]{2}\\){5}\n</code></pre>\n\n<p>and also a simple one</p>\n\n<pre><code>ifconfig eth0 | head -n1 | tr -s ' ' | cut -d' ' -f5`\n</code></pre>\n" }, { "answer_id": 6334173, "author": "Michalis", "author_id": 528634, "author_profile": "https://Stackoverflow.com/users/528634", "pm_score": 7, "selected": false, "text": "<p>You can do a cat under <code>/sys/class/</code> </p>\n\n<pre><code>cat /sys/class/net/*/address\n</code></pre>\n\n<p>Specifically for <code>eth0</code></p>\n\n<pre><code>cat /sys/class/net/eth0/address\n</code></pre>\n" }, { "answer_id": 7583842, "author": "manafire", "author_id": 805003, "author_profile": "https://Stackoverflow.com/users/805003", "pm_score": 2, "selected": false, "text": "<p>I prefer the method described here (with slight modification): <a href=\"http://www.askdavetaylor.com/how_do_i_figure_out_my_ip_address_on_a_mac.html\" rel=\"nofollow\">http://www.askdavetaylor.com/how_do_i_figure_out_my_ip_address_on_a_mac.html</a></p>\n\n<pre><code>ifconfig | grep \"inet \" | grep -v 127.0.0.1 | cut -d \" \" -f2\n</code></pre>\n\n<p>Which you can then alias to a short 'myip' command for future use:</p>\n\n<pre><code>echo \"alias myip=\\\"ifconfig | grep 'inet ' | grep -v 127.0.0.1 | cut -d ' ' -f2\\\"\" &gt;&gt; ~/.bash_profile\n</code></pre>\n" }, { "answer_id": 12180593, "author": "Kyle Clegg", "author_id": 654870, "author_profile": "https://Stackoverflow.com/users/654870", "pm_score": 0, "selected": false, "text": "<p>Note: on OS X eth0 may not work. Use p2p0:</p>\n\n<pre><code>ifconfig p2p0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'\n</code></pre>\n" }, { "answer_id": 15238227, "author": "CRGreen", "author_id": 2092796, "author_profile": "https://Stackoverflow.com/users/2092796", "pm_score": 0, "selected": false, "text": "<p>This works for me on Mac&nbsp;OS&nbsp;X:</p>\n\n<pre><code>ifconfig en0 | grep -Eo ..\\(\\:..\\){5}\n</code></pre>\n\n<p>So does:</p>\n\n<pre><code>ifconfig en0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'\n</code></pre>\n\n<p>Both are variations of examples above.</p>\n" }, { "answer_id": 17108392, "author": "amar", "author_id": 2357995, "author_profile": "https://Stackoverflow.com/users/2357995", "pm_score": -1, "selected": false, "text": "<p>Output of ifconfig:</p>\n\n<pre><code>$ifconfig\n\neth0 Link encap:Ethernet HWaddr 00:1b:fc:72:84:12\n inet addr:172.16.1.13 Bcast:172.16.1.255 Mask:255.255.255.0\n inet6 addr: fe80::21b:fcff:fe72:8412/64 Scope:Link\n UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1\n RX packets:638661 errors:0 dropped:20 overruns:0 frame:0\n TX packets:93858 errors:0 dropped:0 overruns:0 carrier:2\n collisions:0 txqueuelen:1000\n RX bytes:101655955 (101.6 MB) TX bytes:42802760 (42.8 MB)\n Memory:dffc0000-e0000000\n\nlo Link encap:Local Loopback\n inet addr:127.0.0.1 Mask:255.0.0.0\n inet6 addr: ::1/128 Scope:Host\n UP LOOPBACK RUNNING MTU:16436 Metric:1\n RX packets:3796 errors:0 dropped:0 overruns:0 frame:0\n TX packets:3796 errors:0 dropped:0 overruns:0 carrier:0\n collisions:0 txqueuelen:0\n RX bytes:517624 (517.6 KB) TX bytes:517624 (517.6 KB)\n</code></pre>\n\n<p>The best way to extract MAC address is:</p>\n\n<pre><code>ifconfig | sed '1,1!d' | sed 's/.*HWaddr //' | sed 's/\\ .*//' | sed -e 's/:/-/g' &gt; mac_address\n</code></pre>\n" }, { "answer_id": 19874909, "author": "Ashwin Lakshmanan", "author_id": 2485265, "author_profile": "https://Stackoverflow.com/users/2485265", "pm_score": 0, "selected": false, "text": "<pre><code>ifconfig | grep -i hwaddr | cut -d ' ' -f11\n</code></pre>\n" }, { "answer_id": 24263330, "author": "yankeevader", "author_id": 3748399, "author_profile": "https://Stackoverflow.com/users/3748399", "pm_score": -1, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>ifconfig eth0 | grep HWaddr\n</code></pre>\n\n<p>or</p>\n\n<pre><code>ifconfig eth0 |grep HWaddr\n</code></pre>\n\n<p>This will pull just the MAC address and nothing else.</p>\n\n<p>You can change your MAC address to whatever you want:</p>\n\n<pre><code>ifconfig eth0 down,\nifconfig eth0 hw ether (new MAC address),\nifconfig eth0 up\n</code></pre>\n" }, { "answer_id": 26122717, "author": "Fernando_Jr", "author_id": 3284089, "author_profile": "https://Stackoverflow.com/users/3284089", "pm_score": 1, "selected": false, "text": "<p>On Ubuntu 14.04 in terminal </p>\n\n<pre><code>ifconfig | grep HW\n</code></pre>\n" }, { "answer_id": 29298216, "author": "Hugh", "author_id": 1787982, "author_profile": "https://Stackoverflow.com/users/1787982", "pm_score": 0, "selected": false, "text": "<p>Nice and quick one:</p>\n\n<pre><code>ifconfig eth0 | grep HWaddr | cut -d ' ' -f 11\n</code></pre>\n" }, { "answer_id": 37125657, "author": "Dogukan", "author_id": 3916140, "author_profile": "https://Stackoverflow.com/users/3916140", "pm_score": 0, "selected": false, "text": "<p>I needed to get MAC address of the active adapter, so ended up using this command. </p>\n\n<pre><code>ifconfig -a | awk '/^[a-z]/ { iface=$1; mac=$NF; next } /inet addr:/ { print mac }' | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'\n</code></pre>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 37580835, "author": "nPcomp", "author_id": 5074973, "author_profile": "https://Stackoverflow.com/users/5074973", "pm_score": 2, "selected": false, "text": "<p>For Ubuntu/Debian</p>\n\n<pre><code>ifconfig | grep HW | awk '{print $5}'\n</code></pre>\n\n<p>For Rhat or CentOs try </p>\n\n<pre><code>ip add | grep link/ether | awk '{print $2}'\n</code></pre>\n" }, { "answer_id": 52401954, "author": "Sateesh Pasala", "author_id": 5682336, "author_profile": "https://Stackoverflow.com/users/5682336", "pm_score": 0, "selected": false, "text": "<p>ifconfig en0 | grep ether - for wired mac address </p>\n\n<p>ifconfig en1 | grep ether - for wireless mac address </p>\n" }, { "answer_id": 57681372, "author": "Adel Skn", "author_id": 7027431, "author_profile": "https://Stackoverflow.com/users/7027431", "pm_score": 0, "selected": false, "text": "<p>this worked for me </p>\n\n<pre><code>ifconfig eth0 | grep -o -E ..:..:..:..:..:..\n</code></pre>\n\n<p>instead of <code>eth0</code> you can write the interface you need it's mac address </p>\n" }, { "answer_id": 63900424, "author": "Tarun Bansal", "author_id": 12396277, "author_profile": "https://Stackoverflow.com/users/12396277", "pm_score": 1, "selected": false, "text": "<pre><code>ifconfig en1 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' \n</code></pre>\n<ul>\n<li>Replace &quot;en1&quot; with the name of the nic card &quot;eth0&quot; or remove altogether &quot;en1&quot; - easy and useful solution.</li>\n</ul>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29405/" ]
What is the best way to extract the MAC address from `ifconfig`'s output? Sample output: ``` bash-3.00# ifconfig eth0 eth0 Link encap:Ethernet HWaddr 1F:2E:19:10:3B:52 inet addr:127.0.0.66 Bcast:127.255.255.255 Mask:255.0.0.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 .... .... ``` Should I use cut, [AWK](http://en.wikipedia.org/wiki/AWK) or anything else, and what are the merits and demerits of one method over the other.
You can do a cat under `/sys/class/` ``` cat /sys/class/net/*/address ``` Specifically for `eth0` ``` cat /sys/class/net/eth0/address ```
245,929
<p>Some APIs, like the WebClient, use the <a href="http://msdn.microsoft.com/en-us/library/wewwczdw.aspx" rel="nofollow noreferrer">Event-based Async pattern</a>. While this looks simple, and probably works well in a loosely coupled app (say, BackgroundWorker in a UI), it doesn't chain together very well. </p> <p>For instance, here's a program that's multithreaded so the async work doesn't block. (Imagine this is going in a server app and called hundreds of times -- you don't want to block your ThreadPool threads.) We get 3 local variables ("state"), then make 2 async calls, with the result of the first feeding into the second request (so they can't go parallel). State could mutate too (easy to add). </p> <p>Using WebClient, things end up like the following (or you end up creating a bunch of objects to act like closures):</p> <pre><code>using System; using System.Net; class Program { static void onEx(Exception ex) { Console.WriteLine(ex.ToString()); } static void Main() { var url1 = new Uri(Console.ReadLine()); var url2 = new Uri(Console.ReadLine()); var someData = Console.ReadLine(); var webThingy = new WebClient(); DownloadDataCompletedEventHandler first = null; webThingy.DownloadDataCompleted += first = (o, res1) =&gt; { if (res1.Error != null) { onEx(res1.Error); return; } webThingy.DownloadDataCompleted -= first; webThingy.DownloadDataCompleted += (o2, res2) =&gt; { if (res2.Error != null) { onEx(res2.Error); return; } try { Console.WriteLine(someData + res2.Result); } catch (Exception ex) { onEx(ex); } }; try { webThingy.DownloadDataAsync(new Uri(url2.ToString() + "?data=" + res1.Result)); } catch (Exception ex) { onEx(ex); } }; try { webThingy.DownloadDataAsync(url1); } catch (Exception ex) { onEx(ex); } Console.WriteLine("Keeping process alive"); Console.ReadLine(); } </code></pre> <p>}</p> <p>Is there an generic way to refactor this event-based async pattern? (I.e. not have to write detailed extension methods for each API thats like this?) BeginXXX and EndXXX make it easy, but this event way doesn't seem to offer any way.</p>
[ { "answer_id": 246310, "author": "Tim Robinson", "author_id": 32133, "author_profile": "https://Stackoverflow.com/users/32133", "pm_score": 2, "selected": false, "text": "<p>In the past I've implemented this using an iterator method: every time you want another URL requested, you use \"yield return\" to pass control back to the main program. Once the request finishes, the main program calls back into your iterator to execute the next piece of work.</p>\n\n<p>You're effectively using the C# compiler to write a state machine for you. The advantage is that you can write normal-looking C# code in the iterator method to drive the whole thing.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Net;\n\nclass Program\n{\n static void onEx(Exception ex) {\n Console.WriteLine(ex.ToString());\n }\n\n static IEnumerable&lt;Uri&gt; Downloader(Func&lt;DownloadDataCompletedEventArgs&gt; getLastResult) {\n Uri url1 = new Uri(Console.ReadLine());\n Uri url2 = new Uri(Console.ReadLine());\n string someData = Console.ReadLine();\n yield return url1;\n\n DownloadDataCompletedEventArgs res1 = getLastResult();\n yield return new Uri(url2.ToString() + \"?data=\" + res1.Result);\n\n DownloadDataCompletedEventArgs res2 = getLastResult();\n Console.WriteLine(someData + res2.Result);\n }\n\n static void StartNextRequest(WebClient webThingy, IEnumerator&lt;Uri&gt; enumerator) {\n if (enumerator.MoveNext()) {\n Uri uri = enumerator.Current;\n\n try {\n Console.WriteLine(\"Requesting {0}\", uri);\n webThingy.DownloadDataAsync(uri);\n } catch (Exception ex) { onEx(ex); }\n }\n else\n Console.WriteLine(\"Finished\");\n }\n\n static void Main() {\n DownloadDataCompletedEventArgs lastResult = null;\n Func&lt;DownloadDataCompletedEventArgs&gt; getLastResult = delegate { return lastResult; };\n IEnumerable&lt;Uri&gt; enumerable = Downloader(getLastResult);\n using (IEnumerator&lt;Uri&gt; enumerator = enumerable.GetEnumerator())\n {\n WebClient webThingy = new WebClient();\n webThingy.DownloadDataCompleted += delegate(object sender, DownloadDataCompletedEventArgs e) {\n if (e.Error == null) {\n lastResult = e;\n StartNextRequest(webThingy, enumerator);\n }\n else\n onEx(e.Error);\n };\n\n StartNextRequest(webThingy, enumerator);\n }\n\n Console.WriteLine(\"Keeping process alive\");\n Console.ReadLine();\n }\n}\n</code></pre>\n" }, { "answer_id": 643520, "author": "Anton Tykhyy", "author_id": 77724, "author_profile": "https://Stackoverflow.com/users/77724", "pm_score": 2, "selected": true, "text": "<p>You might want to look into <code>F#</code>. <code>F#</code> can automate this coding for you with its «workflow» feature. The '08 PDC presentation of <code>F#</code> dealt with asynchronous web requests using a standard library workflow called <code>async</code>, which handles the <code>BeginXXX</code>/<code>EndXXX</code> pattern, but you can write a workflow for the event pattern without much difficulty, or find a canned one. And F# works well with C#.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27012/" ]
Some APIs, like the WebClient, use the [Event-based Async pattern](http://msdn.microsoft.com/en-us/library/wewwczdw.aspx). While this looks simple, and probably works well in a loosely coupled app (say, BackgroundWorker in a UI), it doesn't chain together very well. For instance, here's a program that's multithreaded so the async work doesn't block. (Imagine this is going in a server app and called hundreds of times -- you don't want to block your ThreadPool threads.) We get 3 local variables ("state"), then make 2 async calls, with the result of the first feeding into the second request (so they can't go parallel). State could mutate too (easy to add). Using WebClient, things end up like the following (or you end up creating a bunch of objects to act like closures): ``` using System; using System.Net; class Program { static void onEx(Exception ex) { Console.WriteLine(ex.ToString()); } static void Main() { var url1 = new Uri(Console.ReadLine()); var url2 = new Uri(Console.ReadLine()); var someData = Console.ReadLine(); var webThingy = new WebClient(); DownloadDataCompletedEventHandler first = null; webThingy.DownloadDataCompleted += first = (o, res1) => { if (res1.Error != null) { onEx(res1.Error); return; } webThingy.DownloadDataCompleted -= first; webThingy.DownloadDataCompleted += (o2, res2) => { if (res2.Error != null) { onEx(res2.Error); return; } try { Console.WriteLine(someData + res2.Result); } catch (Exception ex) { onEx(ex); } }; try { webThingy.DownloadDataAsync(new Uri(url2.ToString() + "?data=" + res1.Result)); } catch (Exception ex) { onEx(ex); } }; try { webThingy.DownloadDataAsync(url1); } catch (Exception ex) { onEx(ex); } Console.WriteLine("Keeping process alive"); Console.ReadLine(); } ``` } Is there an generic way to refactor this event-based async pattern? (I.e. not have to write detailed extension methods for each API thats like this?) BeginXXX and EndXXX make it easy, but this event way doesn't seem to offer any way.
You might want to look into `F#`. `F#` can automate this coding for you with its «workflow» feature. The '08 PDC presentation of `F#` dealt with asynchronous web requests using a standard library workflow called `async`, which handles the `BeginXXX`/`EndXXX` pattern, but you can write a workflow for the event pattern without much difficulty, or find a canned one. And F# works well with C#.
245,947
<p>I have <code>www.example.com</code> and also <code>store.example.com</code>. (Yes they are subdomains of the same parent domain)</p> <p><code>store.example.com</code> is on ASP.NET 1.1</p> <p><code>www.example.com</code> is on ASP.NET 3.5</p> <p>I want to know what options are available for sharing 'session' data between the two sites. I need some kind of shared login and also the abiltity to track user activity no matter which site they started on. </p> <ul> <li><p>Obvously I could send a GUID when transitioning from one site to the other. </p></li> <li><p>I also believe I can set a cookie which can be shared across subdomains. I've never tried this but it is most likely what I will do. I'm not yet clear if this is a true 'session' cookie or if I just set a low expiration date?</p></li> </ul> <p>Are these my best options or is there somethin else?</p>
[ { "answer_id": 245965, "author": "Eli", "author_id": 27580, "author_profile": "https://Stackoverflow.com/users/27580", "pm_score": -1, "selected": false, "text": "<p>Here is how you would do it in PHP:</p>\n\n<p><a href=\"http://php.dtbaker.com.au/post/keeping_cookies_across_multiple_sub_domains.html\" rel=\"nofollow noreferrer\">http://php.dtbaker.com.au/post/keeping_cookies_across_multiple_sub_domains.html</a></p>\n" }, { "answer_id": 246021, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 2, "selected": false, "text": "<p>The important thing to do is to set the cookie domain properly.</p>\n\n<p>It the domain is set to <strong>.example.com</strong> (note the leading period) then it should be included in requests to example.com and also all of the subdomains.</p>\n\n<p>I assume you have a way of sharing the data between your different subdomains.</p>\n" }, { "answer_id": 1271463, "author": "TWith2Sugars", "author_id": 35389, "author_profile": "https://Stackoverflow.com/users/35389", "pm_score": 3, "selected": false, "text": "<p>If you want to share sessions between different apps there are a few things you need to do.</p>\n\n<p>First you'll need to run the session state in SQL mode. \nAt this point I found out that the SQL session state takes the machine key and your _appDomainAppId to generate a key for your app to access it's own session data. So we need to keep these the same between all your apps.</p>\n\n<p>In the web configs of your apps you'll need to use the same machine key. This can be any where inside the system.web tags E.G:</p>\n\n<pre><code> &lt;machineKey decryptionKey=\"EDCDA6DF458176504BBCC720A4E29348E252E652591179E2\" validationKey=\"CC482ED6B5D3569819B3C8F07AC3FA855B2FED7F0130F55D8405597C796457A2F5162D35C69B61F257DB5EFE6BC4F6CEBDD23A4118C4519F55185CB5EB3DFE61\"/&gt;\n</code></pre>\n\n<p>Add an appSetting \"ApplicationName\" and give it name (this has to be the same for both apps)\nYou'll then need to create a shared session module which will change the _appDomainAppId. The one below is what I use.</p>\n\n<pre><code> namespace YourApp\n{\n using System.Configuration;\n using System.Reflection;\n using System.Web;\n\n /// &lt;summary&gt;class used for sharing the session between app domains&lt;/summary&gt;\n public class SharedSessionModule : IHttpModule\n {\n #region IHttpModule Members\n /// &lt;summary&gt;\n /// Initializes a module and prepares it to handle requests.\n /// &lt;/summary&gt;\n /// &lt;param name=\"context\"&gt;An &lt;see cref=\"T:System.Web.HttpApplication\"/&gt;\n /// that provides access to the methods,\n /// properties, and events common to all application objects within an ASP.NET\n /// application&lt;/param&gt;\n /// &lt;created date=\"5/31/2008\" by=\"Peter Femiani\"/&gt;\n public void Init(HttpApplication context)\n {\n // Get the app name from config file...\n string appName = ConfigurationManager.AppSettings[\"ApplicationName\"];\n if (!string.IsNullOrEmpty(appName))\n {\n FieldInfo runtimeInfo = typeof(HttpRuntime).GetField(\"_theRuntime\", BindingFlags.Static | BindingFlags.NonPublic);\n HttpRuntime theRuntime = (HttpRuntime)runtimeInfo.GetValue(null);\n FieldInfo appNameInfo = typeof(HttpRuntime).GetField(\"_appDomainAppId\", BindingFlags.Instance | BindingFlags.NonPublic);\n appNameInfo.SetValue(theRuntime, appName);\n }\n }\n\n /// &lt;summary&gt;\n /// Disposes of the resources (other than memory) used by the module that\n /// implements &lt;see cref=\"T:System.Web.IHttpModule\"/&gt;.\n /// &lt;/summary&gt;\n /// &lt;created date=\"5/31/2008\" by=\"Peter Femiani\"/&gt;\n public void Dispose()\n {\n }\n #endregion\n }\n}\n</code></pre>\n\n<p>In the web config you'll need to add this module:</p>\n\n<pre><code> &lt;add name=\"SharedSessionModule\" type=\"YourApp.SharedSessionModule, YourApp, Version=1.0.0.0, Culture=neutral\" /&gt;\n</code></pre>\n\n<p>Final thing to do is to allow the session cookie to pass between domains...like so</p>\n\n<blockquote>\n<pre><code> var session = HttpContext.Current.Session;\n var request = HttpContext.Current.Request;\n var cookie = request.Cookies[\"ASP.NET_SessionId\"];\n if (cookie != null &amp;&amp; session != null &amp;&amp; session.SessionID != null)\n {\n cookie.Value = session.SessionID;\n cookie.Domain = \"yourappdomain.com\";\n\n // the full stop prefix denotes all sub domains\n cookie.Path = \"/\"; // default session cookie path root\n }\n</code></pre>\n</blockquote>\n\n<p>And that should do the trick.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
I have `www.example.com` and also `store.example.com`. (Yes they are subdomains of the same parent domain) `store.example.com` is on ASP.NET 1.1 `www.example.com` is on ASP.NET 3.5 I want to know what options are available for sharing 'session' data between the two sites. I need some kind of shared login and also the abiltity to track user activity no matter which site they started on. * Obvously I could send a GUID when transitioning from one site to the other. * I also believe I can set a cookie which can be shared across subdomains. I've never tried this but it is most likely what I will do. I'm not yet clear if this is a true 'session' cookie or if I just set a low expiration date? Are these my best options or is there somethin else?
If you want to share sessions between different apps there are a few things you need to do. First you'll need to run the session state in SQL mode. At this point I found out that the SQL session state takes the machine key and your \_appDomainAppId to generate a key for your app to access it's own session data. So we need to keep these the same between all your apps. In the web configs of your apps you'll need to use the same machine key. This can be any where inside the system.web tags E.G: ``` <machineKey decryptionKey="EDCDA6DF458176504BBCC720A4E29348E252E652591179E2" validationKey="CC482ED6B5D3569819B3C8F07AC3FA855B2FED7F0130F55D8405597C796457A2F5162D35C69B61F257DB5EFE6BC4F6CEBDD23A4118C4519F55185CB5EB3DFE61"/> ``` Add an appSetting "ApplicationName" and give it name (this has to be the same for both apps) You'll then need to create a shared session module which will change the \_appDomainAppId. The one below is what I use. ``` namespace YourApp { using System.Configuration; using System.Reflection; using System.Web; /// <summary>class used for sharing the session between app domains</summary> public class SharedSessionModule : IHttpModule { #region IHttpModule Members /// <summary> /// Initializes a module and prepares it to handle requests. /// </summary> /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> /// that provides access to the methods, /// properties, and events common to all application objects within an ASP.NET /// application</param> /// <created date="5/31/2008" by="Peter Femiani"/> public void Init(HttpApplication context) { // Get the app name from config file... string appName = ConfigurationManager.AppSettings["ApplicationName"]; if (!string.IsNullOrEmpty(appName)) { FieldInfo runtimeInfo = typeof(HttpRuntime).GetField("_theRuntime", BindingFlags.Static | BindingFlags.NonPublic); HttpRuntime theRuntime = (HttpRuntime)runtimeInfo.GetValue(null); FieldInfo appNameInfo = typeof(HttpRuntime).GetField("_appDomainAppId", BindingFlags.Instance | BindingFlags.NonPublic); appNameInfo.SetValue(theRuntime, appName); } } /// <summary> /// Disposes of the resources (other than memory) used by the module that /// implements <see cref="T:System.Web.IHttpModule"/>. /// </summary> /// <created date="5/31/2008" by="Peter Femiani"/> public void Dispose() { } #endregion } } ``` In the web config you'll need to add this module: ``` <add name="SharedSessionModule" type="YourApp.SharedSessionModule, YourApp, Version=1.0.0.0, Culture=neutral" /> ``` Final thing to do is to allow the session cookie to pass between domains...like so > > > ``` > var session = HttpContext.Current.Session; > var request = HttpContext.Current.Request; > var cookie = request.Cookies["ASP.NET_SessionId"]; > if (cookie != null && session != null && session.SessionID != null) > { > cookie.Value = session.SessionID; > cookie.Domain = "yourappdomain.com"; > > // the full stop prefix denotes all sub domains > cookie.Path = "/"; // default session cookie path root > } > > ``` > > And that should do the trick.
245,957
<pre><code>void f(cli::array&lt;PointF&gt; ^points){ PointF&amp; a = points[0]; // and so on... } </code></pre> <p>Compile error at line 2. </p> <pre><code>.\ndPanel.cpp(52) : error C2440: 'initializing' : cannot convert from 'System::Drawing::PointF' to 'System::Drawing::PointF &amp;' An object from the gc heap (element of a managed array) cannot be converted to a native reference </code></pre> <p>What is the managed way to declare a reference variable?</p>
[ { "answer_id": 245981, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 1, "selected": false, "text": "<p>You need to use the <code>gcroot</code> template from <code>vcclr.h</code> file:</p>\n\n<p>These are samples from MSDN:</p>\n\n<pre><code>// mcpp_gcroot.cpp\n// compile with: /clr\n#include &lt;vcclr.h&gt;\nusing namespace System;\n\nclass CppClass {\npublic:\n gcroot&lt;String^&gt; str; // can use str as if it were String^\n CppClass() {}\n};\n\nint main() {\n CppClass c;\n c.str = gcnew String(\"hello\");\n Console::WriteLine( c.str ); // no cast required\n}\n\n// mcpp_gcroot_2.cpp\n// compile with: /clr\n// compile with: /clr\n#include &lt;vcclr.h&gt;\nusing namespace System;\n\nstruct CppClass {\n gcroot&lt;String ^&gt; * str;\n CppClass() : str(new gcroot&lt;String ^&gt;) {}\n\n ~CppClass() { delete str; }\n\n};\n\nint main() {\n CppClass c;\n *c.str = gcnew String(\"hello\");\n Console::WriteLine( *c.str );\n}\n\n// mcpp_gcroot_3.cpp\n// compile with: /clr\n#include &lt; vcclr.h &gt;\nusing namespace System;\n\npublic value struct V {\n String^ str;\n};\n\nclass Native {\npublic:\n gcroot&lt; V^ &gt; v_handle;\n};\n\nint main() {\n Native native;\n V v;\n native.v_handle = v;\n native.v_handle-&gt;str = \"Hello\";\n Console::WriteLine(\"String in V: {0}\", native.v_handle-&gt;str);\n}\n</code></pre>\n\n<p>You will find out more <a href=\"http://msdn.microsoft.com/en-us/library/aeb4be4k.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 246076, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 0, "selected": false, "text": "<p>And here is your code changed to use gcroot:</p>\n\n<pre><code>void f(cli::array&lt;gcroot&lt;PointF ^&gt;&gt; points){\n gcroot&lt;PointF ^&gt; a = points[0];\n // and so on... }\n</code></pre>\n" }, { "answer_id": 246761, "author": "Stu Mackellar", "author_id": 28591, "author_profile": "https://Stackoverflow.com/users/28591", "pm_score": 3, "selected": true, "text": "<p>If you just want to declare a reference to the first PointF in the array then you need to use a <a href=\"http://msdn.microsoft.com/en-us/library/8903062a(VS.80).aspx\" rel=\"nofollow noreferrer\">tracking reference</a> (%):</p>\n\n<pre><code>void f(cli::array&lt;PointF&gt;^ points)\n{ \n PointF% a = points[0];\n}\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45603/" ]
``` void f(cli::array<PointF> ^points){ PointF& a = points[0]; // and so on... } ``` Compile error at line 2. ``` .\ndPanel.cpp(52) : error C2440: 'initializing' : cannot convert from 'System::Drawing::PointF' to 'System::Drawing::PointF &' An object from the gc heap (element of a managed array) cannot be converted to a native reference ``` What is the managed way to declare a reference variable?
If you just want to declare a reference to the first PointF in the array then you need to use a [tracking reference](http://msdn.microsoft.com/en-us/library/8903062a(VS.80).aspx) (%): ``` void f(cli::array<PointF>^ points) { PointF% a = points[0]; } ```
245,975
<p>To implement "method-missing"-semantics and such in C# 4.0, you have to implement IDynamicObject:</p> <pre><code>public interface IDynamicObject { MetaObject GetMetaObject(Expression parameter); } </code></pre> <p>As far as I can figure out IDynamicObject is actually part of the DLR, so it is not new. But I have not been able to find much documentation on it.</p> <p>There are some very simple example implementations out there (f.x. <a href="http://blogs.msdn.com/cburrows/archive/2008/10/28/c-dynamic-part-ii.aspx" rel="noreferrer">here</a> and <a href="http://code.msdn.microsoft.com/csharpfuture/Release/ProjectReleases.aspx?ReleaseId=1686" rel="noreferrer">here</a>), but could anyone point me to more complete implementations or some real documentation?</p> <p>Especially, how exactly are you supposed to handle the "parameter"-parameter?</p>
[ { "answer_id": 246629, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 0, "selected": false, "text": "<p>Here is what I have figured out so far:</p>\n\n<p>The Dynamic Language Runtime is currently maintained as part of the <a href=\"http://www.codeplex.com/IronPython\" rel=\"nofollow noreferrer\">IronPython project</a>. So that is the best place to go for information.</p>\n\n<p>The easiest way to implement a class supporting IDynamicObject seems to be to derive from <a href=\"http://www.codeplex.com/IronPython/SourceControl/FileView.aspx?itemId=650479&amp;changeSetId=42603\" rel=\"nofollow noreferrer\">Microsoft.Scripting.Actions.Dynamic</a> and override the relevant methods, for instance the Call-method to implement function call semantics. It looks like Microsoft.Scripting.Actions.Dynamic hasn't been included in the CTP, but the one from IronPython 2.0 looks like it will work.</p>\n\n<p>I am still unclear on the exact meaning of the \"parameter\"-parameter, but it seems to provide context for the binding of the dynamic-object.</p>\n" }, { "answer_id": 246637, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 0, "selected": false, "text": "<p>This presentation also provides a lot of information about the DLR:</p>\n\n<ul>\n<li><a href=\"http://channel9.msdn.com/pdc2008/TL10/\" rel=\"nofollow noreferrer\">Deep Dive: Dynamic Languages in Microsoft .NET</a> by Jim Hugunin.</li>\n</ul>\n" }, { "answer_id": 246693, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 3, "selected": true, "text": "<p>The short answer is that the MetaObject is what's responsible for actually generating the code that will be run at the call site. The mechanism that it uses for this is LINQ expression trees, which have been enhanced in the DLR. So instead of starting with an object, it starts with an expression that represents the object, and ultimately it's going to need to return an expression tree that describes the action to be taken.</p>\n\n<p>When playing with this, please remember that the version of System.Core in the CTP was taken from a snapshot at the end of August. It doesn't correspond very cleanly to any particular beta of IronPython. A number of changes have been made to the DLR since then. </p>\n\n<p>Also, for compatibility with the CLR v2 System.Core, releases of IronPython starting with either beta 4 or beta 5 now rename everything in that's in the System namespace to be in the Microsoft namespace instead.</p>\n" }, { "answer_id": 249697, "author": "Mike Hadlow", "author_id": 3995, "author_profile": "https://Stackoverflow.com/users/3995", "pm_score": 2, "selected": false, "text": "<p>I just blogged about how to do this here:</p>\n\n<p><a href=\"http://mikehadlow.blogspot.com/2008/10/dynamic-dispatch-in-c-40.html\" rel=\"nofollow noreferrer\">http://mikehadlow.blogspot.com/2008/10/dynamic-dispatch-in-c-40.html</a></p>\n" }, { "answer_id": 260440, "author": "Tobias Hertkorn", "author_id": 33827, "author_profile": "https://Stackoverflow.com/users/33827", "pm_score": 2, "selected": false, "text": "<p>If you want an end to end sample including source code, resulting in a dynamic object that stores value for arbitrary properties in a Dictionary then <a href=\"http://saftsack.fs.uni-bayreuth.de/~dun3/archives/first-look-ducktyping-c-4-0-idynamicobject-metaobject/202.html\" rel=\"nofollow noreferrer\" title=\"A first look at Duck Typing in C# 4.0\">my post \"A first look at Duck Typing in C# 4.0\"</a> could be right for you. I wrote that post to show how dynamic object can be cast to statically typed interfaces. It has a complete working implementation of a Duck that is a IDynamicObject and may acts like a IQuack.</p>\n\n<p>If you need more information contact me on my blog and I will help you along, as good as I can.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/245975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5542/" ]
To implement "method-missing"-semantics and such in C# 4.0, you have to implement IDynamicObject: ``` public interface IDynamicObject { MetaObject GetMetaObject(Expression parameter); } ``` As far as I can figure out IDynamicObject is actually part of the DLR, so it is not new. But I have not been able to find much documentation on it. There are some very simple example implementations out there (f.x. [here](http://blogs.msdn.com/cburrows/archive/2008/10/28/c-dynamic-part-ii.aspx) and [here](http://code.msdn.microsoft.com/csharpfuture/Release/ProjectReleases.aspx?ReleaseId=1686)), but could anyone point me to more complete implementations or some real documentation? Especially, how exactly are you supposed to handle the "parameter"-parameter?
The short answer is that the MetaObject is what's responsible for actually generating the code that will be run at the call site. The mechanism that it uses for this is LINQ expression trees, which have been enhanced in the DLR. So instead of starting with an object, it starts with an expression that represents the object, and ultimately it's going to need to return an expression tree that describes the action to be taken. When playing with this, please remember that the version of System.Core in the CTP was taken from a snapshot at the end of August. It doesn't correspond very cleanly to any particular beta of IronPython. A number of changes have been made to the DLR since then. Also, for compatibility with the CLR v2 System.Core, releases of IronPython starting with either beta 4 or beta 5 now rename everything in that's in the System namespace to be in the Microsoft namespace instead.
246,007
<p>When I type <code>uname -a</code>, it gives the following output.</p> <pre><code>Linux mars 2.6.9-67.0.15.ELsmp #1 SMP Tue Apr 22 13:50:33 EDT 2008 i686 i686 i386 GNU/Linux </code></pre> <p>How can I know from this that the given OS is 32 or 64 bit?</p> <p>This is useful when writing <code>configure</code> scripts, for example: what architecture am I building for?</p>
[ { "answer_id": 246012, "author": "Thomas Watnedal", "author_id": 4059, "author_profile": "https://Stackoverflow.com/users/4059", "pm_score": 7, "selected": false, "text": "<p>If you were running a 64 bit platform you would see x86_64 or something very similar in the output from <a href=\"http://manpages.ubuntu.com/manpages/intrepid/man1/uname.html\" rel=\"noreferrer\" title=\"uname\">uname</a> -a</p>\n\n<p>To get your specific machine hardware name run</p>\n\n<pre><code>uname -m\n</code></pre>\n\n<p>You can also call</p>\n\n<pre><code>getconf LONG_BIT\n</code></pre>\n\n<p>which returns either 32 or 64</p>\n" }, { "answer_id": 246014, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 11, "selected": true, "text": "<p>Try <a href=\"http://linuxmanpages.net/manpages/fedora16/man1/uname.1.html\" rel=\"noreferrer\"><code>uname -m</code></a>. Which is short of <code>uname --machine</code> and it outputs: </p>\n\n<pre><code>x86_64 ==&gt; 64-bit kernel\ni686 ==&gt; 32-bit kernel\n</code></pre>\n\n<hr>\n\n<p>Otherwise, <strong>not for the Linux kernel, but for the CPU</strong>, you type:</p>\n\n<pre><code>cat /proc/cpuinfo\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>grep flags /proc/cpuinfo\n</code></pre>\n\n<p>Under \"flags\" parameter, you will see various values: see \"<a href=\"https://unix.stackexchange.com/a/43540\">What do the flags in /proc/cpuinfo mean?</a>\"\nAmong them, one is named <code>lm</code>: <code>Long Mode</code> (<a href=\"http://en.wikipedia.org/wiki/X86-64\" rel=\"noreferrer\">x86-64</a>: amd64, also known as Intel 64, i.e. 64-bit capable)</p>\n\n<pre><code>lm ==&gt; 64-bit processor\n</code></pre>\n\n<p>Or <a href=\"http://linux.die.net/man/1/lshw\" rel=\"noreferrer\">using <code>lshw</code></a> (as mentioned <a href=\"https://stackoverflow.com/a/32717681/6309\">below</a> by <a href=\"https://stackoverflow.com/users/4637585/rolf-of-saxony\">Rolf of Saxony</a>), without <code>sudo</code> (just for grepping the cpu width):</p>\n\n<pre><code>lshw -class cpu|grep \"^ width\"|uniq|awk '{print $2}'\n</code></pre>\n\n<p><strong>Note: you can have a 64-bit CPU with a 32-bit kernel installed</strong>.<br>\n(as <a href=\"https://stackoverflow.com/users/637866/ysdx\">ysdx</a> mentions in <a href=\"https://stackoverflow.com/a/32665383/6309\">his/her own answer</a>, \"Nowadays, a system can be <strong><a href=\"https://wiki.debian.org/Multiarch\" rel=\"noreferrer\">multiarch</a></strong> so it does not make sense anyway. You might want to find the default target of the compiler\")</p>\n" }, { "answer_id": 246018, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 3, "selected": false, "text": "<p>That system is 32bit. iX86 in <code>uname</code> means it is a 32-bit architecture. If it was 64 bit, it would return </p>\n\n<pre><code>Linux mars 2.6.9-67.0.15.ELsmp #1 SMP Tue Apr 22 13:50:33 EDT 2008 x86_64 i686 x86_64 x86_64 GNU/Linux\n</code></pre>\n" }, { "answer_id": 246020, "author": "Denis R.", "author_id": 32015, "author_profile": "https://Stackoverflow.com/users/32015", "pm_score": 3, "selected": false, "text": "<p>If you have a 64-bit OS, instead of i686, you have <code>x86_64</code> or <code>ia64</code> in the output of <code>uname -a</code>. In that you do not have any of these two strings; you have a 32-bit OS (note that this does not mean that your CPU is not 64-bit).</p>\n" }, { "answer_id": 6200504, "author": "kaiwan", "author_id": 779269, "author_profile": "https://Stackoverflow.com/users/779269", "pm_score": 3, "selected": false, "text": "<p>With respect to <a href=\"https://stackoverflow.com/a/246012/63550\">the answer \"getconf LONG_BIT\"</a>.</p>\n\n<p>I wrote a simple function to do it in 'C':</p>\n\n<pre><code>/*\n * check_os_64bit\n *\n * Returns integer:\n * 1 = it is a 64-bit OS\n * 0 = it is NOT a 64-bit OS (probably 32-bit)\n * &lt; 0 = failure\n * -1 = popen failed\n * -2 = fgets failed\n *\n * **WARNING**\n * Be CAREFUL! Just testing for a boolean return may not cut it\n * with this (trivial) implementation! (Think of when it fails,\n * returning -ve; this could be seen as non-zero &amp; therefore true!)\n * Suggestions?\n */\nstatic int check_os_64bit(void)\n{\n FILE *fp=NULL;\n char cb64[3];\n\n fp = popen (\"getconf LONG_BIT\", \"r\");\n if (!fp)\n return -1;\n\n if (!fgets(cb64, 3, fp))\n return -2;\n\n if (!strncmp (cb64, \"64\", 3)) {\n return 1;\n }\n else {\n return 0;\n }\n}\n</code></pre>\n\n<p>Good idea, the 'getconf'!</p>\n" }, { "answer_id": 7030871, "author": "Reed Hedges", "author_id": 39686, "author_profile": "https://Stackoverflow.com/users/39686", "pm_score": 4, "selected": false, "text": "<p>I was wondering about this specifically for building software in <a href=\"http://en.wikipedia.org/wiki/Debian\">Debian</a> (the installed Debian system can be a 32-bit version with a 32 bit kernel, libraries, etc., or it can be a 64-bit version with stuff compiled for the 64-bit rather than 32-bit compatibility mode). </p>\n\n<p>Debian packages themselves need to know what architecture they are for (of course) when they actually create the package with all of its metadata, including platform architecture, so there is a packaging tool that outputs it for other packaging tools and scripts to use, called <strong>dpkg-architecture</strong>. It includes both what it's configured to build for, as well as the current host. (Normally these are the same though.) Example output on a 64-bit machine:</p>\n\n<pre><code>DEB_BUILD_ARCH=amd64\nDEB_BUILD_ARCH_OS=linux\nDEB_BUILD_ARCH_CPU=amd64\nDEB_BUILD_GNU_CPU=x86_64\nDEB_BUILD_GNU_SYSTEM=linux-gnu\nDEB_BUILD_GNU_TYPE=x86_64-linux-gnu\nDEB_HOST_ARCH=amd64\nDEB_HOST_ARCH_OS=linux\nDEB_HOST_ARCH_CPU=amd64\nDEB_HOST_GNU_CPU=x86_64\nDEB_HOST_GNU_SYSTEM=linux-gnu\nDEB_HOST_GNU_TYPE=x86_64-linux-gnu\n</code></pre>\n\n<p>You can print just one of those variables or do a test against their values with command line options to <a href=\"http://en.wikipedia.org/wiki/Dpkg\">dpkg</a>-architecture. </p>\n\n<p>I have no idea how dpkg-architecture deduces the architecture, but you could look at its documentation or source code (dpkg-architecture and much of the dpkg system in general are Perl).</p>\n" }, { "answer_id": 11515090, "author": "asharma", "author_id": 1530443, "author_profile": "https://Stackoverflow.com/users/1530443", "pm_score": 6, "selected": false, "text": "<p><a href=\"http://linuxmanpages.net/manpages/fedora16/man1/lscpu.1.html\" rel=\"noreferrer\"><code>lscpu</code></a> will list out these among other information regarding your CPU:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Architecture: x86_64\nCPU op-mode(s): 32-bit, 64-bit\n...\n</code></pre>\n" }, { "answer_id": 11970831, "author": "scotty", "author_id": 1600775, "author_profile": "https://Stackoverflow.com/users/1600775", "pm_score": 4, "selected": false, "text": "<pre><code>#include &lt;stdio.h&gt;\n\nint main(void)\n{\n printf(\"%d\\n\", __WORDSIZE);\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 15009534, "author": "Michael Shigorin", "author_id": 561921, "author_profile": "https://Stackoverflow.com/users/561921", "pm_score": 1, "selected": false, "text": "<p>If one is severely limited in available binaries (e.g. in initramfs), my colleagues suggested:</p>\n\n<pre><code>$ ls -l /lib*/ld-linux*.so.2\n</code></pre>\n\n<p>On my ALT Linux systems, i586 has <code>/lib/ld-linux.so.2</code> and x86_64 has <code>/lib64/ld-linux-x86-64.so.2</code>.</p>\n" }, { "answer_id": 17597274, "author": "alex", "author_id": 2573280, "author_profile": "https://Stackoverflow.com/users/2573280", "pm_score": 1, "selected": false, "text": "<pre><code>$ grep \"CONFIG_64\" /lib/modules/*/build/.config\n# CONFIG_64BIT is not set\n</code></pre>\n" }, { "answer_id": 21188486, "author": "user3207041", "author_id": 3207041, "author_profile": "https://Stackoverflow.com/users/3207041", "pm_score": 5, "selected": false, "text": "<p>Another useful command for easy determination is as below:</p>\n\n<p>Command:</p>\n\n<pre><code>getconf LONG_BIT\n</code></pre>\n\n<p>Answer:</p>\n\n<ul>\n<li>32, if OS is 32 bit</li>\n<li>64, if OS is 64 bit</li>\n</ul>\n" }, { "answer_id": 24248455, "author": "Greg von Winckel", "author_id": 2308288, "author_profile": "https://Stackoverflow.com/users/2308288", "pm_score": 4, "selected": false, "text": "<p>The command </p>\n\n<pre><code>$ arch \n</code></pre>\n\n<p>is equivalent to </p>\n\n<pre><code>$ uname -m\n</code></pre>\n\n<p>but is twice as fast to type</p>\n" }, { "answer_id": 26845387, "author": "Luchostein", "author_id": 2859065, "author_profile": "https://Stackoverflow.com/users/2859065", "pm_score": 2, "selected": false, "text": "<p>In Bash, using integer overflow:</p>\n\n<pre><code>if ((1 == 1&lt;&lt;32)); then\n echo 32bits\nelse\n echo 64bits\nfi\n</code></pre>\n\n<p>It's much more efficient than invoking another process or opening files.</p>\n" }, { "answer_id": 27345891, "author": "Vikram Thaman", "author_id": 4043995, "author_profile": "https://Stackoverflow.com/users/4043995", "pm_score": -1, "selected": false, "text": "<p>First you have to download Virtual Box. Then select new and a 32-bit Linux. Then boot the linux using it. If it boots then it is 32 bit if it doesn't then it is a 64 bit.</p>\n" }, { "answer_id": 28500619, "author": "Sandeep Giri", "author_id": 96793, "author_profile": "https://Stackoverflow.com/users/96793", "pm_score": 2, "selected": false, "text": "<p>If you shift 1 left by 32 and you get 1, your system is 32 bit.\nIf you shift 1 left by 64 and you get 1, your system is 64 bit.</p>\n\n<p>In other words, </p>\n\n<p><code>if echo $((1&lt;&lt;32)) gives 1 then your system is 32 bit</code>.</p>\n\n<p><code>if echo $((1&lt;&lt;64)) gives 1 then your system is 64 bit</code>.</p>\n" }, { "answer_id": 31239216, "author": "Lakshmikandan", "author_id": 2186189, "author_profile": "https://Stackoverflow.com/users/2186189", "pm_score": 1, "selected": false, "text": "<p>Simple script to get 64 bit or 32 bit</p>\n\n<pre><code> if $(getconf LONG_BIT | grep '64'); then\n echo \"64 bit system\"\n else\n echo \"32 bit system\"\n fi\n</code></pre>\n" }, { "answer_id": 32665383, "author": "ysdx", "author_id": 637866, "author_profile": "https://Stackoverflow.com/users/637866", "pm_score": 3, "selected": false, "text": "<p>Nowadays, a system can be multiarch so it does not make sense anyway. You might want to find the default target of the compiler:</p>\n\n<pre>$ cc -v 2>&1 | grep ^Target\nTarget: x86_64-pc-linux-gn\n</pre>\n\n<p>You can try to compile a hello world:</p>\n\n<pre>$ echo 'int main() { return 0; }' | cc -x c - -o foo\n$ file foo\nfoo: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=b114e029a08abfb3c98db93d3dcdb7435b5bba0c, not stripped\n</pre>\n" }, { "answer_id": 32717681, "author": "Rolf of Saxony", "author_id": 4637585, "author_profile": "https://Stackoverflow.com/users/4637585", "pm_score": 1, "selected": false, "text": "<p>I can't believe that in all this time, no one has mentioned:</p>\n\n<pre><code>sudo lshw -class cpu\n</code></pre>\n\n<p>to get details about the speed, quantity, size and capabilities of the CPU hardware.</p>\n" }, { "answer_id": 35247207, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><em>getconf</em> uses the fewest system calls:</p>\n\n<pre><code>$ strace getconf LONG_BIT | wc -l\n253\n\n$ strace arch | wc -l\n280\n\n$ strace uname -m | wc -l\n281\n\n$ strace grep -q lm /proc/cpuinfo | wc -l\n301\n</code></pre>\n" }, { "answer_id": 35687825, "author": "LinuxMaintwo", "author_id": 5994607, "author_profile": "https://Stackoverflow.com/users/5994607", "pm_score": 2, "selected": false, "text": "<p>You can also check using a environment variable:</p>\n\n<pre><code>echo $HOSTTYPE\n</code></pre>\n\n<p>Result:</p>\n\n<p><code>i386</code> -> 32 bits</p>\n\n<p><code>x86_64</code> -> 64 bits</p>\n\n<p>Extracted from: <a href=\"http://www.sysadmit.com/2016/02/linux-como-saber-si-es-32-o-64-bits.html\" rel=\"nofollow noreferrer\">http://www.sysadmit.com/2016/02/linux-como-saber-si-es-32-o-64-bits.html</a></p>\n" }, { "answer_id": 41116803, "author": "79man", "author_id": 4983314, "author_profile": "https://Stackoverflow.com/users/4983314", "pm_score": 1, "selected": false, "text": "<p><code>[ -z `uname -m | grep 64` ] &amp;&amp; echo \"32-bit\" || echo \"64-bit\"</code></p>\n\n<p>Based on the fact that 64-bit is usually <code>x86_64</code> and 32-bit is <code>i686</code> etc.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11602/" ]
When I type `uname -a`, it gives the following output. ``` Linux mars 2.6.9-67.0.15.ELsmp #1 SMP Tue Apr 22 13:50:33 EDT 2008 i686 i686 i386 GNU/Linux ``` How can I know from this that the given OS is 32 or 64 bit? This is useful when writing `configure` scripts, for example: what architecture am I building for?
Try [`uname -m`](http://linuxmanpages.net/manpages/fedora16/man1/uname.1.html). Which is short of `uname --machine` and it outputs: ``` x86_64 ==> 64-bit kernel i686 ==> 32-bit kernel ``` --- Otherwise, **not for the Linux kernel, but for the CPU**, you type: ``` cat /proc/cpuinfo ``` or: ``` grep flags /proc/cpuinfo ``` Under "flags" parameter, you will see various values: see "[What do the flags in /proc/cpuinfo mean?](https://unix.stackexchange.com/a/43540)" Among them, one is named `lm`: `Long Mode` ([x86-64](http://en.wikipedia.org/wiki/X86-64): amd64, also known as Intel 64, i.e. 64-bit capable) ``` lm ==> 64-bit processor ``` Or [using `lshw`](http://linux.die.net/man/1/lshw) (as mentioned [below](https://stackoverflow.com/a/32717681/6309) by [Rolf of Saxony](https://stackoverflow.com/users/4637585/rolf-of-saxony)), without `sudo` (just for grepping the cpu width): ``` lshw -class cpu|grep "^ width"|uniq|awk '{print $2}' ``` **Note: you can have a 64-bit CPU with a 32-bit kernel installed**. (as [ysdx](https://stackoverflow.com/users/637866/ysdx) mentions in [his/her own answer](https://stackoverflow.com/a/32665383/6309), "Nowadays, a system can be **[multiarch](https://wiki.debian.org/Multiarch)** so it does not make sense anyway. You might want to find the default target of the compiler")
246,017
<p>I have an oc4j installation bereft of any release notes or version documentation. In the absence of such documents, how do I know for sure, which version of oc4j I am using?</p>
[ { "answer_id": 246034, "author": "Maglob", "author_id": 27520, "author_profile": "https://Stackoverflow.com/users/27520", "pm_score": 4, "selected": true, "text": "<p>Check Server header in HTTP headers. For example with wget or curl; </p>\n\n<pre><code>wget -S &lt;url-to-server&gt;\ncurl -I &lt;url-to-server&gt;\n</code></pre>\n\n<p>or with browser, which can show HTTP headers.</p>\n\n<p>There should be a header something like</p>\n\n<pre><code>Server: Oracle-Application-Server-10g/10.1.3.1.0 Oracle-HTTP-Server\n</code></pre>\n" }, { "answer_id": 253234, "author": "Sten Vesterli", "author_id": 9363, "author_profile": "https://Stackoverflow.com/users/9363", "pm_score": 1, "selected": false, "text": "<p>If you simply enter the URL of the server (like <a href=\"http://yourserver:yourport\" rel=\"nofollow noreferrer\">http://yourserver:yourport</a>), you will get a welcome page stating the version. </p>\n\n<p>In my case, <a href=\"http://myserver:7777\" rel=\"nofollow noreferrer\">http://myserver:7777</a> shows \"Welcome to Oracle Application Server 10g (10.1.3.1.0)\". If you don't know the port, try 7777, 7778 and 8888.</p>\n\n<p>If you know where the Oracle software is installed, go to the ORACLE_HOME/install directory and look in the readme.txt file. This will start \"The installation of Oracle Application Server xx was successful\", where xx is the version. If you don't know the location of the software, you could search your file system for readme.txt files - one of them is likely to document your OC4J installation.</p>\n" }, { "answer_id": 253260, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 2, "selected": false, "text": "<p>If you have access to the OC4J JAR file, you can do:</p>\n\n<pre><code>java -jar oc4j.jar -version\n</code></pre>\n" }, { "answer_id": 741002, "author": "dstine", "author_id": 84855, "author_profile": "https://Stackoverflow.com/users/84855", "pm_score": 1, "selected": false, "text": "<p>You could display the OC4J-related system properties. We embed the following scriptlets into a JSP page:</p>\n\n<pre><code>&lt;%= System.getProperty( \"oracle.j2ee.container.name\" ) %&gt;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>&lt;%= application.getAttribute( \"oracle.jsp.versionNumber\" ) %&gt;\n</code></pre>\n\n<p>Sample output:</p>\n\n<blockquote>\n <p>Oracle J2EE Container: Oracle\n Containers for J2EE 10g (10.1.3.3.0)<br>\n Oracle JSP Version: Oracle Containers\n for J2EE 10g (10.1.3.1.0)</p>\n</blockquote>\n" }, { "answer_id": 2314776, "author": "RHT", "author_id": 244461, "author_profile": "https://Stackoverflow.com/users/244461", "pm_score": 1, "selected": false, "text": "<p>Some of the methods mentioned here will not work for an Oracle Application Server and they may not be supported going forward. Also, readme.txt or other files may not be updated when a patch is applied.</p>\n\n<p>Recommended way is to use Oracle's official OPatch utility like this.</p>\n\n<pre><code>OPatch]$ ./opatch lsinventory -invPtrLoc ../oraInst.loc |grep \"Oracle Application Server\"\n\nOracle Application Server PatchSet 10.1.3.4.0\n</code></pre>\n\n<p>Ensure that the environment variable ORALCE_HOME is set correctly and -invPtrLoc pointing to the right inventory location.</p>\n\n<p>Please note that this will only work with a full installation of Oracle Application Server. It will not work for a standalone development OC4J.</p>\n" }, { "answer_id": 2419342, "author": "BlakGeek", "author_id": 290787, "author_profile": "https://Stackoverflow.com/users/290787", "pm_score": 0, "selected": false, "text": "<pre><code>grep Version $ORACLE_HOME/config/ias.properties\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11602/" ]
I have an oc4j installation bereft of any release notes or version documentation. In the absence of such documents, how do I know for sure, which version of oc4j I am using?
Check Server header in HTTP headers. For example with wget or curl; ``` wget -S <url-to-server> curl -I <url-to-server> ``` or with browser, which can show HTTP headers. There should be a header something like ``` Server: Oracle-Application-Server-10g/10.1.3.1.0 Oracle-HTTP-Server ```
246,038
<p>What is the best way to unit test a method that doesn't return anything? Specifically in c#.</p> <p>What I am really trying to test is a method that takes a log file and parses it for specific strings. The strings are then inserted into a database. Nothing that hasn't been done before but being VERY new to TDD I am wondering if it is possible to test this or is it something that doesn't really get tested.</p>
[ { "answer_id": 246044, "author": "Keith Nicholas", "author_id": 10431, "author_profile": "https://Stackoverflow.com/users/10431", "pm_score": 3, "selected": false, "text": "<p>it will have some effect on an object.... query for the result of the effect. If it has no visible effect its not worth unit testing!</p>\n" }, { "answer_id": 246048, "author": "André", "author_id": 9683, "author_profile": "https://Stackoverflow.com/users/9683", "pm_score": 1, "selected": false, "text": "<p>Depends on what it's doing. If it has parameters, pass in mocks that you could ask later on if they have been called with the right set of parameters.</p>\n" }, { "answer_id": 246052, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 5, "selected": false, "text": "<p>As always: test what the method is supposed to do! </p>\n\n<p>Should it change global state (uuh, code smell!) somewhere? </p>\n\n<p>Should it call into an interface?</p>\n\n<p>Should it throw an exception when called with the wrong parameters?</p>\n\n<p>Should it throw no exception when called with the right parameters?</p>\n\n<p>Should it ...?</p>\n" }, { "answer_id": 246059, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 3, "selected": false, "text": "<p>Presumably the method does something, and doesn't simply return?</p>\n\n<p>Assuming this is the case, then:</p>\n\n<ol>\n<li>If it modifies the state of it's owner object, then you should test that the state changed correctly.</li>\n<li>If it takes in some object as a parameter and modifies that object, then your should test the object is correctly modified.</li>\n<li>If it throws exceptions is certain cases, test that those exceptions are correctly thrown.</li>\n<li>If its behaviour varies based on the state of its own object, or some other object, preset the state and test the method has the correct Ithrough one of the three test methods above).</li>\n</ol>\n\n<p>If youy let us know what the method does, I could be more specific.</p>\n" }, { "answer_id": 246060, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 8, "selected": true, "text": "<p>If a method doesn't return anything, it's either one of the following</p>\n\n<ul>\n<li><strong>imperative</strong> - You're either asking the object to do something to itself.. e.g change state (without expecting any confirmation.. its assumed that it will be done)</li>\n<li><strong>informational</strong> - just notifying someone that something happened (without expecting action or response) respectively. </li>\n</ul>\n\n<p>Imperative methods - you can verify if the task was actually performed. Verify if state change actually took place. e.g.</p>\n\n<pre><code>void DeductFromBalance( dAmount ) \n</code></pre>\n\n<p>can be tested by verifying if the balance post this message is indeed less than the initial value by dAmount</p>\n\n<p>Informational methods - are rare as a member of the public interface of the object... hence not normally unit-tested. However if you must, You can verify if the handling to be done on a notification takes place. e.g.</p>\n\n<pre><code>void OnAccountDebit( dAmount ) // emails account holder with info\n</code></pre>\n\n<p>can be tested by verifying if the email is being sent</p>\n\n<p><em>Post more details about your actual method and people will be able to answer better.</em><br>\n<strong>Update</strong>: Your method is doing 2 things. I'd actually split it into two methods that can now be independently tested. </p>\n\n<pre><code>string[] ExamineLogFileForX( string sFileName );\nvoid InsertStringsIntoDatabase( string[] );\n</code></pre>\n\n<p>String[] can be easily verified by providing the first method with a dummy file and expected strings. The second one is slightly tricky.. you can either use a Mock (google or search stackoverflow on mocking frameworks) to mimic the DB or hit the actual DB and verify if the strings were inserted in the right location. Check <a href=\"https://stackoverflow.com/questions/31837/best-books-about-tdd\">this thread</a> for some good books... I'd recomment Pragmatic Unit Testing if you're in a crunch.<br>\nIn the code it would be used like </p>\n\n<pre><code>InsertStringsIntoDatabase( ExamineLogFileForX( \"c:\\OMG.log\" ) );\n</code></pre>\n" }, { "answer_id": 246061, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": false, "text": "<p>Test its side-effects. This includes:</p>\n\n<ul>\n<li>Does it throw any exceptions? (If it should, check that it does. If it shouldn't, try some corner cases which might if you're not careful - null arguments being the most obvious thing.)</li>\n<li>Does it play nicely with its parameters? (If they're mutable, does it mutate them when it shouldn't and vice versa?)</li>\n<li>Does it have the right effect on the state of the object/type you're calling it on?</li>\n</ul>\n\n<p>Of course, there's a limit to how <em>much</em> you can test. You generally can't test with every possible input, for example. Test pragmatically - enough to give you confidence that your code is designed appropriately and implemented correctly, and enough to act as supplemental documentation for what a caller might expect.</p>\n" }, { "answer_id": 246089, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"http://ayende.com/projects/rhino-mocks.aspx\" rel=\"nofollow noreferrer\">Rhino Mocks</a> to set what calls, actions and exceptions might be expected. Assuming you can mock or stub out parts of your method. Hard to know without knowing some specifics here about the method, or even context.</p>\n" }, { "answer_id": 23959605, "author": "Suamere", "author_id": 1831054, "author_profile": "https://Stackoverflow.com/users/1831054", "pm_score": 4, "selected": false, "text": "<p>Void return types / Subroutines are old news. I haven't made a Void return type (Unless I was being extremely lazy) in like 8 years (From the time of this answer, so just a bit before this question was asked).</p>\n\n<p>Instead of a method like:</p>\n\n<pre><code>public void SendEmailToCustomer()\n</code></pre>\n\n<p>Make a method that follows Microsoft's int.TryParse() paradigm:</p>\n\n<pre><code>public bool TrySendEmailToCustomer()\n</code></pre>\n\n<p>Maybe there isn't any information your method needs to return for usage in the long-run, but returning the state of the method after it performs its job is a huge use to the caller.</p>\n\n<p>Also, bool isn't the only state type. There are a number of times when a previously-made Subroutine could actually return three or more different states (Good, Normal, Bad, etc). In those cases, you'd just use</p>\n\n<pre><code>public StateEnum TrySendEmailToCustomer()\n</code></pre>\n\n<p>However, while the Try-Paradigm somewhat answers this question on how to test a void return, there are other considerations too. For example, during/after a \"TDD\" cycle, you would be \"Refactoring\" and notice you are doing two things with your method... thus breaking the \"Single Responsibility Principle.\" So that should be taken care of first. Second, you might have idenetified a dependency... you're touching \"Persistent\" Data.</p>\n\n<p>If you are doing the data access stuff in the method-in-question, you need to refactor into an n-tier'd or n-layer'd architecture. But we can assume that when you say \"The strings are then inserted into a database\", you actually mean you're calling a business logic layer or something. Ya, we'll assume that.</p>\n\n<p>When your object is instantiated, you now understand that your object has dependencies. This is when you need to decide if you are going to do Dependency Injection on the Object, or on the Method. That means your Constructor or the method-in-question needs a new Parameter:</p>\n\n<pre><code>public &lt;Constructor/MethodName&gt; (IBusinessDataEtc otherLayerOrTierObject, string[] stuffToInsert)\n</code></pre>\n\n<p>Now that you can accept an interface of your business/data tier object, you can mock it out during Unit Tests and have no dependencies or fear of \"Accidental\" integration testing.</p>\n\n<p>So in your live code, you pass in a REAL <code>IBusinessDataEtc</code> object. But in your Unit Testing, you pass in a MOCK <code>IBusinessDataEtc</code> object. In that Mock, you can include Non-Interface Properties like <code>int XMethodWasCalledCount</code> or something whose state(s) are updated when the interface methods are called.</p>\n\n<p>So your Unit Test will go through your Method(s)-In-Question, perform whatever logic they have, and call one or two, or a selected set of methods in your <code>IBusinessDataEtc</code> object. When you do your Assertions at the end of your Unit Test you have a couple of things to test now.</p>\n\n<ol>\n<li>The State of the \"Subroutine\" which is now a Try-Paradigm method.</li>\n<li>The State of your Mock <code>IBusinessDataEtc</code> object.</li>\n</ol>\n\n<p>For more information on Dependency Injection ideas on the Construction-level... as they pertain to Unit Testing... look into Builder design patterns. It adds one more interface and class for each current interface/class you have, but they are very tiny and provide HUGE functionality increases for better Unit-Testing.</p>\n" }, { "answer_id": 37180480, "author": "Nathan Alard", "author_id": 3733407, "author_profile": "https://Stackoverflow.com/users/3733407", "pm_score": 5, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>[TestMethod]\npublic void TestSomething()\n{\n try\n {\n YourMethodCall();\n Assert.IsTrue(true);\n }\n catch {\n Assert.IsTrue(false);\n }\n}\n</code></pre>\n" }, { "answer_id": 42490056, "author": "Shreya Kesharkar", "author_id": 7630697, "author_profile": "https://Stackoverflow.com/users/7630697", "pm_score": 0, "selected": false, "text": "<p>What ever instance you are using to call the void method , You can just use ,<code>Verfiy</code> </p>\n\n<p>For Example: </p>\n\n<p>In My case its <code>_Log</code> is the instance and <code>LogMessage</code> is the method to be tested:</p>\n\n<pre><code>try\n{\n this._log.Verify(x =&gt; x.LogMessage(Logger.WillisLogLevel.Info, Logger.WillisLogger.Usage, \"Created the Student with name as\"), \"Failure\");\n}\nCatch \n{\n Assert.IsFalse(ex is Moq.MockException);\n}\n</code></pre>\n\n<p>Is the <code>Verify</code> throws an exception due to failure of the method the test would Fail ?</p>\n" }, { "answer_id": 56358203, "author": "Reyan Chougle", "author_id": 3678363, "author_profile": "https://Stackoverflow.com/users/3678363", "pm_score": 4, "selected": false, "text": "<p>You can even try it this way:</p>\n\n<pre><code>[TestMethod]\npublic void ReadFiles()\n{\n try\n {\n Read();\n return; // indicates success\n }\n catch (Exception ex)\n {\n Assert.Fail(ex.Message);\n }\n}\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/831/" ]
What is the best way to unit test a method that doesn't return anything? Specifically in c#. What I am really trying to test is a method that takes a log file and parses it for specific strings. The strings are then inserted into a database. Nothing that hasn't been done before but being VERY new to TDD I am wondering if it is possible to test this or is it something that doesn't really get tested.
If a method doesn't return anything, it's either one of the following * **imperative** - You're either asking the object to do something to itself.. e.g change state (without expecting any confirmation.. its assumed that it will be done) * **informational** - just notifying someone that something happened (without expecting action or response) respectively. Imperative methods - you can verify if the task was actually performed. Verify if state change actually took place. e.g. ``` void DeductFromBalance( dAmount ) ``` can be tested by verifying if the balance post this message is indeed less than the initial value by dAmount Informational methods - are rare as a member of the public interface of the object... hence not normally unit-tested. However if you must, You can verify if the handling to be done on a notification takes place. e.g. ``` void OnAccountDebit( dAmount ) // emails account holder with info ``` can be tested by verifying if the email is being sent *Post more details about your actual method and people will be able to answer better.* **Update**: Your method is doing 2 things. I'd actually split it into two methods that can now be independently tested. ``` string[] ExamineLogFileForX( string sFileName ); void InsertStringsIntoDatabase( string[] ); ``` String[] can be easily verified by providing the first method with a dummy file and expected strings. The second one is slightly tricky.. you can either use a Mock (google or search stackoverflow on mocking frameworks) to mimic the DB or hit the actual DB and verify if the strings were inserted in the right location. Check [this thread](https://stackoverflow.com/questions/31837/best-books-about-tdd) for some good books... I'd recomment Pragmatic Unit Testing if you're in a crunch. In the code it would be used like ``` InsertStringsIntoDatabase( ExamineLogFileForX( "c:\OMG.log" ) ); ```
246,058
<p>I got this error when trying to update an image. It was a cross-thread update, but I used .Invoke(), so that shouldn't be the problem, should it.</p>
[ { "answer_id": 246064, "author": "Benjol", "author_id": 11410, "author_profile": "https://Stackoverflow.com/users/11410", "pm_score": 4, "selected": true, "text": "<p><em>(Answering my own question, for others, and for future reference)</em></p>\n\n<p>I <em>think</em> (not yet entirely sure) that this is because InvokeRequired will always return false if the control has not yet been loaded/shown. I have done a workaround which seems to work for the moment, which is to simple reference the handle of the associated control in its creator, like so:</p>\n\n<pre><code>var x = this.Handle; \n</code></pre>\n\n<p>(See <a href=\"http://ikriv.com:8765/en/prog/info/dotnet/MysteriousHang.html\" rel=\"nofollow noreferrer\">http://ikriv.com:8765/en/prog/info/dotnet/MysteriousHang.html</a> - down? <a href=\"http://209.85.129.132/search?q=cache:www.ikriv.com/en/prog/info/dotnet/MysteriousHang.html\" rel=\"nofollow noreferrer\">cached version</a>)</p>\n\n<p>(Related question: <a href=\"https://stackoverflow.com/questions/192980/boiler-plate-code-replacement-is-there-anything-bad-about-this-code\">Boiler plate code replacement - is there anything bad about this code?</a>)</p>\n" }, { "answer_id": 246098, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>If the handle doesn't yet exist, you can force it by subclassing the control and calling <code>CreateHandle</code>; however, the bigger question is: why are you doing things with a form that hasn't been loaded? Personally I'd only start such an operation after Load.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11410/" ]
I got this error when trying to update an image. It was a cross-thread update, but I used .Invoke(), so that shouldn't be the problem, should it.
*(Answering my own question, for others, and for future reference)* I *think* (not yet entirely sure) that this is because InvokeRequired will always return false if the control has not yet been loaded/shown. I have done a workaround which seems to work for the moment, which is to simple reference the handle of the associated control in its creator, like so: ``` var x = this.Handle; ``` (See <http://ikriv.com:8765/en/prog/info/dotnet/MysteriousHang.html> - down? [cached version](http://209.85.129.132/search?q=cache:www.ikriv.com/en/prog/info/dotnet/MysteriousHang.html)) (Related question: [Boiler plate code replacement - is there anything bad about this code?](https://stackoverflow.com/questions/192980/boiler-plate-code-replacement-is-there-anything-bad-about-this-code))
246,071
<p>My experience to write a plugin for Firefox is below zero. Is someone out there who could point me to sample code on how to get this accomplished in C++ with VS2005/8? </p> <p>What I need to do with JavaScript in the hosting html page is something like this:</p> <pre><code>var obj = document.getElementById("MyFFPlugin"); var value = obj.CalculateValue; // Work with calculated value </code></pre>
[ { "answer_id": 246083, "author": "RWendi", "author_id": 15152, "author_profile": "https://Stackoverflow.com/users/15152", "pm_score": 3, "selected": true, "text": "<p>The SDK has basic samples on how to write mozzila plugins which can be downloaded here: <a href=\"http://mxr.mozilla.org/seamonkey/source/modules/plugin/tools/sdk/\" rel=\"nofollow noreferrer\">http://mxr.mozilla.org/seamonkey/source/modules/plugin/tools/sdk/</a></p>\n\n<p>Here is the official mozilla plugin site <a href=\"http://www.mozilla.org/projects/plugins/\" rel=\"nofollow noreferrer\">http://www.mozilla.org/projects/plugins/</a></p>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 1065626, "author": "Charles Dietrich", "author_id": 131284, "author_profile": "https://Stackoverflow.com/users/131284", "pm_score": 0, "selected": false, "text": "<p>I highly recommend using Nixysa <a href=\"http://code.google.com/p/nixysa/\" rel=\"nofollow noreferrer\">http://code.google.com/p/nixysa/</a>, which wraps NPAPI. From the site:</p>\n\n<blockquote>\n <p>Nixysa is a framework written in\n Python to automatically generate glue\n code for NPAPI plugins (plugins for\n browsers such as Google Chrome or\n Firefox), letting you easily expose\n C++ classes to Javascript from a\n simple IDL representation. Nixysa was\n originally conceived for the needs of\n O3D, but is flexible enough to support\n a wide range of use cases. </p>\n \n <p>Try it</p>\n \n <p>Check out the code following the\n instructions here and try the sample\n in examples/complex.</p>\n</blockquote>\n\n<p>The sample includes a Visual Studio 2005 project.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1890/" ]
My experience to write a plugin for Firefox is below zero. Is someone out there who could point me to sample code on how to get this accomplished in C++ with VS2005/8? What I need to do with JavaScript in the hosting html page is something like this: ``` var obj = document.getElementById("MyFFPlugin"); var value = obj.CalculateValue; // Work with calculated value ```
The SDK has basic samples on how to write mozzila plugins which can be downloaded here: <http://mxr.mozilla.org/seamonkey/source/modules/plugin/tools/sdk/> Here is the official mozilla plugin site <http://www.mozilla.org/projects/plugins/> Hope it helps.
246,077
<p>For example VK_LEFT, VK_DELETE, VK_ESCAPE, VK_RETURN, etc. How and where are they declared? Are they constants, #defines, or something else? Where do they come from?</p> <p>If possible, please provide a file name/path where they are declared. Or some other info as specific as possible.</p>
[ { "answer_id": 246084, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 3, "selected": true, "text": "<p>These are declared using <code>#define</code> in the file <code>winuser.h</code> in the Platform SDK. In my installation of Visual Studio 2008, the full path is</p>\n\n<pre><code>C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\Include\\WinUser.h\n</code></pre>\n" }, { "answer_id": 246090, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 0, "selected": false, "text": "<p>These are macro-defined constants, <a href=\"http://msdn.microsoft.com/en-us/library/ms646271(VS.85).aspx\" rel=\"nofollow noreferrer\">declared in winuser.h</a>. To find where something is declared or defined you can read its documentation (Microsoft includes a section at the end, in Unix man pages it appears in the beginning), or go to the directory where the headers are and grep for the thing you're looking for.</p>\n" }, { "answer_id": 246154, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 2, "selected": false, "text": "<p>To find how something is declared, install Visual Assist, put the cursor over the identifier in you code and press Alt+G<br>\nOr, right click over the identifier and choose \"Go To Definition\"<br>\nOr press F12 </p>\n" }, { "answer_id": 247072, "author": "QBziZ", "author_id": 11572, "author_profile": "https://Stackoverflow.com/users/11572", "pm_score": 2, "selected": false, "text": "<p>There are also online copies of winuser.h , very handy sometimes :</p>\n\n<p><a href=\"http://www.woodmann.com/fravia/sources/WINUSER.H\" rel=\"nofollow noreferrer\">http://www.woodmann.com/fravia/sources/WINUSER.H</a>\n<a href=\"http://doc.ddart.net/msdn/header/include/winuser.h.html\" rel=\"nofollow noreferrer\">http://doc.ddart.net/msdn/header/include/winuser.h.html</a></p>\n\n<p>A bit of googling will get you more of those.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
For example VK\_LEFT, VK\_DELETE, VK\_ESCAPE, VK\_RETURN, etc. How and where are they declared? Are they constants, #defines, or something else? Where do they come from? If possible, please provide a file name/path where they are declared. Or some other info as specific as possible.
These are declared using `#define` in the file `winuser.h` in the Platform SDK. In my installation of Visual Studio 2008, the full path is ``` C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WinUser.h ```
246,091
<p>The problem is very simple. An object needs to notify some events that might be of interest to observers.</p> <p>When I sat to validate a design that I cooked up now in Ruby just to validate it.. I find myself stumped as to how to implement the object events. In .Net this would be a one-liner.. .Net also does handler method signature verification,etc. e.g.</p> <pre><code>// Object with events public delegate void HandlerSignature(int a); public event HandlerSignature MyEvent; public event HandlerSignature AnotherCriticalEvent; // Client MyObject.MyEvent += new HandlerSignature(MyHandlerMethod); // MyHandlerMethod has same signature as delegate </code></pre> <p>Is there an EventDispatcher module or something that I am missing that I can strap on to a Ruby class ? Hoping for an answer that plays along with Ruby's principle of least surprise. <em>An event would be the name of the event plus a queue of [observer, methodName] objects that need to be invoked when the event takes place.</em></p>
[ { "answer_id": 246157, "author": "Farrel", "author_id": 7889, "author_profile": "https://Stackoverflow.com/users/7889", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://ruby-doc.org/core/classes/Observable.html\" rel=\"nofollow noreferrer\">Observable module</a>? </p>\n" }, { "answer_id": 246245, "author": "janm", "author_id": 7256, "author_profile": "https://Stackoverflow.com/users/7256", "pm_score": 3, "selected": false, "text": "<p>Firstly, in Ruby there are no method signatures. The closest would be checking the function's arity. Duck typing requires thinking differently (slightly).</p>\n\n<p>The Observable module is a start, but if you have a requirement to have multiple events from a single class it might not be enough.</p>\n\n<p>This is a quick sketch. It supports methods and blocks. Modify as necessary to adapt for your code, threading approach, etc. For example, you could use method_missing to have the event name in the method name rather than having it as a parameter.</p>\n\n<pre><code>class EventBase\n def initialize\n @listeners = Hash.new\n end\n\n def listen_event(name, *func, &amp;p)\n if p\n (@listeners[name] ||= Array.new) &lt;&lt; p\n else\n (@listeners[name] ||= Array.new) &lt;&lt; func[0]\n end\n end\n\n def ignore_event(name, func)\n return if [email protected]_key?(name)\n @listeners[name].delete_if { |o| o == func }\n end\n\n def trigger_event(name, *args)\n return if [email protected]_key?(name)\n @listeners[name].each { |f| f.call(*args) }\n end\nend\n\n\nclass MyClass &lt; EventBase\n def raise_event1(*args)\n trigger_event(:event1, *args)\n end\n\n def raise_event2(*args)\n trigger_event(:event2, *args)\n end\nend\n\nclass TestListener\n def initialize(source)\n source.listen_event(:event1, method(:event1_arrival))\n source.listen_event(:event2) do |*a|\n puts \"event 2 arrival, args #{a}\"\n end\n end\n\n def event1_arrival(*a)\n puts \"Event 1 arrived, args #{a}\"\n end\nend\n\ns = MyClass.new\nl = TestListener.new(s)\n\ns.raise_event1(\"here is event 1\")\ns.raise_event2(\"here is event 2\")\n</code></pre>\n" }, { "answer_id": 258647, "author": "Matt Burke", "author_id": 29691, "author_profile": "https://Stackoverflow.com/users/29691", "pm_score": 2, "selected": false, "text": "<p>I'd echo that there isn't a language-level analog in Ruby to .NET events. The way that rails deals with it is with <a href=\"http://www.railsbrain.com/api/rails-2.1.0/doc/index.html?a=C00000430&amp;name=Callbacks\" rel=\"nofollow noreferrer\">ActiveSupport::Callbacks</a> (there is an example on that page).</p>\n" }, { "answer_id": 2205919, "author": "D. Rexin", "author_id": 266896, "author_profile": "https://Stackoverflow.com/users/266896", "pm_score": 3, "selected": false, "text": "<p>Why not write your own event class? Something like</p>\n\n<pre><code>class Event\n def initialize\n @handlers = Array.new\n end\n\n def fire\n @handlers.each do |v|\n v.call\n end\n end\n\n def &lt;&lt; handler\n @handlers &lt;&lt; handler\n end\nend\n\ne = Event.new\n\ne &lt;&lt; lambda { puts \"hello\" }\ne &lt;&lt; lambda { puts \"test\" }\ne.fire\n</code></pre>\n\n<p>This is just a minimal sample, but can be extended in any ways. Add parameters like sender and eventArgs in .Net, or whatever you like ;-)</p>\n" }, { "answer_id": 2735627, "author": "Nathan Kleyn", "author_id": 153432, "author_profile": "https://Stackoverflow.com/users/153432", "pm_score": 0, "selected": false, "text": "<p>I wrote a gem just for this because I had exactly the same issue. Try this:</p>\n\n<pre><code>gem install ruby_events\n</code></pre>\n\n<p>Follow the instructions as on <a href=\"http://github.com/nathankleyn/ruby_events\" rel=\"nofollow noreferrer\">http://github.com/nathankleyn/ruby_events</a>, but in a nutshell:</p>\n\n<pre><code>require 'rubygems'\nrequire 'ruby_events'\n\nclass Example\n def initialize\n events.listen(:test_event) do |event_data|\n puts 'Hai there!'\n puts event_data\n end\n end\n\n def call_me\n events.fire(:test_event, 'My name is Mr Test Man!')\n end\nend\n\ne = Example.new\ne.call_me # Fires the event, and our handler gets called!\n</code></pre>\n" }, { "answer_id": 5217597, "author": "will", "author_id": 108350, "author_profile": "https://Stackoverflow.com/users/108350", "pm_score": 0, "selected": false, "text": "<p>A quick note on this. I suggest you look at <a href=\"https://rubygems.org/gems/eventmachine\" rel=\"nofollow\">EventMachine</a></p>\n\n<ul>\n<li><a href=\"https://rubygems.org/gems/eventmachine\" rel=\"nofollow\">https://rubygems.org/gems/eventmachine</a></li>\n</ul>\n\n<p>It is a different look a the same idea. It implements an event driven paradigm so you are one-level above the equivalent for .Net Events and consider the <a href=\"https://rubygems.org/gems/eventmachine\" rel=\"nofollow\">EventMachine</a> module as the CLR event handler.</p>\n\n<p>Also taking a step back, Ruby follows a Smalltalk processing model where any call to a method is a message (as is an Event) sent to the object (see the Send() method). <a href=\"https://rubygems.org/gems/eventmachine\" rel=\"nofollow\">EventMachine</a> gives you is a single-threaded slice on the events. You can use something like Rack to handle threads or workers.</p>\n" }, { "answer_id": 10086263, "author": "acw", "author_id": 291395, "author_profile": "https://Stackoverflow.com/users/291395", "pm_score": 1, "selected": false, "text": "<p>Take a look into the various <a href=\"https://www.ruby-toolbox.com/categories/state_machines.html\" rel=\"nofollow\" title=\"state machies\">ruby state machine libraries</a>. They intend to solve a large problem than just events, but may provide you with a solution. </p>\n\n<p>I've used the <a href=\"https://github.com/pluginaweek/state_machine\" rel=\"nofollow\">state_machine</a> gem with success, <strong>which does include <a href=\"http://rdoc.info/github/pluginaweek/state_machine/master/StateMachine/Event\" rel=\"nofollow\">events</a></strong>.</p>\n" }, { "answer_id": 11505253, "author": "Kamil Szot", "author_id": 166921, "author_profile": "https://Stackoverflow.com/users/166921", "pm_score": 0, "selected": false, "text": "<p>I'm a noob but Ruby seems really powerful. You can implement C# style events yourself like this:</p>\n\n<pre><code>module Observable\n class Event \n def initialize\n @to_call = []\n end\n def fire(*arguments)\n @to_call.each { |proc| proc.call(*arguments) }\n end\n def call(proc)\n @to_call &lt;&lt; proc\n end\n def dont_call(proc)\n @to_call.delete proc\n end\n end\n def self.append_features(cls)\n def cls.event(sym)\n define_method(sym.to_s) do\n variable_name = \"@#{sym}\"\n if not instance_variable_defined? variable_name then\n instance_variable_set variable_name, Event.new\n end\n instance_variable_get variable_name\n end\n end\n end\nend\n\n# Example \n\nclass Actor \n include Observable\n event :whenActed\n def act\n whenActed.fire(\"Johnny\") # fire event whenActed with parameter Johnny\n end\nend\n\nactor = Actor.new\n\ndef apploud(whom)\n print \"Bravo #{whom}!\\n\"\nend\n\napplouder = method(:apploud)\n\nactor.whenActed.call applouder\n\nactor.act\n</code></pre>\n" }, { "answer_id": 20810615, "author": "M'hammed Amine Asli", "author_id": 2407637, "author_profile": "https://Stackoverflow.com/users/2407637", "pm_score": 0, "selected": false, "text": "<p>I have created a gem doing exactly what you want and surprisingly called event_dispatcher as you mentioned. I hope it gonna help someone : <a href=\"https://github.com/ThatAmine/event_dispatcher\" rel=\"nofollow\">event_dispatcher</a></p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
The problem is very simple. An object needs to notify some events that might be of interest to observers. When I sat to validate a design that I cooked up now in Ruby just to validate it.. I find myself stumped as to how to implement the object events. In .Net this would be a one-liner.. .Net also does handler method signature verification,etc. e.g. ``` // Object with events public delegate void HandlerSignature(int a); public event HandlerSignature MyEvent; public event HandlerSignature AnotherCriticalEvent; // Client MyObject.MyEvent += new HandlerSignature(MyHandlerMethod); // MyHandlerMethod has same signature as delegate ``` Is there an EventDispatcher module or something that I am missing that I can strap on to a Ruby class ? Hoping for an answer that plays along with Ruby's principle of least surprise. *An event would be the name of the event plus a queue of [observer, methodName] objects that need to be invoked when the event takes place.*
Firstly, in Ruby there are no method signatures. The closest would be checking the function's arity. Duck typing requires thinking differently (slightly). The Observable module is a start, but if you have a requirement to have multiple events from a single class it might not be enough. This is a quick sketch. It supports methods and blocks. Modify as necessary to adapt for your code, threading approach, etc. For example, you could use method\_missing to have the event name in the method name rather than having it as a parameter. ``` class EventBase def initialize @listeners = Hash.new end def listen_event(name, *func, &p) if p (@listeners[name] ||= Array.new) << p else (@listeners[name] ||= Array.new) << func[0] end end def ignore_event(name, func) return if [email protected]_key?(name) @listeners[name].delete_if { |o| o == func } end def trigger_event(name, *args) return if [email protected]_key?(name) @listeners[name].each { |f| f.call(*args) } end end class MyClass < EventBase def raise_event1(*args) trigger_event(:event1, *args) end def raise_event2(*args) trigger_event(:event2, *args) end end class TestListener def initialize(source) source.listen_event(:event1, method(:event1_arrival)) source.listen_event(:event2) do |*a| puts "event 2 arrival, args #{a}" end end def event1_arrival(*a) puts "Event 1 arrived, args #{a}" end end s = MyClass.new l = TestListener.new(s) s.raise_event1("here is event 1") s.raise_event2("here is event 2") ```
246,112
<p>We are using LINQ very widely in our system. Particularly LINQ-to-objects. So in some places we end up having a LINQ query in memory build up from some huge expressions. The problem comes when there's some bug in the expressions. So we get NullReferenceException and the stack trace leads us nowhere (to [Lightweight Function]). The exception was thrown inside the dynamic method generated by LINQ.</p> <p>Is there any easy way to debug such dynamic methods? Or do I have to sacrifice myself to learning WinDBG? :-)</p>
[ { "answer_id": 246116, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>If you're using LINQ to Objects, I wouldn't expect to see dynamic methods being created. I'd expect them with LINQ to SQL etc. Could you give an example where you're seeing this?</p>\n\n<p>I don't really have any good debugging tips when it comes to LINQ, but I'm pretty sure MS know about this as a pain point. Could I suggest you try the <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=922B4655-93D0-4476-BDA4-94CF5F8D4814&amp;displaylang=en\" rel=\"nofollow noreferrer\">VS2010 CTP</a> and see if that's better? More for the sake of improving VS than for solving your immediate problem, admittedly.</p>\n" }, { "answer_id": 246132, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "<p>If you are building your own expressions and compiling them, or using AsQueryable, then yes; the LINQ-generated methods will be a royal pain to debug.</p>\n\n<p>You can save some pain by using small fragements of <em>actual</em> methods - at least something useful will show in the stack trace...</p>\n\n<p>Another consideration is: rather than having one huge expression, if you can daisy-chain things a bit more you might have more idea (from the stack trace) where it is failing. The downside is performance - a Where(foo).Where(bar) is two delegate invokes, where-as Where(foo &amp;&amp; bar) can be one.</p>\n\n<p>One option might be to swap in a debug version of the extension methods; unfortunately it is a little inconvenient because <code>IQueryable&lt;T&gt;</code> and <code>Queryable</code> are in the same namespace... this works, though...</p>\n\n<p>Output first:</p>\n\n<pre><code>&gt;Where: x =&gt; ((x % 2) = 0)\n&lt;Where: x =&gt; ((x % 2) = 0)\n&gt;Count\n'WindowsFormsApplication2.vshost.exe' (Managed): Loaded 'Anonymously Hosted DynamicMethods Assembly'\n&lt;Count\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\nusing System.Linq.Expressions;\n\nnamespace Demo\n{\n using DebugLinq;\n static class Program\n {\n static void Main()\n {\n var data = System.Linq.Queryable.AsQueryable(new[] { 1, 2, 3, 4, 5 });\n data.Where(x =&gt; x % 2 == 0).Count(); \n }\n }\n}\nnamespace DebugLinq\n{\n public static class DebugQueryable\n {\n public static int Count&lt;T&gt;(this System.Linq.IQueryable&lt;T&gt; source)\n {\n return Wrap(() =&gt; System.Linq.Queryable.Count(source), \"Count\");\n }\n\n public static System.Linq.IQueryable&lt;T&gt; Where&lt;T&gt;(this System.Linq.IQueryable&lt;T&gt; source, Expression&lt;Func&lt;T, bool&gt;&gt; predicate)\n {\n return Wrap(() =&gt; System.Linq.Queryable.Where(source, predicate), \"Where: \" + predicate);\n }\n static TResult Wrap&lt;TResult&gt;(Func&lt;TResult&gt; func, string caption)\n {\n Debug.WriteLine(\"&gt;\" + caption);\n try\n {\n TResult result = func();\n Debug.WriteLine(\"&lt;\" + caption);\n return result;\n }\n catch\n {\n Debug.WriteLine(\"!\" + caption);\n throw;\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 890676, "author": "VirtualStaticVoid", "author_id": 30521, "author_profile": "https://Stackoverflow.com/users/30521", "pm_score": 0, "selected": false, "text": "<p>Take a look at the <a href=\"http://weblogs.asp.net/rosherove/archive/2007/11/02/debugger-visualizers-for-methodinfo-dynamicmethod-and-methodbase.aspx\" rel=\"nofollow noreferrer\">debug visualizer</a> for dynamic methods originally developed by <a href=\"http://blogs.msdn.com/haibo_luo/archive/2005/10/25/484861.aspx\" rel=\"nofollow noreferrer\">Haibo Luo</a> and taken further by <a href=\"http://weblogs.asp.net/rosherove/archive/2006/04/25/MethodsVisualizer.aspx\" rel=\"nofollow noreferrer\">Roy Osherove</a></p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18001/" ]
We are using LINQ very widely in our system. Particularly LINQ-to-objects. So in some places we end up having a LINQ query in memory build up from some huge expressions. The problem comes when there's some bug in the expressions. So we get NullReferenceException and the stack trace leads us nowhere (to [Lightweight Function]). The exception was thrown inside the dynamic method generated by LINQ. Is there any easy way to debug such dynamic methods? Or do I have to sacrifice myself to learning WinDBG? :-)
If you are building your own expressions and compiling them, or using AsQueryable, then yes; the LINQ-generated methods will be a royal pain to debug. You can save some pain by using small fragements of *actual* methods - at least something useful will show in the stack trace... Another consideration is: rather than having one huge expression, if you can daisy-chain things a bit more you might have more idea (from the stack trace) where it is failing. The downside is performance - a Where(foo).Where(bar) is two delegate invokes, where-as Where(foo && bar) can be one. One option might be to swap in a debug version of the extension methods; unfortunately it is a little inconvenient because `IQueryable<T>` and `Queryable` are in the same namespace... this works, though... Output first: ``` >Where: x => ((x % 2) = 0) <Where: x => ((x % 2) = 0) >Count 'WindowsFormsApplication2.vshost.exe' (Managed): Loaded 'Anonymously Hosted DynamicMethods Assembly' <Count ``` Code: ``` using System; using System.Diagnostics; using System.Linq.Expressions; namespace Demo { using DebugLinq; static class Program { static void Main() { var data = System.Linq.Queryable.AsQueryable(new[] { 1, 2, 3, 4, 5 }); data.Where(x => x % 2 == 0).Count(); } } } namespace DebugLinq { public static class DebugQueryable { public static int Count<T>(this System.Linq.IQueryable<T> source) { return Wrap(() => System.Linq.Queryable.Count(source), "Count"); } public static System.Linq.IQueryable<T> Where<T>(this System.Linq.IQueryable<T> source, Expression<Func<T, bool>> predicate) { return Wrap(() => System.Linq.Queryable.Where(source, predicate), "Where: " + predicate); } static TResult Wrap<TResult>(Func<TResult> func, string caption) { Debug.WriteLine(">" + caption); try { TResult result = func(); Debug.WriteLine("<" + caption); return result; } catch { Debug.WriteLine("!" + caption); throw; } } } } ```
246,121
<p>I have an Ant script that needs to checkout a directory from Subversion. This works using svnant/svnkit. However, Subversion access is authenticated, and I do not want to store my user password in a file.</p> <p>Can I make svnkit pop up a password dialog? Or even better, make it use the same credential caching that subversive/svnkit inside of Eclipse uses (the username can be read from the build.properties)?</p> <p>I cannot switch to public key based authentication, as I do not control the subversion server.</p> <p>Right now, it just says "svn: authentication cancelled".</p>
[ { "answer_id": 246378, "author": "Thilo", "author_id": 14955, "author_profile": "https://Stackoverflow.com/users/14955", "pm_score": 2, "selected": false, "text": "<p>To answer my own question, I can use the Ant [input] task to ask the user for a password and store it in a property that can be passed to the [svn] task. </p>\n\n<pre><code> &lt;target name=\"checkout\"&gt;\n &lt;input\n message=\"Please enter subversion password for ${username}:\"\n addproperty=\"password\"\n /&gt;\n\n &lt;svn svnkit=\"${svnkit}\" username=\"${username}\" password=\"${password}\"&gt;\n &lt;checkout url=\"${urlRepos}/project\" destPath=\"web/\" /&gt;\n &lt;/svn&gt; \n&lt;/target&gt;\n</code></pre>\n\n<p>Unfortunately, this does not mask the password with * * * * *, and I still want to read from the credential cache...</p>\n" }, { "answer_id": 248926, "author": "Thilo", "author_id": 14955, "author_profile": "https://Stackoverflow.com/users/14955", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://www.jera.com/tools/anttasks/\" rel=\"nofollow noreferrer\">Jera Ant Tasks</a> provide a [query] task that supports password input:</p>\n\n<pre><code>&lt;taskdef name=\"query\" classname=\"com.jera.anttasks.Query\" /&gt;\n&lt;target name=\"checkout\"&gt;\n &lt;query\n message=\"Please enter subversion password for ${username}:\"\n name=\"password\" password=\"true\"\n /&gt;\n\n &lt;svn svnkit=\"${svnkit}\" username=\"${username}\" password=\"${password}\"&gt;\n &lt;checkout url=\"${urlRepos}/project\" destPath=\"web/\" /&gt;\n &lt;/svn&gt; \n&lt;/target&gt;\n</code></pre>\n" }, { "answer_id": 1357840, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Use ant-dialog (<a href=\"http://sourceforge.net/projects/ant-dialog/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/ant-dialog/</a>), it can display a java awt window so you can input properties. It also features a *** password like input field type. </p>\n" }, { "answer_id": 1844546, "author": "geowa4", "author_id": 50214, "author_profile": "https://Stackoverflow.com/users/50214", "pm_score": 2, "selected": false, "text": "<p>An analog to <a href=\"https://stackoverflow.com/questions/246121/how-do-i-make-svnant-svnkit-prompt-for-a-username-password/246378#246378\">this answer</a>:</p>\n\n<pre><code>&lt;input message=\"password:&gt;\" addproperty=\"password\"&gt;\n &lt;handler classname=\"org.apache.tools.ant.input.SecureInputHandler\" /&gt;\n&lt;/input&gt;\n</code></pre>\n\n<p>This will make it so that the person's username is not displayed. This requires Ant 1.7.1 or greater.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14955/" ]
I have an Ant script that needs to checkout a directory from Subversion. This works using svnant/svnkit. However, Subversion access is authenticated, and I do not want to store my user password in a file. Can I make svnkit pop up a password dialog? Or even better, make it use the same credential caching that subversive/svnkit inside of Eclipse uses (the username can be read from the build.properties)? I cannot switch to public key based authentication, as I do not control the subversion server. Right now, it just says "svn: authentication cancelled".
To answer my own question, I can use the Ant [input] task to ask the user for a password and store it in a property that can be passed to the [svn] task. ``` <target name="checkout"> <input message="Please enter subversion password for ${username}:" addproperty="password" /> <svn svnkit="${svnkit}" username="${username}" password="${password}"> <checkout url="${urlRepos}/project" destPath="web/" /> </svn> </target> ``` Unfortunately, this does not mask the password with \* \* \* \* \*, and I still want to read from the credential cache...
246,127
<p>Why is <code>volatile</code> needed in C? What is it used for? What will it do?</p>
[ { "answer_id": 246139, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 6, "selected": false, "text": "<p><code>volatile</code> tells the compiler that your variable may be changed by other means, than the code that is accessing it. e.g., it may be a I/O-mapped memory location. If this is not specified in such cases, some variable accesses can be optimised, e.g., its contents can be held in a register, and the memory location not read back in again.</p>\n" }, { "answer_id": 246144, "author": "Manoj Doubts", "author_id": 31116, "author_profile": "https://Stackoverflow.com/users/31116", "pm_score": 8, "selected": false, "text": "<p><code>volatile</code> in C actually came into existence for the purpose of not caching the values of the variable automatically. It will tell the compiler not to cache the value of this variable. So it will generate code to take the value of the given <code>volatile</code> variable from the main memory every time it encounters it. This mechanism is used because at any time the value can be modified by the OS or any interrupt. So using <code>volatile</code> will help us accessing the value afresh every time.</p>\n" }, { "answer_id": 246148, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 9, "selected": false, "text": "<p><code>volatile</code> tells the compiler not to optimize anything that has to do with the <code>volatile</code> variable.</p>\n<p>There are at least three common reasons to use it, all involving situations where the value of the variable can change without action from the visible code:</p>\n<ul>\n<li>When you interface with hardware that changes the value itself</li>\n<li>when there's another thread running that also uses the variable</li>\n<li>when there's a signal handler that might change the value of the variable.</li>\n</ul>\n<p>Let's say you have a little piece of hardware that is mapped into RAM somewhere and that has two addresses: a command port and a data port:</p>\n<pre><code>typedef struct\n{\n int command;\n int data;\n int isBusy;\n} MyHardwareGadget;\n</code></pre>\n<p>Now you want to send some command:</p>\n<pre><code>void SendCommand (MyHardwareGadget * gadget, int command, int data)\n{\n // wait while the gadget is busy:\n while (gadget-&gt;isbusy)\n {\n // do nothing here.\n }\n // set data first:\n gadget-&gt;data = data;\n // writing the command starts the action:\n gadget-&gt;command = command;\n}\n</code></pre>\n<p>Looks easy, but it can fail because the compiler is free to change the order in which data and commands are written. This would cause our little gadget to issue commands with the previous data-value. Also take a look at the wait while busy loop. That one will be optimized out. The compiler will try to be clever, read the value of <code>isBusy</code> just once and then go into an infinite loop. That's not what you want.</p>\n<p>The way to get around this is to declare the pointer <code>gadget</code> as <code>volatile</code>. This way the compiler is forced to do what you wrote. It can't remove the memory assignments, it can't cache variables in registers and it can't change the order of assignments either</p>\n<p>This is the correct version:</p>\n<pre><code>void SendCommand (volatile MyHardwareGadget * gadget, int command, int data)\n{\n // wait while the gadget is busy:\n while (gadget-&gt;isBusy)\n {\n // do nothing here.\n }\n // set data first:\n gadget-&gt;data = data;\n // writing the command starts the action:\n gadget-&gt;command = command;\n}\n</code></pre>\n" }, { "answer_id": 246149, "author": "Ori Pessach", "author_id": 9047, "author_profile": "https://Stackoverflow.com/users/9047", "pm_score": 2, "selected": false, "text": "<p>A volatile can be changed from outside the compiled code (for example, a program may map a volatile variable to a memory mapped register.) The compiler won't apply certain optimizations to code that handles a volatile variable - for example, it won't load it into a register without writing it to memory. This is important when dealing with hardware registers.</p>\n" }, { "answer_id": 246152, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 3, "selected": false, "text": "<p>Volatile is also useful, when you want to force the compiler not to optimize a specific code sequence (e.g. for writing a micro-benchmark).</p>\n" }, { "answer_id": 246392, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 8, "selected": false, "text": "<p>Another use for <code>volatile</code> is signal handlers. If you have code like this:</p>\n\n<pre><code>int quit = 0;\nwhile (!quit)\n{\n /* very small loop which is completely visible to the compiler */\n}\n</code></pre>\n\n<p>The compiler is allowed to notice the loop body does not touch the <code>quit</code> variable and convert the loop to a <code>while (true)</code> loop. Even if the <code>quit</code> variable is set on the signal handler for <code>SIGINT</code> and <code>SIGTERM</code>; the compiler has no way to know that.</p>\n\n<p>However, if the <code>quit</code> variable is declared <code>volatile</code>, the compiler is forced to load it every time, because it can be modified elsewhere. This is exactly what you want in this situation.</p>\n" }, { "answer_id": 2884943, "author": "venu", "author_id": 347393, "author_profile": "https://Stackoverflow.com/users/347393", "pm_score": -1, "selected": false, "text": "<p>it does not allows compiler to automatic changing values of variables. a volatile variable is for dynamic use.</p>\n" }, { "answer_id": 3148813, "author": "Alexandre C.", "author_id": 373025, "author_profile": "https://Stackoverflow.com/users/373025", "pm_score": 4, "selected": false, "text": "<p>A marginal use for volatile is the following. Say you want to compute the numerical derivative of a function <code>f</code> :</p>\n\n<pre><code>double der_f(double x)\n{\n static const double h = 1e-3;\n return (f(x + h) - f(x)) / h;\n}\n</code></pre>\n\n<p>The problem is that <code>x+h-x</code> is generally not equal to <code>h</code> due to roundoff errors. Think about it : when you substract very close numbers, you lose a lot of significant digits which can ruin the computation of the derivative (think 1.00001 - 1). A possible workaround could be</p>\n\n<pre><code>double der_f2(double x)\n{\n static const double h = 1e-3;\n double hh = x + h - x;\n return (f(x + hh) - f(x)) / hh;\n}\n</code></pre>\n\n<p>but depending on your platform and compiler switches, the second line of that function may be wiped out by a aggressively optimizing compiler. So you write instead</p>\n\n<pre><code> volatile double hh = x + h;\n hh -= x;\n</code></pre>\n\n<p>to force the compiler to read the memory location containing hh, forfeiting an eventual optimization opportunity. </p>\n" }, { "answer_id": 3308849, "author": "Robert S. Barnes", "author_id": 71074, "author_profile": "https://Stackoverflow.com/users/71074", "pm_score": 5, "selected": false, "text": "<p>See this article by Andrei Alexandrescu, \"<a href=\"http://www.drdobbs.com/184403766\" rel=\"noreferrer\">volatile - Multithreaded Programmer's Best Friend</a>\"</p>\n\n<blockquote>\n <p>The <b>volatile</b> keyword was\n devised to prevent compiler\n optimizations that might render code\n incorrect in the presence of certain\n asynchronous events. For example, if\n you declare a primitive variable as\n <b>volatile</b>, the compiler is not\n permitted to cache it in a register --\n a common optimization that would be\n disastrous if that variable were\n shared among multiple threads. So the\n general rule is, if you have variables\n of primitive type that must be shared\n among multiple threads, declare those\n variables <b>volatile</b>. But you can\n actually do a lot more with this\n keyword: you can use it to catch code\n that is not thread safe, and you can\n do so at compile time. This article\n shows how it is done; the solution\n involves a simple smart pointer that\n also makes it easy to serialize\n critical sections of code.</p>\n</blockquote>\n\n<p>The article applies to both <code>C</code> and <code>C++</code>.</p>\n\n<p>Also see the article \"<a href=\"http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf\" rel=\"noreferrer\">C++ and the Perils of Double-Checked Locking</a>\" by Scott Meyers and Andrei Alexandrescu:</p>\n\n<blockquote>\n <p>So when dealing with some memory locations (e.g. memory mapped ports or memory referenced by ISRs [ Interrupt Service Routines ] ), some optimizations must be suspended. volatile exists for specifying special treatment for such locations, specifically: (1) the content of a volatile variable is \"unstable\" (can change by means unknown to the compiler), (2) all writes to volatile data are \"observable\" so they must be executed religiously, and (3) all operations on volatile data are executed in the sequence in which they appear in the source code. The first two rules ensure proper reading and writing. The last one allows implementation of I/O protocols that mix input and output. This is informally what C and C++'s volatile guarantees.</p>\n</blockquote>\n" }, { "answer_id": 6632483, "author": "Structure padding", "author_id": 836361, "author_profile": "https://Stackoverflow.com/users/836361", "pm_score": 3, "selected": false, "text": "<p>volatile means the storage is likely to change at anytime and be changed but something outside the control of the user program. This means that if you reference the variable, the program should always check the physical address (ie a mapped input fifo), and not use it in a cached way.</p>\n" }, { "answer_id": 6881183, "author": "Neo Cambell", "author_id": 829846, "author_profile": "https://Stackoverflow.com/users/829846", "pm_score": 4, "selected": false, "text": "<p>There are two uses. These are specially used more often in embedded development.</p>\n\n<ol>\n<li><p>Compiler will not optimise the functions that uses variables that are defined with volatile keyword</p></li>\n<li><p>Volatile is used to access exact memory locations in RAM, ROM, etc... This is used more often to control memory-mapped devices, access CPU registers and locate specific memory locations.</p></li>\n</ol>\n\n<p>See examples with assembly listing.\n<a href=\"http://www.expertcore.org/viewtopic.php?f=18&amp;t=2674#p7737\" rel=\"noreferrer\">Re: Usage of C \"volatile\" Keyword in Embedded Development</a></p>\n" }, { "answer_id": 8277670, "author": "Alexey Frunze", "author_id": 968261, "author_profile": "https://Stackoverflow.com/users/968261", "pm_score": 3, "selected": false, "text": "<p>I'll mention another scenario where volatiles are important.</p>\n\n<p>Suppose you memory-map a file for faster I/O and that file can change behind the scenes (e.g. the file is not on your local hard drive, but is instead served over the network by another computer).</p>\n\n<p>If you access the memory-mapped file's data through pointers to non-volatile objects (at the source code level), then the code generated by the compiler can fetch the same data multiple times without you being aware of it.</p>\n\n<p>If that data happens to change, your program may become using two or more different versions of the data and get into an inconsistent state. This can lead not only to logically incorrect behavior of the program but also to exploitable security holes in it if it processes untrusted files or files from untrusted locations.</p>\n\n<p>If you care about security, and you should, this is an important scenario to consider.</p>\n" }, { "answer_id": 12284234, "author": "coanor", "author_id": 342348, "author_profile": "https://Stackoverflow.com/users/342348", "pm_score": 2, "selected": false, "text": "<p>The Wiki say everything about <code>volatile</code>:</p>\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Volatile_variable\" rel=\"nofollow noreferrer\">volatile (computer programming)</a></li>\n</ul>\n<p>And the Linux kernel's doc also make a excellent notation about <code>volatile</code>:</p>\n<ul>\n<li><a href=\"https://www.kernel.org/doc/html/latest/process/volatile-considered-harmful.html#why-the-volatile-type-class-should-not-be-used\" rel=\"nofollow noreferrer\">Why the &quot;volatile&quot; type class should not be used</a></li>\n</ul>\n" }, { "answer_id": 28123172, "author": "Venkatakrishna Kalepalli", "author_id": 4184683, "author_profile": "https://Stackoverflow.com/users/4184683", "pm_score": 5, "selected": false, "text": "<p>My simple explanation is:</p>\n\n<p>In some scenarios, based on the logic or code, the compiler will do optimisation of variables which it thinks do not change. The <code>volatile</code> keyword prevents a variable being optimised.</p>\n\n<p>For example:</p>\n\n<pre><code>bool usb_interface_flag = 0;\nwhile(usb_interface_flag == 0)\n{\n // execute logic for the scenario where the USB isn't connected \n}\n</code></pre>\n\n<p>From the above code, the compiler may think <code>usb_interface_flag</code> is defined as 0, and that in the while loop it will be zero forever. After optimisation, the compiler will treat it as <code>while(true)</code> all the time, resulting in an infinite loop. </p>\n\n<p>To avoid these kinds of scenarios, we declare the flag as volatile, we are telling to compiler that this value may be changed by an external interface or other module of program, i.e., please don't optimise it. That's the use case for volatile. </p>\n" }, { "answer_id": 35991544, "author": "Oliver", "author_id": 3877336, "author_profile": "https://Stackoverflow.com/users/3877336", "pm_score": 3, "selected": false, "text": "<p>In my opinion, you should not expect too much from <code>volatile</code>. To illustrate, look at the example in <a href=\"https://stackoverflow.com/a/246148/1677912\">Nils Pipenbrinck's highly-voted answer</a>.</p>\n\n<p>I would say, his example is not suitable for <code>volatile</code>. <code>volatile</code> is only used to:\n <em>prevent the compiler from making useful and desirable optimizations</em>. It is nothing about the thread safe, atomic access or even memory order.</p>\n\n<p>In that example:</p>\n\n<pre><code> void SendCommand (volatile MyHardwareGadget * gadget, int command, int data)\n {\n // wait while the gadget is busy:\n while (gadget-&gt;isbusy)\n {\n // do nothing here.\n }\n // set data first:\n gadget-&gt;data = data;\n // writing the command starts the action:\n gadget-&gt;command = command;\n }\n</code></pre>\n\n<p>the <code>gadget-&gt;data = data</code> before <code>gadget-&gt;command = command</code> only is only guaranteed in compiled code by compiler. At running time, the processor still possibly reorders the data and command assignment, regarding to the processor architecture. The hardware could get the wrong data(suppose gadget is mapped to hardware I/O). The memory barrier is needed between data and command assignment.</p>\n" }, { "answer_id": 51333563, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 3, "selected": false, "text": "<p>In the language designed by Dennis Ritchie, every access to any object, other than automatic objects whose address had not been taken, would behave as though it computed the address of the object and then read or wrote the storage at that address. This made the language very powerful, but severely limited optimization opportunities.</p>\n\n<p>While it might have been possible to add a qualifier that would invite a compiler to assume that a particular object wouldn't be changed in weird ways, such an assumption would be appropriate for the vast majority of objects in C programs, and it would have been impractical to add a qualifier to all the objects for which such assumption would be appropriate. On the other hand, some programs need to use some objects for which such an assumption would not hold. To resolve this issue, the Standard says that compilers may assume that objects which are not declared <code>volatile</code> will not have their value observed or changed in ways that are outside the compiler's control, or would be outside a reasonable compiler's understanding.</p>\n\n<p>Because various platforms may have different ways in which objects could be observed or modified outside a compiler's control, it is appropriate that quality compilers for those platforms should differ in their exact handling of <code>volatile</code> semantics. Unfortunately, because the Standard failed to suggest that quality compilers intended for low-level programming on a platform should handle <code>volatile</code> in a way that will recognize any and all relevant effects of a particular read/write operation on that platform, many compilers fall short of doing so in ways that make it harder to process things like background I/O in a way which is efficient but can't be broken by compiler \"optimizations\".</p>\n" }, { "answer_id": 52934789, "author": "rajeshsam", "author_id": 5383418, "author_profile": "https://Stackoverflow.com/users/5383418", "pm_score": 3, "selected": false, "text": "<p>In simple terms, it tells the compiler not to do any optimisation on a particular variable. Variables which are mapped to device register are modified indirectly by the device. In this case, volatile must be used.</p>\n" }, { "answer_id": 59235288, "author": "Siddharth", "author_id": 4287117, "author_profile": "https://Stackoverflow.com/users/4287117", "pm_score": 0, "selected": false, "text": "<p>As rightly suggested by many here, the volatile keyword's popular use is to skip the optimisation of the volatile variable.</p>\n\n<p>The best advantage that comes to mind, and worth mentioning after reading about volatile is -- to prevent <em>rolling back</em> of the variable in case of a <code>longjmp</code>. A non-local jump.</p>\n\n<p>What does this mean?</p>\n\n<p>It simply means that the last value will be retained after you do <em>stack unwinding</em>, to return to some previous stack frame; typically in case of some erroneous scenario.</p>\n\n<p>Since it'd be out of scope of this question, I am not going into details of <code>setjmp/longjmp</code> here, but it's worth reading about it; and how the volatility feature can be used to retain the last value.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Why is `volatile` needed in C? What is it used for? What will it do?
`volatile` tells the compiler not to optimize anything that has to do with the `volatile` variable. There are at least three common reasons to use it, all involving situations where the value of the variable can change without action from the visible code: * When you interface with hardware that changes the value itself * when there's another thread running that also uses the variable * when there's a signal handler that might change the value of the variable. Let's say you have a little piece of hardware that is mapped into RAM somewhere and that has two addresses: a command port and a data port: ``` typedef struct { int command; int data; int isBusy; } MyHardwareGadget; ``` Now you want to send some command: ``` void SendCommand (MyHardwareGadget * gadget, int command, int data) { // wait while the gadget is busy: while (gadget->isbusy) { // do nothing here. } // set data first: gadget->data = data; // writing the command starts the action: gadget->command = command; } ``` Looks easy, but it can fail because the compiler is free to change the order in which data and commands are written. This would cause our little gadget to issue commands with the previous data-value. Also take a look at the wait while busy loop. That one will be optimized out. The compiler will try to be clever, read the value of `isBusy` just once and then go into an infinite loop. That's not what you want. The way to get around this is to declare the pointer `gadget` as `volatile`. This way the compiler is forced to do what you wrote. It can't remove the memory assignments, it can't cache variables in registers and it can't change the order of assignments either This is the correct version: ``` void SendCommand (volatile MyHardwareGadget * gadget, int command, int data) { // wait while the gadget is busy: while (gadget->isBusy) { // do nothing here. } // set data first: gadget->data = data; // writing the command starts the action: gadget->command = command; } ```
246,130
<p>I'm working on a eclipse plug-in and I've tried to create another test project seperate from the plug-in. The reason I do this is to not let the plug-in depend on jUnit when it is exported. However, I can't access the Eclipse Plug-in API when I do the testing. Whenever I try to add Plug-in dependencies the import list to that is empty.</p> <p>Does anyone know how to import Eclipse plug-in API to an existing project? The workspace layout looks like this at the moment:</p> <pre><code>+- com.foo.myplugin | | | +- JRE System Library | | | +- Plug-in Dependencies | | | +- src | | | +- icons, META-INF, plugin.xml, etc... | +- com.foo.myplugin.test | +- JRE System Library | +- JUnit 4 | +- src </code></pre>
[ { "answer_id": 246179, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "<p>You could try to add the plugin nature to your new myplugin.test project.</p>\n\n<p>In your .project file:</p>\n\n<pre><code>&lt;natures&gt;\n\n &lt;nature&gt;org.eclipse.pde.PluginNature&lt;/nature&gt;\n [...]\n&lt;/natures&gt;\n</code></pre>\n\n<p>Then in the .classpath, add:</p>\n\n<pre><code>&lt;classpath&gt;\n [...]\n &lt;classpathentry kind=\"con\" path=\"org.eclipse.pde.core.requiredPlugins\"/&gt;\n [...]\n&lt;/classpath&gt;\n</code></pre>\n\n<p>Delete your myplugin.test from the workspace, re-import that project and see if that does the trick...</p>\n" }, { "answer_id": 246271, "author": "Spoike", "author_id": 3713, "author_profile": "https://Stackoverflow.com/users/3713", "pm_score": 2, "selected": false, "text": "<p>You can export the plug-in dependency from the plug-in project. Easiest way is like this:</p>\n\n<ol>\n<li><p>Go to your <code>com.foo.plugin</code> project properties </p></li>\n<li><p>Go to <em>Java Build Path > Order and Export</em></p></li>\n<li><p>Check the <em>Plug-in Dependencies</em> entry</p></li>\n</ol>\n\n<p>The test project should now be able to use plug-in API without the need to use all plugin configuration required for a plug-in project.</p>\n" }, { "answer_id": 255368, "author": "rcreswick", "author_id": 3446, "author_profile": "https://Stackoverflow.com/users/3446", "pm_score": 4, "selected": true, "text": "<p>The recomended way of ding this seems to be with Plug-in fragments:</p>\n\n<p><a href=\"http://rcpquickstart.com/2007/06/20/unit-testing-plug-ins-with-fragments/\" rel=\"nofollow noreferrer\">http://rcpquickstart.com/2007/06/20/unit-testing-plug-ins-with-fragments/</a></p>\n\n<p>The fragment gets a high-degree of access to your plugin's code and separates the testing logic / dependencies from the plugin itsself.</p>\n\n<p>Now if only I could find a way to test them in an automated system... (see: <a href=\"https://stackoverflow.com/questions/255370/automating-unit-tests-junit-for-eclipse-plugin-deveopment\">Automating unit tests (junit) for Eclipse Plugin development</a> )</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713/" ]
I'm working on a eclipse plug-in and I've tried to create another test project seperate from the plug-in. The reason I do this is to not let the plug-in depend on jUnit when it is exported. However, I can't access the Eclipse Plug-in API when I do the testing. Whenever I try to add Plug-in dependencies the import list to that is empty. Does anyone know how to import Eclipse plug-in API to an existing project? The workspace layout looks like this at the moment: ``` +- com.foo.myplugin | | | +- JRE System Library | | | +- Plug-in Dependencies | | | +- src | | | +- icons, META-INF, plugin.xml, etc... | +- com.foo.myplugin.test | +- JRE System Library | +- JUnit 4 | +- src ```
The recomended way of ding this seems to be with Plug-in fragments: <http://rcpquickstart.com/2007/06/20/unit-testing-plug-ins-with-fragments/> The fragment gets a high-degree of access to your plugin's code and separates the testing logic / dependencies from the plugin itsself. Now if only I could find a way to test them in an automated system... (see: [Automating unit tests (junit) for Eclipse Plugin development](https://stackoverflow.com/questions/255370/automating-unit-tests-junit-for-eclipse-plugin-deveopment) )
246,137
<p>Im a coding a library including textual feedback that I need to translate.</p> <p>I put the following lines in a <code>_config.py</code> module that I import everywhere in my app :</p> <pre><code>import gettext, os, sys pathname = os.path.dirname(sys.argv[0]) localdir = os.path.abspath(pathname) + "/locale" gettext.install("messages", localdir) </code></pre> <p>I have the <code>*.mo</code> files in <code>./locale/lang_LANG/LC_MESSAGES</code> and I apply the <code>_()</code> function to all the strings that need to be translated.</p> <p>Now I just added a feature for the user, supposedly a programmer, to be able to create his own messages. I don't want him to care about the underlying implementation, so I want him to be able to make it something straightforward like :</p> <pre><code>lib_object.message = "My message" </code></pre> <p>I used properties to make it clean, but what if my user whats to translate his own code (that uses mine) and does something like :</p> <pre><code>import gettext, os, sys pathname = os.path.dirname(sys.argv[0]) localdir = os.path.abspath(pathname) + "/locale" gettext.install("user_app", localdir) lib_object.message = _("My message") </code></pre> <p>Is it a problem ? What can I do to avoid troubles without bothering my user ?</p>
[ { "answer_id": 246254, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 2, "selected": false, "text": "<p>You can only gettext.install() once. In general it's useless for library work -- gettext.install() will only do the right thing if the module calling it is in charge of the whole program, since it will only provide you with one catalog to load from. Library code should do something akin to what Mailman does: have their own wrapper for gettext() that passes the right arguments for this module, then imports that as '_' in each module that wants to use it.</p>\n" }, { "answer_id": 398420, "author": "runeh", "author_id": 2906, "author_profile": "https://Stackoverflow.com/users/2906", "pm_score": 3, "selected": true, "text": "<p>You can use the class based gettext api to isolate message catalogs. This is also what is recommended in the <a href=\"http://docs.python.org/library/gettext.html#class-based-api\" rel=\"nofollow noreferrer\">python gettext documentation</a>.</p>\n\n<p>The drawback is that you, or the other dev, will have to use the gettext method or define the <code>_()</code> method in the local scope, bound to the specific gettext class. An example of a class with its own string catalog:</p>\n\n<pre><code>import gettext\n\nclass MyClass(object):\n def __init__(self, locale_for_instance):\n self.lang = gettext.translation(\"appname\", localedir, \\\n locale=locale_for_instance)\n\n def some_method(self, arg):\n return self.lang.gettext(\"You called some method\")\n\n def other_method(self, arg): # does the same thing\n _ = self.lang.gettext\n return _(\"You called some method\")\n</code></pre>\n\n<p>You could stick the code for adding the <code>_()</code> in a decorator, so all the methods that need it is prefixed with something like <code>@with_local_gettext</code></p>\n\n<p>(Note, I've not tested the above could but It Should Work Just Fine(tm) )</p>\n\n<p>If the goal is to not bother your user (and he's not very good) I guess you could use the class based approach in your code and let the user use the global one.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ]
Im a coding a library including textual feedback that I need to translate. I put the following lines in a `_config.py` module that I import everywhere in my app : ``` import gettext, os, sys pathname = os.path.dirname(sys.argv[0]) localdir = os.path.abspath(pathname) + "/locale" gettext.install("messages", localdir) ``` I have the `*.mo` files in `./locale/lang_LANG/LC_MESSAGES` and I apply the `_()` function to all the strings that need to be translated. Now I just added a feature for the user, supposedly a programmer, to be able to create his own messages. I don't want him to care about the underlying implementation, so I want him to be able to make it something straightforward like : ``` lib_object.message = "My message" ``` I used properties to make it clean, but what if my user whats to translate his own code (that uses mine) and does something like : ``` import gettext, os, sys pathname = os.path.dirname(sys.argv[0]) localdir = os.path.abspath(pathname) + "/locale" gettext.install("user_app", localdir) lib_object.message = _("My message") ``` Is it a problem ? What can I do to avoid troubles without bothering my user ?
You can use the class based gettext api to isolate message catalogs. This is also what is recommended in the [python gettext documentation](http://docs.python.org/library/gettext.html#class-based-api). The drawback is that you, or the other dev, will have to use the gettext method or define the `_()` method in the local scope, bound to the specific gettext class. An example of a class with its own string catalog: ``` import gettext class MyClass(object): def __init__(self, locale_for_instance): self.lang = gettext.translation("appname", localedir, \ locale=locale_for_instance) def some_method(self, arg): return self.lang.gettext("You called some method") def other_method(self, arg): # does the same thing _ = self.lang.gettext return _("You called some method") ``` You could stick the code for adding the `_()` in a decorator, so all the methods that need it is prefixed with something like `@with_local_gettext` (Note, I've not tested the above could but It Should Work Just Fine(tm) ) If the goal is to not bother your user (and he's not very good) I guess you could use the class based approach in your code and let the user use the global one.
246,143
<p>this is my old code</p> <hr> <pre><code> protected override bool OnPreAction(string actionName, System.Reflection.MethodInfo methodInfo) { if ("|Register|RegisterPage|Login|LoginPage|Logout|Service".ToLower().Contains(actionName.ToLower())) { return base.OnPreAction(actionName, methodInfo); } Customer = CustomerHelper.GetCustomer(); if (Customer.IsSeccessedLogin()) { return base.OnPreAction(actionName, methodInfo); } Response.Redirect("Login.html"); return false; } </code></pre>
[ { "answer_id": 246778, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 5, "selected": true, "text": "<pre><code>string actionName = (string)filterContext.RouteData.Values[\"action\"];\n</code></pre>\n" }, { "answer_id": 521437, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 5, "selected": false, "text": "<p>FYI, as of RC1, you do it like this:</p>\n\n<pre><code>filterContext.ActionDescriptor.ActionName\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31966/" ]
this is my old code --- ``` protected override bool OnPreAction(string actionName, System.Reflection.MethodInfo methodInfo) { if ("|Register|RegisterPage|Login|LoginPage|Logout|Service".ToLower().Contains(actionName.ToLower())) { return base.OnPreAction(actionName, methodInfo); } Customer = CustomerHelper.GetCustomer(); if (Customer.IsSeccessedLogin()) { return base.OnPreAction(actionName, methodInfo); } Response.Redirect("Login.html"); return false; } ```
``` string actionName = (string)filterContext.RouteData.Values["action"]; ```