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
204,095
<p>I would like to create (in code) tree of controls that would render as a table with several TBODY tags, i.e.:</p> <p> </p> <pre><code>&lt;TBODY&gt; &lt;TR&gt; &lt;TD&gt;&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;&lt;/TD&gt; &lt;/TR&gt; &lt;/TBODY&gt; </code></pre> <p></p> <p>I tried both Table and HtmlTable controls but had no success. Any clues?</p>
[ { "answer_id": 204103, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 3, "selected": true, "text": "<p>How are you generating your data? You could use a templated control like a Repeater or ListView as that gives you full control of the HTML you're generating.</p>\n\n<p>If you're wanting to create the controls purely in C# you can use the HtmlGenericControl (<a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlgenericcontrol.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlgenericcontrol.aspx</a>), you'll need to provide a tag type in the constructor.</p>\n" }, { "answer_id": 204166, "author": "Marcin Hoppe", "author_id": 28154, "author_profile": "https://Stackoverflow.com/users/28154", "pm_score": 0, "selected": false, "text": "<p>I am writing a class that implements IBindableTemplate, so all of the rendering has to be done in code. I will give the HtmlGenericControl a try. Thanks!</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28154/" ]
I would like to create (in code) tree of controls that would render as a table with several TBODY tags, i.e.: ``` <TBODY> <TR> <TD></TD> </TR> <TR> <TD></TD> </TR> </TBODY> ``` I tried both Table and HtmlTable controls but had no success. Any clues?
How are you generating your data? You could use a templated control like a Repeater or ListView as that gives you full control of the HTML you're generating. If you're wanting to create the controls purely in C# you can use the HtmlGenericControl (<http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlgenericcontrol.aspx>), you'll need to provide a tag type in the constructor.
204,115
<p>So there seems to be this problem with GNU Make's $(wildcard) function keeping a directory open on Windows. See (unasnwered) post "<a href="http://www.cygwin.com/ml/cygwin/2003-06/msg01182.html" rel="nofollow noreferrer">make is holding a directory open</a>". Google does not provide much information on the topic.</p> <p>In short: the Makefile uses the $(wildcard) function at some point, and keeps a directory open, which typically prevents the "make clean" rule to do its work correctly. Re-running "make clean" a second time usually solves it.</p> <p>I'm using GNU Make version 3.81 under a standard DOS-Box. The author of the post linked to above is using Cygwin.</p> <p>Has anyone found a fix for this?</p>
[ { "answer_id": 220331, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 2, "selected": false, "text": "<p>Sounds like a file descriptor leak, all right -- harmless for very-short-lived processes (like make) on UNIX, but a right PITA on Windows.</p>\n\n<p>As this is allegedly a bug in make, as opposed to a problem with its usage, it should be addressed first by validating that it still exists when built from source on the newest upstream version, and then by <A HREF=\"http://savannah.gnu.org/bugs/?group=make\" rel=\"nofollow noreferrer\">filing a bug report</A> with the GNU make project (or with any distributor with whom you have an appropriate support contract), or diving into the source and attempting to fix it yourself.</p>\n\n<p>It wouldn't hurt to try to reproduce on Linux -- checking for file descriptor leaks are much easier here, as one can just look at <code>/proc/self/fd</code> (or, for a child of make, <code>/proc/$PPID/fd</code>) for things that don't belong.</p>\n" }, { "answer_id": 388248, "author": "Carl Seleborg", "author_id": 2095, "author_profile": "https://Stackoverflow.com/users/2095", "pm_score": 1, "selected": true, "text": "<p>I did find a <strong>workaround</strong> for the problem, which at least lets me work in peace.</p>\n\n<p>The problem was that the <code>$(wildcard)</code> function was used to collect the sources files. My clean rule, however, only deletes a directory - no need for the collecting to take please. So I basically put the part of the Makefile that needs to collect the sources files in a conditional statement:</p>\n\n<pre><code># The clean rule is always parsed\nclean:\n rm -rf $(OUTPUT_DIRECTORY)\n\n# The compile rule is only interpreted if we did not invoke 'make clean'. We\n# can test the value of $(MAKECMDGOALS) for that:\nifeq ($(filter $(MAKECMDGOALS),clean),)\n\nSOURCE_FILES := $(wildcard ...)\n\ncompile:\n g++ $(SOURCE_FILES) ...\n\nendif\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2095/" ]
So there seems to be this problem with GNU Make's $(wildcard) function keeping a directory open on Windows. See (unasnwered) post "[make is holding a directory open](http://www.cygwin.com/ml/cygwin/2003-06/msg01182.html)". Google does not provide much information on the topic. In short: the Makefile uses the $(wildcard) function at some point, and keeps a directory open, which typically prevents the "make clean" rule to do its work correctly. Re-running "make clean" a second time usually solves it. I'm using GNU Make version 3.81 under a standard DOS-Box. The author of the post linked to above is using Cygwin. Has anyone found a fix for this?
I did find a **workaround** for the problem, which at least lets me work in peace. The problem was that the `$(wildcard)` function was used to collect the sources files. My clean rule, however, only deletes a directory - no need for the collecting to take please. So I basically put the part of the Makefile that needs to collect the sources files in a conditional statement: ``` # The clean rule is always parsed clean: rm -rf $(OUTPUT_DIRECTORY) # The compile rule is only interpreted if we did not invoke 'make clean'. We # can test the value of $(MAKECMDGOALS) for that: ifeq ($(filter $(MAKECMDGOALS),clean),) SOURCE_FILES := $(wildcard ...) compile: g++ $(SOURCE_FILES) ... endif ```
204,123
<p>I am cloning a hidden table row then populating it and after validation I want to show the row using a jquery effect ... say .show("slow")</p> <pre><code>var baseRow = $("#tasks tr#baseTaskLine"); var newRow = baseRow.clone(); var lastRow = $("#tasks tr[id^='TaskLine_']" + dayClass + ":last"); var newRowId; if (lastRow.length == 0) { newRowId = "TaskLine_new0"; } else { newRowId = "TaskLine_new" + lastRow[0].rowIndex; } newRow.attr("id", newRowId); : [populate new row] : if (lastRow.length == 0) { baseRow.after(newRow); } else { lastRow.after(newRow); } newRow.hide(); : : [validate via webservice call] : newRow.show("slow"); </code></pre> <p>This does show the row but it appears instantly. I have tried hiding all the <code>&lt;td&gt;</code> elements of the row then showing those and that does seem to work but some strange styles get added to each <code>&lt;td&gt;</code> which interfere with the formatting i.e. <code>style="display: block;"</code></p>
[ { "answer_id": 204142, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 4, "selected": true, "text": "<p>This is not going to work this way. Table rows and cells are not meant to be displayed as blocks so the show/fade effects are not going to work on table rows directly.</p>\n\n<p>You could, however, put a &lt;div&gt; in each of the cells, something like this:</p>\n\n<pre><code>&lt;table&gt;\n&lt;tr id=\"row1\"&gt;&lt;td&gt;&lt;div&gt;Cell1:1&lt;/div&gt;&lt;/td&gt;&lt;td&gt;&lt;div&gt;Cell2:1&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;tr id=\"row2\"&gt;&lt;td&gt;&lt;div&gt;Cell1:2&lt;/div&gt;&lt;/td&gt;&lt;td&gt;&lt;div&gt;Cell2:2&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>and then to the following:</p>\n\n<pre><code>$('#row2 td div').show('slow');\n</code></pre>\n\n<p>This will yield the expected behaviour.</p>\n" }, { "answer_id": 204672, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "<p>Could you perhaps animate the height property of the row? I'm not sure if this would work, but it might be a lot simpler than adding extra markup.</p>\n\n<pre><code>&lt;table id=\"myTable\"&gt;\n &lt;tbody&gt;\n &lt;tr&gt;&lt;td&gt;Row 1,1&lt;/td&gt;&lt;td&gt;Row 1,2&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;Row 2,1&lt;/td&gt;&lt;td&gt;Row 2,2&lt;/td&gt;&lt;/tr&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>and this:</p>\n\n<pre><code>// get the row you're after.\nvar $row = $(\"#myTable tr:last\");\n// store its height\nvar h = $row.height();\n\n$row\n .css(\"height\", 0) // set the height back to 0\n .animate({\n height : h + \"px\" // animate it back to normal.\n }, \"slow\")\n;\n</code></pre>\n" }, { "answer_id": 3003094, "author": "Fletch", "author_id": 359426, "author_profile": "https://Stackoverflow.com/users/359426", "pm_score": -1, "selected": false, "text": "<p>I wrote a jQuery plugin that lets you do this. You can add and remove rows (with animation) and it doesn't require wrapping your data with a div or anything like that. Check it out at <a href=\"http://www.fletchzone.com/post/jQuery-Unobtrusively-Animated-Add-and-Remove-Table-Rows.aspx\" rel=\"nofollow noreferrer\">http://www.fletchzone.com/post/jQuery-Unobtrusively-Animated-Add-and-Remove-Table-Rows.aspx</a></p>\n\n<p>Best,</p>\n\n<p>Fletch</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18349/" ]
I am cloning a hidden table row then populating it and after validation I want to show the row using a jquery effect ... say .show("slow") ``` var baseRow = $("#tasks tr#baseTaskLine"); var newRow = baseRow.clone(); var lastRow = $("#tasks tr[id^='TaskLine_']" + dayClass + ":last"); var newRowId; if (lastRow.length == 0) { newRowId = "TaskLine_new0"; } else { newRowId = "TaskLine_new" + lastRow[0].rowIndex; } newRow.attr("id", newRowId); : [populate new row] : if (lastRow.length == 0) { baseRow.after(newRow); } else { lastRow.after(newRow); } newRow.hide(); : : [validate via webservice call] : newRow.show("slow"); ``` This does show the row but it appears instantly. I have tried hiding all the `<td>` elements of the row then showing those and that does seem to work but some strange styles get added to each `<td>` which interfere with the formatting i.e. `style="display: block;"`
This is not going to work this way. Table rows and cells are not meant to be displayed as blocks so the show/fade effects are not going to work on table rows directly. You could, however, put a <div> in each of the cells, something like this: ``` <table> <tr id="row1"><td><div>Cell1:1</div></td><td><div>Cell2:1</div></td></tr> <tr id="row2"><td><div>Cell1:2</div></td><td><div>Cell2:2</div></td></tr> </table> ``` and then to the following: ``` $('#row2 td div').show('slow'); ``` This will yield the expected behaviour.
204,128
<p>I am new to Hudson, perhaps someone knows the solution: I am trying to checkout the parent pom from the VSS in Hudson (vss plugin installed) and now I get class cast exception:</p> <pre><code>FATAL: hudson.maven.MavenModuleSetBuild cannot be cast to hudson.model.Build java.lang.ClassCastException: hudson.maven.MavenModuleSetBuild cannot be cast to hudson.model.Build at scm.vss.VSSSCM.checkout(VSSSCM.java:227) at hudson.model.AbstractProject.checkout(AbstractProject.java:664) at hudson.model.AbstractBuild$AbstractRunner.checkout(AbstractBuild.java:260) at hudson.model.AbstractBuild$AbstractRunner.run(AbstractBuild.java:234) at hudson.model.Run.run(Run.java:793) at hudson.maven.MavenModuleSetBuild.run(MavenModuleSetBuild.java:205) at hudson.model.ResourceController.execute(ResourceController.java:70) at hudson.model.Executor.run(Executor.java:88) </code></pre> <p>The line in question is here:</p> <pre><code>Build lastBuild = (Build)build.getPreviousBuild(); </code></pre> <p>Has the interface changed? Anyone knows the solution?</p>
[ { "answer_id": 222199, "author": "PEELY", "author_id": 17641, "author_profile": "https://Stackoverflow.com/users/17641", "pm_score": 0, "selected": false, "text": "<p>Looks like it's a bug in that version of Hudson. Have you tried a slightly older or newer version? IIRC they provide very frequent stable builds, almost nightly...</p>\n" }, { "answer_id": 320147, "author": "Carlos", "author_id": 27866, "author_profile": "https://Stackoverflow.com/users/27866", "pm_score": 0, "selected": false, "text": "<p>I've never faced that situation, but I have faced other problems when using maven projects in hudson like infinite loops upon builds and so (that I think Hudson itself should evaluate and avoid). By this I mean that this feature is quitely young and error-prone.</p>\n\n<p>Regarding at your exception, I can advise you to configure the project as a freestyle software project. If you set up the \"Execute maven top-level targets\" option on the build steps, the project will be built using Maven and probably the exception will dissapear.</p>\n\n<p>The other thing that Hudson does automatically when a project is configured as a maven project is triggering builds for dependent project on successfull build, but, you also can configure it manually by using the \"Build other projects\" feature.</p>\n\n<p>As you see, it's a little configuration price to pay and I strongly think that your exception will dissapear.</p>\n\n<p>Hope it helps.</p>\n\n<p>Carlos</p>\n" }, { "answer_id": 1100464, "author": "Michael Donohue", "author_id": 75204, "author_profile": "https://Stackoverflow.com/users/75204", "pm_score": 1, "selected": false, "text": "<p>Looks like Shashi filed this as Hudson issue <a href=\"http://issues.hudson-ci.org/browse/HUDSON-2665\" rel=\"nofollow noreferrer\">2665</a> which remains open.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15045/" ]
I am new to Hudson, perhaps someone knows the solution: I am trying to checkout the parent pom from the VSS in Hudson (vss plugin installed) and now I get class cast exception: ``` FATAL: hudson.maven.MavenModuleSetBuild cannot be cast to hudson.model.Build java.lang.ClassCastException: hudson.maven.MavenModuleSetBuild cannot be cast to hudson.model.Build at scm.vss.VSSSCM.checkout(VSSSCM.java:227) at hudson.model.AbstractProject.checkout(AbstractProject.java:664) at hudson.model.AbstractBuild$AbstractRunner.checkout(AbstractBuild.java:260) at hudson.model.AbstractBuild$AbstractRunner.run(AbstractBuild.java:234) at hudson.model.Run.run(Run.java:793) at hudson.maven.MavenModuleSetBuild.run(MavenModuleSetBuild.java:205) at hudson.model.ResourceController.execute(ResourceController.java:70) at hudson.model.Executor.run(Executor.java:88) ``` The line in question is here: ``` Build lastBuild = (Build)build.getPreviousBuild(); ``` Has the interface changed? Anyone knows the solution?
Looks like Shashi filed this as Hudson issue [2665](http://issues.hudson-ci.org/browse/HUDSON-2665) which remains open.
204,140
<p>How can I move items from one list box control to another listbox control using JavaScript in ASP.NET?</p>
[ { "answer_id": 204161, "author": "Remy Sharp", "author_id": 22617, "author_profile": "https://Stackoverflow.com/users/22617", "pm_score": 5, "selected": false, "text": "<p>If you're happy to use jQuery, it's very, very simple.</p>\n\n<pre><code>$('#firstSelect option:selected').appendTo('#secondSelect');\n</code></pre>\n\n<p>Where #firstSelect is the ID of the select box.</p>\n\n<p>I've included a working example here:</p>\n\n<p><a href=\"http://jsbin.com/aluzu\" rel=\"noreferrer\">http://jsbin.com/aluzu</a> (to edit: <a href=\"http://jsbin.com/aluzu/edit\" rel=\"noreferrer\">http://jsbin.com/aluzu/edit</a>)</p>\n" }, { "answer_id": 204429, "author": "Tom", "author_id": 20, "author_profile": "https://Stackoverflow.com/users/20", "pm_score": 4, "selected": true, "text": "<p>This code assumes that you have an anchor or that will trigger to movement when it is clicked:</p>\n\n<pre><code>document.getElementById('moveTrigger').onclick = function() {\n\n var listTwo = document.getElementById('secondList');\n var options = document.getElementById('firstList').getElementsByTagName('option');\n\n while(options.length != 0) {\n listTwo.appendChild(options[0]);\n }\n\n }\n</code></pre>\n" }, { "answer_id": 204457, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 3, "selected": false, "text": "<p>A library-independent solution:</p>\n\n<pre><code>function Move(inputControl)\n{\n var left = document.getElementById(\"Left\");\n var right = document.getElementById(\"Right\");\n var from, to;\n var bAll = false;\n switch (inputControl.value)\n {\n case '&lt;&lt;':\n bAll = true;\n // Fall through\n case '&lt;':\n from = right; to = left;\n break;\n case '&gt;&gt;':\n bAll = true;\n // Fall through\n case '&gt;':\n from = left; to = right;\n break;\n default:\n alert(\"Check your HTML!\");\n }\n for (var i = from.length - 1; i &gt;= 0; i--)\n {\n var o = from.options[i];\n if (bAll || o.selected)\n {\n from.remove(i);\n try\n {\n to.add(o, null); // Standard method, fails in IE (6&amp;7 at least)\n }\n catch (e)\n {\n to.add(o); // IE only\n }\n }\n }\n}\n</code></pre>\n\n<p>HTML</p>\n\n<pre><code>&lt;select id=\"Left\" multiple=\"multiple\" size=\"10\"&gt;\n &lt;option&gt;Some&lt;/option&gt;\n &lt;option&gt;List&lt;/option&gt;\n &lt;option&gt;Of&lt;/option&gt;\n &lt;option&gt;Items&lt;/option&gt;\n &lt;option&gt;To&lt;/option&gt;\n &lt;option&gt;Move&lt;/option&gt;\n &lt;option&gt;Around&lt;/option&gt;\n&lt;/select&gt;\n\n&lt;div id=\"Toolbar\"&gt;\n &lt;input type=\"button\" value=\"&amp;gt;\" onclick=\"Move(this)\"/&gt;\n &lt;input type=\"button\" value=\"&amp;gt;&amp;gt;\" onclick=\"Move(this)\"/&gt;\n &lt;input type=\"button\" value=\"&amp;lt;&amp;lt;\" onclick=\"Move(this)\"/&gt;\n &lt;input type=\"button\" value=\"&amp;lt;\" onclick=\"Move(this)\"/&gt;\n&lt;/div&gt;\n\n&lt;select id=\"Right\" multiple=\"multiple\" size=\"10\"&gt;\n&lt;/select&gt;\n</code></pre>\n\n<p>CSS (example)</p>\n\n<pre><code>select { width: 200px; float: left; }\n#Toolbar { width: 50px; float: left; text-align: center; padding-top: 30px; }\n#Toolbar input { width: 40px; }\n</code></pre>\n\n<p>Quick test FF3 and IE6 &amp; 7 only.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
How can I move items from one list box control to another listbox control using JavaScript in ASP.NET?
This code assumes that you have an anchor or that will trigger to movement when it is clicked: ``` document.getElementById('moveTrigger').onclick = function() { var listTwo = document.getElementById('secondList'); var options = document.getElementById('firstList').getElementsByTagName('option'); while(options.length != 0) { listTwo.appendChild(options[0]); } } ```
204,164
<p>I have a problem with a Delphi 2009 project : It can't initialize Indy 10 ! This code worked fine before in Delphi 2007 (although we might have been using an older revision of Indy, but I suspect that has not much to do with it);</p> <p>The initial call to IdWinsock2.InitializeWinSock(), raises this exception (with error code 998) :</p> <pre><code>Project EAServer.exe raised exception class EIdWinsockStubError with message 'Error on loading Winsock2 library (WS2\_32.DLL): Invalid access to memory location'. </code></pre> <p>But ws2_32.dll is in C:\Windows\System32 allright, with these version details :</p> <pre><code>File Version : 5.1.2600.5512 (xpsp.080413-0852) Description : Windows Socket 2.0 32-Bit DLL Copyright : © Microsoft Corporation. All rights reserved. </code></pre> <p>(this shows I'm on WinXP btw).</p> <p>The silly thing is, that when I look at the process itself (using "Process Explorer"), I can see the process already has this DLL open. The reason "WS2_32.DLL" is already loaded, seems to be because we use the RTL unit Winsock.pas in this project too. This unit is statically linked to "wsock32.dll", which has a dependancy on WS2_32.DLL, so there.</p> <p>Does anyone know why this code worked fine before (in Delphi 2007), and now (in Delphi 2009) it suddenly breaks?</p> <p>And is this inability to re-open the ws2_32 dll common knowledge, or is there really something wrong here? (I did check : I only have 1 version of these DLL's present on my system).</p> <p>Better yet : Can anyone help me fixing this?</p>
[ { "answer_id": 207060, "author": "Argalatyr", "author_id": 18484, "author_profile": "https://Stackoverflow.com/users/18484", "pm_score": 0, "selected": false, "text": "<p>This may be overly simplistic, but have you tried changing the order in which the relevant units are listed in your uses clause? Sometimes this helps in these situations.</p>\n" }, { "answer_id": 211423, "author": "Michał Niklas", "author_id": 22595, "author_profile": "https://Stackoverflow.com/users/22595", "pm_score": 0, "selected": false, "text": "<p>I think it could be problem with Ansi/Unicode calls of Win32 API (including WinSock API). Check if code using AnsiString/AnsiPchar call XxxA functions (eg MessageBoxA), and String/Pchar call xxW function (eg MessageBoxW). In previous versions of Delphi String was alias to AnsiString and XxxA Win API function was used, but now String is unicode by default and XxxW functions should be used.</p>\n" }, { "answer_id": 261962, "author": "PatrickvL", "author_id": 12170, "author_profile": "https://Stackoverflow.com/users/12170", "pm_score": 3, "selected": true, "text": "<p>I finally found an answer to this : The affected applications contained a bit of code-hooking that randomly damaged parts of System.dcu! (FYI : We're using a Delphi 2009 beta version of madshi's madCodeHook library). As soon as we switched to another code-hooking library, these symptoms disapeared... I guess that's what happens when you use beta-software. Anyway, sorry for bothering you with this. Problem solved!</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12170/" ]
I have a problem with a Delphi 2009 project : It can't initialize Indy 10 ! This code worked fine before in Delphi 2007 (although we might have been using an older revision of Indy, but I suspect that has not much to do with it); The initial call to IdWinsock2.InitializeWinSock(), raises this exception (with error code 998) : ``` Project EAServer.exe raised exception class EIdWinsockStubError with message 'Error on loading Winsock2 library (WS2\_32.DLL): Invalid access to memory location'. ``` But ws2\_32.dll is in C:\Windows\System32 allright, with these version details : ``` File Version : 5.1.2600.5512 (xpsp.080413-0852) Description : Windows Socket 2.0 32-Bit DLL Copyright : © Microsoft Corporation. All rights reserved. ``` (this shows I'm on WinXP btw). The silly thing is, that when I look at the process itself (using "Process Explorer"), I can see the process already has this DLL open. The reason "WS2\_32.DLL" is already loaded, seems to be because we use the RTL unit Winsock.pas in this project too. This unit is statically linked to "wsock32.dll", which has a dependancy on WS2\_32.DLL, so there. Does anyone know why this code worked fine before (in Delphi 2007), and now (in Delphi 2009) it suddenly breaks? And is this inability to re-open the ws2\_32 dll common knowledge, or is there really something wrong here? (I did check : I only have 1 version of these DLL's present on my system). Better yet : Can anyone help me fixing this?
I finally found an answer to this : The affected applications contained a bit of code-hooking that randomly damaged parts of System.dcu! (FYI : We're using a Delphi 2009 beta version of madshi's madCodeHook library). As soon as we switched to another code-hooking library, these symptoms disapeared... I guess that's what happens when you use beta-software. Anyway, sorry for bothering you with this. Problem solved!
204,169
<p>I have a very simple question. I want to test whether a particular port is currently under use or not. For this, I want to bind a TCP socket to the port, if the connection is refused means the port is in use and if not that mean the port is free.</p> <p>Can someone please tell me how can I write the TCP socket code in C? I am on a solaris platform.</p> <p>I know its very basic. But I appreciate your help. Thanks in advance.</p>
[ { "answer_id": 204219, "author": "Anonymous", "author_id": 15073, "author_profile": "https://Stackoverflow.com/users/15073", "pm_score": -1, "selected": false, "text": "<p>You might want to look at the source code of netstat. I believe there is a netstat in Solaris as well.</p>\n" }, { "answer_id": 204236, "author": "Joel Cunningham", "author_id": 5360, "author_profile": "https://Stackoverflow.com/users/5360", "pm_score": 5, "selected": true, "text": "<p>The call to bind function will return -1 if there is an error. This includes the case where the address is already in use.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;sys/socket.h&gt;\n#include &lt;netinet/in.h&gt;\n\n#define PORT 12345\n\nint main()\n{\n struct sockaddr_in addr;\n int fd;\n\n fd = socket(AF_INET, SOCK_STREAM, 0);\n if(fd == -1)\n {\n printf(\"Error opening socket\\n\");\n return -1;\n }\n\n addr.sin_port = htons(PORT);\n addr.sin_addr.s_addr = 0;\n addr.sin_addr.s_addr = INADDR_ANY;\n addr.sin_family = AF_INET;\n\n if(bind(fd, (struct sockaddr *)&amp;addr,sizeof(struct sockaddr_in) ) == -1)\n {\n printf(\"Error binding socket\\n\");\n return -1;\n }\n\n printf(\"Successfully bound to port %u\\n\", PORT);\n}\n</code></pre>\n" }, { "answer_id": 204237, "author": "moogs", "author_id": 26374, "author_profile": "https://Stackoverflow.com/users/26374", "pm_score": -1, "selected": false, "text": "<p>Do you just want to test if the particular port is currently in use? (and don't really need to make a program).\nIf so, you can use telnet:</p>\n\n<blockquote>\n <p>telnet host port</p>\n</blockquote>\n\n<p>If the connection fails, it's not in use. If it connects and waits for input from you, it's in use :)</p>\n" }, { "answer_id": 204362, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 3, "selected": false, "text": "<p>It depends slightly on exactly what you're trying to test.</p>\n\n<p>Using <code>bind()</code> in the way that joelc suggested will tell you if the port is open on <em>any</em> interface on your machine. Although to be thorough, you should not only be checking the return value from <code>bind()</code>, but also checking <code>errno == EADDRINUSE</code>.</p>\n\n<p>ie. (modification of joelc's code)</p>\n\n<pre><code>\nif(bind(socket, (struct sockaddr *)&sin,sizeof(struct sockaddr_in) ) == -1)\n{\n if( errno == EADDRINUSE )\n {\n // handle port already open case\n }\n else\n {\n // handle other errors\n }\n}\n</code></pre>\n\n<p>By changing the address used in the line: eg.</p>\n\n<pre><code>\n sin.sin_addr.s_addr = inet_addr(\"192.168.1.1\");\n</code></pre>\n\n<p>...you can test whether a port is available on a specific interface.</p>\n\n<p>Be aware though that this isn't a perfect test for port state. If another process had the port open and was terminated before it gracefully closed the port (ie. before calling <code>close()</code> on the socket) then you will usually get the same <code>EADDRINUSE</code> error.\n(depending on whether the SO_REUSEADDR option had been set on the socket)</p>\n\n<p>(side note: unless your test application is running with sufficient privileges you won't be able to bind() to any ports below 1024)</p>\n\n<p>As Anonymous suggested, you can also have a look at <code>netstat</code>. This will give you all of the same information that you can get by repeatedly calling <code>bind()</code> much more quickly and without any of the side effects (like it doesn't have to actually bind to the ports, which would make them unusable to any other processes).\nJust calling <code>netstat -a --numeric-ports -t</code> and analysing the output should give you everything that you're after.</p>\n\n<p>A comment on moogs suggestion though - calling telnet on each port will only tell you if a socket is listening on that port - not whether it's actually open.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27778/" ]
I have a very simple question. I want to test whether a particular port is currently under use or not. For this, I want to bind a TCP socket to the port, if the connection is refused means the port is in use and if not that mean the port is free. Can someone please tell me how can I write the TCP socket code in C? I am on a solaris platform. I know its very basic. But I appreciate your help. Thanks in advance.
The call to bind function will return -1 if there is an error. This includes the case where the address is already in use. ``` #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #define PORT 12345 int main() { struct sockaddr_in addr; int fd; fd = socket(AF_INET, SOCK_STREAM, 0); if(fd == -1) { printf("Error opening socket\n"); return -1; } addr.sin_port = htons(PORT); addr.sin_addr.s_addr = 0; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_family = AF_INET; if(bind(fd, (struct sockaddr *)&addr,sizeof(struct sockaddr_in) ) == -1) { printf("Error binding socket\n"); return -1; } printf("Successfully bound to port %u\n", PORT); } ```
204,170
<p>So I need to update a text field. Neither the UPDATE statement or the WRITETEXT statement work when used below</p> <pre><code>CREATE TABLE MyTable (IDField int, MyField text) INSERT INTO MyTable (IDField) SELECT 1 DECLARE @Data1 varchar(8000), @Data2 varchar(8000), @ptrval binary(16) SELECT @Data1 = REPLICATE('1',8000) SELECT @Data2 = REPLICATE('2',8000) -- this sets MyField to string of only 8000 characters UPDATE MyTable SET MyField = @Data1 + @Data2 WHERE IDField = 1 SELECT @ptrval = TEXTPTR(MyField ) FROM MyTable WHERE IDField = 1 -- this causes an error: Incorrect syntax near '+'. --WRITETEXT MyTable.MyField @ptrval @Data1 + @Data2 </code></pre> <p>How am I supposed to do this when local variables cannot be of type TEXT? (If I had SSQL Server 2005 I would use varchar(max) - but I don't)</p>
[ { "answer_id": 204255, "author": "Jim Birchall", "author_id": 989, "author_profile": "https://Stackoverflow.com/users/989", "pm_score": 4, "selected": true, "text": "<p>Try using UPDATETEXT instead</p>\n\n<pre><code>WRITETEXT MyTable.MyField @ptrval @Data1 \nUPDATETEXT MyTable.MyField @ptrval 8000 NULL @Data2\n</code></pre>\n\n<p>The insert offset is zero based so 8000 should write into the 8001st character.\nThe delete offset is null as a value of NULL deletes all data from the insert_offset position to the end of the existing text. </p>\n\n<p>Ref: <a href=\"http://msdn.microsoft.com/en-us/library/ms189466.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms189466.aspx</a></p>\n\n<p>Do not forget nvarchar (which you should use with ntext field) have a maximum capacity of half the varchar fields that you are using so your block sizes need to be reduced to 4000 in that case. </p>\n" }, { "answer_id": 204392, "author": "Mark Plumpton", "author_id": 10422, "author_profile": "https://Stackoverflow.com/users/10422", "pm_score": 2, "selected": false, "text": "<p>the values will actually vary in length so I will try it like this tomorrow:</p>\n\n<pre><code>WRITETEXT MyTable.MyField @ptrval @Data1 \nUPDATETEXT MyTable.MyField @ptrval Len(@Data1) NULL @Data2\n</code></pre>\n\n<p>the above worked but I had to calculate the length first:</p>\n\n<pre><code>WRITETEXT MyTable.MyField @ptrval @Data1\nSET @Len = LEN(@Data1)\nUPDATETEXT MyTable.MyField @ptrval @Len NULL @Data2\n</code></pre>\n\n<p>not sure why you can't use a function like LEN() where a parameter is expected.</p>\n" }, { "answer_id": 25936794, "author": "Jim Torguson", "author_id": 4058859, "author_profile": "https://Stackoverflow.com/users/4058859", "pm_score": 0, "selected": false, "text": "<p>I had a hard time with this one.</p>\n\n<p>I was trying to save long strings (actually rich text box contents) to a ntext feild.</p>\n\n<p>The solution turned out to be fairly simple.</p>\n\n<pre><code> SQLst = \"UPDATE Test SET Text = cast (@value as ntext)\" &amp; _\n \" WHERE Num = 3 \"\n\n Debug.Print(SQLst.ToString)\n\n Dim cnn As New SqlServerCe.SqlCeConnection(Tcon)\n Dim cmd = New SqlCeCommand(SQLst, cnn)\n cmd.Parameters.AddWithValue(\"@value\", strQuestionQUESTION)\n cnn.Open()\n cmd.ExecuteNonQuery()\n cnn.Close()\n</code></pre>\n\n<p>Note: strQuestionQUESTION was about 3000 characters or formatting code and text. \"Num\" is just an integer field in the \"Test\" database which also contain the ntext field name \"Text\"</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10422/" ]
So I need to update a text field. Neither the UPDATE statement or the WRITETEXT statement work when used below ``` CREATE TABLE MyTable (IDField int, MyField text) INSERT INTO MyTable (IDField) SELECT 1 DECLARE @Data1 varchar(8000), @Data2 varchar(8000), @ptrval binary(16) SELECT @Data1 = REPLICATE('1',8000) SELECT @Data2 = REPLICATE('2',8000) -- this sets MyField to string of only 8000 characters UPDATE MyTable SET MyField = @Data1 + @Data2 WHERE IDField = 1 SELECT @ptrval = TEXTPTR(MyField ) FROM MyTable WHERE IDField = 1 -- this causes an error: Incorrect syntax near '+'. --WRITETEXT MyTable.MyField @ptrval @Data1 + @Data2 ``` How am I supposed to do this when local variables cannot be of type TEXT? (If I had SSQL Server 2005 I would use varchar(max) - but I don't)
Try using UPDATETEXT instead ``` WRITETEXT MyTable.MyField @ptrval @Data1 UPDATETEXT MyTable.MyField @ptrval 8000 NULL @Data2 ``` The insert offset is zero based so 8000 should write into the 8001st character. The delete offset is null as a value of NULL deletes all data from the insert\_offset position to the end of the existing text. Ref: <http://msdn.microsoft.com/en-us/library/ms189466.aspx> Do not forget nvarchar (which you should use with ntext field) have a maximum capacity of half the varchar fields that you are using so your block sizes need to be reduced to 4000 in that case.
204,172
<p>How can I turn off certificate revocation for a WCF service's client? The client proxy was generated by wsdl.exe and inherits SoapHttpClientProtocol.</p>
[ { "answer_id": 204209, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 4, "selected": true, "text": "<p>I think you're looking for <code>ServicePointManager.ServerCertificateValidationCallback</code>:</p>\n<blockquote>\n<p><a href=\"http://msdn.microsoft.com/en-gb/library/system.net.servicepointmanager.servercertificatevalidationcallback.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-gb/library/system.net.servicepointmanager.servercertificatevalidationcallback.aspx</a></p>\n</blockquote>\n<p>Which takes a <code>RemoteCertificateValidationCallback</code> Delegate:</p>\n<blockquote>\n<p><a href=\"http://msdn.microsoft.com/en-gb/library/system.net.security.remotecertificatevalidationcallback.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-gb/library/system.net.security.remotecertificatevalidationcallback.aspx</a></p>\n</blockquote>\n<p>I've never dealt with a revoked certificate before (I have hand to handle other issues such as expired SSL's), but I'm guessing you'd just do something like:</p>\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n ServicePointManager.ServerCertificateValidationCallback +=\n new RemoteCertificateValidationCallback(ValidateCertificate);\n\n // Do WCF calls...\n }\n\n public static bool ValidateCertificate(object sender, X509Certificate cert, \n X509Chain chain, SslPolicyErrors sslPolicyErrors)\n {\n if(sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)\n {\n foreach(X509ChainStatus chainStatus in chain.ChainStatus)\n {\n if(chainStatus.Status == X509ChainStatusFlags.Revoked)\n {\n return true;\n }\n }\n }\n \n /* \n WARNING!\n \n You should perform other cert validation checks here and not blindly \n override your cert validation by returning true.\n\n Otherwise the secure channel between your client and service\n may not be secure.\n\n */\n\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 204908, "author": "jezell", "author_id": 27453, "author_profile": "https://Stackoverflow.com/users/27453", "pm_score": 1, "selected": false, "text": "<p>You can set certificate validation and revocation options in the config file for your application:</p>\n\n<p><a href=\"http://www.request-response.com/blog/PermaLink,guid,e9bb929b-d0b4-4626-b302-1d2715fc344a.aspx\" rel=\"nofollow noreferrer\">http://www.request-response.com/blog/PermaLink,guid,e9bb929b-d0b4-4626-b302-1d2715fc344a.aspx</a></p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19956/" ]
How can I turn off certificate revocation for a WCF service's client? The client proxy was generated by wsdl.exe and inherits SoapHttpClientProtocol.
I think you're looking for `ServicePointManager.ServerCertificateValidationCallback`: > > <http://msdn.microsoft.com/en-gb/library/system.net.servicepointmanager.servercertificatevalidationcallback.aspx> > > > Which takes a `RemoteCertificateValidationCallback` Delegate: > > <http://msdn.microsoft.com/en-gb/library/system.net.security.remotecertificatevalidationcallback.aspx> > > > I've never dealt with a revoked certificate before (I have hand to handle other issues such as expired SSL's), but I'm guessing you'd just do something like: ``` class Program { static void Main(string[] args) { ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateCertificate); // Do WCF calls... } public static bool ValidateCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if(sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors) { foreach(X509ChainStatus chainStatus in chain.ChainStatus) { if(chainStatus.Status == X509ChainStatusFlags.Revoked) { return true; } } } /* WARNING! You should perform other cert validation checks here and not blindly override your cert validation by returning true. Otherwise the secure channel between your client and service may not be secure. */ return false; } } ```
204,186
<p>In writing some test code I have found that Selector.select() can return without Selector.selectedKeys() containing any keys to process. This is happening in a tight loop when I register an accept()ed channel with</p> <pre>SelectionKey.OP_READ | SelectionKey.OP_CONNECT</pre> <p>as the operations of interest.</p> <p>According to the docs, select() should return when:</p> <p>1) There are channels that can be acted upon.</p> <p>2) You explicitly call Selector.wakeup() - no keys are selected.</p> <p>3) You explicitly Thread.interrupt() the thread doing the select() - no keys are selected.</p> <p>If I get no keys after the select() I must be in cases (2) and (3). However, my code is not calling wakeup() or interrupt() to initiate these returns.</p> <p>Any ideas as to what is causing this behaviour?</p>
[ { "answer_id": 205354, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 4, "selected": true, "text": "<p>Short answer: remove <code>OP_CONNECT</code> from the list of operations you are interested in for the accepted connection -- an accepted connection is already connected.</p>\n\n<p>I managed to reproduce the issue, which might be exactly what's happening to you:</p>\n\n<pre><code>import java.net.*;\nimport java.nio.channels.*;\n\n\npublic class MyNioServer {\n public static void main(String[] params) throws Exception {\n final ServerSocketChannel serverChannel = ServerSocketChannel.open();\n serverChannel.configureBlocking(true);\n serverChannel.socket().bind(new InetSocketAddress(\"localhost\", 12345));\n System.out.println(\"Listening for incoming connections\");\n final SocketChannel clientChannel = serverChannel.accept();\n System.out.println(\"Accepted connection: \" + clientChannel);\n\n\n final Selector selector = Selector.open();\n clientChannel.configureBlocking(false);\n final SelectionKey clientKey = clientChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT);\n System.out.println(\"Selecting...\");\n System.out.println(selector.select());\n System.out.println(selector.selectedKeys().size());\n System.out.println(clientKey.readyOps());\n }\n}\n</code></pre>\n\n<p>After the above server receives a connection, the very first <code>select()</code> on the connection exits without blocking and there are no keys with ready operations. I don't know why Java behaves in this way, but it appears many people get bitten by this behavior.</p>\n\n<p>The outcome is the same on Sun's JVM 1.5.0_06 on Windows XP as well as Sun's JVM 1.5.0_05 and 1.4.2_04 on Linux 2.6.</p>\n" }, { "answer_id": 6646131, "author": "user207421", "author_id": 207421, "author_profile": "https://Stackoverflow.com/users/207421", "pm_score": 3, "selected": false, "text": "<p>The reason is that <code>OP_CONNECT</code> and <code>OP_WRITE</code> are the same thing under the hood, so you should never be registered for both simultaneously (ditto <code>OP_ACCEPT</code> and <code>OP_READ</code>), and you should never be registered for <code>OP_CONNECT</code> at all when the channel is already connected, as it is in this case, having been accepted.</p>\n\n<p>And <code>OP_WRITE</code> is almost always ready, except when the socket send buffer in e kernel is full, so you should only register for that after you get a zero length write. So by registering the already connected channel for <code>OP_CONNECT,</code> you were really registering for <code>OP_WRITE,</code> which was ready, so <code>select()</code> got triggered.</p>\n" }, { "answer_id": 74562799, "author": "Pavel Moukhataev", "author_id": 5260478, "author_profile": "https://Stackoverflow.com/users/5260478", "pm_score": 0, "selected": false, "text": "<p>You should use <code>OP_CONNECT</code> when you connect to server, not when you are listening for incoming connections. Also make sure to configureBlocking <strong>before</strong> connect:</p>\n<pre><code> Selector selector = Selector.open();\n SocketChannel serverChannel = SocketChannel.open(StandardProtocolFamily.INET);\n serverChannel.configureBlocking(false);\n serverChannel.connect(new InetSocketAddress(&quot;localhost&quot;, 5454));\n serverChannel.register(selector, SelectionKey.OP_CONNECT);\n // event process cycle\n { \n int count = selector.select();\n for (SelectionKey key : selector.selectedKeys()) {\n log.info(&quot; {}&quot;, key.readyOps());\n if (key.isConnectable()) {\n log.info(&quot;Connection is ready&quot;);\n key.interestOps(SelectionKey.OP_READ);\n }\n if (key.isReadable()) {\n // read data here\n }\n }\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28164/" ]
In writing some test code I have found that Selector.select() can return without Selector.selectedKeys() containing any keys to process. This is happening in a tight loop when I register an accept()ed channel with ``` SelectionKey.OP_READ | SelectionKey.OP_CONNECT ``` as the operations of interest. According to the docs, select() should return when: 1) There are channels that can be acted upon. 2) You explicitly call Selector.wakeup() - no keys are selected. 3) You explicitly Thread.interrupt() the thread doing the select() - no keys are selected. If I get no keys after the select() I must be in cases (2) and (3). However, my code is not calling wakeup() or interrupt() to initiate these returns. Any ideas as to what is causing this behaviour?
Short answer: remove `OP_CONNECT` from the list of operations you are interested in for the accepted connection -- an accepted connection is already connected. I managed to reproduce the issue, which might be exactly what's happening to you: ``` import java.net.*; import java.nio.channels.*; public class MyNioServer { public static void main(String[] params) throws Exception { final ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.configureBlocking(true); serverChannel.socket().bind(new InetSocketAddress("localhost", 12345)); System.out.println("Listening for incoming connections"); final SocketChannel clientChannel = serverChannel.accept(); System.out.println("Accepted connection: " + clientChannel); final Selector selector = Selector.open(); clientChannel.configureBlocking(false); final SelectionKey clientKey = clientChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT); System.out.println("Selecting..."); System.out.println(selector.select()); System.out.println(selector.selectedKeys().size()); System.out.println(clientKey.readyOps()); } } ``` After the above server receives a connection, the very first `select()` on the connection exits without blocking and there are no keys with ready operations. I don't know why Java behaves in this way, but it appears many people get bitten by this behavior. The outcome is the same on Sun's JVM 1.5.0\_06 on Windows XP as well as Sun's JVM 1.5.0\_05 and 1.4.2\_04 on Linux 2.6.
204,208
<p>I want to detect and replace malformed UTF-8 characters with blank space using a Perl script while loading the data using SQL*Loader. How can I do this? </p>
[ { "answer_id": 204223, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>EDIT: (Removed bit about SQL Loader as it seems to no longer be relevant.)</p>\n\n<p>One problem is going to be working out what counts as the \"end\" of a malformed UTF-8 character. It's easy to say what's illegal, but it may not be obvious where the next legal character starts.</p>\n" }, { "answer_id": 204424, "author": "Mike G.", "author_id": 18901, "author_profile": "https://Stackoverflow.com/users/18901", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://www.rfc-editor.org/rfc/rfc3629\" rel=\"nofollow noreferrer\">RFC 3629</a> describes the structure of UTF-8 characters. If you take a look at that, you'll see that it's pretty straightforward to find invalid characters, AND that the next character boundary is always easy to find (it's a character &lt; 128, or one of the &quot;long character&quot; start markers, with leading bits of 110, 1110, or 11110).</p>\n<p>But BKB is probably correct - the easiest answer is to let perl do it for you, although I'm not sure what Perl does when it detects the incorrect utf-8 with that filter in effect.</p>\n" }, { "answer_id": 205713, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 2, "selected": false, "text": "<p>Consider Python. It allows to extend codecs with user-defined error handlers, so you can replace undecodable bytes with anything you want.</p>\n\n<pre><code>import codecs\ncodecs.register_error('spacer', lambda ex: (u' ', ex.start + 1))\ns = 'spam\\xb0\\xc0eggs\\xd0bacon'.decode('utf8', 'spacer')\nprint s.encode('utf8')\n</code></pre>\n\n<p>This prints:</p>\n\n<pre><code>spam eggs bacon\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to detect and replace malformed UTF-8 characters with blank space using a Perl script while loading the data using SQL\*Loader. How can I do this?
Consider Python. It allows to extend codecs with user-defined error handlers, so you can replace undecodable bytes with anything you want. ``` import codecs codecs.register_error('spacer', lambda ex: (u' ', ex.start + 1)) s = 'spam\xb0\xc0eggs\xd0bacon'.decode('utf8', 'spacer') print s.encode('utf8') ``` This prints: ``` spam eggs bacon ```
204,226
<p>I am connecting to CRM with the intention of retrieving a list of picklist values. On my development machine I am working under my own login name and all works fine. On the test server, the code executes under the NETWORK SERVICE account. When it connects to the CRM web service everything is great. When it connects to the metadata service I get 401 Unauthorised messages.</p> <p>This is the first time I have used the metadata service so I am hoping someone can tell me why I get the error. The connection is configured using the code below and the failure happens when you try to retrieve the picklist data.</p> <pre><code>CrmAuthenticationToken token = new CrmAuthenticationToken(); token.OrganizationName = config.AppSettings.Settings["CrmTargetOrganisation"].Value; token.AuthenticationType = 0; MetadataService service = new MetadataService(); service.Credentials = System.Net.CredentialCache.DefaultCredentials; service.Url = config.AppSettings.Settings["CrmMetadataServiceUrl"].Value; service.CrmAuthenticationTokenValue = token; service.UnsafeAuthenticatedConnectionSharing = true; </code></pre>
[ { "answer_id": 215513, "author": "Rihan Meij", "author_id": 29287, "author_profile": "https://Stackoverflow.com/users/29287", "pm_score": 2, "selected": true, "text": "<p>I suspect it might be a Kerberos / delegation issue, to make sure it is try replacing DefaultCredentials with\nnew System.Security.Net.NetworkCredentials(\"username\",\"password\",\"domain\");</p>\n\n<p>See if that still gives you a 401.</p>\n\n<p>This is the quick way I normally try to see if it is kerbos/security related. </p>\n\n<p>I need a bit more information about your environment to make any other intelligent comments. </p>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 39521645, "author": "QuickDanger", "author_id": 1618438, "author_profile": "https://Stackoverflow.com/users/1618438", "pm_score": 0, "selected": false, "text": "<p>In my case (yes, we still use CRM 4), the website in IIS wasn't bound to the hostname being used to access the metadata service on port 5555.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21862/" ]
I am connecting to CRM with the intention of retrieving a list of picklist values. On my development machine I am working under my own login name and all works fine. On the test server, the code executes under the NETWORK SERVICE account. When it connects to the CRM web service everything is great. When it connects to the metadata service I get 401 Unauthorised messages. This is the first time I have used the metadata service so I am hoping someone can tell me why I get the error. The connection is configured using the code below and the failure happens when you try to retrieve the picklist data. ``` CrmAuthenticationToken token = new CrmAuthenticationToken(); token.OrganizationName = config.AppSettings.Settings["CrmTargetOrganisation"].Value; token.AuthenticationType = 0; MetadataService service = new MetadataService(); service.Credentials = System.Net.CredentialCache.DefaultCredentials; service.Url = config.AppSettings.Settings["CrmMetadataServiceUrl"].Value; service.CrmAuthenticationTokenValue = token; service.UnsafeAuthenticatedConnectionSharing = true; ```
I suspect it might be a Kerberos / delegation issue, to make sure it is try replacing DefaultCredentials with new System.Security.Net.NetworkCredentials("username","password","domain"); See if that still gives you a 401. This is the quick way I normally try to see if it is kerbos/security related. I need a bit more information about your environment to make any other intelligent comments. Hope it helps.
204,303
<p>I'm starting to investigate T4 for Code Generation.</p> <p>I get that you have a basic template in which you can embed little chunks of c#/vb which can perform clever stuff...</p> <pre><code>&lt;#@ template language="VB" debug="True" hostspecific="True" #&gt; &lt;#@ output extension=".vb" debug="True" hostspecific="True" #&gt; Imports System &lt;#For Each Table as String in New String(0 {"Table1","Table2"}#&gt; Public Class &lt;#=Table#&gt;DA Public Sub New &lt;#= WriteConstructorBody() #&gt; End Sub End Class &lt;#Next#&gt; &lt;#+ Public Function WriteConstructorBody() as String return "' Some comment" End function #&gt; </code></pre> <p>This is great.. However I would like to be able to write my main block thus...</p> <pre><code>&lt;#@ template language="VB" debug="True" hostspecific="True" #&gt; &lt;#@ output extension=".vb" debug="True" hostspecific="True" #&gt; Imports System &lt;# For Each BaseTableName as String in New String(){"Table1","Table2"} WriteRecDataInterface(BaseTableName) WriteRecDataClass(BaseTableName) WriteDAInterface(BaseTableName) WriteDAClass(BaseTableName) Next #&gt; </code></pre> <p>Then I would like to be able to have the WriteX methods exist in a Class Block but themselves be writable using code by example ie escaped Code blocks.</p> <p>How can I achieve this?</p>
[ { "answer_id": 204367, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 2, "selected": true, "text": "<p>It seems that you can mix static output with template code in Class Blocks. Here is an example with C#:</p>\n\n<pre><code>&lt;#@ template language=\"C#\" #&gt;\n&lt;# HelloWorld(); #&gt;\n&lt;#+\n private string _field = \"classy\";\n private void HelloWorld()\n {\n for(int i = 1; i &lt;= 3; i++)\n {\n#&gt;\nHello &lt;#=_field#&gt; World &lt;#= i #&gt;!\n&lt;#+\n }\n }\n#&gt;\n</code></pre>\n" }, { "answer_id": 204376, "author": "Rory Becker", "author_id": 11356, "author_profile": "https://Stackoverflow.com/users/11356", "pm_score": 2, "selected": false, "text": "<p>You can write.....</p>\n\n<pre><code>&lt;#@ template language=\"VB\" debug=\"True\" hostspecific=\"True\" #&gt;\n&lt;#@ output extension=\".vb\" debug=\"True\" hostspecific=\"True\" #&gt;\nImports System\n&lt;# \nFor Each BaseTableName as String in New String(){\"Table1\",\"Table2\"} \n WriteRecDataInterface(BaseTableName) \n\n ' WriteRecDataClass(BaseTableName) \n ' WriteDAInterface(BaseTableName) \n ' WriteDAClass(BaseTableName) \nNext \n#&gt;\n\n\n&lt;#+ Public Sub WriteRecDataInterface(BaseTableName as String)#&gt;\n Some Templated unescaped code might go here\n &lt;#+ For SomeLoopVar as Integer = 1 to 10 #&gt;\n Some Templated unescaped code might go here\n &lt;#+ Next #&gt;\n Some Templated unescaped code might go here\n&lt;#+ End Sub #&gt;\n'...\n'...\n' Other Subs left out for brevity\n'...\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11356/" ]
I'm starting to investigate T4 for Code Generation. I get that you have a basic template in which you can embed little chunks of c#/vb which can perform clever stuff... ``` <#@ template language="VB" debug="True" hostspecific="True" #> <#@ output extension=".vb" debug="True" hostspecific="True" #> Imports System <#For Each Table as String in New String(0 {"Table1","Table2"}#> Public Class <#=Table#>DA Public Sub New <#= WriteConstructorBody() #> End Sub End Class <#Next#> <#+ Public Function WriteConstructorBody() as String return "' Some comment" End function #> ``` This is great.. However I would like to be able to write my main block thus... ``` <#@ template language="VB" debug="True" hostspecific="True" #> <#@ output extension=".vb" debug="True" hostspecific="True" #> Imports System <# For Each BaseTableName as String in New String(){"Table1","Table2"} WriteRecDataInterface(BaseTableName) WriteRecDataClass(BaseTableName) WriteDAInterface(BaseTableName) WriteDAClass(BaseTableName) Next #> ``` Then I would like to be able to have the WriteX methods exist in a Class Block but themselves be writable using code by example ie escaped Code blocks. How can I achieve this?
It seems that you can mix static output with template code in Class Blocks. Here is an example with C#: ``` <#@ template language="C#" #> <# HelloWorld(); #> <#+ private string _field = "classy"; private void HelloWorld() { for(int i = 1; i <= 3; i++) { #> Hello <#=_field#> World <#= i #>! <#+ } } #> ```
204,305
<p>I have an asp.net server control (with the asp: in its definition). The button has been set to do post back.</p> <p>On the server side, I have the on click event handler e.g btnSave_click()</p> <p>On the client side, I have a javascript function to be invoked on the click event e.g btnSave.Attributes.Add("onclick","javascript: return CheckIsDirty();")</p> <p>Am not sure which order these two will be executed. Because I want first on the client side to warn of any data entry fields that are not yet filled-out before actually saving any data.</p> <p>Any help?</p>
[ { "answer_id": 204325, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 3, "selected": true, "text": "<p>First client side, second server-side.</p>\n\n<p>So you can use it.</p>\n\n<p>I also use it in some cases, like:</p>\n\n<pre><code>close.Attributes[\"OnClick\"] = \"return confirm('Are you sure?')\";\n</code></pre>\n\n<p>In this case if the user presses 'No' then the server-side event handler does not even play a role.</p>\n" }, { "answer_id": 204339, "author": "Albert", "author_id": 24065, "author_profile": "https://Stackoverflow.com/users/24065", "pm_score": 0, "selected": false, "text": "<p>I think you need a much better understanding of what it means client side and what it means server side and how they all relate together. I've seen more and more developers make a mess of it.</p>\n\n<p>Of course the client side will execute first in your case. Actually there's no way to execute it after the server code is executed (except if you do something manually). I'll try to give a brief explanation:</p>\n\n<p>Whatever you have in your server, will generate some HTML on the client and the user is always interacting on the client. So you have a html button that the user is clicking. What the browser will do is execute the javascript associated with it or if no javascript is specified and the button is a submit button it will submit the form. if you check the generated html you will see that for the onclick event you will have the script you have added followed by some autogenerated script that actually will submit the form to the server. Your server side code will execute only if the page will be submitted.</p>\n" }, { "answer_id": 204341, "author": "Pbearne", "author_id": 3582, "author_profile": "https://Stackoverflow.com/users/3582", "pm_score": 2, "selected": false, "text": "<p>The trick here is to set this global variable \"Page_IsValid\" false if your test fails and this will stop the post back.</p>\n\n<p>Read this page <a href=\"http://msdn.microsoft.com/en-us/library/aa479045.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa479045.aspx</a> which explains both server side and client Validation. There is sone good code example you can use. </p>\n" }, { "answer_id": 204454, "author": "Jason Whitehorn", "author_id": 27860, "author_profile": "https://Stackoverflow.com/users/27860", "pm_score": 1, "selected": false, "text": "<p>The way you are setting your onClick JavaScript event will actually prevent it from posting back as you are overwritten the ASP.NET event handler. The correct way to accomplish the validation you are intending is to:</p>\n\n<pre><code>btnSave.Attributes.Add(\"onclick\", \"CheckIsDirty();\" + GetPostBackEventReference(btnSave).ToString());\n</code></pre>\n\n<p>Notice that you append the result of GetPostBackEventReference, so that in JavaScript you first call your CheckIsDirty() method and then call the ASP.NET postback method. Assuming your method returns true, then the button will post. If it returns false then it will not cause a post back.</p>\n\n<p>Does that sound like what you are trying to accomplish?</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13370/" ]
I have an asp.net server control (with the asp: in its definition). The button has been set to do post back. On the server side, I have the on click event handler e.g btnSave\_click() On the client side, I have a javascript function to be invoked on the click event e.g btnSave.Attributes.Add("onclick","javascript: return CheckIsDirty();") Am not sure which order these two will be executed. Because I want first on the client side to warn of any data entry fields that are not yet filled-out before actually saving any data. Any help?
First client side, second server-side. So you can use it. I also use it in some cases, like: ``` close.Attributes["OnClick"] = "return confirm('Are you sure?')"; ``` In this case if the user presses 'No' then the server-side event handler does not even play a role.
204,308
<p>I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use <code>hasattr</code> like this:</p> <pre><code>class Foo(object): @classmethod def singleton(self): if not hasattr(self, 'instance'): self.instance = Foo() return self.instance </code></pre> <p>But you can also do this:</p> <pre><code>class Foo(object): @classmethod def singleton(self): try: return self.instance except AttributeError: self.instance = Foo() return self.instance </code></pre> <p>Is one method better of the other?</p> <p><strong>Edit:</strong> Added the <code>@classmethod</code> ... But note that the question is <em>not</em> about how to make a singleton but how to check the presence of a member in an object.</p> <p><strong>Edit:</strong> For that example, a typical usage would be:</p> <pre><code>s = Foo.singleton() </code></pre> <p>Then <code>s</code> is an object of type <code>Foo</code>, the same each time. And, typically, the method is called many times.</p>
[ { "answer_id": 204318, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "<p>It depends on which case is \"typical\", because exceptions should model, well, atypical conditions. So, if the typical case is that the <code>instance</code> attribute should exist, then use the second code style. If not having <code>instance</code> is as typical as having <code>instance</code>, then use the first style.</p>\n\n<p>In the specific case of creating a singleton, I'm inclined to go with the first style, because creating a singleton the initial time is a typical use case. :-)</p>\n" }, { "answer_id": 204481, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 3, "selected": false, "text": "<p>I just tried to measure times:</p>\n\n<pre><code>class Foo(object):\n @classmethod\n def singleton(self):\n if not hasattr(self, 'instance'):\n self.instance = Foo()\n return self.instance\n\n\n\nclass Bar(object):\n @classmethod\n def singleton(self):\n try:\n return self.instance\n except AttributeError:\n self.instance = Bar()\n return self.instance\n\n\n\nfrom time import time\n\nn = 1000000\nfoo = [Foo() for i in xrange(0,n)]\nbar = [Bar() for i in xrange(0,n)]\n\nprint \"Objs created.\"\nprint\n\n\nfor times in xrange(1,4):\n t = time()\n for d in foo: d.singleton()\n print \"#%d Foo pass in %f\" % (times, time()-t)\n\n t = time()\n for d in bar: d.singleton()\n print \"#%d Bar pass in %f\" % (times, time()-t)\n\n print\n</code></pre>\n\n<p>On my machine:</p>\n\n<pre><code>Objs created.\n\n#1 Foo pass in 1.719000\n#1 Bar pass in 1.140000\n\n#2 Foo pass in 1.750000\n#2 Bar pass in 1.187000\n\n#3 Foo pass in 1.797000\n#3 Bar pass in 1.203000\n</code></pre>\n\n<p>It seems that try/except is faster. It seems also more readable to me, anyway depends on the case, this test was very simple maybe you'd need a more complex one.</p>\n" }, { "answer_id": 204520, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 0, "selected": false, "text": "<p>I have to agree with Chris. Remember, don't optimize until you actually need to do so. I really doubt checking for existence is going to be a bottleneck in any reasonable program.</p>\n\n<p>I did see <a href=\"http://code.activestate.com/recipes/52558/\" rel=\"nofollow noreferrer\">http://code.activestate.com/recipes/52558/</a> as a way to do this, too. Uncommented copy of that code (\"spam\" is just a random method the class interface has):</p>\n\n<pre><code>class Singleton:\n class __impl:\n def spam(self):\n return id(self)\n __instance = None\n def __init__(self):\n if Singleton.__instance is None:\n Singleton.__instance = Singleton.__impl()\n self.__dict__['_Singleton__instance'] = Singleton.__instance\n def __getattr__(self, attr):\n return getattr(self.__instance, attr)\n def __setattr__(self, attr, value):\n return setattr(self.__instance, attr, value)\n</code></pre>\n" }, { "answer_id": 204523, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 6, "selected": true, "text": "<p>These are two different methodologies: №1 is LBYL (look before you leap) and №2 is EAFP (easier to ask forgiveness than permission).</p>\n\n<p>Pythonistas typically suggest that EAFP is better, with arguments in style of \"what if a process creates the file between the time you test for it and the time you try to create it yourself?\". This argument does not apply here, but it's the general idea. Exceptions should not be treated as <em>too</em> exceptional.</p>\n\n<p>Performance-wise in your case —since setting up exception managers (the <code>try</code> keyword) is very cheap in CPython while creating an exception (the <code>raise</code> keyword and internal exception creation) is what is relatively expensive— using method №2 the exception would be raised only once; afterwards, you just use the property.</p>\n" }, { "answer_id": 204561, "author": "gx.", "author_id": 21580, "author_profile": "https://Stackoverflow.com/users/21580", "pm_score": 1, "selected": false, "text": "<p>A little off-topic in the way of using it. Singletons are overrated, and a \"shared-state\" method is as effective, and mostly, very clean in python, for example:</p>\n\n<pre><code>class Borg:\n __shared_state = {}\n def __init__(self):\n self.__dict__ = self.__shared_state\n # and whatever else you want in your class -- that's all!\n</code></pre>\n\n<p>Now every time you do:</p>\n\n<pre><code>obj = Borg()\n</code></pre>\n\n<p>it will have the same information, or, be somewhat the same instance.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7136/" ]
I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use `hasattr` like this: ``` class Foo(object): @classmethod def singleton(self): if not hasattr(self, 'instance'): self.instance = Foo() return self.instance ``` But you can also do this: ``` class Foo(object): @classmethod def singleton(self): try: return self.instance except AttributeError: self.instance = Foo() return self.instance ``` Is one method better of the other? **Edit:** Added the `@classmethod` ... But note that the question is *not* about how to make a singleton but how to check the presence of a member in an object. **Edit:** For that example, a typical usage would be: ``` s = Foo.singleton() ``` Then `s` is an object of type `Foo`, the same each time. And, typically, the method is called many times.
These are two different methodologies: №1 is LBYL (look before you leap) and №2 is EAFP (easier to ask forgiveness than permission). Pythonistas typically suggest that EAFP is better, with arguments in style of "what if a process creates the file between the time you test for it and the time you try to create it yourself?". This argument does not apply here, but it's the general idea. Exceptions should not be treated as *too* exceptional. Performance-wise in your case —since setting up exception managers (the `try` keyword) is very cheap in CPython while creating an exception (the `raise` keyword and internal exception creation) is what is relatively expensive— using method №2 the exception would be raised only once; afterwards, you just use the property.
204,316
<p>According to this</p> <p><a href="http://perldoc.perl.org/UNIVERSAL.html" rel="noreferrer">http://perldoc.perl.org/UNIVERSAL.html</a></p> <p>I shouldn't use UNIVERSAL::isa() and should instead use $obj->isa() or CLASS->isa().</p> <p>This means that to find out if something is a reference in the first place and then is reference to this class I have to do</p> <pre><code>eval { $poss-&gt;isa("Class") } </code></pre> <p>and check $@ and all that gumph, or else</p> <pre><code>use Scalar::Util 'blessed'; blessed $ref &amp;&amp; $ref-&gt;isa($class); </code></pre> <p>My question is why? What's wrong with UNIVERSAL::isa called like that? It's much cleaner for things like:</p> <pre><code>my $self = shift if UNIVERSAL::isa($_[0], __PACKAGE__) </code></pre> <p>To see whether this function is being called on the object or not. And is there a nice clean alternative that doesn't get cumbersome with ampersands and potentially long lines?</p>
[ { "answer_id": 204352, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "<p>To directly answer your question, the answer is at the bottom of the page you linked to, namely that if a package defines an <code>isa</code> method, then calling <code>UNIVERSAL::isa</code> directly will not call the package <code>isa</code> method. This is very unintuitive behaviour from an object-orientation point of view.</p>\n\n<p>The rest of this post is just more questions about why you're doing this in the first place.</p>\n\n<p>In code like the above, in what cases would that specific <code>isa</code> test fail? i.e., if it's a method, in which case would the first argument not be the package class or an instance thereof?</p>\n\n<p>I ask this because I wonder if there is a legitimate reason why you would want to test whether the first argument is an object in the first place. i.e., are you just trying to catch people saying <code>FooBar::method</code> instead of <code>FooBar-&gt;method</code> or <code>$foobar-&gt;method</code>? I guess Perl isn't designed for that sort of coddling, and if people mistakenly use <code>FooBar::method</code> they'll find out soon enough.</p>\n\n<p>Your mileage may vary.</p>\n" }, { "answer_id": 204355, "author": "Penfold", "author_id": 11952, "author_profile": "https://Stackoverflow.com/users/11952", "pm_score": 3, "selected": false, "text": "<p>See the docs for <a href=\"http://search.cpan.org/dist/UNIVERSAL-isa/lib/UNIVERSAL/isa.pm\" rel=\"nofollow noreferrer\">UNIVERSAL::isa</a> and <a href=\"http://search.cpan.org/dist/UNIVERSAL-can/lib/UNIVERSAL/can.pm\" rel=\"nofollow noreferrer\">UNIVERSAL::can</a> for why you shouldn't do it.</p>\n\n<p>In a nutshell, there are important modules with a genuine need to override 'isa' (such as <a href=\"http://search.cpan.org/dist/Test-MockObject/\" rel=\"nofollow noreferrer\">Test::MockObject</a>), and if you call it as a function, you break this.</p>\n\n<p>I have to say, <code>my $self = shift if UNIVERSAL::isa($_[0], __PACKAGE__)</code> doesn't look terribly clean to me - anti-Perl advocates would be complaining about line noise. :)</p>\n" }, { "answer_id": 204368, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 6, "selected": true, "text": "<p>The primary problem is that if you call <code>UNIVERSAL::isa</code> directly, you are bypassing any classes that have overloaded <code>isa</code>. If those classes rely on the overloaded behavior (which they probably do or else they would not have overridden it), then this is a problem. If you invoke <code>isa</code> directly on your blessed object, then the correct <code>isa</code> method will be called in either case (overloaded if it exists, UNIVERSAL:: if not).</p>\n\n<p>The second problem is that <code>UNIVERSAL::isa</code> will only perform the test you want on a blessed reference just like every other use of <code>isa</code>. It has different behavior for non-blessed references and simple scalars. So your example that doesn't check whether <code>$ref</code> is blessed is not doing the right thing, you're ignoring an error condition and using <code>UNIVERSAL</code>'s alternate behavior. In certain circumstances this can cause subtle errors (for example, if your variable contains the name of a class).</p>\n\n<p>Consider:</p>\n\n<pre><code>use CGI;\n\nmy $a = CGI-&gt;new();\n\nmy $b = \"CGI\";\n\nprint UNIVERSAL::isa($a,\"CGI\"); # prints 1, $a is a CGI object.\nprint UNIVERSAL::isa($b,\"CGI\"); # Also prints 1!! Uh-oh!!\n</code></pre>\n\n<p>So, in summary, don't use <code>UNIVERSAL::isa</code>... Do the extra error check and invoke <code>isa</code> on your object directly.</p>\n" }, { "answer_id": 204387, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 2, "selected": false, "text": "<p>Assuming your example of what you want to be able to do is within an object method, you're being unnecessarily paranoid. The first passed item will always be either a reference to an object of the appropriate class (or a subclass) or it will be the name of the class (or a subclass). It will never be a reference of any other type, unless the method has been deliberately called as a function. You can, therefore, safely just use <strong>ref</strong> to distinguish between the two cases.</p>\n\n<pre><code>if (ref $_[0]) {\n my $self = shift;\n # called on instance, so do instancey things\n} else {\n my $class = shift;\n # called as a class/static method, so do classy things\n}\n</code></pre>\n" }, { "answer_id": 204899, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 3, "selected": false, "text": "<p>Everyone else has told you <em>why</em> you don't want to use <code>UNIVERSAL::isa</code>, because it breaks when things overload <code>isa</code>. If they've gone to all the habit of overloading that very special method, you certainly want to respect it. Sure, you <em>could</em> do this by writing:</p>\n\n<pre><code>if (eval { $foo-&gt;isa(\"thing\") }) {\n # Do thingish things\n}\n</code></pre>\n\n<p>because <code>eval</code> guarantees to return false if it throws an exception, and the last value otherwise. But that looks <em>awful</em>, and you shouldn't need to write your code in funny ways because the language wants you to. What we really want is to write just:</p>\n\n<pre><code>if ( $foo-&gt;isa(\"thing\") ) {\n # Do thingish things\n}\n</code></pre>\n\n<p>To do that, we'd have to make sure that <code>$foo</code> is always an object. But <code>$foo</code> could be a string, a number, a reference, an undefined value, or all sorts of weird stuff. What a shame Perl can't make <em>everything</em> a first class object.</p>\n\n<p>Oh, wait, it can...</p>\n\n<pre><code>use autobox; # Everything is now a first class object.\nuse CGI; # Because I know you have it installed.\n\nmy $x = 5;\nmy $y = CGI-&gt;new;\n\nprint \"\\$x is a CGI object\\n\" if $x-&gt;isa('CGI'); # This isn't printed.\nprint \"\\$y is a CGI object\\n\" if $y-&gt;isa('CGI'); # This is!\n</code></pre>\n\n<p>You can grab <a href=\"http://search.cpan.org/perldoc?autobox\" rel=\"noreferrer\">autobox</a> from the CPAN. You can also use it with lexical scope, so everything can be a first class object just for the files or blocks where you want to use <code>-&gt;isa()</code> without all the extra headaches. It also does a <em>lot</em> more than what I've covered in this simple example.</p>\n" }, { "answer_id": 2302118, "author": "codeholic", "author_id": 268224, "author_profile": "https://Stackoverflow.com/users/268224", "pm_score": 1, "selected": false, "text": "<p>Right. It does a wrong thing for classes that overload <code>isa</code>. Just use the following idiom:</p>\n\n<pre><code>if (eval { $obj-&gt;isa($class) }) {\n</code></pre>\n\n<p>It is easily understood and commonly accepted.</p>\n" }, { "answer_id": 65603289, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 1, "selected": false, "text": "<p>Update for 2020: Perl v5.32 has the <a href=\"https://www.effectiveperlprogramming.com/2020/01/use-the-infix-class-instance-operator/\" rel=\"nofollow noreferrer\">class infix operator</a>, <code>isa</code>, which handles any sort of thing on the lefthand side. If the <code>$something</code> is not an object, you get back false with no blowup.</p>\n<pre><code>use v5.32;\n\nif( $something isa 'Animal' ) { ... }\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2386199/" ]
According to this <http://perldoc.perl.org/UNIVERSAL.html> I shouldn't use UNIVERSAL::isa() and should instead use $obj->isa() or CLASS->isa(). This means that to find out if something is a reference in the first place and then is reference to this class I have to do ``` eval { $poss->isa("Class") } ``` and check $@ and all that gumph, or else ``` use Scalar::Util 'blessed'; blessed $ref && $ref->isa($class); ``` My question is why? What's wrong with UNIVERSAL::isa called like that? It's much cleaner for things like: ``` my $self = shift if UNIVERSAL::isa($_[0], __PACKAGE__) ``` To see whether this function is being called on the object or not. And is there a nice clean alternative that doesn't get cumbersome with ampersands and potentially long lines?
The primary problem is that if you call `UNIVERSAL::isa` directly, you are bypassing any classes that have overloaded `isa`. If those classes rely on the overloaded behavior (which they probably do or else they would not have overridden it), then this is a problem. If you invoke `isa` directly on your blessed object, then the correct `isa` method will be called in either case (overloaded if it exists, UNIVERSAL:: if not). The second problem is that `UNIVERSAL::isa` will only perform the test you want on a blessed reference just like every other use of `isa`. It has different behavior for non-blessed references and simple scalars. So your example that doesn't check whether `$ref` is blessed is not doing the right thing, you're ignoring an error condition and using `UNIVERSAL`'s alternate behavior. In certain circumstances this can cause subtle errors (for example, if your variable contains the name of a class). Consider: ``` use CGI; my $a = CGI->new(); my $b = "CGI"; print UNIVERSAL::isa($a,"CGI"); # prints 1, $a is a CGI object. print UNIVERSAL::isa($b,"CGI"); # Also prints 1!! Uh-oh!! ``` So, in summary, don't use `UNIVERSAL::isa`... Do the extra error check and invoke `isa` on your object directly.
204,320
<p>Is there a way to declare a variable as Nullable in c#?</p> <pre><code>struct MyStruct { int _yer, _ner; public MyStruct() { _yer = Nullable&lt;int&gt;; //This does not work. _ner = 0; } } </code></pre>
[ { "answer_id": 204326, "author": "Joel Cunningham", "author_id": 5360, "author_profile": "https://Stackoverflow.com/users/5360", "pm_score": 1, "selected": false, "text": "<p>Try declaring your variable like this:</p>\n\n<pre><code>int? yer;\n</code></pre>\n" }, { "answer_id": 204327, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 0, "selected": false, "text": "<p>How about <a href=\"http://msdn.microsoft.com/en-us/library/2cf62fcy(VS.80).aspx\" rel=\"nofollow noreferrer\">nullable types</a>:</p>\n\n<pre><code>struct MyStruct\n{\n private int? _yer, _ner;\n public MyStruct(int? yer, int? ner)\n {\n _yer = yer;\n _ner = ner;\n }\n}\n</code></pre>\n" }, { "answer_id": 204328, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 0, "selected": false, "text": "<p>Try declaring _yer as type Nullable initially, rather than as a standard int.</p>\n" }, { "answer_id": 204329, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": true, "text": "<p>_yer must be declare as int? or Nullable&lt;int&gt;.</p>\n\n<pre><code> int? _yer;\n int _ner;\n\n public MyStruct(int? ver, int ner) {\n\n _yer = ver;\n _ner = ner;\n }\n}\n</code></pre>\n\n<p>Or like this:</p>\n\n<pre><code> Nullable&lt;int&gt; _yer;\n int _ner;\n\n public MyStruct(Nullable&lt;int&gt; ver, int ner) {\n\n _yer = ver;\n _ner = ner;\n }\n}\n</code></pre>\n\n<p><strong>Remember that structs cannot contain explicit parameterless constructors.</strong></p>\n\n<pre><code>error CS0568: Structs cannot contain explicit parameterless constructors\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
Is there a way to declare a variable as Nullable in c#? ``` struct MyStruct { int _yer, _ner; public MyStruct() { _yer = Nullable<int>; //This does not work. _ner = 0; } } ```
\_yer must be declare as int? or Nullable<int>. ``` int? _yer; int _ner; public MyStruct(int? ver, int ner) { _yer = ver; _ner = ner; } } ``` Or like this: ``` Nullable<int> _yer; int _ner; public MyStruct(Nullable<int> ver, int ner) { _yer = ver; _ner = ner; } } ``` **Remember that structs cannot contain explicit parameterless constructors.** ``` error CS0568: Structs cannot contain explicit parameterless constructors ```
204,360
<p>What's the term for this design?</p> <pre><code>object.method1().method2().method3() </code></pre> <p>..when all methods return *this?</p> <p>I found the term for this a while ago, but lost it meanwhile. I have no clue how to search for this on google :) Also if anyone can think of a better title for the question, feel free to change it.</p> <p>Thanks</p> <p><strong>Update-Gishu</strong>: After reading about it, I feel that your question is misleading w.r.t. code snippet provided.. (Feel free to rollback)</p> <p><em>Method Chaining</em></p> <pre><code>object.method1().method2().method3() </code></pre> <p><em>Fluent Interfaces</em></p> <pre><code>private void makeFluent(Customer customer) { customer.newOrder() .with(6, "TAL") .with(5, "HPK").skippable() .with(3, "LGV") .priorityRush(); } </code></pre>
[ { "answer_id": 204364, "author": "Joel Cunningham", "author_id": 5360, "author_profile": "https://Stackoverflow.com/users/5360", "pm_score": 4, "selected": true, "text": "<p>Looks to me like you are describing a fluent interface. Ive also heard it referred to as pipelineing or chaining.</p>\n\n<p>Update-Gishu: <a href=\"http://martinfowler.com/bliki/FluentInterface.html\" rel=\"noreferrer\">http://martinfowler.com/bliki/FluentInterface.html</a> </p>\n" }, { "answer_id": 204366, "author": "PW.", "author_id": 927, "author_profile": "https://Stackoverflow.com/users/927", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>It chains these method calls, which is why this is called <a href=\"https://isocpp.org/wiki/faq/references#method-chaining\" rel=\"nofollow noreferrer\">method chaining</a></p>\n</blockquote>\n" }, { "answer_id": 204372, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>It's usually called method chaining. An example of its application is the <a href=\"http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.18\" rel=\"noreferrer\">Named Parameter Idiom</a>.</p>\n\n<p>As an aside, I find it amusing that searching in Google for \"object method1 method2\" comes up with exactly the page you were looking for. :)</p>\n" }, { "answer_id": 204373, "author": "moogs", "author_id": 26374, "author_profile": "https://Stackoverflow.com/users/26374", "pm_score": 1, "selected": false, "text": "<p>The term you're looking for is <a href=\"https://isocpp.org/wiki/faq/references#method-chaining\" rel=\"nofollow noreferrer\">method chaining</a>.</p>\n" }, { "answer_id": 204382, "author": "Robert Gould", "author_id": 15124, "author_profile": "https://Stackoverflow.com/users/15124", "pm_score": 2, "selected": false, "text": "<p>chaining is a more common name in the industry and most developers have at least heard of it, while fluent interface is more academic and lots of people will have no idea what your talking about.</p>\n" }, { "answer_id": 28081241, "author": "Barry", "author_id": 2069064, "author_profile": "https://Stackoverflow.com/users/2069064", "pm_score": 2, "selected": false, "text": "<p>It's called <a href=\"http://en.wikipedia.org/wiki/Method_chaining\" rel=\"nofollow\">Method Chaining</a>. As an example, there's a boost library that provided a chaining way of assigning into a container before brace-initialization came around (<a href=\"http://www.boost.org/doc/libs/1_57_0/libs/assign/doc/index.html\" rel=\"nofollow\">Boost.Assignment</a>):</p>\n\n<pre><code>vector&lt;int&gt; v; \nv += 1,2,3,4,5,6,7,8,9;\n\ntypedef pair&lt; string,string &gt; str_pair;\ndeque&lt;str_pair&gt; deq;\npush_front( deq )( \"foo\", \"bar\")( \"boo\", \"far\" ); \n</code></pre>\n\n<p>Typically though, you see it more in other languages to do things like providing a <a href=\"http://en.wikipedia.org/wiki/Fluent_interface\" rel=\"nofollow\">fluent interface</a>:</p>\n\n<pre><code> FluentGlutApp(argc, argv)\n .withDoubleBuffer().withRGBA().withAlpha().withDepth()\n .at(200, 200).across(500, 500)\n .named(\"My OpenGL/GLUT App\")\n .create();\n</code></pre>\n\n<p>I don't see it that much in C++ personally, outside of streaming.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21240/" ]
What's the term for this design? ``` object.method1().method2().method3() ``` ..when all methods return \*this? I found the term for this a while ago, but lost it meanwhile. I have no clue how to search for this on google :) Also if anyone can think of a better title for the question, feel free to change it. Thanks **Update-Gishu**: After reading about it, I feel that your question is misleading w.r.t. code snippet provided.. (Feel free to rollback) *Method Chaining* ``` object.method1().method2().method3() ``` *Fluent Interfaces* ``` private void makeFluent(Customer customer) { customer.newOrder() .with(6, "TAL") .with(5, "HPK").skippable() .with(3, "LGV") .priorityRush(); } ```
Looks to me like you are describing a fluent interface. Ive also heard it referred to as pipelineing or chaining. Update-Gishu: <http://martinfowler.com/bliki/FluentInterface.html>
204,369
<p>Recently our company has started measuring the cyclomatic complexity (CC) of the functions in our code on a weekly basis, and reporting which functions have improved or worsened. So we have started paying a lot more attention to the CC of functions.</p> <p>I've read that CC could be informally calculated as 1 + the number of decision points in a function (e.g. if statement, for loop, select etc), or also the number of paths through a function...</p> <p>I understand that the easiest way of reducing CC is to use the Extract Method refactoring repeatedly...</p> <p>There are somethings I am unsure about, e.g. what is the CC of the following code fragments?</p> <p>1)</p> <pre><code>for (int i = 0; i &lt; 3; i++) Console.WriteLine("Hello"); </code></pre> <p>And</p> <pre><code>Console.WriteLine("Hello"); Console.WriteLine("Hello"); Console.WriteLine("Hello"); </code></pre> <p>They both do the same thing, but does the first version have a higher CC because of the for statement?</p> <p>2)</p> <pre><code>if (condition1) if (condition2) if (condition 3) Console.WriteLine("wibble"); </code></pre> <p>And</p> <pre><code>if (condition1 &amp;&amp; condition2 &amp;&amp; condition3) Console.WriteLine("wibble"); </code></pre> <p>Assuming the language does short-circuit evaluation, such as C#, then these two code fragments have the same effect... but is the CC of the first fragment higher because it has 3 decision points/if statements?</p> <p>3)</p> <pre><code>if (condition1) { Console.WriteLine("one"); if (condition2) Console.WriteLine("one and two"); } </code></pre> <p>And</p> <pre><code>if (condition3) Console.WriteLine("fizz"); if (condition4) Console.WriteLine("buzz"); </code></pre> <p>These two code fragments do different things, but do they have the same CC? Or does the nested if statement in the first fragment have a higher CC? i.e. nested if statements are mentally more complex to understand, but is that reflected in the CC?</p>
[ { "answer_id": 204385, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 2, "selected": false, "text": "<p>CC is not a panacea for measuring quality. Clearly a repeated statement is not \"better\" than a loop, even if a loop has a bigger CC. The reason the loop has a bigger CC is that sometimes it might get executed and sometimes it might not, which leads to two different \"cases\" which should both be tested. In your case the loop will <em>always</em> be executed three times because you use a constant, but CC is not clever enough to detect this.</p>\n\n<p>Same with the chained ifs in example 2 - this structure allows you to have a statment which would be executed if only condition1 and condition2 is true. This is a special case which is not possible in the case using &amp;&amp;. So the if-chain has a bigger potential for special cases even if you dont utilize this in your code. </p>\n" }, { "answer_id": 204386, "author": "moogs", "author_id": 26374, "author_profile": "https://Stackoverflow.com/users/26374", "pm_score": 3, "selected": false, "text": "<p>After browsing thru the wikipedia entry and on Thomas J. McCabe's <a href=\"http://www.literateprogramming.com/mccabe.pdf\" rel=\"nofollow noreferrer\">original paper</a>, it seems that the items you mentioned above are known problems with the metric.</p>\n\n<p>However, most metrics do have pros and cons. I suppose in a large enough program the CC value could point to <strong>possibly complex</strong> parts of your code. But that higher CC does not necessarily mean complex.</p>\n" }, { "answer_id": 204415, "author": "PW.", "author_id": 927, "author_profile": "https://Stackoverflow.com/users/927", "pm_score": 0, "selected": false, "text": "<p>[Off topic] If you favor readability over good score in the metrics (Was it J.Spolsky that said, \"what's measured, get's done\" ? - meaning that metrics are abused more often than not I suppose), it is often better to use a well-named boolean to replace your complex conditional statement.</p>\n\n<p>then</p>\n\n<pre><code>if (condition1 &amp;&amp; condition2 &amp;&amp; condition3)\n Console.WriteLine(\"wibble\");\n</code></pre>\n\n<p>become</p>\n\n<pre><code>bool/boolean theWeatherIsFine = condition1 &amp;&amp; condition2 &amp;&amp; condition3;\n\nif (theWeatherIsFine)\n Console.WriteLine(\"wibble\");\n</code></pre>\n" }, { "answer_id": 204428, "author": "Onorio Catenacci", "author_id": 2820, "author_profile": "https://Stackoverflow.com/users/2820", "pm_score": 1, "selected": false, "text": "<p>This is the danger of applying <em>any</em> metric blindly. The CC metric certainly has a lot of merit but as with any other technique for improving code it can't be evaluated divorced from context. Point your management at Casper Jone's discussion of the Lines of Code measurement (wish I could find a link for you). He points out that if Lines of Code is a good measure of productivity then assembler language developers are the most productive developers on earth. Of course they're no more productive than other developers; it just takes them a lot more code to accomplish what higher level languages do with less source code. I mention this, as I say, so you can show your managers how dumb it is to blindly apply metrics without intelligent review of what the metric is telling you.</p>\n\n<p>I would suggest that if they're not, that your management would be wise to use the CC measure as a way of spotting potential hot spots in the code that should be reviewed further. Blindly aiming for the goal of lower CC without any reference to code maintainability or other measures of good coding is just foolish. </p>\n" }, { "answer_id": 204435, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 3, "selected": false, "text": "<p>Like all software metrics, CC is not perfect. Used on a big enough code base, it can give you an idea of where <em>might</em> be a problematic zone.</p>\n\n<p>There are two things to keep in mind here:</p>\n\n<ol>\n<li>Big enough code base: In any non trivial project you will have functions that have a really high CC value. So high that it does not matter if in one of your examples, the CC would be 2 or 3. A function with a CC of let's say over 300 is definitely something to analyse. Doesn't matter if the CC is 301 or 302.</li>\n<li>Don't forget to use your head. There are methods that need many decision points. Often they can be refactored somehow to have fewer, but sometimes they can't. Do not go with a rule like \"Refactor all methods with a CC > xy\". Have a look at them and use your brain to decide what to do.</li>\n</ol>\n\n<p>I like the idea of a weekly analysis. In quality control, trend analysis is a very effective tool for indentifying problems <strong>during their creation</strong>. This is so much better than having to wait until they get so big that they become obvious (see <a href=\"http://en.wikipedia.org/wiki/Statistical_process_control\" rel=\"noreferrer\">SPC</a> for some details).</p>\n" }, { "answer_id": 204904, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 4, "selected": true, "text": "<ol>\n<li>Yes. Your first example has a decision point and your second does not, so the first has a higher CC.</li>\n<li>Yes-maybe, your first example has multiple decision points and thus a higher CC. (See below for explanation.)</li>\n<li>Yes-maybe. Obviously they have the same number of decision points, but there are different ways to calculate CC, which means ...</li>\n</ol>\n\n<p>... if your company is measuring CC in a specific way, then you need to become familiar with that method (hopefully they are using tools to do this). There are different ways to calculate CC for different situations (case statements, Boolean operators, etc.), but you should get the same kind of information from the metric no matter what convention you use. </p>\n\n<p>The bigger problem is what others have mentioned, that your company seems to be focusing more on CC than on the code behind it. In general, sure, below 5 is great, below 10 is good, below 20 is okay, 21 to 50 should be a warning sign, and above 50 should be a big warning sign, but those are guides, not absolute rules. You should probably examine the code in a procedure that has a CC above 50 to ensure it isn't just a huge heap of code, but maybe there is a specific reason why the procedure is written that way, and it's not feasible (for any number of reasons) to refactor it.</p>\n\n<p>If you use tools to refactor your code to reduce CC, make sure you understand what the tools are doing, and that they're not simply shifting one problem to another place. Ultimately, you want your code to have few defects, to work properly, and to be relatively easy to maintain. If that code also has a low CC, good for it. If your code meets these criteria and has a CC above 10, maybe it's time to sit down with whatever management you can and defend your code (and perhaps get them to examine their policy).</p>\n" }, { "answer_id": 2013581, "author": "fremis", "author_id": 230510, "author_profile": "https://Stackoverflow.com/users/230510", "pm_score": 1, "selected": false, "text": "<p>Cyclomatic complexity is analogous to temperature. They are both measurements, and in most cases meaningless without context. If I said the temperature outside was 72 degrees that doesn’t mean much; but if I added the fact that I was at North Pole, the number 72 becomes significant. If someone told me a method has a cyclomatic complexity of 10, I can’t determine if that is good or bad without its context. </p>\n\n<p>When I code review an existing application, I find cyclomatic complexity a useful “starting point” metric. The first thing I check for are methods with a CC > 10. These “>10” methods are not necessarily bad. They just provide me a starting point for reviewing the code.</p>\n\n<p>General rules when considering a CC number:</p>\n\n<ul>\n<li>The relationship between CC # and # of tests, should be CC# &lt;= #tests</li>\n<li>Refactor for CC# only if it increases\nmaintainability</li>\n<li>CC above 10 often indicates one or more <a href=\"http://c2.com/cgi/wiki?CodeSmell\" rel=\"nofollow noreferrer\"> Code Smells</a></li>\n</ul>\n" }, { "answer_id": 19698183, "author": "Buttle Butkus", "author_id": 631764, "author_profile": "https://Stackoverflow.com/users/631764", "pm_score": 0, "selected": false, "text": "<p>I'm no expert at this subject, but I thought I would give my two cents. And maybe that's all this is worth.</p>\n\n<p>Cyclomatic Complexity seems to be just a particular automated shortcut to finding potentially (but not definitely) problematic code snippets. But isn't the real problem to be solved one of testing? How many test cases does the code require? If CC is higher, but number of test cases is the same and code is cleaner, don't worry about CC.</p>\n\n<p>1.) There is no decision point there. There is one and only one path through the program there, only one possible result with either of the two versions. The first is more concise and better, Cyclomatic Complexity be damned.</p>\n\n<p>1 test case for both</p>\n\n<p>2.) In both cases, you either write \"wibble\" or you don't.</p>\n\n<p>2 test cases for both</p>\n\n<p>3.) First one could result in nothing, \"one\", or \"one\" and \"one and two\". 3 paths. 2nd one could result in nothing, either of the two, or both of them. 4 paths.</p>\n\n<p>3 test cases for the first\n4 test cases for the second</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7261/" ]
Recently our company has started measuring the cyclomatic complexity (CC) of the functions in our code on a weekly basis, and reporting which functions have improved or worsened. So we have started paying a lot more attention to the CC of functions. I've read that CC could be informally calculated as 1 + the number of decision points in a function (e.g. if statement, for loop, select etc), or also the number of paths through a function... I understand that the easiest way of reducing CC is to use the Extract Method refactoring repeatedly... There are somethings I am unsure about, e.g. what is the CC of the following code fragments? 1) ``` for (int i = 0; i < 3; i++) Console.WriteLine("Hello"); ``` And ``` Console.WriteLine("Hello"); Console.WriteLine("Hello"); Console.WriteLine("Hello"); ``` They both do the same thing, but does the first version have a higher CC because of the for statement? 2) ``` if (condition1) if (condition2) if (condition 3) Console.WriteLine("wibble"); ``` And ``` if (condition1 && condition2 && condition3) Console.WriteLine("wibble"); ``` Assuming the language does short-circuit evaluation, such as C#, then these two code fragments have the same effect... but is the CC of the first fragment higher because it has 3 decision points/if statements? 3) ``` if (condition1) { Console.WriteLine("one"); if (condition2) Console.WriteLine("one and two"); } ``` And ``` if (condition3) Console.WriteLine("fizz"); if (condition4) Console.WriteLine("buzz"); ``` These two code fragments do different things, but do they have the same CC? Or does the nested if statement in the first fragment have a higher CC? i.e. nested if statements are mentally more complex to understand, but is that reflected in the CC?
1. Yes. Your first example has a decision point and your second does not, so the first has a higher CC. 2. Yes-maybe, your first example has multiple decision points and thus a higher CC. (See below for explanation.) 3. Yes-maybe. Obviously they have the same number of decision points, but there are different ways to calculate CC, which means ... ... if your company is measuring CC in a specific way, then you need to become familiar with that method (hopefully they are using tools to do this). There are different ways to calculate CC for different situations (case statements, Boolean operators, etc.), but you should get the same kind of information from the metric no matter what convention you use. The bigger problem is what others have mentioned, that your company seems to be focusing more on CC than on the code behind it. In general, sure, below 5 is great, below 10 is good, below 20 is okay, 21 to 50 should be a warning sign, and above 50 should be a big warning sign, but those are guides, not absolute rules. You should probably examine the code in a procedure that has a CC above 50 to ensure it isn't just a huge heap of code, but maybe there is a specific reason why the procedure is written that way, and it's not feasible (for any number of reasons) to refactor it. If you use tools to refactor your code to reduce CC, make sure you understand what the tools are doing, and that they're not simply shifting one problem to another place. Ultimately, you want your code to have few defects, to work properly, and to be relatively easy to maintain. If that code also has a low CC, good for it. If your code meets these criteria and has a CC above 10, maybe it's time to sit down with whatever management you can and defend your code (and perhaps get them to examine their policy).
204,396
<p>When returning objects from a class, when is the right time to release the memory?</p> <p>Example,</p> <pre><code>class AnimalLister { public: Animal* getNewAnimal() { Animal* animal1 = new Animal(); return animal1; } } </code></pre> <p>If i create an instance of Animal Lister and get Animal reference from it, then where am i supposed to delete it?</p> <pre><code>int main() { AnimalLister al; Animal *a1, *a2; a1 = al.getNewAnimal(); a2 = al.getNewAnimal(); } </code></pre> <p>The problem here is AnimalLister doesnot have a way to track the list of Animals Created, so how do i change the logic of such code to have a way to delete the objects created.</p>
[ { "answer_id": 204408, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": false, "text": "<p>I advise returning a <code>std::tr1::shared_ptr</code> (or <code>boost::shared_ptr</code>, if your C++ implementation does not have TR1) instead of a raw pointer. So, instead of using <code>Animal*</code>, use <code>std::tr1::shared_ptr&lt;Animal&gt;</code> instead.</p>\n\n<p>Shared pointers handle reference tracking for you, and delete the object automatically if there are no references left to it.</p>\n" }, { "answer_id": 204410, "author": "Igor Semenov", "author_id": 11401, "author_profile": "https://Stackoverflow.com/users/11401", "pm_score": 3, "selected": false, "text": "<p>The simpliest way is to return smart pointer instead of regular pointers.\nFor example:</p>\n\n<pre><code>std::auto_ptr&lt; Animal&gt; getNewAnimal() \n{\n std::auto_ptr&lt; Animal &gt; animal1( new Animal() );\n return animal1;\n}\n</code></pre>\n\n<p>If you are able to use TR1 or Boost, you can also use shared_ptr&lt;>.</p>\n" }, { "answer_id": 204421, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 3, "selected": false, "text": "<p>Kind of a classic issue with pointers and allocated memory. It's about responsibility - who is responsible for cleaning up the memory allocated by the AnimalLister object.</p>\n\n<p>You could store off a pointer to each of those allocated Animals in the AnimalLister itself and have it clean things up.</p>\n\n<p>But, you do have a couple of pointers to Animals sitting there in main() that would be referencing memory that was deleted.</p>\n\n<p>One of the reasons I think the reference counting solutions work better than rolling your own solution.</p>\n" }, { "answer_id": 204422, "author": "brianb", "author_id": 27892, "author_profile": "https://Stackoverflow.com/users/27892", "pm_score": 2, "selected": false, "text": "<p>Or you could follow the COM-ish approach, and apply simple reference counting.</p>\n\n<ul>\n<li>When you create the object, give it a reference value of 1 instantly</li>\n<li>When anyone gets a copy of the pointer, they AddRef()</li>\n<li>When anyone gives up their copy of the pointer, they Release()</li>\n</ul>\n\n<p>If the reference count hits 0, the object deletes itself.</p>\n\n<p>Its ultimately what the shared_ptr does under the hood, but it gives you more control over whats going on, and in my experience easier to debug. (Its also very cross-platform).</p>\n\n<p>I haven't given shared_ ptr too much of a chance in my development as yet, so that may serve your purposes perfectly.</p>\n" }, { "answer_id": 204466, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 3, "selected": false, "text": "<ol>\n<li>shared_ptr (which works well),</li>\n<li>return a simple pointer and tell the user of your class that it is their animal now, and they have the responsibility to delete it when finished,</li>\n<li><p>implement a 'freeAnimal(Animal*)' method that makes it obvious that deletion of the animal pointer is required.</p></li>\n<li><p>An alternative way is to simply return the animal object directly, no pointers, no calls to new. The copy constructor will ensure the caller gets their own animal object that they can store on the heap or stack, or copy into a container as they desire.</p></li>\n</ol>\n\n<p>So:</p>\n\n<pre><code>class AnimalLister \n{\nAnimal getAnimal() { Animal a; return a; }; // uses fast Return Value Optimisation\n};\n\nAnimal myownanimal = AnimalLister.getAnimal(); // copy ctors into your Animal object\n</code></pre>\n\n<p>RVO means that returning the object instead of the pointer is actually faster (as the compiler doesn't create a new object and copies it into the caller's object, but uses the caller's object directly).</p>\n" }, { "answer_id": 204542, "author": "martinsb", "author_id": 837, "author_profile": "https://Stackoverflow.com/users/837", "pm_score": 2, "selected": false, "text": "<p>The time to release the memory occupied by an object is when you don't need that particular object any more. In your particular case, the user of a class AnimalLister requested a pointer to a new allocated object of class Animal. So, he's the one that is responsible for freeing memory when he does need that pointer/object any more.</p>\n\n<pre><code>AnimalLister lister;\nAnimal* a = lister.getNewAnimal();\na-&gt;sayMeow();\ndelete a;\n</code></pre>\n\n<p>In my opinion, there's no need to over-engineer anything in this case. AnimalLister is just a factory that creates new Animal objects and that's it.</p>\n" }, { "answer_id": 418252, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 5, "selected": false, "text": "<p>Depending on your usage, there are a couple of options you could go with here:</p>\n\n<ol>\n<li><p>Make a copy every time you create an animal:</p>\n\n<pre><code>class AnimalLister \n{\npublic:\n Animal getNewAnimal() \n {\n return Animal();\n }\n};\n\nint main() {\n AnimalLister al;\n Animal a1 = al.getNewAnimal();\n Animal a2 = al.getNewAnimal();\n}\n</code></pre>\n\n<p>Pros:</p>\n\n<ul>\n<li>Easy to understand. </li>\n<li>Requires no extra libraries or supporting code.</li>\n</ul>\n\n<p>Cons:</p>\n\n<ul>\n<li>It requires <code>Animal</code> to have a well-behaved copy-constructor.</li>\n<li>It can involve a lot of copying if <code>Animal</code> is larg and complex, although <a href=\"https://en.wikipedia.org/wiki/Return_value_optimization\" rel=\"noreferrer\">return value optimization</a> can alleviate that in many situations.</li>\n<li>Doesn't work if you plan on returning sub-classes derived from <code>Animal</code> as they will be <a href=\"http://cplusplusgems.blogspot.com/2005/10/what-is-slicing-problem-class-base.html\" rel=\"noreferrer\">sliced</a> down to a plain <code>Animal</code>, losing all the extra data in the sub-class. </li>\n</ul></li>\n<li><p>Return a <code>shared_ptr&lt;Animal&gt;</code>:</p>\n\n<pre><code>class AnimalLister \n{\npublic:\n shared_ptr&lt;Animal&gt; getNewAnimal() \n {\n return new Animal();\n }\n};\n\nint main() {\n AnimalLister al;\n shared_ptr&lt;Animal&gt; a1 = al.getNewAnimal();\n shared_ptr&lt;Animal&gt; a2 = al.getNewAnimal();\n}\n</code></pre>\n\n<p>Pros:</p>\n\n<ul>\n<li>Works with object-hierarchies (no object slicing).</li>\n<li>No issues with having to copy large objects.</li>\n<li>No need for <code>Animal</code> to define a copy constructor.</li>\n</ul>\n\n<p>Cons:</p>\n\n<ul>\n<li>Requires either Boost or TR1 libraries, or another smart-pointer implementation.</li>\n</ul></li>\n<li><p>Track all <code>Animal</code> allocations in <code>AnimalLister</code> </p>\n\n<pre><code>class AnimalLister \n{\n vector&lt;Animal *&gt; Animals;\n\npublic:\n Animal *getNewAnimal() \n {\n Animals.push_back(NULL);\n Animals.back() = new Animal();\n return Animals.back();\n }\n\n ~AnimalLister()\n {\n for(vector&lt;Animal *&gt;::iterator iAnimal = Animals.begin(); iAnimal != Animals.end(); ++iAnimal)\n delete *iAnimal;\n }\n};\n\nint main() {\n AnimalLister al;\n Animal *a1 = al.getNewAnimal();\n Animal *a2 = al.getNewAnimal();\n} // All the animals get deleted when al goes out of scope.\n</code></pre>\n\n<p>Pros:</p>\n\n<ul>\n<li>Ideal for situations where you need a bunch of <code>Animal</code>s for a limited amount of time, and plan to release them all at once.</li>\n<li>Easily adaptable to custom memory-pools and releasing all the <code>Animal</code>s in a single <code>delete</code>.</li>\n<li>Works with object-hierarchies (no object slicing).</li>\n<li>No issues with having to copy large objects.</li>\n<li>No need for <code>Animal</code> to define a copy constructor.</li>\n<li>No need for external libraries.</li>\n</ul>\n\n<p>Cons:</p>\n\n<ul>\n<li>The implementation as written above is not thread-safe</li>\n<li>Requires extra support code</li>\n<li>Less clear than the previous two schemes</li>\n<li>It's non-obvious that when the AnimalLister goes out of scope, it's going to take the Animals with it. You can't hang on to the Animals any longer than you hang on the AnimalLister.</li>\n</ul></li>\n</ol>\n" }, { "answer_id": 524697, "author": "BigSandwich", "author_id": 26983, "author_profile": "https://Stackoverflow.com/users/26983", "pm_score": 0, "selected": false, "text": "<p>I really like Josh's answer, but I thought I might throw in another pattern because it hasn't been listed yet. The idea is just force the client code to deal with keeping track of the animals.</p>\n\n<pre><code>class Animal\n{\n...\nprivate:\n //only let the lister create or delete animals.\n Animal() { ... }\n ~Animal() { ... } \nfriend class AnimalLister;\n...\n}\n\nclass AnimalLister \n{\n static s_count = 0;\n\npublic:\n ~AnimalLister() { ASSERT(s_count == 0); } //warn if all animals didn't get cleaned up\n\n Animal* NewAnimal() \n {\n ++count;\n return new Animal();\n }\n\n void FreeAnimal(Animal* a)\n {\n delete a;\n --s_count;\n }\n}\n</code></pre>\n" }, { "answer_id": 980645, "author": "amit kumar", "author_id": 19501, "author_profile": "https://Stackoverflow.com/users/19501", "pm_score": 2, "selected": false, "text": "<p>In a <a href=\"http://www.aristeia.com/Papers/resourceReturnProblem.txt\" rel=\"nofollow noreferrer\">thorough discussion by Scott Meyers</a>, he concludes that using shared_ptr or auto_ptr is the best. </p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28202/" ]
When returning objects from a class, when is the right time to release the memory? Example, ``` class AnimalLister { public: Animal* getNewAnimal() { Animal* animal1 = new Animal(); return animal1; } } ``` If i create an instance of Animal Lister and get Animal reference from it, then where am i supposed to delete it? ``` int main() { AnimalLister al; Animal *a1, *a2; a1 = al.getNewAnimal(); a2 = al.getNewAnimal(); } ``` The problem here is AnimalLister doesnot have a way to track the list of Animals Created, so how do i change the logic of such code to have a way to delete the objects created.
I advise returning a `std::tr1::shared_ptr` (or `boost::shared_ptr`, if your C++ implementation does not have TR1) instead of a raw pointer. So, instead of using `Animal*`, use `std::tr1::shared_ptr<Animal>` instead. Shared pointers handle reference tracking for you, and delete the object automatically if there are no references left to it.
204,398
<p>Let's have the following class hierarchy:</p> <pre><code>public class ParentClass implements SomeInterface { } public class ChildClass extends ParentClass { } </code></pre> <p>Then let's have these two instances:</p> <pre><code>ParentClass parent; ChildClass child; </code></pre> <p>Then we have the following TRUE statements</p> <pre><code>(parent instanceof SomeInterface) == true (child instanceof SomeInterface) == true </code></pre> <p>Is it possible to unimplement the SomeInterface in the ChildClass, so when we check with the instanceof operator it returns false?</p> <p>If not possible, is there a workaround?</p>
[ { "answer_id": 204409, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 2, "selected": false, "text": "<p>It's not possible and doing so would violate the implied IS-A relationship between ChildClass and ParentClass. Why do you want to do this?</p>\n" }, { "answer_id": 204413, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": -1, "selected": false, "text": "<p>Maybe you have a specific case where a better solution could be devised, but for the generic case you need some black magic. Eventually <a href=\"http://www.csg.is.titech.ac.jp/~chiba/javassist/\" rel=\"nofollow noreferrer\">Javassist</a> could be used \"hack\" your objects but I'm not so sure.</p>\n" }, { "answer_id": 204416, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>I don't think you can \"unimplement\" it but you could check if it is an instance of the parent class. Is the interface yours? If so you could extend it to include an \"IsObjectDerived\" method with semantics that it returns true iff the class only derives from object. Since you are writing the class all you would need to do is implement it in the parent and have it return true if the object is of class Parent and false otherwise.</p>\n\n<p>You could also do this with reflection by checking the superclass of the current class and make sure it is object. I'd probably do it this way since then implementing classes can't lie. You may want to look a <a href=\"http://java.sun.com/docs/books/tutorial/reflect/class/classModifiers.html\" rel=\"nofollow noreferrer\">tutorial</a> on reflection in Java that I found.</p>\n\n<p>[EDIT] In general I agree that this seems unnecessary in a reasonable design, but it can be done.</p>\n" }, { "answer_id": 204417, "author": "Simon", "author_id": 24039, "author_profile": "https://Stackoverflow.com/users/24039", "pm_score": 0, "selected": false, "text": "<p>I think you should take this problem as a clear indication that your interface and class design is flawed. Even if you could do it in Java (and I don't think you can) you shouldn't. </p>\n\n<p>How about re-factoring ParentClass so you have the SomeInterface implementation separate from that which you want in ChildClass. Maybe you need a common base class for ParentClass and ChildClass.</p>\n" }, { "answer_id": 204418, "author": "user28205", "author_id": 28205, "author_profile": "https://Stackoverflow.com/users/28205", "pm_score": 5, "selected": true, "text": "<p>No it is not possible, and your intent to do so is a good hint that something is flawed in your class hierarchy. </p>\n\n<p>Workaround: change the class hierarchy, eg. like this: </p>\n\n<pre><code>interface SomeInterface {}\nabstract class AbstractParentClass {}\nclass ParentClass extends AbstractParentClass implements SomeInterface {}\nclass ChildClass extends AbstractParentClass {}\n</code></pre>\n" }, { "answer_id": 204423, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 3, "selected": false, "text": "<p>Maybe composition instead of inheritance is what you want, i.e. have a \"base class\" object as a member and just implement the interfaces you need, forwarding any methods needed to the member.</p>\n" }, { "answer_id": 204654, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I fail to see how this would be sound practice, but you <i>could</i> alter a class dynamically using the excellent package Javassist created by Shigeru Chiba et al. Using this, you can add and remove features from classes and then use instances of these classes without saving as classfiles.</p>\n\n<p>Dynamic, interesting and totally confusing for anyone else. Use with care is my advice, but do play around with it as it makes you a better programmer in my opinion.</p>\n\n<p>(I believe ASM works in a similar fashion, but I have not tried it so far. It does seem to be very popular amongs the non-java language creators working on the JVM, so it is probably good.)</p>\n" }, { "answer_id": 216198, "author": "Oddthinking", "author_id": 8014, "author_profile": "https://Stackoverflow.com/users/8014", "pm_score": 2, "selected": false, "text": "<p>I agree with other answers that it is not possible in Java.</p>\n\n<p>The other answers further suggest it shows a flaw in your design. </p>\n\n<p>While I agree with them, it is only fair to point out that some prominent OO experts (particularly Bertrand Meyer) disagree with us, and believe such a design should be allowed.</p>\n\n<p>Other OO inheritance models (notably, Meyer's Eiffel programming language) do support the \"Change of Availability or Type\" (CAT) feature that you are looking for.</p>\n" }, { "answer_id": 216629, "author": "JohnnySoftware", "author_id": 29380, "author_profile": "https://Stackoverflow.com/users/29380", "pm_score": 1, "selected": false, "text": "<p>Since inheritance, the basis of OOP polymorphism, denotes an is-A relationship - your question seems to request a way to redefine \"is\" relationships to be \"is not\" relationships.</p>\n\n<p>That won't work.</p>\n\n<p>Go back to some introductory object-oriented texts or online material and study what object-oriented means: polymorphism, encapsulation, and identity.</p>\n\n<ol>\n<li>Strip off identity, and you've got COM/ActiveX and stolen credentials.</li>\n<li>Strip off encapsulation and nobody is safe.</li>\n<li>Strip off polyphism's type rules and you basically have nothing is necessarily what it says it is.</li>\n</ol>\n\n<p>If you want a situation like that, then program in \"C\". Don't mess around with pretending to write OOP code using OOP language features. Just use struct to hold your data. Put unions everywhere. Use typecast with abandon.</p>\n\n<p>Your program likely will not work reliably but you will be able to circumvent any restrictions languages like Java and C++ have introduced to make programs more reliable, easier to read, and easier to write/modify.</p>\n\n<p>In a dynamic programming language like SmalTalk or Python, you can essentially rip the wings off a butterfly at runtime. But only by changing/corrupting the type of the object.</p>\n\n<p>Doing so does not buy you anything. There are coding/design techniques and design patterns that let you accomplish any \"good\" result that you might be after that are similar to this.</p>\n\n<p>It is best if you think of what exactly you are trying to do in your application, and then try to find the safest/simplest way to accomplish that using sound techniques.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446104/" ]
Let's have the following class hierarchy: ``` public class ParentClass implements SomeInterface { } public class ChildClass extends ParentClass { } ``` Then let's have these two instances: ``` ParentClass parent; ChildClass child; ``` Then we have the following TRUE statements ``` (parent instanceof SomeInterface) == true (child instanceof SomeInterface) == true ``` Is it possible to unimplement the SomeInterface in the ChildClass, so when we check with the instanceof operator it returns false? If not possible, is there a workaround?
No it is not possible, and your intent to do so is a good hint that something is flawed in your class hierarchy. Workaround: change the class hierarchy, eg. like this: ``` interface SomeInterface {} abstract class AbstractParentClass {} class ParentClass extends AbstractParentClass implements SomeInterface {} class ChildClass extends AbstractParentClass {} ```
204,404
<p>We're developing an EPiServer-based website and trying to deploy our latest build onto a WinXP IIS6 box.</p> <p>When browsing to site, we're getting the following stack trace</p> <pre><code>[ClassFactoryException: ClassFactory not initialized] EPiServer.BaseLibrary.ClassFactory.get_Instance() +123 EPiServer.BaseLibrary.Context.get_Repository() +14 EPiServer.WorkflowFoundation.StorageProviders.ObjectStoreStorageProvider.VerifyCommonSchemas() +15 EPiServer.WorkflowFoundation.AspNetWorkflowManager.get_StorageProvider() +44 EPiServer.WorkflowFoundation.AspNetWorkflowManager.Initialize(Boolean lazyLoading) +589 EPiServer.WorkflowFoundation.AspNetWorkflowManager.get_InstanceHandler() +16 EPiServer.WorkflowFoundation.Workflows.ApprovalService..ctor() +93 [TargetInvocationException: Exception has been thrown by the target of an invocation.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean&amp; canBeCached, RuntimeMethodHandle&amp; ctor, Boolean&amp; bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +103 System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +261 System.Activator.CreateInstance(Type type, Boolean nonPublic) +66 EPiServer.WorkflowFoundation.WorkflowSystem.RegisterServices(IWorkflowManager manager, WorkflowSettingsElement configuration) +338 EPiServer.WorkflowFoundation.WorkflowSystem.Init(HttpApplication context) +240 System.Web.HttpApplication.InitModules() +267 System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers) +1251 System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context) +243 System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context) +106 System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +214 </code></pre> <p>I've googled it, and visited the EPiServer forums, but I've not found any concrete suggestions or solutions. Has anyone else out there run into this?</p> <p>Ross</p>
[ { "answer_id": 428061, "author": "aanund", "author_id": 7335, "author_profile": "https://Stackoverflow.com/users/7335", "pm_score": 0, "selected": false, "text": "<p>I am going out on a limb and guessing here, but did you by chance do development on EPiServer 5 SP 2 and deploy on EPiServer 5 SP 3?</p>\n\n<p>In EPiServer 5 SP3 there was some remodelling in how a EPiServer handles the initialization of the application. These changes made it so that it's not possible to hook into the datafactory events in Application_Start. Instead you need to first hook into Application_FirstBeginRequest and then we have a instance of the DataFactory to work with.</p>\n\n<p><a href=\"http://world.episerver.com/Forum/Pages/Thread.aspx?id=23087&amp;epslanguage=en\" rel=\"nofollow noreferrer\">Suggested reading</a></p>\n" }, { "answer_id": 826896, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>The configuration file is written for IIS7 but you build in webserver in Studio want a IIS6 sonfig file. \nI have wrote abut this in ny EPiServer notes\n<a href=\"http://epiwiki.se/troubleshooting/classfactory-not-initialized\" rel=\"nofollow noreferrer\">http://epiwiki.se/troubleshooting/classfactory-not-initialized</a> </p>\n" }, { "answer_id": 1028928, "author": "Ted Nyberg", "author_id": 87043, "author_profile": "https://Stackoverflow.com/users/87043", "pm_score": 0, "selected": false, "text": "<p>Definitely sounds like a configuration error. As Mattias said, the default web.config is for IIS7. This can cause problems when running IIS6 or Cassini.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12277/" ]
We're developing an EPiServer-based website and trying to deploy our latest build onto a WinXP IIS6 box. When browsing to site, we're getting the following stack trace ``` [ClassFactoryException: ClassFactory not initialized] EPiServer.BaseLibrary.ClassFactory.get_Instance() +123 EPiServer.BaseLibrary.Context.get_Repository() +14 EPiServer.WorkflowFoundation.StorageProviders.ObjectStoreStorageProvider.VerifyCommonSchemas() +15 EPiServer.WorkflowFoundation.AspNetWorkflowManager.get_StorageProvider() +44 EPiServer.WorkflowFoundation.AspNetWorkflowManager.Initialize(Boolean lazyLoading) +589 EPiServer.WorkflowFoundation.AspNetWorkflowManager.get_InstanceHandler() +16 EPiServer.WorkflowFoundation.Workflows.ApprovalService..ctor() +93 [TargetInvocationException: Exception has been thrown by the target of an invocation.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +103 System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +261 System.Activator.CreateInstance(Type type, Boolean nonPublic) +66 EPiServer.WorkflowFoundation.WorkflowSystem.RegisterServices(IWorkflowManager manager, WorkflowSettingsElement configuration) +338 EPiServer.WorkflowFoundation.WorkflowSystem.Init(HttpApplication context) +240 System.Web.HttpApplication.InitModules() +267 System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers) +1251 System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context) +243 System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context) +106 System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +214 ``` I've googled it, and visited the EPiServer forums, but I've not found any concrete suggestions or solutions. Has anyone else out there run into this? Ross
The configuration file is written for IIS7 but you build in webserver in Studio want a IIS6 sonfig file. I have wrote abut this in ny EPiServer notes <http://epiwiki.se/troubleshooting/classfactory-not-initialized>
204,406
<p>I am trying to convert all DateTime values in a DataTable to strings. Here is the method I use:</p> <pre><code>private static void ConvertDateTimesToStrings(DataTable dataTable) { if (dataTable == null) { return; } for (int rowIndex = 0; rowIndex &lt; dataTable.Rows.Count; rowIndex++ ) { for (int i = 0; i &lt; dataTable.Columns.Count; i++) { DateTime dateTime; try { dateTime = (DateTime)dataTable.Rows[rowIndex][i]; } catch (InvalidCastException) { continue; } dataTable.Rows[rowIndex][i] = dateTime.ToString("dd.MM.yyyy hh:mm:ss"); } } } </code></pre> <p>After this line works:</p> <pre><code>dataTable.Rows[rowIndex][i] = dateTime.ToString("dd.MM.yyyy hh:mm:ss"); </code></pre> <p>I check the value of dataTable.Rows[rowIndex][i] and see it is still a DateTime, not a string. Why does this happen and how can I solve this?</p> <p>Edit: I am trying to do this because I am fighting an api and unfortunately I do not have the choice of which component to use.</p>
[ { "answer_id": 204419, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 4, "selected": false, "text": "<p>This simply won't work, because you haven't changed the underlaying data type.</p>\n\n<p>You have a DataTable, with a column which has data type DateTime.</p>\n\n<p>You can assign a String to it, but it will convert back to DateTime.</p>\n\n<p>Why do you want to change it to a formatted string? Can't you format only when you need to display it, and handle as a DateTime until you have to display it?</p>\n\n<p><strong>Update:</strong> it is also better if you check the column's type before you try to convert, it can be much faster:</p>\n\n<pre><code>if (dataTable.Columns[0].DataType == typeof(DateTime))\n{\n}\n</code></pre>\n" }, { "answer_id": 204420, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 4, "selected": true, "text": "<p>It may have determined that the column data type is date time and is reboxing the values to datetime when you save the value back in there. </p>\n\n<p>Try this...\nCreate a new column on the datatable as a TypeOf(String), and save the string value into that column. When all the values have been copied, drop the date time column.</p>\n" }, { "answer_id": 204507, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 1, "selected": false, "text": "<p>It won't work beacuse the DataType of the column is still DateTime and it'll convert the string back to datetime.\nI'd suggest to format the date to string when generating your API message. If you still need to generate a string column for datetime values</p>\n\n<pre><code>foreach (DataColumn column in dataTable.Columns) {\n if (column.DataType == typeof(DateTime)) {\n dataTable.Columns.Add(column.ColumnName + \"_string\", typeof(string));\n }\n}\n\nforeach (DataRow row in dataTable.Rows) {\n foreach (DataColumn column in dataTable.Columns) {\n if (column.DataType == typeof(DateTime)) {\n row[column.ColumnName + \"_string\"] = row[column.ColumnName].ToString(\"dd.MM.yyyy hh:mm:ss\");\n }\n }\n}\n</code></pre>\n\n<p>Then you can remove all DateTime columns or use a dataTable.Select() to get only the columns you need.\nPS: I didn't test the code, it's up to you.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
I am trying to convert all DateTime values in a DataTable to strings. Here is the method I use: ``` private static void ConvertDateTimesToStrings(DataTable dataTable) { if (dataTable == null) { return; } for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; rowIndex++ ) { for (int i = 0; i < dataTable.Columns.Count; i++) { DateTime dateTime; try { dateTime = (DateTime)dataTable.Rows[rowIndex][i]; } catch (InvalidCastException) { continue; } dataTable.Rows[rowIndex][i] = dateTime.ToString("dd.MM.yyyy hh:mm:ss"); } } } ``` After this line works: ``` dataTable.Rows[rowIndex][i] = dateTime.ToString("dd.MM.yyyy hh:mm:ss"); ``` I check the value of dataTable.Rows[rowIndex][i] and see it is still a DateTime, not a string. Why does this happen and how can I solve this? Edit: I am trying to do this because I am fighting an api and unfortunately I do not have the choice of which component to use.
It may have determined that the column data type is date time and is reboxing the values to datetime when you save the value back in there. Try this... Create a new column on the datatable as a TypeOf(String), and save the string value into that column. When all the values have been copied, drop the date time column.
204,444
<p>As can be seen in the Mozilla changlog for JavaScript 1.7 they have added destructuring assignment. Sadly I'm not very fond of the syntax (why write a and b twice?):</p> <pre><code>var a, b; [a, b] = f(); </code></pre> <p>Something like this would have been a lot better:</p> <pre><code>var [a, b] = f(); </code></pre> <p>That would still be backwards compatible. Python-like destructuring would not be backwards compatible.</p> <p>Anyway the best solution for JavaScript 1.5 that I have been able to come up with is:</p> <pre><code>function assign(array, map) { var o = Object(); var i = 0; $.each(map, function(e, _) { o[e] = array[i++]; }); return o; } </code></pre> <p>Which works like:</p> <pre><code>var array = [1,2]; var _ = assign[array, { var1: null, var2: null }); _.var1; // prints 1 _.var2; // prints 2 </code></pre> <p>But this really sucks because _ has no meaning. It's just an empty shell to store the names. But sadly it's needed because JavaScript doesn't have pointers. On the plus side you can assign default values in the case the values are not matched. Also note that this solution doesn't try to slice the array. So you can't do something like <code>{first: 0, rest: 0}</code>. But that could easily be done, if one wanted that behavior.</p> <p>What is a better solution?</p>
[ { "answer_id": 205254, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "<p>You don't need the dummy \"_\" variable. You can directly create \"global\" variables by using the window object scope:</p>\n\n<pre><code>window[\"foo\"] = \"bar\";\nalert(foo); // Gives \"bar\"\n</code></pre>\n\n<p>Here are few more points:</p>\n\n<ul>\n<li>I wouldn't name this function\n\"assign\" because that's too generic\na term.</li>\n<li>To more closely resemble JS\n1.7 syntax, I'd make the function take the destination as the first\nargument and the source as the\nsecond argument.</li>\n<li>Using an object literal to pass the destination variables is cool but can be confused with JS 1.7 destructuring where the destination is actually an object and not an array. I prefer just using a comma delimited list of variable names as a string.</li>\n</ul>\n\n<p>Here's what I came up with:</p>\n\n<pre><code>function destructure(dest, src) { \n dest = dest.split(\",\"); \n\n for (var i = 0; i &lt; src.length; i++) { \n window[dest[i]] = src[i]; \n } \n} \n\nvar arr = [42, 66]; \n\ndestructure(\"var1,var2\", arr); \n\nalert(var1); // Gives 42\nalert(var2); // Gives 66\n</code></pre>\n" }, { "answer_id": 206566, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 6, "selected": true, "text": "<p>First off, <code>var [a, b] = f()</code> works just fine in JavaScript 1.7 - try it!</p>\n\n<p>Second, you can smooth out the usage syntax <em>slightly</em> using <code>with()</code>:</p>\n\n<pre><code>var array = [1,2];\nwith (assign(array, { var1: null, var2: null }))\n{\n var1; // == 1\n var2; // == 2\n}\n</code></pre>\n\n<p>Of course, this won't allow you to modify the values of existing variables, so IMHO it's a whole lot less useful than the JavaScript 1.7 feature. In code I'm writing <em>now</em>, I just return objects directly and reference their members - I'll wait for the 1.7 features to become more widely available.</p>\n" }, { "answer_id": 18805777, "author": "Eamonn O'Brien-Strain", "author_id": 978525, "author_profile": "https://Stackoverflow.com/users/978525", "pm_score": 0, "selected": false, "text": "<p>In standard JavaScript we get used to all kinds of ugliness, and emulating destructuring assignment using an intermediate variable is not too bad:</p>\n\n<pre><code>function divMod1(a, b) {\n return [ Math.floor(a / b), a % b ];\n}\n\nvar _ = divMod1(11, 3);\nvar div = _[0];\nvar mod = _[1];\nalert(\"(1) div=\" + div + \", mod=\" + mod );\n</code></pre>\n\n<p>However I think the following pattern is more idomatic:</p>\n\n<pre><code>function divMod2(a, b, callback) {\n callback(Math.floor(a / b), a % b);\n}\n\ndivMod2(11, 3, function(div, mod) {\n alert(\"(2) div=\" + div + \", mod=\" + mod );\n});\n</code></pre>\n\n<p>Note, that instead of returning the two results as an array, we pass them as arguments to a callback function.</p>\n\n<p>(See code running at <a href=\"http://jsfiddle.net/vVQE3/\" rel=\"nofollow\">http://jsfiddle.net/vVQE3/</a> )</p>\n" }, { "answer_id": 34422974, "author": "Sam", "author_id": 2125737, "author_profile": "https://Stackoverflow.com/users/2125737", "pm_score": 1, "selected": false, "text": "<p>Here's what I did in PHPstorm 10:</p>\n\n<p><em>File -> Settings -> Languages &amp; Frameworks -> ...</em></p>\n\n<p>... set JavaScript language version to e.g. JavaScript 1.8.5...</p>\n\n<p><em>-> click Apply.</em></p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13995/" ]
As can be seen in the Mozilla changlog for JavaScript 1.7 they have added destructuring assignment. Sadly I'm not very fond of the syntax (why write a and b twice?): ``` var a, b; [a, b] = f(); ``` Something like this would have been a lot better: ``` var [a, b] = f(); ``` That would still be backwards compatible. Python-like destructuring would not be backwards compatible. Anyway the best solution for JavaScript 1.5 that I have been able to come up with is: ``` function assign(array, map) { var o = Object(); var i = 0; $.each(map, function(e, _) { o[e] = array[i++]; }); return o; } ``` Which works like: ``` var array = [1,2]; var _ = assign[array, { var1: null, var2: null }); _.var1; // prints 1 _.var2; // prints 2 ``` But this really sucks because \_ has no meaning. It's just an empty shell to store the names. But sadly it's needed because JavaScript doesn't have pointers. On the plus side you can assign default values in the case the values are not matched. Also note that this solution doesn't try to slice the array. So you can't do something like `{first: 0, rest: 0}`. But that could easily be done, if one wanted that behavior. What is a better solution?
First off, `var [a, b] = f()` works just fine in JavaScript 1.7 - try it! Second, you can smooth out the usage syntax *slightly* using `with()`: ``` var array = [1,2]; with (assign(array, { var1: null, var2: null })) { var1; // == 1 var2; // == 2 } ``` Of course, this won't allow you to modify the values of existing variables, so IMHO it's a whole lot less useful than the JavaScript 1.7 feature. In code I'm writing *now*, I just return objects directly and reference their members - I'll wait for the 1.7 features to become more widely available.
204,461
<p>Suppose you have:</p> <pre><code>A-B-C </code></pre> <p>Now your build/test fails. The fix should be merged in A. My current work-flow is like this:</p> <pre><code>$ git commit -m "fixA" A-B-C-fixA $ git rebase -i A~1 </code></pre> <p>And squash fixA in A, result in: </p> <pre><code>A'-B-C </code></pre> <p>Is there a command to do something like:</p> <pre><code>A-B-C + (index with fix for A) $ git commit -supperdupper A </code></pre> <p>Result:</p> <pre><code>A'-B-C </code></pre>
[ { "answer_id": 4607280, "author": "Jo Liss", "author_id": 525872, "author_profile": "https://Stackoverflow.com/users/525872", "pm_score": 5, "selected": true, "text": "<p><em>If you're just looking for the easy solution for fixing up earlier commits, read the question! It explains it all. But since Elmarco was asking for a slick way, here we go:</em></p>\n\n<p>As of Git 1.7.0, there is an <code>--autosquash</code> option for <a href=\"https://www.kernel.org/pub/software/scm/git/docs/git-rebase.html\" rel=\"nofollow\"><code>rebase</code></a>, which does what you want. There is also the <code>--fixup</code> and <code>--squash</code> options for <a href=\"https://www.kernel.org/pub/software/scm/git/docs/git-commit.html\" rel=\"nofollow\"><code>commit</code></a> to make things easier. With some aliasing you can probably even get the whole thing into a single command.</p>\n\n<p>I'd suggest upgrading to the newest Git for maximum awesomeness:</p>\n\n<pre><code>git/Documentation/RelNotes $ grep -i -A1 autosquash\\\\\\|fixup *\n1.7.0.txt: * \"git rebase -i\" learned new action \"fixup\" that squashes the change\n1.7.0.txt- but does not affect existing log message.\n--\n1.7.0.txt: * \"git rebase -i\" also learned --autosquash option that is useful\n1.7.0.txt: together with the new \"fixup\" action.\n1.7.0.txt-\n--\n1.7.3.txt: * \"git rebase -i\" peeks into rebase.autosquash configuration and acts as\n1.7.3.txt: if you gave --autosquash from the command line.\n1.7.3.txt-\n--\n1.7.4.txt: * \"git commit\" learned --fixup and --squash options to help later invocation\n1.7.4.txt- of the interactive rebase.\n--\n1.7.4.txt: * \"git rebase --autosquash\" can use SHA-1 object names to name which\n1.7.4.txt: commit to fix up (e.g. \"fixup! e83c5163\").\n1.7.4.txt-\n</code></pre>\n" }, { "answer_id": 5538884, "author": "lanoxx", "author_id": 474034, "author_profile": "https://Stackoverflow.com/users/474034", "pm_score": 2, "selected": false, "text": "<p>If you want to squash the last two commits then you have to invoke</p>\n\n<pre><code>git rebase --interactive &lt;3rd last commit&gt;\n</code></pre>\n\n<p>You then need to pick the last commit and squash the second-to-last commit. You cannot squash the topmost commit of a history.</p>\n" }, { "answer_id": 14959746, "author": "bkeepers", "author_id": 262540, "author_profile": "https://Stackoverflow.com/users/262540", "pm_score": 3, "selected": false, "text": "<p>I <a href=\"https://gist.github.com/bkeepers/4986257\" rel=\"noreferrer\">created some aliases</a> to make it easier to use the <code>git commit --fixup</code> and <code>git commit --squash</code> commands added in git 1.7. Add these to your <code>~/.gitconfig</code>:</p>\n\n<pre><code>[alias]\n fixup = !sh -c 'REV=$(git rev-parse $1) &amp;&amp; git commit --fixup $@ &amp;&amp; git rebase -i --autosquash $REV^' -\n squash = !sh -c 'REV=$(git rev-parse $1) &amp;&amp; git commit --squash $@ &amp;&amp; git rebase -i --autosquash $REV^' -\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$ git commit -am 'bad commit'\n$ git commit -am 'good commit'\n\n$ git add . # Stage changes to correct the bad commit\n$ git fixup HEAD^ # HEAD^ can be replaced by the SHA of the bad commit\n</code></pre>\n\n<p>The bad commit can be several commits back.</p>\n" }, { "answer_id": 24656286, "author": "Mika Eloranta", "author_id": 1058622, "author_profile": "https://Stackoverflow.com/users/1058622", "pm_score": 2, "selected": false, "text": "<p>My current git work flow is so <code>--fixup</code>/<code>--squash</code> intensive, that I wrote a new <code>git-fixup</code> command that handles most of the annoying bits automatically:</p>\n\n<ul>\n<li><code>git fixup</code> shows the modified files grouped under that latest commits that touch the <em>same files</em></li>\n<li><code>git fixup -a</code> commits all those changes as <code>--fixup</code> changes with their corresponding \"parent\" commits</li>\n<li><code>git fixup -r</code> does an automatic <code>git rebase --autosquash</code> for all the fixup commits</li>\n</ul>\n\n<p>A lot of changes are such that just the three commands above are enough to get the job done, no copy-pasting of commit-id's or reading thru the <code>git log</code> to find the right <code>--fixup</code> targets.</p>\n\n<p>Source: <a href=\"https://github.com/ohmu/git-crust\" rel=\"nofollow\">https://github.com/ohmu/git-crust</a></p>\n" }, { "answer_id": 36317398, "author": "Oktalist", "author_id": 1639256, "author_profile": "https://Stackoverflow.com/users/1639256", "pm_score": 0, "selected": false, "text": "<p>I think the root of the problem is that git (and version control generally) forces you to think in terms of sequences of changes, but a changeset or feature-branch or whatever you call a cohesive group of related changes is in general not logically sequential. The order in which the code was written is incidental and not necessarily related to the order in which it should be read.</p>\n\n<p>I don't have a solution to that, but I have written a <a href=\"https://gist.github.com/oktal3700/cafe086b49c89f814be4a7507a32a3f7\" rel=\"nofollow\">Perl script</a> to help automate the process of rewriting history. It's similar to the Python script of @MikaEloranta which I hadn't seen when I wrote it.</p>\n\n<p><code>commit --fixup</code> and <code>rebase --autosquash</code> are great, but they don't do enough. When I have a sequence of commits <code>A-B-C</code> and I write some more changes in my working tree which belong in one or more of those existing commits, I have to manually look at the history, decide which changes belong in which commits, stage them and create the <code>fixup!</code> commits. But git already has access to enough information to be able to do all that for me.</p>\n\n<p>For each hunk in <code>git diff</code> the script uses <code>git blame</code> to find the commit that last touched the relevant lines, and calls <code>git commit --fixup</code> to write the appropriate <code>fixup!</code> commits, essentially doing the same thing I was doing manually before.</p>\n\n<p>If the script can't resolve a hunk to a single, unambiguous commit, it will report it as a failed hunk and you'll have to fall back to the manual approach for that one. If you changed a line twice in two separate commits, the script will resolve a change on that line to the most recent of those commits, which might not always be the correct resolution. IMHO in a \"normal form\" feature branch you shouldn't be changing a line twice in two different commits, each commit should be presenting the final version of the lines that it touches, to help the reviewer(s). However, it can happen in a bugfix branch, to contrive an example the line <code>foo(bar());</code> could be touched by commit A (rename <code>foo</code> to <code>fox</code>) and commit B (rename <code>bar</code> to <code>baz</code>).</p>\n\n<p>If you find the script useful, please feel free to improve and iterate on it and maybe one day we'll get such a feature in <code>git</code> proper. I'd love to see a tool that can understand how a merge conflict should be resolved when it has been introduced by an interactive rebase.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1277510/" ]
Suppose you have: ``` A-B-C ``` Now your build/test fails. The fix should be merged in A. My current work-flow is like this: ``` $ git commit -m "fixA" A-B-C-fixA $ git rebase -i A~1 ``` And squash fixA in A, result in: ``` A'-B-C ``` Is there a command to do something like: ``` A-B-C + (index with fix for A) $ git commit -supperdupper A ``` Result: ``` A'-B-C ```
*If you're just looking for the easy solution for fixing up earlier commits, read the question! It explains it all. But since Elmarco was asking for a slick way, here we go:* As of Git 1.7.0, there is an `--autosquash` option for [`rebase`](https://www.kernel.org/pub/software/scm/git/docs/git-rebase.html), which does what you want. There is also the `--fixup` and `--squash` options for [`commit`](https://www.kernel.org/pub/software/scm/git/docs/git-commit.html) to make things easier. With some aliasing you can probably even get the whole thing into a single command. I'd suggest upgrading to the newest Git for maximum awesomeness: ``` git/Documentation/RelNotes $ grep -i -A1 autosquash\\\|fixup * 1.7.0.txt: * "git rebase -i" learned new action "fixup" that squashes the change 1.7.0.txt- but does not affect existing log message. -- 1.7.0.txt: * "git rebase -i" also learned --autosquash option that is useful 1.7.0.txt: together with the new "fixup" action. 1.7.0.txt- -- 1.7.3.txt: * "git rebase -i" peeks into rebase.autosquash configuration and acts as 1.7.3.txt: if you gave --autosquash from the command line. 1.7.3.txt- -- 1.7.4.txt: * "git commit" learned --fixup and --squash options to help later invocation 1.7.4.txt- of the interactive rebase. -- 1.7.4.txt: * "git rebase --autosquash" can use SHA-1 object names to name which 1.7.4.txt: commit to fix up (e.g. "fixup! e83c5163"). 1.7.4.txt- ```
204,467
<p>I have trouble using Perl grep() with a string that <em>may</em> contain chars that are interpreted as regular expressions quantifiers. </p> <p>I got the following error when the grep pattern is "g++" because the '+' symbols are interpreted as quantifiers. Here is the output of for program that follows:</p> <pre><code>1..3 ok 1 - grep, pattern not found ok 2 - grep, pattern found Nested quantifiers in regex; marked by &lt;-- HERE in m/g++ &lt;-- HERE / at escape_regexp_quantifier.pl line 8. </code></pre> <p>Is there a modifier I could use to indicate to grep that the quantifiers shall be ignored, or is there a function that would escape the quantifiers ?</p> <pre><code>#! /usr/bin/perl sub test_grep($) { my $filter = shift; my @output = ("-r-xr-xr-x 3 root bin 122260 Jan 23 2005 gcc", "-r-xr-xr-x 4 root bin 124844 Jan 23 2005 g++"); return grep (!/$filter/, @output); } use Test::Simple tests =&gt; 2; ok(test_grep("foo"), "grep, pattern not found"); ok(test_grep("gcc"), "grep, pattern found"); ok(test_grep("g++"), "grep, pattern found"); </code></pre> <p>PS: in addition to the answer question above, I welcome any feedback on Perl usage in the above as I'm still learning. Thanks</p>
[ { "answer_id": 204474, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 6, "selected": true, "text": "<p>The standard way is to use the <code>\\Q</code> escape indicator before your variable, to tell Perl not to parse the contents as a regular expression:</p>\n\n<pre><code>return grep (!/\\Q$filter/, @output);\n</code></pre>\n\n<p>Altering that line in your code yields:</p>\n\n<pre>\n1..3\nok 1 - grep, pattern not found\nok 2 - grep, pattern found\nok 3 - grep, pattern found\n</pre>\n" }, { "answer_id": 204480, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 4, "selected": false, "text": "<p>I think you are looking for <a href=\"http://perldoc.perl.org/functions/quotemeta.html\" rel=\"nofollow noreferrer\">quotemeta</a></p>\n" }, { "answer_id": 204490, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "<p><em>in addition to the answer question above, I welcome any feedback on Perl usage in the above as I'm still learning. Thanks</em></p>\n\n<p>I would advice you not to use prototypes (the <em>($)</em> after test_grep). They have their uses, but not for most cases and definitely not in this one.</p>\n" }, { "answer_id": 204943, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>PS: in addition to the answer question\n above, I welcome any feedback on Perl\n usage in the above as I'm still\n learning.</p>\n</blockquote>\n\n<p>The best advice I can give for Perl coding advice in general is to install <a href=\"http://search.cpan.org/perldoc?Perl::Critic\" rel=\"nofollow noreferrer\">Perl::Critic</a> and use the <a href=\"http://search.cpan.org/perldoc?perlcritic\" rel=\"nofollow noreferrer\">perlcritic</a> command on your code. If you can't do that, you can use the <a href=\"http://perlcritic.com/\" rel=\"nofollow noreferrer\">on-line perl critic tool</a>. It will help if you have a copy of <a href=\"http://oreilly.com/catalog/9780596001735/\" rel=\"nofollow noreferrer\">Perl Best Practices</a> handy, since <code>Perl::Critic</code> has already read the book and will give you references to page numbers, however even if you don't have the book around you can still find extended feedback in the <a href=\"http://search.cpan.org/dist/Perl-Critic/\" rel=\"nofollow noreferrer\">Perl::Critic documentation</a> sections starting with <code>Perl::Critic::Policy::</code>.</p>\n" }, { "answer_id": 205144, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 2, "selected": false, "text": "<p>I'd suggest using qr to create Regexp objects rather than strings in this case anyway.</p>\n\n<pre><code>ok(test_grep(qr/foo/), \"grep, pattern not found\");\nok(test_grep(qr/gcc/), \"grep, pattern found\");\nok(test_grep(qr/g\\+\\+/), \"grep, pattern found\");\n</code></pre>\n\n<p>Then you don't need the \\Q escape. Though you can still use it:</p>\n\n<pre><code>ok(test_grep(qr/\\Qg++/), \"grep, pattern found\");\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18804/" ]
I have trouble using Perl grep() with a string that *may* contain chars that are interpreted as regular expressions quantifiers. I got the following error when the grep pattern is "g++" because the '+' symbols are interpreted as quantifiers. Here is the output of for program that follows: ``` 1..3 ok 1 - grep, pattern not found ok 2 - grep, pattern found Nested quantifiers in regex; marked by <-- HERE in m/g++ <-- HERE / at escape_regexp_quantifier.pl line 8. ``` Is there a modifier I could use to indicate to grep that the quantifiers shall be ignored, or is there a function that would escape the quantifiers ? ``` #! /usr/bin/perl sub test_grep($) { my $filter = shift; my @output = ("-r-xr-xr-x 3 root bin 122260 Jan 23 2005 gcc", "-r-xr-xr-x 4 root bin 124844 Jan 23 2005 g++"); return grep (!/$filter/, @output); } use Test::Simple tests => 2; ok(test_grep("foo"), "grep, pattern not found"); ok(test_grep("gcc"), "grep, pattern found"); ok(test_grep("g++"), "grep, pattern found"); ``` PS: in addition to the answer question above, I welcome any feedback on Perl usage in the above as I'm still learning. Thanks
The standard way is to use the `\Q` escape indicator before your variable, to tell Perl not to parse the contents as a regular expression: ``` return grep (!/\Q$filter/, @output); ``` Altering that line in your code yields: ``` 1..3 ok 1 - grep, pattern not found ok 2 - grep, pattern found ok 3 - grep, pattern found ```
204,468
<p>So I have the following:</p> <pre><code>public class Singleton { private Singleton(){} public static readonly Singleton instance = new Singleton(); public string DoSomething(){ ... } public string DoSomethingElse(){ ... } } </code></pre> <p>Using reflection how can I invoke the DoSomething Method? </p> <p>Reason I ask is because I store the method names in XML and dynamically create the UI. For example I'm dynamically creating a button and telling it what method to call via reflection when the button is clicked. In some cases it would be DoSomething or in others it would be DoSomethingElse.</p>
[ { "answer_id": 204508, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>Untested, but should work...</p>\n\n<pre><code>string methodName = \"DoSomething\"; // e.g. read from XML\nMethodInfo method = typeof(Singleton).GetMethod(methodName);\nFieldInfo field = typeof(Singleton).GetField(\"instance\",\n BindingFlags.Static | BindingFlags.Public);\nobject instance = field.GetValue(null);\nmethod.Invoke(instance, Type.EmptyTypes);\n</code></pre>\n" }, { "answer_id": 2205668, "author": "nasser", "author_id": 266859, "author_profile": "https://Stackoverflow.com/users/266859", "pm_score": 2, "selected": false, "text": "<p>Great job. Thanks. </p>\n\n<p>Here's the same approach with slight modification for cases that one can't have a reference to the remote assembly. We just need to know basic things such as the class fullname (i.e namespace.classname and the path to the remote assembly). </p>\n\n<pre><code>static void Main(string[] args)\n {\n Assembly asm = null;\n string assemblyPath = @\"C:\\works\\...\\StaticMembers.dll\" \n string classFullname = \"StaticMembers.MySingleton\";\n string doSomethingMethodName = \"DoSomething\";\n string doSomethingElseMethodName = \"DoSomethingElse\";\n\n asm = Assembly.LoadFrom(assemblyPath);\n if (asm == null)\n throw new FileNotFoundException();\n\n\n Type[] types = asm.GetTypes();\n Type theSingletonType = null;\n foreach(Type ty in types)\n {\n if (ty.FullName.Equals(classFullname))\n {\n theSingletonType = ty;\n break;\n }\n }\n if (theSingletonType == null)\n {\n Console.WriteLine(\"Type was not found!\");\n return;\n }\n MethodInfo doSomethingMethodInfo = \n theSingletonType.GetMethod(doSomethingMethodName );\n\n\n FieldInfo field = theSingletonType.GetField(\"instance\", \n BindingFlags.Static | BindingFlags.Public);\n\n object instance = field.GetValue(null);\n\n string msg = (string)doSomethingMethodInfo.Invoke(instance, Type.EmptyTypes);\n\n Console.WriteLine(msg);\n\n MethodInfo somethingElse = theSingletonType.GetMethod(\n doSomethingElseMethodName );\n msg = (string)doSomethingElse.Invoke(instance, Type.EmptyTypes);\n Console.WriteLine(msg);}\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6204/" ]
So I have the following: ``` public class Singleton { private Singleton(){} public static readonly Singleton instance = new Singleton(); public string DoSomething(){ ... } public string DoSomethingElse(){ ... } } ``` Using reflection how can I invoke the DoSomething Method? Reason I ask is because I store the method names in XML and dynamically create the UI. For example I'm dynamically creating a button and telling it what method to call via reflection when the button is clicked. In some cases it would be DoSomething or in others it would be DoSomethingElse.
Untested, but should work... ``` string methodName = "DoSomething"; // e.g. read from XML MethodInfo method = typeof(Singleton).GetMethod(methodName); FieldInfo field = typeof(Singleton).GetField("instance", BindingFlags.Static | BindingFlags.Public); object instance = field.GetValue(null); method.Invoke(instance, Type.EmptyTypes); ```
204,476
<p>What is the correct (most efficient) way to define the <code>main()</code> function in C and C++ — <code>int main()</code> or <code>void main()</code> — and why? And how about the arguments? If <code>int main()</code> then <code>return 1</code> or <code>return 0</code>?</p> <hr> <p><em>There are numerous duplicates of this question, including:</em></p> <ul> <li><a href="https://stackoverflow.com/questions/2108192/what-are-the-valid-signatures-for-cs-main-function/">What are the valid signatures for C's <code>main()</code> function?</a></li> <li><a href="https://stackoverflow.com/questions/17715008/the-return-type-of-main-function/">The return type of <code>main()</code> function</a></li> <li><a href="https://stackoverflow.com/questions/636829/difference-between-void-main-and-int-main">Difference between <code>void main()</code> and <code>int main()</code>?</a></li> <li><a href="https://stackoverflow.com/questions/1621574/mains-signature-in-c"><code>main()</code>'s signature in C++</a></li> <li><a href="https://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main">What is the proper declaration of <code>main()</code>?</a> — For C++, with a very good answer indeed.</li> <li><a href="https://stackoverflow.com/questions/8692120/styles-of-main-functions-in-c">Styles of <code>main()</code> functions in C</a></li> <li><a href="https://stackoverflow.com/questions/10915713/return-type-of-main-method-in-c">Return type of <code>main()</code> method in C</a></li> <li><a href="https://stackoverflow.com/questions/9356510/int-main-vs-void-main-in-c"><code>int main()</code> vs <code>void main()</code> in C</a></li> </ul> <p>Related:</p> <ul> <li><a href="https://stackoverflow.com/questions/5191965/c-int-mainint-argc-char-argv">C++ — <code>int main(int argc, char **argv)</code></a></li> <li><a href="https://stackoverflow.com/questions/5217395/c-int-mainint-argc-char-argv">C++ — <code>int main(int argc, char *argv[])</code></a></li> <li><a href="https://stackoverflow.com/questions/10321435/is-char-envp-as-a-third-argument-to-main-portable">Is <code>char *envp[]</code> as a third argument to <code>main()</code> portable?</a></li> <li><a href="https://stackoverflow.com/questions/18402853/must-the-int-main-function-return-a-value-in-all-compilers">Must the <code>int main()</code> function return a value in all compilers?</a></li> <li><a href="https://stackoverflow.com/questions/5296163/why-is-the-type-of-the-main-function-in-c-and-c-left-to-the-user-to-define">Why is the type of the <code>main()</code> function in C and C++ left to the user to define?</a></li> <li><a href="https://stackoverflow.com/questions/22239/why-does-int-main-compile">Why does <code>int main(){}</code> compile?</a></li> <li><a href="https://stackoverflow.com/questions/26470912/legal-definitions-of-main-in-c14">Legal definitions of <code>main()</code> in C++14?</a></li> </ul>
[ { "answer_id": 204483, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 10, "selected": true, "text": "<p>The return value for <code>main</code> indicates how the program exited. Normal exit is represented by a 0 return value from <code>main</code>. Abnormal exit is signaled by a non-zero return, but there is no standard for how non-zero codes are interpreted. As noted by others, <code>void main()</code> is prohibited by the C++ standard and should not be used. The valid C++ <code>main</code> signatures are:</p>\n\n<pre><code>int main()\n</code></pre>\n\n<p>and</p>\n\n<pre><code>int main(int argc, char* argv[])\n</code></pre>\n\n<p>which is equivalent to</p>\n\n<pre><code>int main(int argc, char** argv)\n</code></pre>\n\n<p>It is also worth noting that in C++, <code>int main()</code> can be left without a return-statement, at which point it defaults to returning 0. This is also true with a C99 program. Whether <code>return 0;</code> should be omitted or not is open to debate. The range of valid C program main signatures is much greater. </p>\n\n<p>Efficiency is not an issue with the <code>main</code> function. It can only be entered and left once (marking the program's start and termination) according to the C++ standard. For C, re-entering <code>main()</code> is allowed, but should be avoided.</p>\n" }, { "answer_id": 204487, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 5, "selected": false, "text": "<p>Return 0 on success and non-zero for error. This is the standard used by UNIX and DOS scripting to find out what happened with your program.</p>\n" }, { "answer_id": 204530, "author": "dmityugov", "author_id": 3232, "author_profile": "https://Stackoverflow.com/users/3232", "pm_score": 6, "selected": false, "text": "<p>I believe that <code>main()</code> should return either <code>EXIT_SUCCESS</code> or <code>EXIT_FAILURE</code>. They are defined in <code>stdlib.h</code></p>\n" }, { "answer_id": 205141, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 3, "selected": false, "text": "<p>Keep in mind that,even though you're returning an int, some OSes (Windows) truncate the returned value to a single byte (0-255).</p>\n" }, { "answer_id": 207992, "author": "Chris Young", "author_id": 9417, "author_profile": "https://Stackoverflow.com/users/9417", "pm_score": 8, "selected": false, "text": "<p>The accepted answer appears to be targetted for C++, so I thought I'd add an answer that pertains to C, and this differs in a few ways. There were also some changes made between ISO/IEC 9899:1989 (C90) and ISO/IEC 9899:1999 (C99).</p>\n<p><code>main()</code> should be declared as either:</p>\n<pre><code>int main(void)\nint main(int argc, char **argv)\n</code></pre>\n<p>Or equivalent. For example, <code>int main(int argc, char *argv[])</code> is equivalent to the second one. In C90, the <code>int</code> return type can be omitted as it is a default, but in C99 and newer, the <code>int</code> return type may not be omitted.</p>\n<p>If an implementation permits it, <code>main()</code> can be declared in other ways (e.g., <code>int main(int argc, char *argv[], char *envp[])</code>), but this makes the program implementation defined, and no longer strictly conforming.</p>\n<p>The standard defines 3 values for returning that are strictly conforming (that is, does not rely on implementation defined behaviour): <code>0</code> and <code>EXIT_SUCCESS</code> for a successful termination, and <code>EXIT_FAILURE</code> for an unsuccessful termination. Any other values are non-standard and implementation defined. In C90, <code>main()</code> must have an explicit <code>return</code> statement at the end to avoid undefined behaviour. In C99 and newer, you may omit the return statement from <code>main()</code>. If you do, and <code>main()</code> finished, there is an implicit <code>return 0</code>.</p>\n<p>Finally, there is nothing wrong from a standards point of view with calling <code>main()</code> <em>recursively</em> from a C program.</p>\n" }, { "answer_id": 5180411, "author": "Luca C.", "author_id": 571410, "author_profile": "https://Stackoverflow.com/users/571410", "pm_score": 2, "selected": false, "text": "<p>If you really have issues related to efficiency of returning an integer from a process, you should probably avoid to call that process so many times that this return value becomes an issue.</p>\n\n<p>If you are doing this (call a process so many times), you should find a way to put your logic directly inside the caller, or in a DLL file, without allocate a specific process for each call; the multiple process allocations bring you the relevant efficiency problem in this case.</p>\n\n<p>In detail, if you only want to know if returning 0 is more or less efficient than returning 1, it could depend from the compiler in some cases, but generically, assuming they are read from the same source (local, field, constant, embedded in the code, function result, etc.) it requires exactly the same number of clock cycles.</p>\n" }, { "answer_id": 5260799, "author": "phoxis", "author_id": 702361, "author_profile": "https://Stackoverflow.com/users/702361", "pm_score": 2, "selected": false, "text": "<p>What to return depends on what you want to do with the executable. For example if you are using your program with a command line shell, then you need to return 0 for a success and a non zero for failure. Then you would be able to use the program in shells with conditional processing depending on the outcome of your code. Also you can assign any nonzero value as per your interpretation, for example for critical errors different program exit points could terminate a program with different exit values , and which is available to the calling shell which can decide what to do by inspecting the value returned.\nIf the code is not intended for use with shells and the returned value does not bother anybody then it might be omitted. I personally use the signature <code>int main (void) { .. return 0; .. }</code></p>\n" }, { "answer_id": 6550681, "author": "Yochai Timmer", "author_id": 536086, "author_profile": "https://Stackoverflow.com/users/536086", "pm_score": 3, "selected": false, "text": "<p>The return value can be used by the operating system to check how the program was closed.</p>\n\n<p>Return value 0 usually means OK in most operating systems (the ones I can think of anyway).</p>\n\n<p>It also can be checked when you call a process yourself, and see if the program exited and finished properly.</p>\n\n<p>It's <strong>NOT</strong> just a programming convention.</p>\n" }, { "answer_id": 6554135, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The return value of <code>main()</code> shows how the program exited. If the return value is <code>zero</code> it means that the execution was successful while any non-zero value will represent that something went bad in the execution.</p>\n" }, { "answer_id": 8642388, "author": "Jeegar Patel", "author_id": 775964, "author_profile": "https://Stackoverflow.com/users/775964", "pm_score": 3, "selected": false, "text": "<p><code>main()</code> in C89 and K&amp;R C unspecified return types default to ’int`.</p>\n<pre><code>return 1? return 0?\n</code></pre>\n<ol>\n<li>If you do not write a return statement in <code>int main()</code>, the closing <code>}</code> will return 0 by default.</li>\n</ol>\n<p>(In c++ and c99 onwards only, for c90 you must write return statement. Please see <a href=\"https://stackoverflow.com/questions/8677672/why-main-does-not-return-0-here\">Why main does not return 0 here?</a>)</p>\n<ol start=\"2\">\n<li><code>return 0</code> or <code>return 1</code> will be received by the parent process. In a shell it goes into a shell variable, and if you are running your program form a shell and not using that variable then you need not worry about the return value of <code>main()</code>.</li>\n</ol>\n<p>See <a href=\"https://stackoverflow.com/q/8626109/775964\">How can I get what my main function has returned?</a>.</p>\n<pre><code>$ ./a.out\n$ echo $?\n</code></pre>\n<p>This way you can see that it is the variable <code>$?</code> which receives the least significant byte of the return value of <code>main()</code>.</p>\n<p>In Unix and DOS scripting, <code>return 0</code> on success and non-zero for error are usually returned. This is the standard used by Unix and DOS scripting to find out what happened with your program and controlling the whole flow.</p>\n" }, { "answer_id": 13524721, "author": "Vamsi Pavan Mahesh", "author_id": 1395129, "author_profile": "https://Stackoverflow.com/users/1395129", "pm_score": 2, "selected": false, "text": "<p>Returning 0 should tell the programmer that the program has successfully finished the job.</p>\n" }, { "answer_id": 18721336, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 7, "selected": false, "text": "<h2>Standard C — Hosted Environment</h2>\n<p>For a hosted environment (that's the normal one), the C11 standard (ISO/IEC 9899:2011) says:</p>\n<blockquote>\n<h3>5.1.2.2.1 Program startup</h3>\n<p>The function called at program startup is named <code>main</code>. The implementation declares no\nprototype for this function. It shall be defined with a return type of <code>int</code> and with no\nparameters:</p>\n<pre><code>int main(void) { /* ... */ }\n</code></pre>\n<p>or with two parameters (referred to here as <code>argc</code> and <code>argv</code>, though any names may be\nused, as they are local to the function in which they are declared):</p>\n<pre><code>int main(int argc, char *argv[]) { /* ... */ }\n</code></pre>\n<p>or equivalent;<sup>10)</sup> or in some other implementation-defined manner.</p>\n<p>If they are declared, the parameters to the main function shall obey the following\nconstraints:</p>\n<ul>\n<li>The value of <code>argc</code> shall be nonnegative.</li>\n<li><code>argv[argc]</code> shall be a null pointer.</li>\n<li>If the value of <code>argc</code> is greater than zero, the array members <code>argv[0]</code> through\n<code>argv[argc-1]</code> inclusive shall contain pointers to strings, which are given\nimplementation-defined values by the host environment prior to program startup. The\nintent is to supply to the program information determined prior to program startup\nfrom elsewhere in the hosted environment. If the host environment is not capable of\nsupplying strings with letters in both uppercase and lowercase, the implementation\nshall ensure that the strings are received in lowercase.</li>\n<li>If the value of <code>argc</code> is greater than zero, the string pointed to by <code>argv[0]</code>\nrepresents the program name; <code>argv[0][0]</code> shall be the null character if the\nprogram name is not available from the host environment. If the value of <code>argc</code> is\ngreater than one, the strings pointed to by <code>argv[1]</code> through <code>argv[argc-1]</code>\nrepresent the program parameters.</li>\n<li>The parameters <code>argc</code> and <code>argv</code> and the strings pointed to by the <code>argv</code> array shall\nbe modifiable by the program, and retain their last-stored values between program\nstartup and program termination.</li>\n</ul>\n<p><sup>10)</sup> Thus, <code>int</code> can be replaced by a typedef name defined as <code>int</code>, or the type of <code>argv</code> can be written as\n<code>char **argv</code>, and so on.</p>\n</blockquote>\n<h3>Program termination in C99 or C11</h3>\n<p>The value returned from <code>main()</code> is transmitted to the 'environment' in an implementation-defined way.</p>\n<blockquote>\n<h3>5.1.2.2.3 Program termination</h3>\n<p>1 If the return type of the <code>main</code> function is a type compatible with <code>int</code>, a return from the\ninitial call to the <code>main</code> function is equivalent to calling the <code>exit</code> function with the value\nreturned by the <code>main</code> function as its argument;<sup>11)</sup> reaching the <code>}</code> that terminates the\n<code>main</code> function returns a value of 0. If the return type is not compatible with <code>int</code>, the\ntermination status returned to the host environment is unspecified.</p>\n<p><sup>11)</sup> In accordance with 6.2.4, the lifetimes of objects with automatic storage duration declared in <code>main</code>\nwill have ended in the former case, even where they would not have in the latter.</p>\n</blockquote>\n<p>Note that <code>0</code> is mandated as 'success'. You can use <code>EXIT_FAILURE</code> and <code>EXIT_SUCCESS</code> from <code>&lt;stdlib.h&gt;</code> if you prefer, but 0 is well established, and so is 1. See also <a href=\"https://stackoverflow.com/questions/179565/exitcodes-bigger-than-255-possible/\">Exit codes greater than 255 — possible?</a>.</p>\n<p>In C89 (and hence in Microsoft C), there is no statement about what happens if the <code>main()</code> function returns but does not specify a return value; it therefore leads to undefined behaviour.</p>\n<blockquote>\n<h3>7.22.4.4 The <code>exit</code> function</h3>\n<p>¶5 Finally, control is returned to the host environment. If the value of <code>status</code> is zero or <code>EXIT_SUCCESS</code>, an implementation-defined form of the status <em>successful termination</em> is returned. If the value of <code>status</code> is <code>EXIT_FAILURE</code>, an implementation-defined form of the status <em>unsuccessful termination</em> is returned. Otherwise the status returned is implementation-defined.</p>\n</blockquote>\n<h2>Standard C++ — Hosted Environment</h2>\n<p>The C++11 standard (ISO/IEC 14882:2011) says:</p>\n<blockquote>\n<h3>3.6.1 Main function [basic.start.main]</h3>\n<p>¶1 A program shall contain a global function called main, which is the designated start of the program. [...]</p>\n<p>¶2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall\nhave a return type of type int, but otherwise its type is implementation defined.\nAll implementations\nshall allow both of the following definitions of main:</p>\n<pre><code>int main() { /* ... */ }\n</code></pre>\n<p>and</p>\n<pre><code>int main(int argc, char* argv[]) { /* ... */ }\n</code></pre>\n<p>In the latter form <code>argc</code> shall be the number of arguments passed to the program from the environment\nin which the program is run. If <code>argc</code> is nonzero these arguments shall be supplied in <code>argv[0]</code>\nthrough <code>argv[argc-1]</code> as pointers to the initial characters of null-terminated multibyte strings (NTMBSs) (17.5.2.1.4.2) and <code>argv[0]</code> shall be the pointer to the initial character of a NTMBS that represents the\nname used to invoke the program or <code>&quot;&quot;</code>. The value of <code>argc</code> shall be non-negative. The value of <code>argv[argc]</code>\nshall be 0. [Note: It is recommended that any further (optional) parameters be added after <code>argv</code>. —end\nnote]</p>\n<p>¶3 The function <code>main</code> shall not be used within a program. The linkage (3.5) of <code>main</code> is implementation-defined. [...]</p>\n<p>¶5 A return statement in main has the effect of leaving the main function (destroying any objects with automatic\nstorage duration) and calling <code>std::exit</code> with the return value as the argument. If control reaches the end\nof main without encountering a return statement, the effect is that of executing</p>\n<pre><code>return 0;\n</code></pre>\n</blockquote>\n<p>The C++ standard explicitly says &quot;It [the main function] shall have a return type of type <code>int</code>, but otherwise its type is implementation defined&quot;, and requires the same two signatures as the C standard to be supported as options. So a 'void main()' is directly not allowed by the C++ standard, though there's nothing it can do to stop a non-standard implementation allowing alternatives. Note that C++ forbids the user from calling <code>main</code> (but the C standard does not).</p>\n<p>There's a paragraph of §18.5 <strong>Start and termination</strong> in the C++11 standard that is identical to the paragraph from §7.22.4.4 <strong>The <code>exit</code> function</strong> in the C11 standard (quoted above), apart from a footnote (which simply documents that <code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code> are defined in <code>&lt;cstdlib&gt;</code>).</p>\n<h2>Standard C — Common Extension</h2>\n<p>Classically, Unix systems support a third variant:</p>\n<pre><code>int main(int argc, char **argv, char **envp) { ... }\n</code></pre>\n<p>The third argument is a null-terminated list of pointers to strings, each of which is an environment variable which has a name, an equals sign, and a value (possibly empty). If you do not use this, you can still get at the environment via '<code>extern char **environ;</code>'. This global variable is unique among those in POSIX in that it does not have a header that declares it.</p>\n<p>This is recognized by the C standard as a common extension, documented in Annex J:</p>\n<blockquote>\n<p>###J.5.1 Environment arguments</p>\n<p>¶1 In a hosted environment, the main function receives a third argument, <code>char *envp[]</code>,\nthat points to a null-terminated array of pointers to <code>char</code>, each of which points to a string\nthat provides information about the environment for this execution of the program (5.1.2.2.1).</p>\n</blockquote>\n<h2>Microsoft C</h2>\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/6wd819wh%28v=vs.100%29.aspx\" rel=\"nofollow noreferrer\">Microsoft VS 2010</a> compiler is interesting. The web site says:</p>\n<blockquote>\n<p>The declaration syntax for main is</p>\n<pre><code> int main();\n</code></pre>\n<p>or, optionally,</p>\n<pre><code>int main(int argc, char *argv[], char *envp[]);\n</code></pre>\n<p>Alternatively, the <code>main</code> and <code>wmain</code> functions can be declared as returning <code>void</code> (no return value). If you declare <code>main</code> or <code>wmain</code> as returning void, you cannot return an exit code to the parent process or operating system by using a return statement. To return an exit code when <code>main</code> or <code>wmain</code> is declared as <code>void</code>, you must use the <code>exit</code> function.</p>\n</blockquote>\n<p>It is not clear to me what happens (what exit code is returned to the parent or OS) when a program with <code>void main()</code> does exit — and the MS web site is silent too.</p>\n<p>Interestingly, MS does not prescribe the two-argument version of <code>main()</code> that the C and C++ standards require. It only prescribes a three argument form where the third argument is <code>char **envp</code>, a pointer to a list of environment variables.</p>\n<p>The Microsoft page also lists some other alternatives — <code>wmain()</code> which takes wide character strings, and some more.</p>\n<p>The Microsoft <a href=\"http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005\" rel=\"nofollow noreferrer\">Visual Studio 2005</a> version of <a href=\"http://msdn.microsoft.com/en-us/library/6wd819wh%28v=vs.80%29.aspx\" rel=\"nofollow noreferrer\">this page</a> does not list <code>void main()</code> as an alternative. The <a href=\"http://msdn.microsoft.com/en-us/library/6wd819wh%28v=vs.90%29.aspx\" rel=\"nofollow noreferrer\">versions</a> from Microsoft <a href=\"http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2008\" rel=\"nofollow noreferrer\">Visual Studio 2008</a> onwards do.</p>\n<h2>Standard C — Freestanding Environment</h2>\n<p>As noted early on, the requirements above apply to hosted environments. If you are working with a freestanding environment (which is the alternative to a hosted environment), then the standard has much less to say. For a freestanding environment, the function called at program startup need not be called <code>main</code> and there are no constraints on its return type. The standard says:</p>\n<blockquote>\n<h3>5.1.2 Execution environments</h3>\n<p>Two execution environments are defined: freestanding and hosted. In both cases,\nprogram startup occurs when a designated C function is called by the execution\nenvironment. All objects with static storage duration shall be initialized (set to their initial values) before program startup. The manner and timing of such initialization are otherwise unspecified. Program termination returns control to the execution environment.</p>\n<h3>5.1.2.1 Freestanding environment</h3>\n<p>In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined. Any library facilities available to a freestanding program, other than the minimal set required by clause 4, are implementation-defined.</p>\n<p>The effect of program termination in a freestanding environment is implementation-defined.</p>\n</blockquote>\n<p>The cross-reference to clause 4 Conformance refers to this:</p>\n<blockquote>\n<p>¶5 A <em>strictly conforming program</em> shall use only those features of the language and library specified in this International Standard.<sup>3)</sup> It shall not produce output dependent on any unspecified, undefined, or implementation-defined behavior, and shall not exceed any minimum implementation limit.</p>\n<p>¶6 The two forms of conforming implementation are <em>hosted</em> and <em>freestanding</em>. A <em>conforming hosted implementation</em> shall accept any strictly conforming program. A <em>conforming freestanding implementation</em> shall accept any strictly conforming program in which the use of the features specified in the library clause (clause 7) is confined to the contents of the standard headers <code>&lt;float.h&gt;</code>, <code>&lt;iso646.h&gt;</code>, <code>&lt;limits.h&gt;</code>, <code>&lt;stdalign.h&gt;</code>,\n<code>&lt;stdarg.h&gt;</code>, <code>&lt;stdbool.h&gt;</code>, <code>&lt;stddef.h&gt;</code>, <code>&lt;stdint.h&gt;</code>, and\n<code>&lt;stdnoreturn.h&gt;</code>. A conforming implementation may have extensions (including\nadditional library functions), provided they do not alter the behavior of any strictly conforming program.<sup>4)</sup></p>\n<p>¶7 A <em>conforming program</em> is one that is acceptable to a conforming implementation.<sup>5)</sup></p>\n<p><sup>3)</sup> A strictly conforming program can use conditional features (see 6.10.8.3) provided the use is guarded by an appropriate conditional inclusion preprocessing directive using the related macro. For example:</p>\n<pre><code>#ifdef __STDC_IEC_559__ /* FE_UPWARD defined */\n /* ... */\n fesetround(FE_UPWARD);\n /* ... */\n#endif\n</code></pre>\n<p><sup>4)</sup> This implies that a conforming implementation reserves no identifiers other than those explicitly reserved in this International Standard.</p>\n<p><sup>5)</sup> Strictly conforming programs are intended to be maximally portable among conforming implementations. Conforming programs may depend upon non-portable features of a conforming implementation.</p>\n</blockquote>\n<p>It is noticeable that the only header required of a freestanding environment that actually defines any functions is <code>&lt;stdarg.h&gt;</code> (and even those may be — and often are — just macros).</p>\n<h2>Standard C++ — Freestanding Environment</h2>\n<p>Just as the C standard recognizes both hosted and freestanding environment, so too does the C++ standard. (Quotes from ISO/IEC 14882:2011.)</p>\n<blockquote>\n<h3>1.4 Implementation compliance [intro.compliance]</h3>\n<p>¶7 Two kinds of implementations are defined: a <em>hosted implementation</em> and a <em>freestanding implementation</em>. For a hosted implementation, this International Standard defines the set of available libraries. A freestanding\nimplementation is one in which execution may take place without the benefit of an operating system, and has an implementation-defined set of libraries that includes certain language-support libraries (17.6.1.3).</p>\n<p>¶8 A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any well-formed program. Implementations are required to diagnose programs that\nuse such extensions that are ill-formed according to this International Standard. Having done so, however, they can compile and execute such programs.</p>\n<p>¶9 Each implementation shall include documentation that identifies all conditionally-supported constructs that it does not support and defines all locale-specific characteristics.<sup>3</sup></p>\n<p><sup>3)</sup> This documentation also defines implementation-defined behavior; see 1.9.</p>\n<h3>17.6.1.3 Freestanding implementations [compliance]</h3>\n<p>Two kinds of implementations are defined: hosted and freestanding (1.4). For a hosted implementation, this International Standard describes the set of available headers.</p>\n<p>A freestanding implementation has an implementation-defined set of headers. This set shall include at least the headers shown in Table 16.</p>\n<p>The supplied version of the header <code>&lt;cstdlib&gt;</code> shall declare at least the functions <code>abort</code>, <code>atexit</code>, <code>at_quick_exit</code>, <code>exit</code>, and <code>quick_exit</code> (18.5). The other headers listed in this table shall meet the same requirements as for a hosted implementation.</p>\n<p>Table 16 — C++ headers for freestanding implementations</p>\n<pre><code>Subclause Header(s)\n</code></pre>\n</blockquote>\n<pre><code> &lt;ciso646&gt;\n18.2 Types &lt;cstddef&gt;\n18.3 Implementation properties &lt;cfloat&gt; &lt;limits&gt; &lt;climits&gt;\n18.4 Integer types &lt;cstdint&gt;\n18.5 Start and termination &lt;cstdlib&gt;\n18.6 Dynamic memory management &lt;new&gt;\n18.7 Type identification &lt;typeinfo&gt;\n18.8 Exception handling &lt;exception&gt;\n18.9 Initializer lists &lt;initializer_list&gt;\n18.10 Other runtime support &lt;cstdalign&gt; &lt;cstdarg&gt; &lt;cstdbool&gt;\n20.9 Type traits &lt;type_traits&gt;\n29 Atomics &lt;atomic&gt;\n</code></pre>\n<h2>What about using <code>int main()</code> in C?</h2>\n<p>The standard §5.1.2.2.1 of the C11 standard shows the preferred notation — <code>int main(void)</code> — but there are also two examples in the standard which show <code>int main()</code>: <a href=\"https://port70.net/%7Ensz/c/c11/n1570.html#6.5.3.4p8\" rel=\"nofollow noreferrer\">§6.5.3.4 ¶8</a> and <a href=\"https://port70.net/%7Ensz/c/c11/n1570.html#6.7.6.3p20\" rel=\"nofollow noreferrer\">§6.7.6.3 ¶20</a>. Now, it is important to note that examples are not 'normative'; they are only illustrative. If there are bugs in the examples, they do not directly affect the main text of the standard. That said, they are strongly indicative of expected behaviour, so if the standard includes <code>int main()</code> in an example, it suggests that <code>int main()</code> is not forbidden, even if it is not the preferred notation.</p>\n<blockquote>\n<h3>6.5.3.4 The <code>sizeof</code> and <code>_Alignof</code> operators</h3>\n<p>…</p>\n<p>¶8 EXAMPLE 3 In this example, the size of a variable length array is computed and returned from a function:</p>\n<pre><code>#include &lt;stddef.h&gt;\n\nsize_t fsize3(int n)\n{\n char b[n+3]; // variable length array\n return sizeof b; // execution time sizeof\n}\nint main()\n{\n size_t size;\n size = fsize3(10); // fsize3 returns 13\n return 0;\n}\n</code></pre>\n</blockquote>\n<p>A function definition like <code>int main(){ … }</code> does specify that the function takes no arguments, but does not provide a function prototype, AFAICT. For <code>main()</code> that is seldom a problem; but it does mean that if you have recursive calls to <code>main()</code>, the arguments won't be checked. For other functions, it is more of a problem — you really need a prototype in scope when the function is called to ensure that the arguments are correct.</p>\n<p>You don't normally call <code>main()</code> recursively, outside of places like IOCCC — and you are explicitly forbidden from doing so in C++. I do have a test program that does it — mainly for novelty. If you have:</p>\n<pre><code>int i = 0;\nint main()\n{\n if (i++ &lt; 10)\n main(i, i * i);\n return 0;\n}\n</code></pre>\n<p>and compile with GCC and don't include <code>-Wstrict-prototypes</code>, it compiles cleanly under stringent warnings. If it's <code>main(void)</code>, it fails to compile because the function definition says &quot;no arguments&quot;.</p>\n" }, { "answer_id": 28443025, "author": "rbaleksandar", "author_id": 1559401, "author_profile": "https://Stackoverflow.com/users/1559401", "pm_score": 2, "selected": false, "text": "<p>Here is a small demonstration of the usage of return codes...</p>\n<p>When using the various tools that the Linux terminal provides one can use the return code for example for error handling after the process has been completed. Imagine that the following text file myfile is present:</p>\n<blockquote>\n<p>This is some example in order to check how grep works.</p>\n</blockquote>\n<p>When you execute the grep command a process is created. Once it is through (and didn't break) it returns some code between 0 and 255. For example:</p>\n<pre><code>$ grep order myfile\n</code></pre>\n<p>If you do</p>\n<pre><code>$ echo $?\n$ 0\n</code></pre>\n<p>you will get a 0. Why? Because <a href=\"http://en.wikipedia.org/wiki/Grep\" rel=\"nofollow noreferrer\">grep</a> found a match and returned an exit code 0, which is the usual value for exiting with a success. Why that is probably lies in the boolean nature of a simple check whether everything is ok or not. A simple negation of a 0 (boolean false) returns 1 (boolean true), which can easily be handled in a if-else statements.</p>\n<p>Let's check it out again but with something that is not inside our text file and thus no match will be found:</p>\n<pre><code>$ grep foo myfile\n$ echo $?\n$ 1\n</code></pre>\n<p>Since grep failed to match the token &quot;foo&quot; with the content of our file the return code is 1 (this is the usual case when a failure occurs but as stated above you have plenty of values to choose from). Again if we put this in the simple boolean context (everything is ok or not) negating the 1 (boolean true) yields a 0 (boolean false), which again can easily be handled by an if-else statement. When it comes to boolean values anything that is not a 0 is considered to be equivalent to 1 (so 2, 3, 4 etc. in a simple if-else statement for checking whether an error has occurred or not will work the same way as if a 1 was used). You can use different return values to increase the granularity of your error state. It is considered a bad practice to use anything but a 0 for the state of successful execution (due to the reasons given above).</p>\n<p>The following bash script (simply type it in a Linux terminal) although very basic should give some idea of error handling:</p>\n<pre><code>$ grep foo myfile\n$ CHECK=$?\n$ [ $CHECK -eq 0] &amp;&amp; echo 'Match found'; [ $CHECK -ne 0] &amp;&amp; echo 'No match was found'\n$ No match was found\n</code></pre>\n<p>After the second line nothing is printed to the terminal since &quot;foo&quot; made grep return 1 and we check if the return code of grep was equal to 0. The second conditional statement echoes its message in the last line since it is true due to CHECK == 1.</p>\n<p>As you can see if you are calling this and that process it is sometimes essential to see what it has returned (by the return value of main()), e.g. when running tests.</p>\n" }, { "answer_id": 31263079, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 6, "selected": false, "text": "<p>Note that the C and C++ standards define two kinds of implementations: freestanding and hosted.</p>\n<ul>\n<li><strong>C90 hosted environment</strong></li>\n</ul>\n<p>Allowed forms <sup>1</sup>:</p>\n<pre><code>int main (void)\nint main (int argc, char *argv[])\n\nmain (void)\nmain (int argc, char *argv[])\n/*... etc, similar forms with implicit int */\n</code></pre>\n<p>Comments:</p>\n<p>The former two are explicitly stated as the allowed forms, the others are implicitly allowed because C90 allowed &quot;implicit int&quot; for return type and function parameters. No other form is allowed.</p>\n<ul>\n<li><strong>C90 freestanding environment</strong></li>\n</ul>\n<p>Any form or name of main is allowed <sup>2</sup>.</p>\n<ul>\n<li><strong>C99 hosted environment</strong></li>\n</ul>\n<p>Allowed forms <sup>3</sup>:</p>\n<pre><code>int main (void)\nint main (int argc, char *argv[])\n/* or in some other implementation-defined manner. */\n</code></pre>\n<p>Comments:</p>\n<p>C99 removed &quot;implicit int&quot; so <code>main()</code> is no longer valid.</p>\n<p>A strange, ambiguous sentence &quot;or in some other implementation-defined manner&quot; has been introduced. This can either be interpreted as &quot;the parameters to <code>int main()</code> may vary&quot; or as &quot;main can have any implementation-defined form&quot;.</p>\n<p>Some compilers have chosen to interpret the standard in the latter way. Arguably, one cannot easily state that they are not conforming by citing the standard in itself, since it is is ambiguous.</p>\n<p>However, to allow completely wild forms of <code>main()</code> was probably(?) not the intention of this new sentence. The C99 rationale (not normative) implies that the sentence refers to additional parameters to <code>int main</code> <sup>4</sup>.</p>\n<p>Yet the section for hosted environment program termination then goes on arguing about the case where main does not return int <sup>5</sup>. Although that section is not normative for how main should be declared, it definitely implies that main might be declared in a completely implementation-defined way even on hosted systems.</p>\n<ul>\n<li><strong>C99 freestanding environment</strong></li>\n</ul>\n<p>Any form or name of main is allowed <sup>6</sup>.</p>\n<ul>\n<li><strong>C11 hosted environment</strong></li>\n</ul>\n<p>Allowed forms <sup>7</sup>:</p>\n<pre><code>int main (void)\nint main (int argc, char *argv[])\n/* or in some other implementation-defined manner. */\n</code></pre>\n<ul>\n<li><strong>C11 freestanding environment</strong></li>\n</ul>\n<p>Any form or name of main is allowed <sup>8</sup>.</p>\n<hr />\n<p>Note that <code>int main()</code> was never listed as a valid form for any hosted implementation of C in any of the above versions. In C, unlike C++, <code>()</code> and <code>(void)</code> have different meanings. The former is an obsolescent feature which may be removed from the language. See C11 future language directions:</p>\n<blockquote>\n<p>6.11.6 Function declarators</p>\n<p>The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.</p>\n</blockquote>\n<hr />\n<ul>\n<li><strong>C++03 hosted environment</strong></li>\n</ul>\n<p>Allowed forms <sup>9</sup>:</p>\n<pre><code>int main ()\nint main (int argc, char *argv[])\n</code></pre>\n<p>Comments:</p>\n<p>Note the empty parenthesis in the first form. C++ and C are different in this case, because in C++ this means that the function takes no parameters. But in C it means that it may take any parameter.</p>\n<ul>\n<li><strong>C++03 freestanding environment</strong></li>\n</ul>\n<p>The name of the function called at startup is implementation-defined. If it is named <code>main()</code> it must follow the stated forms <sup>10</sup>:</p>\n<pre><code>// implementation-defined name, or \nint main ()\nint main (int argc, char *argv[])\n</code></pre>\n<ul>\n<li><strong>C++11 hosted environment</strong></li>\n</ul>\n<p>Allowed forms <sup>11</sup>:</p>\n<pre><code>int main ()\nint main (int argc, char *argv[])\n</code></pre>\n<p>Comments:</p>\n<p>The text of the standard has been changed but it has the same meaning.</p>\n<ul>\n<li><strong>C++11 freestanding environment</strong></li>\n</ul>\n<p>The name of the function called at startup is implementation-defined. If it is named <code>main()</code> it must follow the stated forms <sup>12</sup>:</p>\n<pre><code>// implementation-defined name, or \nint main ()\nint main (int argc, char *argv[])\n</code></pre>\n<hr />\n<p><strong>References</strong></p>\n<ol>\n<li>ANSI X3.159-1989 2.1.2.2 Hosted environment. &quot;Program startup&quot;</li>\n</ol>\n<blockquote>\n<p>The function called at program startup is named main. The\nimplementation declares no prototype for this function. It shall be\ndefined with a return type of int and with no parameters:</p>\n</blockquote>\n<pre><code>int main(void) { /* ... */ } \n</code></pre>\n<blockquote>\n<p>or with two parameters (referred to here as\nargc and argv, though any names may be used, as they are local to the\nfunction in which they are declared):</p>\n</blockquote>\n<pre><code>int main(int argc, char *argv[]) { /* ... */ }\n</code></pre>\n<ol start=\"2\">\n<li>ANSI X3.159-1989 2.1.2.1 Freestanding environment:</li>\n</ol>\n<blockquote>\n<p>In a freestanding environment (in which C program execution may take\nplace without any benefit of an operating system), the name and type\nof the function called at program startup are implementation-defined.</p>\n</blockquote>\n<ol start=\"3\">\n<li>ISO 9899:1999 5.1.2.2 Hosted environment -&gt; 5.1.2.2.1 Program startup</li>\n</ol>\n<blockquote>\n<p>The function called at program startup is named main. The\nimplementation declares no prototype for this function. It shall be\ndefined with a return type of int and with no parameters:</p>\n</blockquote>\n<pre><code>int main(void) { /* ... */ } \n</code></pre>\n<blockquote>\n<p>or with two parameters (referred to here as\nargc and argv, though any names may be used, as they are local to the\nfunction in which they are declared):</p>\n</blockquote>\n<pre><code>int main(int argc, char *argv[]) { /* ... */ }\n</code></pre>\n<blockquote>\n<p>or equivalent;9) or in some other implementation-defined\nmanner.</p>\n</blockquote>\n<ol start=\"4\">\n<li>Rationale for International Standard — Programming Languages — C, Revision 5.10. 5.1.2.2 Hosted environment --&gt; 5.1.2.2.1 Program startup</li>\n</ol>\n<blockquote>\n<p>The behavior of the arguments to main, and of the interaction of exit, main and atexit\n(see §7.20.4.2) has been codified to curb some unwanted variety in the representation of argv\nstrings, and in the meaning of values returned by main.</p>\n</blockquote>\n<blockquote>\n<p>The specification of argc and argv as arguments to main recognizes extensive prior practice.\nargv[argc] is required to be a null pointer to provide a redundant check for the end of the list, also on the basis of common practice.</p>\n</blockquote>\n<blockquote>\n<p>main is the only function that may portably be declared either with zero or two arguments. (The number of other functions’ arguments must match exactly between invocation and definition.)\nThis special case simply recognizes the widespread practice of leaving off the arguments to main when the program does not access the program argument strings. While many implementations support more than two arguments to main, such practice is neither blessed nor forbidden by the Standard; a program that defines main with three arguments is not strictly conforming (see §J.5.1.).</p>\n</blockquote>\n<ol start=\"5\">\n<li>ISO 9899:1999 5.1.2.2 Hosted environment --&gt; 5.1.2.2.3 Program termination</li>\n</ol>\n<blockquote>\n<p>If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument;11) reaching the <code>}</code> that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified.</p>\n</blockquote>\n<ol start=\"6\">\n<li>ISO 9899:1999 5.1.2.1 Freestanding environment</li>\n</ol>\n<blockquote>\n<p>In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined.</p>\n</blockquote>\n<ol start=\"7\">\n<li>ISO 9899:2011 5.1.2.2 Hosted environment -&gt; 5.1.2.2.1 Program startup</li>\n</ol>\n<p>This section is identical to the C99 one cited above.</p>\n<ol start=\"8\">\n<li>ISO 9899:1999 5.1.2.1 Freestanding environment</li>\n</ol>\n<p>This section is identical to the C99 one cited above.</p>\n<ol start=\"9\">\n<li>ISO 14882:2003 3.6.1 Main function</li>\n</ol>\n<blockquote>\n<p>An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:</p>\n</blockquote>\n<pre><code>int main() { /* ... */ }\n</code></pre>\n<blockquote>\n<p>and</p>\n</blockquote>\n<pre><code>int main(int argc, char* argv[]) { /* ... */ }\n</code></pre>\n<ol start=\"10\">\n<li>ISO 14882:2003 3.6.1 Main function</li>\n</ol>\n<blockquote>\n<p>It is implementation-defined whether a program in a freestanding environment is required to define a main function.</p>\n</blockquote>\n<ol start=\"11\">\n<li>ISO 14882:2011 3.6.1 Main function</li>\n</ol>\n<blockquote>\n<p>An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall\nallow both</p>\n<p>— a function of () returning int and</p>\n<p>— a function of (int, pointer to pointer to char) returning int</p>\n<p>as the type of main (8.3.5).</p>\n</blockquote>\n<ol start=\"12\">\n<li>ISO 14882:2011 3.6.1 Main function</li>\n</ol>\n<p>This section is identical to the C++03 one cited above.</p>\n" }, { "answer_id": 43558724, "author": "Edward", "author_id": 3191481, "author_profile": "https://Stackoverflow.com/users/3191481", "pm_score": 2, "selected": false, "text": "<h2>Omit <code>return 0</code></h2>\n\n<p>When a C or C++ program reaches the end of <code>main</code> the compiler will automatically generate code to return 0, so there is no need to put <code>return 0;</code> explicitly at the end of <code>main</code>. </p>\n\n<p><strong>Note:</strong> when I make this suggestion, it's almost invariably followed by one of two kinds of comments: \"I didn't know that.\" or \"That's bad advice!\" My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard. For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:</p>\n\n<blockquote>\n <p>[...] a return from the initial call to the <code>main</code> function is equivalent to calling the <code>exit</code> function with the value returned by the <code>main</code> function as its argument; reaching the <code>}</code> that terminates the <code>main</code> function returns a value of 0.</p>\n</blockquote>\n\n<p>For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:</p>\n\n<blockquote>\n <p>If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;</p>\n</blockquote>\n\n<p>All versions of both standards since then (C99 and C++98) have maintained the same idea. We rely on automatically generated member functions in C++, and few people write explicit <code>return;</code> statements at the end of a <code>void</code> function. Reasons against omitting seem to boil down to <a href=\"https://stackoverflow.com/questions/2581993/what-the-reasons-for-against-returning-0-from-main-in-iso-c/2582015#2582015\">\"it looks weird\"</a>. If, like me, you're curious about the rationale for the change to the C standard <a href=\"https://stackoverflow.com/questions/31394171/what-was-the-rationale-for-making-return-0-at-the-end-of-main-optional\">read this question</a>. Also note that in the early 1990s this was considered \"sloppy practice\" because it was undefined behavior (although widely supported) at the time. </p>\n\n<p>Additionally, the <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md\" rel=\"nofollow noreferrer\">C++ Core Guidelines</a> contains multiple instances of omitting <code>return 0;</code> at the end of <code>main</code> and no instances in which an explicit return is written. Although there is not yet a specific guideline on this particular topic in that document, that seems at least a tacit endorsement of the practice.</p>\n\n<p>So I advocate omitting it; others disagree (often vehemently!) In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.</p>\n" }, { "answer_id": 46554052, "author": "Steve Summit", "author_id": 3923896, "author_profile": "https://Stackoverflow.com/users/3923896", "pm_score": 2, "selected": false, "text": "<blockquote>\n<p>What is the correct (most efficient) way to define the main() function in C and C++ — int main() or void main() — and why?</p>\n</blockquote>\n<p>Those words &quot;(most efficient)&quot; don't change the question. Unless you're in a freestanding environment, there is one universally correct way to declare <code>main()</code>, and that's as returning <code>int</code>.</p>\n<blockquote>\n<p>What should <code>main()</code> return in C and C++?</p>\n</blockquote>\n<p>An <code>int</code>, pure and simple. And it's more than &quot;what should <code>main()</code> return&quot;, it's &quot;what <em>must</em> <code>main()</code> return&quot;. <code>main()</code> is, of course, a function that someone else calls. You don't have any control over the code that calls <code>main</code>. Therefore, you must declare <code>main</code> with a type-correct signature to match its caller. You simply don't have any choice in the matter. You don't have to ask yourself what's more or less efficient, or what's better or worse style, or anything like that, because the answer is already perfectly well defined, for you, by the C and C+ standards. Just follow them.</p>\n<blockquote>\n<p>If int main() then return 1 or return 0?</p>\n</blockquote>\n<p>0 for success, nonzero for failure. Again, not something you need to (or get to) pick: it's defined by the interface you're supposed to be conforming to.</p>\n" }, { "answer_id": 64295173, "author": "gsamaras", "author_id": 2411320, "author_profile": "https://Stackoverflow.com/users/2411320", "pm_score": 0, "selected": false, "text": "<p>In C, the <a href=\"http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf\" rel=\"nofollow noreferrer\">Section 5.1.2.2.1 of the C11 standard</a> (emphasis mine):</p>\n<blockquote>\n<p>It shall be defined with a <strong>return type of <code>int</code></strong> and with no\nparameters:</p>\n<pre><code>int main(void) { /* ... */ }\n</code></pre>\n<p>or with two parameters (referred to here as <code>argc</code> and <code>argv</code>, though\nany names may be used, as they are local to the function in which they\nare declared):</p>\n<pre><code>int main(int argc, char *argv[]) { /* ... */ }\n</code></pre>\n</blockquote>\n<p>However for some beginners like me, an abstract example would allow me to get a grasp on it:</p>\n<p>When you write a method in your program, e.g. <code>int read_file(char filename[LEN]);</code>, then you want, as the caller of this method to know if everything went well (because failures can happen, e.g. file could not be found). By checking the return value of the method you can know if everything went well or not, it's a mechanism for the method to signal you about its successful execution (or not), and let the caller (you, e.g. in your main method) decide how to handle an unexpected failure.</p>\n<p>So now imagine I write a C program for a micro-mechanism which is used in a more complex system. When the system calls the micro-mechanism, it wants to know if everything went as expected, so that it can handle any potential error. If the C program's main method would return void, then how would the calling-system know about the execution of its subsystem (the micro-mechanism)? It cannot, that's why main() returns int, in order to communicate to its caller a successful (or not) execution.</p>\n<p>In other words:</p>\n<p>The rational is that the host environment (i.e. Operating System (OS)) needs to know if the program finished correctly. Without an int-compatible type as a return type (eg. void), the &quot;status returned to the host environment is unspecified&quot; (i.e. undefined behavior on most OS).</p>\n" }, { "answer_id": 68975989, "author": "Dwedit", "author_id": 2300396, "author_profile": "https://Stackoverflow.com/users/2300396", "pm_score": -1, "selected": false, "text": "<p>On Windows, if a program crashes due to an access violation, the exit code will be <code>STATUS_ACCESS_VIOLATION (0xC0000005)</code>. Similar for other kinds of crashes from an x86 exception as well.</p>\n<p>So there are things other than what you return from <code>main</code> or pass to <code>exit</code> that can cause an exit code to be seen.</p>\n" }, { "answer_id": 73409204, "author": "NinjaDarth", "author_id": 4289763, "author_profile": "https://Stackoverflow.com/users/4289763", "pm_score": 1, "selected": false, "text": "<p>&quot;int&quot; is now mandated by the ISO for both C and C++ as the return type for &quot;main&quot;.</p>\n<p>Both languages previously allowed implicit &quot;int&quot;, and for &quot;main&quot; to be declared without any return type. In fact, the very first external release of C++, itself (Release E of &quot;cfront&quot; from February 1985), which is written in its own language, declared &quot;main&quot; without any return type ... but returned an integer value: the number of errors or 127, whichever was smaller</p>\n<p>As to the question of <em>what</em> to return: the ISO standards for C and C++ work in synchronization with the POSIX standard. For any hosted environment conforming to the POSIX standard,<br/>\n(1) 126 is reserved for the OS's shell to indicate utilities that are not executable,<br/>\n(2) 127 is reserved for the OS's shell to indicate that a command that is not found,<br/>\n(3) the exit values for utilities are separately spelled out on a utility-by-utility basis,<br/>\n(4) programs that invoke utilities outside the shell should use similar values for their own exits,<br/>\n(5) the values 128 and above are meant for use to indicate termination that results from receiving a signal,<br/>\n(6) the values 1-125 are for failures,<br/>\n(7) the value 0 is for success.</p>\n<p>In C and C++ the value EXIT_SUCCESS and EXIT_FAILURE are meant for use to handle the most common situation: for programs that report a success or just a generic failure. They may, but need not, be respectively equal to 0 and 1.</p>\n<p>That means if you want a program to return different values for different failure modes or status indications, while continuing to make use of those two constants, you might have to resort to first making sure that your additional &quot;failure&quot; or &quot;status&quot; values lie strictly between max(EXIT_SUCCESS, EXIT_FAILURE) and 126 (and hope that there's enough room in-between), and to reserve EXIT_FAILURE to mark the generic or default failure mode.</p>\n<p>Otherwise, if you're not going to use the constants, then you should go by what POSIX mandates.</p>\n<p>For programs meant for use on free-standing environments or on hosts that are not POSIX-compliant, I can say nothing more, except the following:</p>\n<p>I have written free-standing programs -- as multi-threaded programs on a custom run-time system (and a custom tool-base for everything else). The general rule I followed was that:<br/>\n(1) &quot;main&quot; ran the foreground processes, which usually consisted only of start-up, configuration or initialization routines, but could have just as well included foreground processes meant for continual operation (like polling loops),<br/>\n(2) &quot;main&quot; returns into an infinite sleep &amp; wait loop,<br/>\n(3) no return value for &quot;main&quot; was defined or used,<br/>\n(4) background processes ran separately, as interrupt-driven &amp; event-driven threads, independently of &quot;main&quot;, terminated only by the receipt of a reset signal or by other threads ... or by simply shutting off the monitoring of whatever event was driving the thread.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25632/" ]
What is the correct (most efficient) way to define the `main()` function in C and C++ — `int main()` or `void main()` — and why? And how about the arguments? If `int main()` then `return 1` or `return 0`? --- *There are numerous duplicates of this question, including:* * [What are the valid signatures for C's `main()` function?](https://stackoverflow.com/questions/2108192/what-are-the-valid-signatures-for-cs-main-function/) * [The return type of `main()` function](https://stackoverflow.com/questions/17715008/the-return-type-of-main-function/) * [Difference between `void main()` and `int main()`?](https://stackoverflow.com/questions/636829/difference-between-void-main-and-int-main) * [`main()`'s signature in C++](https://stackoverflow.com/questions/1621574/mains-signature-in-c) * [What is the proper declaration of `main()`?](https://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main) — For C++, with a very good answer indeed. * [Styles of `main()` functions in C](https://stackoverflow.com/questions/8692120/styles-of-main-functions-in-c) * [Return type of `main()` method in C](https://stackoverflow.com/questions/10915713/return-type-of-main-method-in-c) * [`int main()` vs `void main()` in C](https://stackoverflow.com/questions/9356510/int-main-vs-void-main-in-c) Related: * [C++ — `int main(int argc, char **argv)`](https://stackoverflow.com/questions/5191965/c-int-mainint-argc-char-argv) * [C++ — `int main(int argc, char *argv[])`](https://stackoverflow.com/questions/5217395/c-int-mainint-argc-char-argv) * [Is `char *envp[]` as a third argument to `main()` portable?](https://stackoverflow.com/questions/10321435/is-char-envp-as-a-third-argument-to-main-portable) * [Must the `int main()` function return a value in all compilers?](https://stackoverflow.com/questions/18402853/must-the-int-main-function-return-a-value-in-all-compilers) * [Why is the type of the `main()` function in C and C++ left to the user to define?](https://stackoverflow.com/questions/5296163/why-is-the-type-of-the-main-function-in-c-and-c-left-to-the-user-to-define) * [Why does `int main(){}` compile?](https://stackoverflow.com/questions/22239/why-does-int-main-compile) * [Legal definitions of `main()` in C++14?](https://stackoverflow.com/questions/26470912/legal-definitions-of-main-in-c14)
The return value for `main` indicates how the program exited. Normal exit is represented by a 0 return value from `main`. Abnormal exit is signaled by a non-zero return, but there is no standard for how non-zero codes are interpreted. As noted by others, `void main()` is prohibited by the C++ standard and should not be used. The valid C++ `main` signatures are: ``` int main() ``` and ``` int main(int argc, char* argv[]) ``` which is equivalent to ``` int main(int argc, char** argv) ``` It is also worth noting that in C++, `int main()` can be left without a return-statement, at which point it defaults to returning 0. This is also true with a C99 program. Whether `return 0;` should be omitted or not is open to debate. The range of valid C program main signatures is much greater. Efficiency is not an issue with the `main` function. It can only be entered and left once (marking the program's start and termination) according to the C++ standard. For C, re-entering `main()` is allowed, but should be avoided.
204,488
<p>I am trying to create a new contact using Dynamic Entity. The sample i found in CRM SDK had this code.</p> <pre><code>// Set the properties of the contact using property objects. StringProperty firstname = new StringProperty(); firstname.Name = "firstname"; firstname.Value = "Jesper"; StringProperty lastname = new StringProperty(); lastname.Name = "lastname"; lastname.Value = "Aaberg"; // Create the DynamicEntity object. DynamicEntity contactEntity = new DynamicEntity(); // Set the name of the entity type. contactEntity.Name = EntityName.contact.ToString(); // Set the properties of the contact. contactEntity.Properties = new Property[] {firstname, lastname}; </code></pre> <p>In my code i have the following implementation.</p> <pre><code> StringProperty sp_Field1 = new StringProperty("Field1","Value1"); StringProperty sp_Field2 = new StringProperty("Field2","Value1"); CrmService service = new CrmService(); service.Credentials = System.Net.CredentialCache.DefaultCredentials; // Create the DynamicEntity object. DynamicEntity contactEntity = new DynamicEntity(); // Set the name of the entity type. contactEntity.Name = EntityName.contact.ToString(); // Set the properties of the contact. contactEntity.Properties = new Property[] {sp_Field1,sp_Field2}; </code></pre> <p>I don't see much differences in the code. In the examples i found in the internet i have the same implementation as i found in SDK. But if i run the same i get the following error</p> <blockquote> <p>CS0029: Cannot implicitly convert type 'Microsoft.Crm.Sdk.StringProperty' to 'Microsoft.Crm.Sdk.PropertyCollection'</p> </blockquote> <p>I tried created a new variable of type PropertyCollection(one that belongs in mscrm namespace) and added the stringpropertys into that and passed it to the entity. </p> <pre><code>Microsoft.Crm.Sdk.PropertyCollection propTest = new Microsoft.Crm.Sdk.PropertyCollection(); propTest.Add(sp_SSNNo); propTest.Add(sp_FirstName); contactEntity.Properties = new Property[] {propTest}; </code></pre> <p>This gave me the following error</p> <blockquote> <p>CS0029: Cannot implicitly convert type 'Microsoft.Crm.Sdk.PropertyCollection' to 'Microsoft.Crm.Sdk.Property'</p> </blockquote> <p>I am sure its a minor typecasting error but i am not able to figure out where the error is. And moreover, even if it was a typecasting error why is it working for all the samples given in the internet and not for me. I tried getting the code sample to run but i am encountering the same conversion error. Please let me know if you need more info on this, any help on this would be appreciated.</p>
[ { "answer_id": 204849, "author": "SaaS Developer", "author_id": 7215, "author_profile": "https://Stackoverflow.com/users/7215", "pm_score": 0, "selected": false, "text": "<p>I believe the issue is that you are referencing the dynamic entity class in the Microsoft.Crm.Sdk assembly. The sample in the SDK is using a reference to the CRM web service. This can get confusing as both assemblies contain many of the same types, however they are different.</p>\n" }, { "answer_id": 204985, "author": "SaaS Developer", "author_id": 7215, "author_profile": "https://Stackoverflow.com/users/7215", "pm_score": 3, "selected": true, "text": "<p>Here is an article from Microsoft that makes an attempt to discuss this topic:</p>\n\n<p><a href=\"http://community.dynamics.com/blogs/cscrmblog/archive/2008/06/23/web-services-amp-dlls-or-what-s-up-with-all-the-duplicate-classes.aspx\" rel=\"nofollow noreferrer\">http://community.dynamics.com/blogs/cscrmblog/archive/2008/06/23/web-services-amp-dlls-or-what-s-up-with-all-the-duplicate-classes.aspx</a></p>\n\n<p>This is not a bug that you are running into but more of a difference in design between the way the two assemblies work and what they are designed to do.</p>\n\n<p>If you want to continue to use the Microsoft.Crm.Sdk.dll you should be able to accomplish your goal with the following...</p>\n\n<pre><code> StringProperty sp_Field1 = new StringProperty(\"Field1\",\"Value1\");\n StringProperty sp_Field2 = new StringProperty(\"Field2\",\"Value1\");\n\n CrmService service = new CrmService();\n service.Credentials = System.Net.CredentialCache.DefaultCredentials;\n // Create the DynamicEntity object.\n DynamicEntity contactEntity = new DynamicEntity();\n // Set the name of the entity type.\n contactEntity.Name = EntityName.contact.ToString();\n\n // Set the properties of the contact.\n PropertyCollection properties = new PropertyCollection();\n properties.Add(sp_Field1);\n contactEntity.Properties = properties;\n</code></pre>\n" }, { "answer_id": 205046, "author": "vikramjb", "author_id": 2245, "author_profile": "https://Stackoverflow.com/users/2245", "pm_score": 1, "selected": false, "text": "<p>Thanks SaaS Developer, that code is working fine now. One more way of doing it would be to directly add the StringProperty to the entity property collection.</p>\n\n<pre><code>contactEntity.Properties.Add(sp_SSNNo);\n</code></pre>\n\n<p>Thanks again for replying :)</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2245/" ]
I am trying to create a new contact using Dynamic Entity. The sample i found in CRM SDK had this code. ``` // Set the properties of the contact using property objects. StringProperty firstname = new StringProperty(); firstname.Name = "firstname"; firstname.Value = "Jesper"; StringProperty lastname = new StringProperty(); lastname.Name = "lastname"; lastname.Value = "Aaberg"; // Create the DynamicEntity object. DynamicEntity contactEntity = new DynamicEntity(); // Set the name of the entity type. contactEntity.Name = EntityName.contact.ToString(); // Set the properties of the contact. contactEntity.Properties = new Property[] {firstname, lastname}; ``` In my code i have the following implementation. ``` StringProperty sp_Field1 = new StringProperty("Field1","Value1"); StringProperty sp_Field2 = new StringProperty("Field2","Value1"); CrmService service = new CrmService(); service.Credentials = System.Net.CredentialCache.DefaultCredentials; // Create the DynamicEntity object. DynamicEntity contactEntity = new DynamicEntity(); // Set the name of the entity type. contactEntity.Name = EntityName.contact.ToString(); // Set the properties of the contact. contactEntity.Properties = new Property[] {sp_Field1,sp_Field2}; ``` I don't see much differences in the code. In the examples i found in the internet i have the same implementation as i found in SDK. But if i run the same i get the following error > > CS0029: Cannot implicitly convert type 'Microsoft.Crm.Sdk.StringProperty' to 'Microsoft.Crm.Sdk.PropertyCollection' > > > I tried created a new variable of type PropertyCollection(one that belongs in mscrm namespace) and added the stringpropertys into that and passed it to the entity. ``` Microsoft.Crm.Sdk.PropertyCollection propTest = new Microsoft.Crm.Sdk.PropertyCollection(); propTest.Add(sp_SSNNo); propTest.Add(sp_FirstName); contactEntity.Properties = new Property[] {propTest}; ``` This gave me the following error > > CS0029: Cannot implicitly convert type 'Microsoft.Crm.Sdk.PropertyCollection' to 'Microsoft.Crm.Sdk.Property' > > > I am sure its a minor typecasting error but i am not able to figure out where the error is. And moreover, even if it was a typecasting error why is it working for all the samples given in the internet and not for me. I tried getting the code sample to run but i am encountering the same conversion error. Please let me know if you need more info on this, any help on this would be appreciated.
Here is an article from Microsoft that makes an attempt to discuss this topic: <http://community.dynamics.com/blogs/cscrmblog/archive/2008/06/23/web-services-amp-dlls-or-what-s-up-with-all-the-duplicate-classes.aspx> This is not a bug that you are running into but more of a difference in design between the way the two assemblies work and what they are designed to do. If you want to continue to use the Microsoft.Crm.Sdk.dll you should be able to accomplish your goal with the following... ``` StringProperty sp_Field1 = new StringProperty("Field1","Value1"); StringProperty sp_Field2 = new StringProperty("Field2","Value1"); CrmService service = new CrmService(); service.Credentials = System.Net.CredentialCache.DefaultCredentials; // Create the DynamicEntity object. DynamicEntity contactEntity = new DynamicEntity(); // Set the name of the entity type. contactEntity.Name = EntityName.contact.ToString(); // Set the properties of the contact. PropertyCollection properties = new PropertyCollection(); properties.Add(sp_Field1); contactEntity.Properties = properties; ```
204,505
<p>I use LINQ to Objects instructions on an ordered array. Which operations shouldn't I do to be sure the order of the array is not changed?</p>
[ { "answer_id": 204512, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "<p>Are you actually talking about SQL, or about arrays? To put it another way, are you using LINQ to SQL or LINQ to Objects?</p>\n\n<p>The LINQ to Objects operators don't actually change their original data source - they build sequences which are effectively backed by the data source. The only operations which change the ordering are OrderBy/OrderByDescending/ThenBy/ThenByDescending - and even then, those are stable for equally ordered elements. Of course, many operations will filter out some elements, but the elements which are returned will be in the same order.</p>\n\n<p>If you convert to a different data structure, e.g. with ToLookup or ToDictionary, I don't believe order is preserved at that point - but that's somewhat different anyway. (The order of values mapping to the same key is preserved for lookups though, I believe.)</p>\n" }, { "answer_id": 204516, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "<p>If you are working on an array, it sounds like you are using LINQ-to-Objects, not SQL; can you confirm? Most LINQ operations don't re-order anything (the output will be in the same order as the input) - so don't apply another sort (OrderBy[Descending]/ThenBy[Descending]).</p>\n\n<p>[edit: as Jon put more clearly; LINQ generally creates a <em>new</em> sequence, leaving the original data alone]</p>\n\n<p>Note that pushing the data into a <code>Dictionary&lt;,&gt;</code> (ToDictionary) will scramble the data, as dictionary does not respect any particular sort order.</p>\n\n<p>But most common things (Select, Where, Skip, Take) should be fine.</p>\n" }, { "answer_id": 204583, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 2, "selected": false, "text": "<p>Any 'group by' or 'order by' will possibly change the order.</p>\n" }, { "answer_id": 204777, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 10, "selected": true, "text": "<p>I examined the methods of <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable_methods.aspx\" rel=\"noreferrer\">System.Linq.Enumerable</a>, discarding any that returned non-IEnumerable results. I checked the remarks of each to determine how the order of the result would differ from order of the source.</p>\n\n<p>Preserves Order Absolutely. You can map a source element by index to a result element</p>\n\n<ul>\n<li>AsEnumerable</li>\n<li>Cast</li>\n<li>Concat</li>\n<li>Select</li>\n<li>ToArray</li>\n<li>ToList</li>\n</ul>\n\n<p>Preserves Order. Elements are filtered or added, but not re-ordered.</p>\n\n<ul>\n<li>Distinct</li>\n<li>Except</li>\n<li>Intersect</li>\n<li>OfType</li>\n<li>Prepend (new in .net 4.7.1)</li>\n<li>Skip</li>\n<li>SkipWhile</li>\n<li>Take</li>\n<li>TakeWhile</li>\n<li>Where</li>\n<li>Zip (new in .net 4)</li>\n</ul>\n\n<p>Destroys Order - we don't know what order to expect results in.</p>\n\n<ul>\n<li>ToDictionary</li>\n<li>ToLookup</li>\n</ul>\n\n<p>Redefines Order Explicitly - use these to change the order of the result</p>\n\n<ul>\n<li>OrderBy</li>\n<li>OrderByDescending</li>\n<li>Reverse</li>\n<li>ThenBy</li>\n<li>ThenByDescending</li>\n</ul>\n\n<p>Redefines Order according to some rules.</p>\n\n<ul>\n<li>GroupBy - The IGrouping objects are yielded in an order based on the order of the elements in source that produced the first key of each IGrouping. Elements in a grouping are yielded in the order they appear in source. </li>\n<li>GroupJoin - GroupJoin preserves the order of the elements of outer, and for each element of outer, the order of the matching elements from inner.</li>\n<li>Join - preserves the order of the elements of outer, and for each of these elements, the order of the matching elements of inner. </li>\n<li>SelectMany - for each element of source, selector is invoked and a sequence of values is returned.</li>\n<li>Union - When the object returned by this method is enumerated, Union enumerates first and second in that order and yields each element that has not already been yielded. </li>\n</ul>\n\n<hr>\n\n<p>Edit: I've moved Distinct to Preserving order based on this <a href=\"https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/Enumerable.cs\" rel=\"noreferrer\">implementation</a>.</p>\n\n<pre><code> private static IEnumerable&lt;TSource&gt; DistinctIterator&lt;TSource&gt;\n (IEnumerable&lt;TSource&gt; source, IEqualityComparer&lt;TSource&gt; comparer)\n {\n Set&lt;TSource&gt; set = new Set&lt;TSource&gt;(comparer);\n foreach (TSource element in source)\n if (set.Add(element)) yield return element;\n }\n</code></pre>\n" }, { "answer_id": 24172557, "author": "Curtis Yallop", "author_id": 854342, "author_profile": "https://Stackoverflow.com/users/854342", "pm_score": 3, "selected": false, "text": "<p>I found a great answer in a similar question which references official documentation. To quote it:</p>\n\n<p>For <code>Enumerable</code> methods (LINQ to Objects, which applies to <code>List&lt;T&gt;</code>), you can rely on the order of elements returned by <code>Select</code>, <code>Where</code>, or <code>GroupBy</code>. This is not the case for things that are inherently unordered like <code>ToDictionary</code> or <code>Distinct</code>.</p>\n\n<blockquote>\n <h3>From <a href=\"http://msdn.microsoft.com/en-us/library/bb534501.aspx\" rel=\"nofollow noreferrer\">Enumerable.GroupBy</a> documentation:</h3>\n \n <p>The <code>IGrouping&lt;TKey, TElement&gt;</code> objects are yielded in an order based on the order of the elements in source that produced the first key of each <code>IGrouping&lt;TKey, TElement&gt;</code>. Elements in a grouping are yielded in the order they appear in <code>source</code>.</p>\n</blockquote>\n\n<p>This is not necessarily true for <code>IQueryable</code> extension methods (other LINQ providers).</p>\n\n<p>Source: <a href=\"https://stackoverflow.com/questions/6146724/do-linqs-enumerable-methods-maintain-relative-order-of-elements#6146742\">Do LINQ&#39;s Enumerable Methods Maintain Relative Order of Elements?</a></p>\n" }, { "answer_id": 56206435, "author": "andrew pate", "author_id": 2668869, "author_profile": "https://Stackoverflow.com/users/2668869", "pm_score": 0, "selected": false, "text": "<p>The question here is specifically referring to LINQ-to-Objects.</p>\n\n<p>If your using LINQ-to-SQL instead there is no order there unless you impose one with something like: </p>\n\n<pre><code>mysqlresult.OrderBy(e=&gt;e.SomeColumn)\n</code></pre>\n\n<p>If you do not do this with LINQ-to-SQL then the order of results can vary between subsequent queries, even of the same data, which could cause an intermittant bug.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28216/" ]
I use LINQ to Objects instructions on an ordered array. Which operations shouldn't I do to be sure the order of the array is not changed?
I examined the methods of [System.Linq.Enumerable](http://msdn.microsoft.com/en-us/library/system.linq.enumerable_methods.aspx), discarding any that returned non-IEnumerable results. I checked the remarks of each to determine how the order of the result would differ from order of the source. Preserves Order Absolutely. You can map a source element by index to a result element * AsEnumerable * Cast * Concat * Select * ToArray * ToList Preserves Order. Elements are filtered or added, but not re-ordered. * Distinct * Except * Intersect * OfType * Prepend (new in .net 4.7.1) * Skip * SkipWhile * Take * TakeWhile * Where * Zip (new in .net 4) Destroys Order - we don't know what order to expect results in. * ToDictionary * ToLookup Redefines Order Explicitly - use these to change the order of the result * OrderBy * OrderByDescending * Reverse * ThenBy * ThenByDescending Redefines Order according to some rules. * GroupBy - The IGrouping objects are yielded in an order based on the order of the elements in source that produced the first key of each IGrouping. Elements in a grouping are yielded in the order they appear in source. * GroupJoin - GroupJoin preserves the order of the elements of outer, and for each element of outer, the order of the matching elements from inner. * Join - preserves the order of the elements of outer, and for each of these elements, the order of the matching elements of inner. * SelectMany - for each element of source, selector is invoked and a sequence of values is returned. * Union - When the object returned by this method is enumerated, Union enumerates first and second in that order and yields each element that has not already been yielded. --- Edit: I've moved Distinct to Preserving order based on this [implementation](https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/Enumerable.cs). ``` private static IEnumerable<TSource> DistinctIterator<TSource> (IEnumerable<TSource> source, IEqualityComparer<TSource> comparer) { Set<TSource> set = new Set<TSource>(comparer); foreach (TSource element in source) if (set.Add(element)) yield return element; } ```
204,538
<p>I am having a listbox in ASP.net. I am populating the listbox values from another listbox in a page dynamically. During postbacks the values of output listbox are not persisted. (while going to another page and come back to this page).</p> <p>Please suggest some good answer. EnableViewstate = "true" is not working.</p>
[ { "answer_id": 204551, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 3, "selected": true, "text": "<p>Are you doing anything in Page_Load that should be in a </p>\n\n<pre><code>if(!IsPostBack) {}\n</code></pre>\n\n<p>Initialization code in load needs to only be called when the page is first loaded, not on postbacks.</p>\n\n<p>If you are going to another page and then coming back to this page, I think you need to preserve the information yourself in the Session and then restore it when you come back to the page.</p>\n" }, { "answer_id": 204575, "author": "Jason Whitehorn", "author_id": 27860, "author_profile": "https://Stackoverflow.com/users/27860", "pm_score": 0, "selected": false, "text": "<p>Initialize the content of your controls in your Page's Init event (Page_Init). That way any values the user supplies are not overwritten by your defaults.</p>\n" }, { "answer_id": 204577, "author": "thmsn", "author_id": 28145, "author_profile": "https://Stackoverflow.com/users/28145", "pm_score": 1, "selected": false, "text": "<p>The viewstate is only preserved as long as your on the same page doing postbacks.\nAs Lou Franco wrote</p>\n\n<pre><code>if(!IsPostBack) {}\n</code></pre>\n\n<p>You use this on the initial pagerequest to fill in the data. if you wish to preserve the data across pages using the session to store the values is the best bet.</p>\n\n<p>preferably you fill in the data in your listbox before the SaveViewState event thats in PreInit as far as I recall.</p>\n" }, { "answer_id": 204578, "author": "stevemegson", "author_id": 25028, "author_profile": "https://Stackoverflow.com/users/25028", "pm_score": 0, "selected": false, "text": "<p>EnableViewState will just repopulate the output listbox with the values that it had when the page first rendered, since they're still the ones stored in the viewstate. The browser sends only the selected value in the postback, so there's no way for the server to know what other values you added on the client.</p>\n\n<p>You can work around this by adding a hidden input to the page and populating it with the dynamic values when you update the listbox. Your page can then check that value during a postback and repopulate the list properly.</p>\n" }, { "answer_id": 5276756, "author": "user512374", "author_id": 512374, "author_profile": "https://Stackoverflow.com/users/512374", "pm_score": 0, "selected": false, "text": "<p>Changes made to the listbox on the client side are not persisted during a postback, you need to record that information in hidden fields and then configure the control during the page_load event to make the changes stick during the rest of the postback.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
I am having a listbox in ASP.net. I am populating the listbox values from another listbox in a page dynamically. During postbacks the values of output listbox are not persisted. (while going to another page and come back to this page). Please suggest some good answer. EnableViewstate = "true" is not working.
Are you doing anything in Page\_Load that should be in a ``` if(!IsPostBack) {} ``` Initialization code in load needs to only be called when the page is first loaded, not on postbacks. If you are going to another page and then coming back to this page, I think you need to preserve the information yourself in the Session and then restore it when you come back to the page.
204,549
<p>I need to insert some data into a table in Oracle. </p> <p>The only problem is one of the fields is a timestamp(6) type and it is required data. I don't care about what actually goes in here I just need to get the right syntax for an entry so that the database will accept it.</p> <p>I'm using the gui web client to enter data however I don't mind using raw SQL if I have to.</p> <p>Thanks.</p>
[ { "answer_id": 204620, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 4, "selected": false, "text": "<p>I dunno if this helps at all, but in SQL*Plus I did this:</p>\n\n<pre><code>create table x ( a timestamp(6));\ninsert into x values ( current_timestamp );\nselect * from x;\n</code></pre>\n\n<p>getting me this:</p>\n\n<pre><code>T\n---------------------------------------------------------------------------\n15-OCT-08 02.01.25.604309 PM\n</code></pre>\n\n<p>So it looks like that works.</p>\n\n<p>If you need to put a previously-known value into the column, how about the TO_TIMESTAMP() function? Something like this:</p>\n\n<pre><code>select to_timestamp('27/02/2002 15:51.12.539880', 'dd/mm/yyyy hh24:mi.ss.ff') \nfrom dual ; \n</code></pre>\n" }, { "answer_id": 1399554, "author": "Benedikt Waldvogel", "author_id": 4308, "author_profile": "https://Stackoverflow.com/users/4308", "pm_score": 3, "selected": false, "text": "<p>using <code>to_timestamp()</code> is one option.\nthe other is doing this:</p>\n\n<pre><code>INSERT INTO table VALUES (timestamp'2009-09-09 09:30:25 CET');\n</code></pre>\n" }, { "answer_id": 29661721, "author": "Cale Sweeney", "author_id": 2242045, "author_profile": "https://Stackoverflow.com/users/2242045", "pm_score": 0, "selected": false, "text": "<p>Here are a couple of different TO_TIMESTAMP functions that worked for me...</p>\n\n<p>This TO_TIMESTAMP function worked on an INSERT against a column of type TIMESTAMP(6):</p>\n\n<pre><code>TO_TIMESTAMP('04/14/2015 2:25:55','mm/dd/yyyy hh24:mi.ss.ff')\n</code></pre>\n\n<p>This TO_TIMESTAMP function worked on an INSERT against a column of type DATE:</p>\n\n<pre><code>TO_TIMESTAMP('04/15/2015','mm/dd/yyyy')\n</code></pre>\n" }, { "answer_id": 50120973, "author": "Piyush", "author_id": 9168466, "author_profile": "https://Stackoverflow.com/users/9168466", "pm_score": 0, "selected": false, "text": "<pre><code>insert into x values(to_timestamp('22:20:00','hh24:mi'));\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22061/" ]
I need to insert some data into a table in Oracle. The only problem is one of the fields is a timestamp(6) type and it is required data. I don't care about what actually goes in here I just need to get the right syntax for an entry so that the database will accept it. I'm using the gui web client to enter data however I don't mind using raw SQL if I have to. Thanks.
I dunno if this helps at all, but in SQL\*Plus I did this: ``` create table x ( a timestamp(6)); insert into x values ( current_timestamp ); select * from x; ``` getting me this: ``` T --------------------------------------------------------------------------- 15-OCT-08 02.01.25.604309 PM ``` So it looks like that works. If you need to put a previously-known value into the column, how about the TO\_TIMESTAMP() function? Something like this: ``` select to_timestamp('27/02/2002 15:51.12.539880', 'dd/mm/yyyy hh24:mi.ss.ff') from dual ; ```
204,557
<p>I'm working on scripts that apply database schema updates. I've setup all my SQL update scripts using start transaction/commit. I pass these scripts to psql on the command line.</p> <p>I now need to apply multiple scripts at the same time, and in one transaction. So far the only solution I've come up with is to remove the start transaction/commit from the original set of scripts, then jam them together inside a new start transaction/commit block. I'm writing perl scripts to do this on the fly.</p> <p>Effectively I want nested transactions, which I can't figure out how to do in postgresql. </p> <p>Is there any way to do or simulate nested transactions for this purpose? I have things setup to automatically bail out on any error, so I don't need to continue in the top level transaction if any of the lower ones fail.</p>
[ { "answer_id": 204592, "author": "MysticSlayer", "author_id": 28139, "author_profile": "https://Stackoverflow.com/users/28139", "pm_score": 4, "selected": true, "text": "<p>Well you have the possibility to use nested transactions inside postgresql using SavePoints.</p>\n\n<p>Take this code example:</p>\n\n<pre><code>CREATE TABLE t1 (a integer PRIMARY KEY);\n\nCREATE FUNCTION test_exception() RETURNS boolean LANGUAGE plpgsql AS\n$$BEGIN\n INSERT INTO t1 (a) VALUES (1);\n INSERT INTO t1 (a) VALUES (2);\n INSERT INTO t1 (a) VALUES (1);\n INSERT INTO t1 (a) VALUES (3);\n RETURN TRUE;\nEXCEPTION\n WHEN integrity_constraint_violation THEN\n RAISE NOTICE 'Rollback to savepoint';\n RETURN FALSE;\nEND;$$;\n\nBEGIN;\n\nSELECT test_exception();\nNOTICE: Rollback to savepoint\n test_exception \n----------------\n f\n(1 row)\n\nCOMMIT;\n\nSELECT count(*) FROM t1;\n count \n-------\n 0\n(1 row)\n</code></pre>\n\n<p>Maybe this will help you out a little bit.</p>\n" }, { "answer_id": 208770, "author": "Michael Kohne", "author_id": 5801, "author_profile": "https://Stackoverflow.com/users/5801", "pm_score": 0, "selected": false, "text": "<p>I've ended up 'solving' my problem out of band - I use a perl script to re-work the input scripts to eliminate their start transaction/commit calls, then push them all into one file, which gets it's own start transaction/commit.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5801/" ]
I'm working on scripts that apply database schema updates. I've setup all my SQL update scripts using start transaction/commit. I pass these scripts to psql on the command line. I now need to apply multiple scripts at the same time, and in one transaction. So far the only solution I've come up with is to remove the start transaction/commit from the original set of scripts, then jam them together inside a new start transaction/commit block. I'm writing perl scripts to do this on the fly. Effectively I want nested transactions, which I can't figure out how to do in postgresql. Is there any way to do or simulate nested transactions for this purpose? I have things setup to automatically bail out on any error, so I don't need to continue in the top level transaction if any of the lower ones fail.
Well you have the possibility to use nested transactions inside postgresql using SavePoints. Take this code example: ``` CREATE TABLE t1 (a integer PRIMARY KEY); CREATE FUNCTION test_exception() RETURNS boolean LANGUAGE plpgsql AS $$BEGIN INSERT INTO t1 (a) VALUES (1); INSERT INTO t1 (a) VALUES (2); INSERT INTO t1 (a) VALUES (1); INSERT INTO t1 (a) VALUES (3); RETURN TRUE; EXCEPTION WHEN integrity_constraint_violation THEN RAISE NOTICE 'Rollback to savepoint'; RETURN FALSE; END;$$; BEGIN; SELECT test_exception(); NOTICE: Rollback to savepoint test_exception ---------------- f (1 row) COMMIT; SELECT count(*) FROM t1; count ------- 0 (1 row) ``` Maybe this will help you out a little bit.
204,564
<p>Is there any way to get the custom attributes of a specific object I am receiving in a method?</p> <p>I do not want nor can to iterate over Type.GetMembers() and search for my member. I have the object, which is also a member, that has the attribute.</p> <p>How do I get the attribute?</p> <pre><code>class Custom { [Availability] private object MyObject = "Hello"; private void Do(object o) { //does object 'o' has any custom attributes of type 'Availability'? } //somewhere I make the call: Do(MyObject) } </code></pre>
[ { "answer_id": 204573, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 1, "selected": false, "text": "<p>You cannot do this without at least 1 Reflection call. After that, save the value somehow.</p>\n\n<p>Example:</p>\n\n<pre><code>abstract MyBase\n{\n public string Name;\n protected MyBase()\n {\n //look up value of Name attribute and assign to Name\n } \n}\n\n[Name(\"Foo\")]\nclass MyClass : MyBase\n{\n}\n</code></pre>\n" }, { "answer_id": 204581, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "<p>No. Objects don't have attributes - members do. By the time you're in the \"Do\" method, there's no record of the fact that you called Do(MyObject) vs Do(MyOtherFieldWhichHasTheSameValue).</p>\n\n<p>If you need to look up the attributes on a member, you'll basically have to pass in the relevant MemberInfo, not what it happens to evaluate to.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2130892/" ]
Is there any way to get the custom attributes of a specific object I am receiving in a method? I do not want nor can to iterate over Type.GetMembers() and search for my member. I have the object, which is also a member, that has the attribute. How do I get the attribute? ``` class Custom { [Availability] private object MyObject = "Hello"; private void Do(object o) { //does object 'o' has any custom attributes of type 'Availability'? } //somewhere I make the call: Do(MyObject) } ```
No. Objects don't have attributes - members do. By the time you're in the "Do" method, there's no record of the fact that you called Do(MyObject) vs Do(MyOtherFieldWhichHasTheSameValue). If you need to look up the attributes on a member, you'll basically have to pass in the relevant MemberInfo, not what it happens to evaluate to.
204,576
<p>In my MFC program I am using a splitter to create two panes. I now want to split one of these panes in half again and put in another view, can someone talk me through how to do it or point me in the direction of some code?</p> <p>I would prefer to code it myself so I am not interested in custom derived classes unless they are extremely basic.</p> <p>Thanks!</p>
[ { "answer_id": 204584, "author": "pmlarocque", "author_id": 7419, "author_profile": "https://Stackoverflow.com/users/7419", "pm_score": 0, "selected": false, "text": "<p>I am not an expert in MFC, but can't you just put a splitter in one of the panes you made with the first splitter ? that how we do in winform....</p>\n" }, { "answer_id": 204662, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 4, "selected": true, "text": "<p>In <code>CMainFrame::OnCreateClient</code></p>\n\n<pre><code>// Create splitter with 2 rows and 1 col\nm_wndSplitter.CreateStatic(this, 2, 1);\n// Create a view in the top row\nm_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CView1), CSize(100, 100), pContext);\n// Create a 2 column splitter that will go in the bottom row of the first\nm_wndSplitter2.CreateStatic(&amp;m_wndSplitter, 1, 2, WS_CHILD|WS_VISIBLE, m_wndSplitter.IdFromRowCol(1, 0));\n// Create views for the bottom splitter\nm_wndSplitter2.CreateView(0, 0, RUNTIME_CLASS(CView2), CSize(100, 100), pContext); \nm_wndSplitter2.CreateView(0, 1, RUNTIME_CLASS(CView3), CSize(100, 100), pContext);\n...\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18664/" ]
In my MFC program I am using a splitter to create two panes. I now want to split one of these panes in half again and put in another view, can someone talk me through how to do it or point me in the direction of some code? I would prefer to code it myself so I am not interested in custom derived classes unless they are extremely basic. Thanks!
In `CMainFrame::OnCreateClient` ``` // Create splitter with 2 rows and 1 col m_wndSplitter.CreateStatic(this, 2, 1); // Create a view in the top row m_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CView1), CSize(100, 100), pContext); // Create a 2 column splitter that will go in the bottom row of the first m_wndSplitter2.CreateStatic(&m_wndSplitter, 1, 2, WS_CHILD|WS_VISIBLE, m_wndSplitter.IdFromRowCol(1, 0)); // Create views for the bottom splitter m_wndSplitter2.CreateView(0, 0, RUNTIME_CLASS(CView2), CSize(100, 100), pContext); m_wndSplitter2.CreateView(0, 1, RUNTIME_CLASS(CView3), CSize(100, 100), pContext); ... ```
204,611
<p>I am working with Crystal Reports and MS SQL Server. I need to remap the crystal report to point to a different database on the same SQL Server. Is there an automated way of doing this, or do I have to remap for every single report? I am currently doing this by adding a new data connection, and then updating the stored procedure with the specified paramether to change database(catalog). Also, after remaping, the .asp that displays the report crashes like this:</p> <p>Active Server Pages, ASP 0115 (0x80004005) A trappable error (E06D7363) occurred in an external object. The script cannot continue running.</p> <p>The code is: </p> <p>Set mainReportTableCollection = Session("oRpt").Database.Tables</p> <pre><code>For Each mnTable in mainReportTableCollection With mnTable.ConnectionProperties .Item("user ID") = "&lt;some_login_name&gt;" .Item("Password") = "&lt;some_password&gt;" .Item("DSN") = "&lt;some_DSN&gt;" .Item("Database") ="&lt;some_Database&gt;" End With Next </code></pre> <p>It runs, however, if i comment out the last two assignations.</p> <p>Thanks in advance.</p> <p>Yours trully, Silviu.</p>
[ { "answer_id": 209010, "author": "Jas", "author_id": 777, "author_profile": "https://Stackoverflow.com/users/777", "pm_score": 0, "selected": false, "text": "<p>You can get any of the info from the current report connection info. So if your not changing servers, then set the crystalServer variable to the reports current server.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>'SET REPORT CONNECTION INFO\nFor i = 0 To rsource.ReportDocument.DataSourceConnections.Count - 1\n rsource.ReportDocument.DataSourceConnections(i).SetConnection(crystalServer, crystalDB, crystalUser, crystalPassword)\nNext\n\nFor i = 0 To rsource.ReportDocument.Subreports.Count - 1\n For x = 0 To rsource.ReportDocument.Subreports(i).DataSourceConnections.Count - 1\n rsource.ReportDocument.OpenSubreport(rsource.ReportDocument.Subreports(i).Name).DataSourceConnections(x).SetConnection(crystalServer, crystalDB, crystalUser, crystalPassword)\n Next\nNext\n</code></pre>\n" }, { "answer_id": 217756, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 2, "selected": false, "text": "<p>You'll find hereafter the procedure I use (I simplified it on the fly, suppressing our own objects and global variables). This procedure allows to redirect a report from an original connection used at development time to the active SQL server. It is written in VB and uses 2 main objects:</p>\n\n<ol>\n<li>The original report object opened through an instance of crystal report</li>\n<li>An ADODB connection being the active connection (called P_currentConnection) to the current SQL server</li>\n</ol>\n\n<p>This function (could be also a sub) is called before viewing/printing the report object in the application. It can be used when distributing reports among replicated databases where users, depending on their location, connect to different servers/databases.</p>\n\n<pre><code>Public Function connectReportToDatabase( _\n P_report As CRAXDRT.Report)\n\nDim table As CRAXDRT.DatabaseTable, _\n\nFor Each table In P_report.Database.tables\n\n If table.DllName &lt;&gt; \"crdb_ado.dll\" Then\n table.DllName = \"crdb_ado.dll\"\n End If\n\n table.ConnectionProperties.DeleteAll\n\n table.ConnectionProperties.Add \"Provider\", P_currentConnection.Provider\n table.ConnectionProperties.Add \"Data source\", P_currentConnection.Properties(\"Data source\").Value\n table.ConnectionProperties.Add \"Database\", P_currentConnection.DefaultDatabase\n table.ConnectionProperties.Add \"Integrated security\", P_currentConnection.Properties(\"Integrated security\").Value\n table.ConnectionProperties.Add \"Persist Security Info\", P_currentConnection.Properties(\"Persist Security Info\").Value\n table.ConnectionProperties.Add \"Initial Catalog\", P_currentConnection.Properties(\"Initial Catalog\").Value\n\n table.SetTableLocation table.location, \"\", P_currentConnection.ConnectionString\n\n table.TestConnectivity\n\nNext table\n</code></pre>\n\n<p>It can be called with a procedure such as:</p>\n\n<pre><code>Dim crystal As CRAXDRT.Application, _\n m_report as CRAXDRT.report \n\nSet crystal = New CRAXDRT.Application\nSet m_rapport = crystal.OpenReport(nameOfTheReport &amp; \".rpt\")\n\nconnectreportToDatabase(m_report)\n</code></pre>\n\n<p>In case your report includes subreports, You might also have to redirect them to the active connection. In this case, you'll have to browse all objects in your report, check the ones that are of the report type and redirect them to the new connection. I am sure you'll have fun adding the corresponding extra lines to this original procedure.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am working with Crystal Reports and MS SQL Server. I need to remap the crystal report to point to a different database on the same SQL Server. Is there an automated way of doing this, or do I have to remap for every single report? I am currently doing this by adding a new data connection, and then updating the stored procedure with the specified paramether to change database(catalog). Also, after remaping, the .asp that displays the report crashes like this: Active Server Pages, ASP 0115 (0x80004005) A trappable error (E06D7363) occurred in an external object. The script cannot continue running. The code is: Set mainReportTableCollection = Session("oRpt").Database.Tables ``` For Each mnTable in mainReportTableCollection With mnTable.ConnectionProperties .Item("user ID") = "<some_login_name>" .Item("Password") = "<some_password>" .Item("DSN") = "<some_DSN>" .Item("Database") ="<some_Database>" End With Next ``` It runs, however, if i comment out the last two assignations. Thanks in advance. Yours trully, Silviu.
You'll find hereafter the procedure I use (I simplified it on the fly, suppressing our own objects and global variables). This procedure allows to redirect a report from an original connection used at development time to the active SQL server. It is written in VB and uses 2 main objects: 1. The original report object opened through an instance of crystal report 2. An ADODB connection being the active connection (called P\_currentConnection) to the current SQL server This function (could be also a sub) is called before viewing/printing the report object in the application. It can be used when distributing reports among replicated databases where users, depending on their location, connect to different servers/databases. ``` Public Function connectReportToDatabase( _ P_report As CRAXDRT.Report) Dim table As CRAXDRT.DatabaseTable, _ For Each table In P_report.Database.tables If table.DllName <> "crdb_ado.dll" Then table.DllName = "crdb_ado.dll" End If table.ConnectionProperties.DeleteAll table.ConnectionProperties.Add "Provider", P_currentConnection.Provider table.ConnectionProperties.Add "Data source", P_currentConnection.Properties("Data source").Value table.ConnectionProperties.Add "Database", P_currentConnection.DefaultDatabase table.ConnectionProperties.Add "Integrated security", P_currentConnection.Properties("Integrated security").Value table.ConnectionProperties.Add "Persist Security Info", P_currentConnection.Properties("Persist Security Info").Value table.ConnectionProperties.Add "Initial Catalog", P_currentConnection.Properties("Initial Catalog").Value table.SetTableLocation table.location, "", P_currentConnection.ConnectionString table.TestConnectivity Next table ``` It can be called with a procedure such as: ``` Dim crystal As CRAXDRT.Application, _ m_report as CRAXDRT.report Set crystal = New CRAXDRT.Application Set m_rapport = crystal.OpenReport(nameOfTheReport & ".rpt") connectreportToDatabase(m_report) ``` In case your report includes subreports, You might also have to redirect them to the active connection. In this case, you'll have to browse all objects in your report, check the ones that are of the report type and redirect them to the new connection. I am sure you'll have fun adding the corresponding extra lines to this original procedure.
204,616
<p>We are in the process of moving our SVN repositories from one machine to another one, and with it will come a new domain name for the new repo. The problem is, that within the repository, there are lots of svn:externals references to other projects within the repository. So for example, we have projectA, which has in the svn:externals properties:</p> <pre><code>external/libraryA svn://oldserver.net/repo/libraryA external/libraryB svn://oldserver.net/repo/libraryB </code></pre> <p>...and so on. All of the URL's reference this particular domain name, so it can be easily parsed. Having already learned my lesson, I will migrate these URLs to be "svn://localhost/", but I need to find a way to go through the repository history and rewrite all of the old URLs, so that we can still check out older revisions of these projects without having broken links.</p> <p>How would I go about doing this?</p>
[ { "answer_id": 204736, "author": "conny", "author_id": 23023, "author_profile": "https://Stackoverflow.com/users/23023", "pm_score": 0, "selected": false, "text": "<p>You could:</p>\n\n<p>a) check out the old revision, and change your hosts-file to point the old name to the new address, then svn update. In case the URL-path also changed... well then you might as well:</p>\n\n<p>b) take the time to write a script that find the properties in the current (old revision-) working copy and changes the URLs there, without committing them. OR:</p>\n\n<p>c) make a note of the revision(-s) where you checked in the new property values, check out the old version, and simply do a merge those revisions (-that only affect the properties) into your working copy. </p>\n\n<p>d) or, possibly, use svndump to dump the repository data, string-replace the URL in the dump, then restore it.. I would not give you any guarantee that that even works ;-)</p>\n" }, { "answer_id": 234106, "author": "yvandermeer", "author_id": 31201, "author_profile": "https://Stackoverflow.com/users/31201", "pm_score": 4, "selected": true, "text": "<p>As you indicated that you still want to be able to check out older revisions, the only solution is really to \"rewrite\" the entire history (solution D mentioned earlier).</p>\n\n<p>To do this, you should:</p>\n\n<p>1) Dump the contents of the <em>entire</em> repository using <a href=\"http://svnbook.red-bean.com/en/1.1/re31.html\" rel=\"noreferrer\" title=\"svnadmin dump\">svnadmin dump</a>:</p>\n\n<pre><code>$ svnadmin dump /path/to/repos &gt; original-dumpfile\n* Dumped revision 0.\n* Dumped revision 1.\n* Dumped revision 2.\n* Dumped revision 3.\n</code></pre>\n\n<p>2) Edit the dump file, to change the svn:externals URLs. <strong>This is the most difficult part</strong>: Assuming the repository contains binary data as well, opening the dump file in a plain text editor will most likely corrupt the dump file. I've had good experiences using a so-called \"hex-editor\", for instance the <a href=\"http://www.chmaas.handshake.de/delphi/freeware/xvi32/xvi32.htm\" rel=\"noreferrer\" title=\"Freeware Hex Editor XVI32\">Freeware Hex Editor XVI32</a></p>\n\n<p>3) Create a new repository and load the modified dumpfile into it:</p>\n\n<pre><code>$ svnadmin create newrepos\n$ svnadmin load newrepos &lt; modified-dumpfile\n</code></pre>\n\n<p>For more information, you might also be interested in this link:<br>\n<a href=\"http://svnbook.red-bean.com/en/1.1/ch05s03.html\" rel=\"noreferrer\">http://svnbook.red-bean.com/en/1.1/ch05s03.html</a></p>\n\n<p>NOTE: Subversion 1.5 actually added support for <em>relative URLs</em> in the svn:externals property, which can precisely prevent these sort of problems in the future:<br>\n<a href=\"http://subversion.tigris.org/svn_1.5_releasenotes.html#externals\" rel=\"noreferrer\">http://subversion.tigris.org/svn_1.5_releasenotes.html#externals</a></p>\n" }, { "answer_id": 3526100, "author": "ldav1s", "author_id": 425738, "author_profile": "https://Stackoverflow.com/users/425738", "pm_score": 4, "selected": false, "text": "<p>I'd use <a href=\"http://svn.borg.ch/svndumptool/\" rel=\"noreferrer\">SvnDumpTool</a> for this. It has exactly what you're looking for:</p>\n\n<pre><code>svndumptool transform-prop svn:externals \"(\\S*) (|-r ?\\d* ?)http://oldserver.net(/\\S*)\" \"\\2\\3 \\1\" source.dumpfile source-fixed-externals.dumpfile\n</code></pre>\n\n<p>This fixes up each external to the <a href=\"http://subversion.apache.org/docs/release-notes/1.5.html#externals\" rel=\"noreferrer\">subversion 1.5 format</a>, and uses relative URLs.</p>\n\n<p>So svn:externals like:</p>\n\n<pre><code>external/libraryA svn://oldserver.net/repo/libraryA\n</code></pre>\n\n<p>become:</p>\n\n<pre><code> /repo/libraryA external/libraryA\n</code></pre>\n\n<p>using server root relative URLs.</p>\n" }, { "answer_id": 35939092, "author": "Leo", "author_id": 221284, "author_profile": "https://Stackoverflow.com/users/221284", "pm_score": 1, "selected": false, "text": "<p>I had to relocate 12 working copies across 9 users and 4 deployments. It was a simple change, replacing a domain with an IP, i.e. <code>thing.domain.net -&gt; 192.168.0.1</code></p>\n\n<p>Expecting <code>svn relocate</code> to behave as described (traverse nested externals) I wrote a simple DOS instruction to run at each location: </p>\n\n<p><code>for /D %G in (*) do (\ncd ./%G\n&amp; svn relocate http://thing.domain.net http://192.168.0.1\n&amp; cd ..)</code></p>\n\n<p>This didn't work as expected, only relocating the parent WC.</p>\n\n<p>My solution was to edit the repositories themselves (I used Tortoise Repo Browser) to change the location of the externals. Following this change an update to the relocated parent was all that was required to bring everything into line.</p>\n\n<p><em>It would probably be a good idea to get all the Tortoise users to clear their URL history so they don't inadvertently perform operations using the old URL (it still exists in the DNS lookup):</em> </p>\n\n<p><em><strong><code>Settings-&gt;Saved Data-&gt;URL history-&gt;Clear</code></strong></em></p>\n" }, { "answer_id": 36511707, "author": "user293122", "author_id": 6179567, "author_profile": "https://Stackoverflow.com/users/6179567", "pm_score": 1, "selected": false, "text": "<p>I edited my dump file with vi but I had to use the \"-b\" switch to edit in binary mode such that any characters that could be interpreted to be line endings did not get converted.</p>\n\n<p>e.g. vi -b filename.dump</p>\n\n<p>Also, I found that, if your URL length changes, there are string lengths that also had to be modified. \nFor example, consider an entry that looks like this:</p>\n\n<p>Node-path: trunk/src/include</p>\n\n<p>Node-kind: dir</p>\n\n<p>Node-action: change</p>\n\n<p>Prop-content-length: 192</p>\n\n<p>Content-length: 192</p>\n\n<p>K13</p>\n\n<p>svn:externals</p>\n\n<p>V 156</p>\n\n<p>MGL_ABC svn://server_name/dir1/dir2</p>\n\n<p>MGL_DEF svn://server_name/dir1/dir3</p>\n\n<p>When you modify those URLs, if the length of the string changes, you need to also change the \"192\", \"192\" and \"156\" to match the new length. \nI found it difficult to compute the absolute length but easy to find the differential.<br>\nFor example, let's say URL 1 becomes shorter by 3 characters and URL 2 becomes shorter by 4 characters. Then, you would have to subract '7' from each of those three string length numbers.</p>\n" }, { "answer_id": 43887534, "author": "Axel Bregnsbo", "author_id": 155425, "author_profile": "https://Stackoverflow.com/users/155425", "pm_score": 0, "selected": false, "text": "<p>All my externals were in directories named <code>flow</code>. I fixed the URLs in my externals with this one-liner (bash shell):</p>\n\n<pre>\nfor p in $(find -maxdepth 4 -name flow); do svn ps svn:externals \"$(svn pg svn:externals $p/.. | perl -pe 's/^(\\w+) svn\\+ssh.*thing\\.domain\\.net(.*)/$2 $1/')\" $p/..; done\n</pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14302/" ]
We are in the process of moving our SVN repositories from one machine to another one, and with it will come a new domain name for the new repo. The problem is, that within the repository, there are lots of svn:externals references to other projects within the repository. So for example, we have projectA, which has in the svn:externals properties: ``` external/libraryA svn://oldserver.net/repo/libraryA external/libraryB svn://oldserver.net/repo/libraryB ``` ...and so on. All of the URL's reference this particular domain name, so it can be easily parsed. Having already learned my lesson, I will migrate these URLs to be "svn://localhost/", but I need to find a way to go through the repository history and rewrite all of the old URLs, so that we can still check out older revisions of these projects without having broken links. How would I go about doing this?
As you indicated that you still want to be able to check out older revisions, the only solution is really to "rewrite" the entire history (solution D mentioned earlier). To do this, you should: 1) Dump the contents of the *entire* repository using [svnadmin dump](http://svnbook.red-bean.com/en/1.1/re31.html "svnadmin dump"): ``` $ svnadmin dump /path/to/repos > original-dumpfile * Dumped revision 0. * Dumped revision 1. * Dumped revision 2. * Dumped revision 3. ``` 2) Edit the dump file, to change the svn:externals URLs. **This is the most difficult part**: Assuming the repository contains binary data as well, opening the dump file in a plain text editor will most likely corrupt the dump file. I've had good experiences using a so-called "hex-editor", for instance the [Freeware Hex Editor XVI32](http://www.chmaas.handshake.de/delphi/freeware/xvi32/xvi32.htm "Freeware Hex Editor XVI32") 3) Create a new repository and load the modified dumpfile into it: ``` $ svnadmin create newrepos $ svnadmin load newrepos < modified-dumpfile ``` For more information, you might also be interested in this link: <http://svnbook.red-bean.com/en/1.1/ch05s03.html> NOTE: Subversion 1.5 actually added support for *relative URLs* in the svn:externals property, which can precisely prevent these sort of problems in the future: <http://subversion.tigris.org/svn_1.5_releasenotes.html#externals>
204,627
<p>I'm trying to start using LINQ and specifically LINQ to SQL but I'm having some difficulties</p> <p>I've tried this with SqlMetal and now using the database table designer in Visual Studio and I keep getting similar errors, like in this code, using the data context I created with the database layout designer in VS2008.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack) { string usn = UserNameBox.Text; string pss = PassBox.Text; if (usn == "" || pss == "") return; DataClassesDataContext dc = new DataClassesDataContext(); var user = from u in User where u.UserName == usn select u; } } } </code></pre> <p>I get an error on the where saying: Could not find an implementation of the query pattern for source type 'System.Security.Principal.IPrincipal'. And also: 'Where' not found.</p> <p>I had something similar to this when I tried to use the results of SqlMetal. I deleted that source and started over using the designer. I must be missing something here but I can't figure out what. Shouldn't the tables implement what I need since I'm using LINQ to SQL, or do I need to do something extra to make that happen?</p>
[ { "answer_id": 204631, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 2, "selected": false, "text": "<p>Shouldn't you <strong>use</strong> the dc you create somewhere in your query?</p>\n\n<p>Something like:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e) \n{ \n if (Page.IsPostBack) \n {\n string usn = UserNameBox.Text; \n string pss = PassBox.Text; \n if (usn == \"\" || pss == \"\") \n return; \n DataClassesDataContext dc = new DataClassesDataContext(); \n var user = from u in dc.User where u.UserName == usn select u; \n } \n}\n</code></pre>\n" }, { "answer_id": 204632, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": false, "text": "<p>Try changing <code>User</code> to <code>dc.User</code>:</p>\n\n<pre><code>var user = from u in dc.User\n where u.UserName == usn\n select u;\n</code></pre>\n\n<p>The <code>User</code> is the property <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.page.user.aspx\" rel=\"nofollow noreferrer\">System.Web.UI.Page.User</a>.</p>\n" }, { "answer_id": 204633, "author": "Joel Cunningham", "author_id": 5360, "author_profile": "https://Stackoverflow.com/users/5360", "pm_score": 4, "selected": true, "text": "<p>Try </p>\n\n<pre><code>var user = from u in dc.User\n where u.UserName == usn\n select u;\n</code></pre>\n" }, { "answer_id": 204636, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Your query expression should use dc.User, not just User:</p>\n\n<pre><code>DataClassesDataContext dc = new DataClassesDataContext();\nvar user = from u in dc.User\n where u.UserName == usn\n select u;\n</code></pre>\n\n<p>If you've got pluralisation turned on, it may be dc.Users instead.</p>\n" }, { "answer_id": 205105, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 0, "selected": false, "text": "<p>The User you are referring to (when you don't use dc.User) is the Page.User member. That's why intellisense isn't complaining.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26140/" ]
I'm trying to start using LINQ and specifically LINQ to SQL but I'm having some difficulties I've tried this with SqlMetal and now using the database table designer in Visual Studio and I keep getting similar errors, like in this code, using the data context I created with the database layout designer in VS2008. ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack) { string usn = UserNameBox.Text; string pss = PassBox.Text; if (usn == "" || pss == "") return; DataClassesDataContext dc = new DataClassesDataContext(); var user = from u in User where u.UserName == usn select u; } } } ``` I get an error on the where saying: Could not find an implementation of the query pattern for source type 'System.Security.Principal.IPrincipal'. And also: 'Where' not found. I had something similar to this when I tried to use the results of SqlMetal. I deleted that source and started over using the designer. I must be missing something here but I can't figure out what. Shouldn't the tables implement what I need since I'm using LINQ to SQL, or do I need to do something extra to make that happen?
Try ``` var user = from u in dc.User where u.UserName == usn select u; ```
204,646
<p>Does anyone have a simple, efficient way of checking that a string doesn't contain HTML? Basically, I want to check that certain fields only contain plain text. I thought about looking for the &lt; character, but that can easily be used in plain text. Another way might be to create a new System.Xml.Linq.XElement using:</p> <pre><code>XElement.Parse("&lt;wrapper&gt;" + MyString + "&lt;/wrapper&gt;") </code></pre> <p>and check that the XElement contains no child elements, but this seems a little heavyweight for what I need.</p>
[ { "answer_id": 204664, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 6, "selected": false, "text": "<p>The following will match any matching set of tags. i.e. &lt;b>this&lt;/b></p>\n\n<pre><code>Regex tagRegex = new Regex(@\"&lt;\\s*([^ &gt;]+)[^&gt;]*&gt;.*?&lt;\\s*/\\s*\\1\\s*&gt;\");\n</code></pre>\n\n<p>The following will match any single tag. i.e. &lt;b> (it doesn't have to be closed).</p>\n\n<pre><code>Regex tagRegex = new Regex(@\"&lt;[^&gt;]+&gt;\");\n</code></pre>\n\n<p>You can then use it like so</p>\n\n<pre><code>bool hasTags = tagRegex.IsMatch(myString);\n</code></pre>\n" }, { "answer_id": 204668, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 4, "selected": false, "text": "<p>Here you go:</p>\n\n<pre><code>using System.Text.RegularExpressions;\nprivate bool ContainsHTML(string checkString)\n{\n return Regex.IsMatch(checkString, \"&lt;(.|\\n)*?&gt;\");\n}\n</code></pre>\n\n<p>That is the simplest way, since items in brackets are unlikely to occur naturally. </p>\n" }, { "answer_id": 204706, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 2, "selected": false, "text": "<p>Angle brackets may not be your only challenge. Other characters can also be potentially harmful script injection. Such as the common double hyphen \"--\", which can also used in SQL injection. And there are others.</p>\n\n<p>On an ASP.Net page, if validateRequest = true in machine.config, web.config or the page directive, the user will get an error page stating \"A potentially dangerous Request.Form value was detected from the client\" if an HTML tag or various other potential script-injection attacks are detected. You probably want to avoid this and provide a more elegant, less-scary UI experience.</p>\n\n<p>You could test for both the opening and closing tags &lt;> using a regular expression, and allow the text if only one of them occcurs. Allow &lt; or >, but not &lt; followed by some text and then >, in that order.</p>\n\n<p>You could allow angle brackets and HtmlEncode the text to preserve them when the data is persisted. </p>\n" }, { "answer_id": 204720, "author": "J c", "author_id": 25837, "author_profile": "https://Stackoverflow.com/users/25837", "pm_score": 5, "selected": false, "text": "<p>You could ensure plain text by encoding the input using <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httputility.htmlencode.aspx\" rel=\"noreferrer\">HttpUtility.HtmlEncode</a>.</p>\n\n<p>In fact, depending on how strict you want the check to be, you could use it to determine if the string contains HTML:</p>\n\n<pre><code>bool containsHTML = (myString != HttpUtility.HtmlEncode(myString));\n</code></pre>\n" }, { "answer_id": 205353, "author": "Ben Mills", "author_id": 203, "author_profile": "https://Stackoverflow.com/users/203", "pm_score": 4, "selected": true, "text": "<p>I just tried my XElement.Parse solution. I created an extension method on the string class so I can reuse the code easily:</p>\n\n<pre><code>public static bool ContainsXHTML(this string input)\n{\n try\n {\n XElement x = XElement.Parse(\"&lt;wrapper&gt;\" + input + \"&lt;/wrapper&gt;\");\n return !(x.DescendantNodes().Count() == 1 &amp;&amp; x.DescendantNodes().First().NodeType == XmlNodeType.Text);\n }\n catch (XmlException ex)\n {\n return true;\n }\n}\n</code></pre>\n\n<p>One problem I found was that plain text ampersand and less than characters cause an XmlException and indicate that the field contains HTML (which is wrong). To fix this, the input string passed in first needs to have the ampersands and less than characters converted to their equivalent XHTML entities. I wrote another extension method to do that:</p>\n\n<pre><code>public static string ConvertXHTMLEntities(this string input)\n{\n // Convert all ampersands to the ampersand entity.\n string output = input;\n output = output.Replace(\"&amp;amp;\", \"amp_token\");\n output = output.Replace(\"&amp;\", \"&amp;amp;\");\n output = output.Replace(\"amp_token\", \"&amp;amp;\");\n\n // Convert less than to the less than entity (without messing up tags).\n output = output.Replace(\"&lt; \", \"&amp;lt; \");\n return output;\n}\n</code></pre>\n\n<p>Now I can take a user submitted string and check that it doesn't contain HTML using the following code:</p>\n\n<pre><code>bool ContainsHTML = UserEnteredString.ConvertXHTMLEntities().ContainsXHTML();\n</code></pre>\n\n<p>I'm not sure if this is bullet proof, but I think it's good enough for my situation.</p>\n" }, { "answer_id": 5281021, "author": "Mark", "author_id": 413653, "author_profile": "https://Stackoverflow.com/users/413653", "pm_score": 0, "selected": false, "text": "<p>Beware when using the HttpUtility.HtmlEncode method mentioned above. If you are checking some text with special characters, but not HTML, it will evaluate incorrectly. Maybe that's why J c used \"...depending on how strict you want the check to be...\"</p>\n" }, { "answer_id": 27448890, "author": "kns98", "author_id": 3583192, "author_profile": "https://Stackoverflow.com/users/3583192", "pm_score": 3, "selected": false, "text": "<p>this also checks for things like &lt; br /> self enclosed tags with optional whitespace. the list does not contain new html5 tags.</p>\n\n<pre><code>internal static class HtmlExts\n{\n public static bool containsHtmlTag(this string text, string tag)\n {\n var pattern = @\"&lt;\\s*\" + tag + @\"\\s*\\/?&gt;\";\n return Regex.IsMatch(text, pattern, RegexOptions.IgnoreCase);\n }\n\n public static bool containsHtmlTags(this string text, string tags)\n {\n var ba = tags.Split('|').Select(x =&gt; new {tag = x, hastag = text.containsHtmlTag(x)}).Where(x =&gt; x.hastag);\n\n return ba.Count() &gt; 0;\n }\n\n public static bool containsHtmlTags(this string text)\n {\n return\n text.containsHtmlTags(\n \"a|abbr|acronym|address|area|b|base|bdo|big|blockquote|body|br|button|caption|cite|code|col|colgroup|dd|del|dfn|div|dl|DOCTYPE|dt|em|fieldset|form|h1|h2|h3|h4|h5|h6|head|html|hr|i|img|input|ins|kbd|label|legend|li|link|map|meta|noscript|object|ol|optgroup|option|p|param|pre|q|samp|script|select|small|span|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|ul|var\");\n }\n}\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/203/" ]
Does anyone have a simple, efficient way of checking that a string doesn't contain HTML? Basically, I want to check that certain fields only contain plain text. I thought about looking for the < character, but that can easily be used in plain text. Another way might be to create a new System.Xml.Linq.XElement using: ``` XElement.Parse("<wrapper>" + MyString + "</wrapper>") ``` and check that the XElement contains no child elements, but this seems a little heavyweight for what I need.
I just tried my XElement.Parse solution. I created an extension method on the string class so I can reuse the code easily: ``` public static bool ContainsXHTML(this string input) { try { XElement x = XElement.Parse("<wrapper>" + input + "</wrapper>"); return !(x.DescendantNodes().Count() == 1 && x.DescendantNodes().First().NodeType == XmlNodeType.Text); } catch (XmlException ex) { return true; } } ``` One problem I found was that plain text ampersand and less than characters cause an XmlException and indicate that the field contains HTML (which is wrong). To fix this, the input string passed in first needs to have the ampersands and less than characters converted to their equivalent XHTML entities. I wrote another extension method to do that: ``` public static string ConvertXHTMLEntities(this string input) { // Convert all ampersands to the ampersand entity. string output = input; output = output.Replace("&amp;", "amp_token"); output = output.Replace("&", "&amp;"); output = output.Replace("amp_token", "&amp;"); // Convert less than to the less than entity (without messing up tags). output = output.Replace("< ", "&lt; "); return output; } ``` Now I can take a user submitted string and check that it doesn't contain HTML using the following code: ``` bool ContainsHTML = UserEnteredString.ConvertXHTMLEntities().ContainsXHTML(); ``` I'm not sure if this is bullet proof, but I think it's good enough for my situation.
204,653
<p>Using a web service is often an excellent architectural approach. And, with the advent of WCF in .Net, it's getting even better.</p> <p>But, in my experience, some people seem to think that web services should always be used in the data access layer for calls to the database. I don't think that web services are the universal solution.</p> <p>I am thinking of smaller intranet applications with a few dozen users. The web app and its web service are deployed to one web server, not a web farm. There isn't going to be another web app in the future that can use this particular web service. It seems to me that the cost of calling the web service unnecessarily increases the burden on the web server. There is a performance hit to inter-process calls. Maintaining and debugging the code for the web app and the web service is more complicated. So is deployment. I just don't see the advantages of using a web service here.</p> <p>One could test this by creating two versions of the web app, with and without the web service, and do stress testing, but I haven't done it.</p> <p>Do you have an opinion on using web services for small-scale web app's? Any other occasions when web services are not a good architectural choice?</p>
[ { "answer_id": 204680, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": 3, "selected": false, "text": "<p>If you are just coding a tiny (less than 50 users) web application for your intranet, a web service seems overkill. Especially if its primary function (providing a single point of access to many services) won't be used.</p>\n" }, { "answer_id": 204689, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 2, "selected": false, "text": "<p>For a small-scale web app (You have to ask the question, \"Will it always remain small scale?\" though) using web services, separate business layers, data layers, and so on and so forth can be overkill.</p>\n\n<p>Before anyone shoots me, I do agree that separation of logic between layers along with unit tests, continuous integration, et al are bloody brilliant. In my current role I'd be utterly lost and rocking in the corner without them. However for a very small-scale web app being used to, for example, track contact numbers and addresses for a company of 36 employees, the cost/benefit analysis would suggest that all the \"niceties\" listed above would be overkill.</p>\n\n<p>However... Remember to ask the question \"Will it always remain small scale?\" :-)</p>\n" }, { "answer_id": 204691, "author": "MBoy", "author_id": 15511, "author_profile": "https://Stackoverflow.com/users/15511", "pm_score": 2, "selected": false, "text": "<p>I agree that the use of a web service in a small scale web app adds a layer of complexity that does not seem justified. Most of my solutions, internet and intranet, 10-50 users, do not employ web services. I am glad others feel the same...I thought I was the only one.</p>\n" }, { "answer_id": 204713, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 6, "selected": true, "text": "<p>Web Services are an absolutely horrible choice for data access. It's a ton of overhead and complexity for almost zero benefit.</p>\n\n<p>If your app is going to run on one machine, why deny it the ability to do in-process data access calls? I'm not talking about directly accessing the database from your UI code, I'm talking about abstracting your repositories away but still including their assemblies in your running web site.</p>\n\n<p>There are cases where I'd recommend web services (and I'm assuming you mean SOAP) but that's mostly for interoperability.</p>\n\n<p>The granularity of the services is also in question here. A service in the SOA sense will encapsulate an operation or a business process. Data access methods are only part of that process.</p>\n\n<p>In other words:</p>\n\n<pre><code> - someService.SaveOrder(order); // &lt;-- bad\n // some other code for shipping, charging, emailing, etc\n\n - someService.FulfillOrder(order); //&lt;-- better\n //the service encapsulates the entire process\n</code></pre>\n\n<p>Web services for the sake of web services is irresponsible programming.</p>\n" }, { "answer_id": 204731, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 3, "selected": false, "text": "<p>Just because the tool generates a bunch of stubs doesn't mean it's a good use. WS-* excels in scenarios where you expose <em>services</em> to external parties. This means that each operation should be on the granularity of business process as opposed to data access.</p>\n\n<p>The multitude of standards can be used to describe different facets of your contract in great detail and a (hypothetical) fully compliant WS stack can take away a lot of pain from the third party developers and even allow the fabled point and click integration a'la Yahoo Pipes. With good governance controls you can evolve your public interface and manage the backward compatibility as needed. </p>\n\n<p>All this is next to impossible to be generated automatically. The C# stub generator knows only the physical interface of your class, but doesn't have any idea about the semantics involved. See <a href=\"http://www.hpl.hp.com/techreports/2005/HPL-2005-83.pdf\" rel=\"noreferrer\">this paper</a> for more detailed discussion.</p>\n\n<p>If you are building a web site, then build a web site. If you want asynchronous messaging inside your application, use <a href=\"http://en.wikipedia.org/wiki/MSMQ\" rel=\"noreferrer\">MSMQ</a>. If you want to expose data to internal clients, use <a href=\"http://en.wikipedia.org/wiki/Plain_Old_XML\" rel=\"noreferrer\">POX</a>. If you need efficient binary message format, check Google's <a href=\"http://code.google.com/p/protobuf/\" rel=\"noreferrer\">Protocol Buffers</a> or if you need RPC check <a href=\"http://www.hessiancsharp.org/\" rel=\"noreferrer\">Hessian for C#</a> or DCOM.</p>\n\n<p>Web services are a coarse grained integration solution. They are rigid, they are slower than alternatives, they take too much effort to do well (and when not done well are next to pointless). </p>\n\n<p>To summarize: \"When should a web service <strong>not</strong> be used?\" - anytime you can get away without it</p>\n" }, { "answer_id": 204792, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 4, "selected": false, "text": "<p>Nick Harrison, a brilliant developer in Charlotte, suggested these scenarios where using a web service makes sense:</p>\n\n<ul>\n<li>On a Web farm, where there are multiple web servers hosting website(s), all pointing to web service(s) running on another web server. This allows for distributing the load over multiple servers.</li>\n<li>Client/server, where Windows forms apps can call a web service.</li>\n<li>Cross platform</li>\n<li>Passing through a firewall</li>\n</ul>\n" }, { "answer_id": 1266663, "author": "Matthew", "author_id": 65519, "author_profile": "https://Stackoverflow.com/users/65519", "pm_score": 2, "selected": false, "text": "<p>For a small scale web app I think that using web services is often quite a good idea, you can use it to easily decouple the web server from the data tier. With the straightofrward development requirements and great tooling I don't see the problem.</p>\n\n<p>However <strong>don't</strong> use web services in the following scenarios:</p>\n\n<ul>\n<li>When you must use Http as the transport and Xml serialization of your data and you need lots of different bits of data, synchronously and often. Whether REST or SOAP or WS-* you're going to suffer performance issues. The more calls you make the slower your system will be. If you want medium size chunks of data less frequently, asynchronously and you can use straight TcpIp (e.g. Wcf netTcpBinding) you'd be better off.</li>\n<li>When you need to query and join data from your web service with other data sources, rather motivate for a data warehouse which can be populated with properly consolidated and rationalized data from across the enterprize</li>\n</ul>\n\n<p>This is my experience, hope it helps.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27637/" ]
Using a web service is often an excellent architectural approach. And, with the advent of WCF in .Net, it's getting even better. But, in my experience, some people seem to think that web services should always be used in the data access layer for calls to the database. I don't think that web services are the universal solution. I am thinking of smaller intranet applications with a few dozen users. The web app and its web service are deployed to one web server, not a web farm. There isn't going to be another web app in the future that can use this particular web service. It seems to me that the cost of calling the web service unnecessarily increases the burden on the web server. There is a performance hit to inter-process calls. Maintaining and debugging the code for the web app and the web service is more complicated. So is deployment. I just don't see the advantages of using a web service here. One could test this by creating two versions of the web app, with and without the web service, and do stress testing, but I haven't done it. Do you have an opinion on using web services for small-scale web app's? Any other occasions when web services are not a good architectural choice?
Web Services are an absolutely horrible choice for data access. It's a ton of overhead and complexity for almost zero benefit. If your app is going to run on one machine, why deny it the ability to do in-process data access calls? I'm not talking about directly accessing the database from your UI code, I'm talking about abstracting your repositories away but still including their assemblies in your running web site. There are cases where I'd recommend web services (and I'm assuming you mean SOAP) but that's mostly for interoperability. The granularity of the services is also in question here. A service in the SOA sense will encapsulate an operation or a business process. Data access methods are only part of that process. In other words: ``` - someService.SaveOrder(order); // <-- bad // some other code for shipping, charging, emailing, etc - someService.FulfillOrder(order); //<-- better //the service encapsulates the entire process ``` Web services for the sake of web services is irresponsible programming.
204,670
<p>If I query a table with a condition on the key field as in:</p> <pre><code> var user = from u in dc.Users where u.UserName == usn select u; </code></pre> <p>I know that I will either get zero results or one result. Should I still go ahead and retrieve the results using a for-each or is there another preferred way to handle this kind of situation. </p>
[ { "answer_id": 204678, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 4, "selected": false, "text": "<p>Why not something like</p>\n\n<pre><code>var user = dc.Users.SingleOrDefault(u=&gt; u.UserName==usn);\n</code></pre>\n" }, { "answer_id": 204679, "author": "Joel Cunningham", "author_id": 5360, "author_profile": "https://Stackoverflow.com/users/5360", "pm_score": 1, "selected": false, "text": "<p>I would use the SingleOrDefault method.</p>\n\n<pre><code>var user = (from u in dc.Users\n where u.UserName == usn\n select u).SingleOrDefault();\n</code></pre>\n" }, { "answer_id": 204681, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 7, "selected": true, "text": "<p>Try something like this:</p>\n\n<pre><code>var user = (from u in dc.Users\n where u.UserName == usn\n select u).FirstOrDefault();\n</code></pre>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/bb549141.aspx\" rel=\"noreferrer\">FirstOrDefault</a> method returns the first element of a sequence that satisfies a specified condition or a default value if no such element is found.</p>\n" }, { "answer_id": 204686, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 2, "selected": false, "text": "<p>I would use First() or FirstOrDefault().</p>\n\n<p>The difference: on First() there will be an exception thrown if no row can be found.</p>\n" }, { "answer_id": 204707, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<p>Also it should be noted that First/FirstOrDefault/Single/SingleOrDefault are the point of execution for a LINQ to Sql command. Since the LINQ statement has not been executed before that, it is able to affect the SQL generated (e.g., It can add a TOP 1 to the sql command)</p>\n" }, { "answer_id": 31032731, "author": "Just Trying to Help", "author_id": 5045632, "author_profile": "https://Stackoverflow.com/users/5045632", "pm_score": 0, "selected": false, "text": "<p>Another option is to use Contains(username) as opposed to \"==\"</p>\n\n<pre><code>var user = (from u in dc.UserInfo \n where u.Users.Contains(username) \n select u).SingleOrDefault();\n</code></pre>\n" }, { "answer_id": 74086619, "author": "Abhishek Panchal", "author_id": 20191073, "author_profile": "https://Stackoverflow.com/users/20191073", "pm_score": 0, "selected": false, "text": "<p>Summarized from <a href=\"https://www.c-sharpcorner.com/Blogs/first-firstordefault-single-singleordefault-in-c-sharp\" rel=\"nofollow noreferrer\">here</a>:</p>\n<ol>\n<li><p><code>First()</code>\nIt returns the first element of a sequence.\nIt throws an error when there is no element in the result, or source is null.\nWe should use it if more than one element is expected and you want only the first\nelement.</p>\n</li>\n<li><p><code>FirstOrDefault()</code>\nIt returns the first element of a sequence, or a default value if no element is\nfound.\nIt throws an error only if the source is null.\nWe should use it if more than one element is expected and you want only the first\nelement. It's also good if the result is empty.</p>\n</li>\n<li><p><code>Single()</code>\nIt returns the only item of a sequence.\nThis will throw an exception if the result contains 0 or more than 1 elements.\nWe should use it, when we know that exactly one element is expected but neither 0\nnor 2 or more.</p>\n</li>\n<li><p><code>SingleOrDefault()</code>\nIt returns single specific element, and if the element is not found, it returns\nthe default value of it.\nThis will throw an exception if the result contains 2 or more elements.\nWe should use it when we know that 0 or 1 element is expected as result.</p>\n</li>\n</ol>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26140/" ]
If I query a table with a condition on the key field as in: ``` var user = from u in dc.Users where u.UserName == usn select u; ``` I know that I will either get zero results or one result. Should I still go ahead and retrieve the results using a for-each or is there another preferred way to handle this kind of situation.
Try something like this: ``` var user = (from u in dc.Users where u.UserName == usn select u).FirstOrDefault(); ``` The [FirstOrDefault](http://msdn.microsoft.com/en-us/library/bb549141.aspx) method returns the first element of a sequence that satisfies a specified condition or a default value if no such element is found.
204,676
<p>I'm about to release a set of Eclipse plug-ins as Open Source and noticed that most source code released under the LGPL/EPL contains a header banner in each file that refers to the license or contains the license itself.</p> <p>Since adding these banners to each file manually seems to be a daunting and error-prone task. How can I go about automating the insertion of these banners?</p> <p><strong><em>Edit:</em></strong> I've eventually found <a href="https://marketplace.eclipse.org/content/copyright-wizard" rel="nofollow noreferrer">Copyright Wizard</a> and <a href="https://marketplace.eclipse.org/content/eclipse-copyright-generator" rel="nofollow noreferrer">Copyright Generator</a> which are Eclipse plug-ins which also allow for updating existing license banners.</p>
[ { "answer_id": 204928, "author": "idrosid", "author_id": 17876, "author_profile": "https://Stackoverflow.com/users/17876", "pm_score": 3, "selected": false, "text": "<p>Concerning best practises, I believe you should have your license text in a separate file and have a build tool (ie ant) to add it at the beginning of all other files. Since you are talking about an open source project you would need a build process anyway for thinks like generating the javadocs, publishing releases etc.</p>\n\n<p>BTW,ant tasks are simple Java classes so it should be easy to write one yourself if you don't find an ant plugin that does exactly that.</p>\n\n<p>Coming to eclipse, to my knowledge, it cannot do something like this. The quickest way I can think of to do it is with bash (if you are using Linux). Assume the file msg contains the text you want to add at the beginning of every file.</p>\n\n<ol>\n<li><p>Create a new directory to store the files:</p>\n\n<p>mkdir ~/outdir</p></li>\n<li><p>Add the msg at the beginning of every file and put the result at the outdir </p>\n\n<p>for i in <code>ls \"*.java\"</code>; do cat msg $i > ~/outdir/$i ; done</p></li>\n</ol>\n\n<p>Similarly you can write a command that does the same recursively, with an extra step to create the directory strucutre:</p>\n\n<pre><code>mkdir ~/outdir\nfor i in `find -type d | sed 's/\\.//' | grep -v \"^$\"`; do mkdir ~/outdir$i; done\nfor i in `find -name \"*.java\"`; do cat msg $i &gt; ~/outdir/$i ; done\n</code></pre>\n" }, { "answer_id": 206602, "author": "Chris R", "author_id": 23309, "author_profile": "https://Stackoverflow.com/users/23309", "pm_score": 2, "selected": false, "text": "<p>A more Eclipse-like approach than the manual addition is the following, done via GUI in Eclipse. Note that these are the Linux / Windows menus; Mac is a bit different.</p>\n\n<ol>\n<li>Open <code>Windows-&gt;Preferences</code></li>\n<li>Navigate to <code>Java-&gt;Code Style-&gt;Code Templates</code></li>\n<li>Edit the <code>Comments-&gt;Files</code> comment template to include your boilerplate.<br>\nThere are variables for the current year, file name, etc...</li>\n</ol>\n\n<p>Note, also, that this is a solution for new files only; it's not going to help you with old files; for that, I would use something like idrosid's solution for your existing code</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4445/" ]
I'm about to release a set of Eclipse plug-ins as Open Source and noticed that most source code released under the LGPL/EPL contains a header banner in each file that refers to the license or contains the license itself. Since adding these banners to each file manually seems to be a daunting and error-prone task. How can I go about automating the insertion of these banners? ***Edit:*** I've eventually found [Copyright Wizard](https://marketplace.eclipse.org/content/copyright-wizard) and [Copyright Generator](https://marketplace.eclipse.org/content/eclipse-copyright-generator) which are Eclipse plug-ins which also allow for updating existing license banners.
Concerning best practises, I believe you should have your license text in a separate file and have a build tool (ie ant) to add it at the beginning of all other files. Since you are talking about an open source project you would need a build process anyway for thinks like generating the javadocs, publishing releases etc. BTW,ant tasks are simple Java classes so it should be easy to write one yourself if you don't find an ant plugin that does exactly that. Coming to eclipse, to my knowledge, it cannot do something like this. The quickest way I can think of to do it is with bash (if you are using Linux). Assume the file msg contains the text you want to add at the beginning of every file. 1. Create a new directory to store the files: mkdir ~/outdir 2. Add the msg at the beginning of every file and put the result at the outdir for i in `ls "*.java"`; do cat msg $i > ~/outdir/$i ; done Similarly you can write a command that does the same recursively, with an extra step to create the directory strucutre: ``` mkdir ~/outdir for i in `find -type d | sed 's/\.//' | grep -v "^$"`; do mkdir ~/outdir$i; done for i in `find -name "*.java"`; do cat msg $i > ~/outdir/$i ; done ```
204,682
<p>I want to limit the number of words a person can enter in a text field. How can I track the number of words (by using a second field) in that field as each word is entered?</p>
[ { "answer_id": 206708, "author": "Ichorus", "author_id": 27247, "author_profile": "https://Stackoverflow.com/users/27247", "pm_score": 0, "selected": false, "text": "<p>From <a href=\"http://www.mediacollege.com\" rel=\"nofollow noreferrer\">Media College</a> :</p>\n\n<p><a href=\"http://www.mediacollege.com/internet/javascript/form/limit-characters.html\" rel=\"nofollow noreferrer\">Limit the Number of Characters in a Textarea or Text Field in javaScript </a></p>\n" }, { "answer_id": 2408592, "author": "Phil Rykoff", "author_id": 284364, "author_profile": "https://Stackoverflow.com/users/284364", "pm_score": 2, "selected": false, "text": "<p>use this js (using jquery):</p>\n\n<pre><code>$('#newKeywords').bind('change', function() {\n\n $('#wordsLong').text($('#newKeywords').val().split(' ').length + 1);\n\n});\n</code></pre>\n\n<p>and this html:</p>\n\n<pre><code>&lt;textarea id=\"newKeywords\"&gt;&lt;/textarea&gt;\n&lt;div&gt;The text consists of &lt;span id=\"wordsLong\"&gt;&lt;/span&gt; keywords.&lt;/div&gt;\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to limit the number of words a person can enter in a text field. How can I track the number of words (by using a second field) in that field as each word is entered?
use this js (using jquery): ``` $('#newKeywords').bind('change', function() { $('#wordsLong').text($('#newKeywords').val().split(' ').length + 1); }); ``` and this html: ``` <textarea id="newKeywords"></textarea> <div>The text consists of <span id="wordsLong"></span> keywords.</div> ```
204,695
<p>I'm writing a page that can use a couple of different themes, and I'm going to store some information about each theme in the web.config. </p> <p>Is it more efficient to create a new sectionGroup and store everything together, or just put everything in appSettings?</p> <p><b>configSection solution</b></p> <pre><code>&lt;configSections&gt; &lt;sectionGroup name="SchedulerPage"&gt; &lt;section name="Providers" type="System.Configuration.NameValueSectionHandler"/&gt; &lt;section name="Themes" type="System.Configuration.NameValueSectionHandler"/&gt; &lt;/sectionGroup&gt; &lt;/configSections&gt; &lt;SchedulerPage&gt; &lt;Themes&gt; &lt;add key="PI" value="PISchedulerForm"/&gt; &lt;add key="UB" value="UBSchedulerForm"/&gt; &lt;/Themes&gt; &lt;/SchedulerPage&gt; </code></pre> <p>To access values in the configSection, I am using this code:</p> <pre><code> NameValueCollection themes = ConfigurationManager.GetSection("SchedulerPage/Themes") as NameValueCollection; String SchedulerTheme = themes["UB"]; </code></pre> <p><b>appSettings solution</b></p> <pre><code>&lt;appSettings&gt; &lt;add key="PITheme" value="PISchedulerForm"/&gt; &lt;add key="UBTheme" value="UBSchedulerForm"/&gt; &lt;/appSettings&gt; </code></pre> <p>To access values in appSettings, I am using this code</p> <pre><code> String SchedulerTheme = ConfigurationManager.AppSettings["UBSchedulerForm"].ToString(); </code></pre>
[ { "answer_id": 204703, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "<p>There will be no measurable difference in terms of efficiency.</p>\n\n<p>AppSettings is great if all you need are name/value pairs.</p>\n\n<p>For anything more complex, it's worth creating a custom configuration section.</p>\n\n<p>For the example you mention, I'd use appSettings.</p>\n" }, { "answer_id": 204745, "author": "Nick Allen", "author_id": 12918, "author_profile": "https://Stackoverflow.com/users/12918", "pm_score": 5, "selected": true, "text": "<p>For more complex configuration setup, I would use a custom configuration section that clearly defines the roles of each section for example</p>\n\n<pre><code>&lt;appMonitoring enabled=\"true\" smtpServer=\"xxx\"&gt;\n &lt;alertRecipients&gt;\n &lt;add name=\"me\" email=\"[email protected]\"/&gt;\n &lt;/alertRecipient&gt;\n&lt;/appMonitoring&gt;\n</code></pre>\n\n<p>In your configuration class you can expose your properties with something like</p>\n\n<pre><code>public class MonitoringConfig : ConfigurationSection\n{\n [ConfigurationProperty(\"smtp\", IsRequired = true)]\n public string Smtp\n {\n get { return this[\"smtp\"] as string; }\n }\n public static MonitoringConfig GetConfig()\n {\n return ConfigurationManager.GetSection(\"appMonitoring\") as MonitoringConfig\n }\n}\n</code></pre>\n\n<p>You can then access configuration properties in the following way from your code</p>\n\n<pre><code>string smtp = MonitoringConfig.GetConfig().Smtp;\n</code></pre>\n" }, { "answer_id": 204764, "author": "stevemegson", "author_id": 25028, "author_profile": "https://Stackoverflow.com/users/25028", "pm_score": 3, "selected": false, "text": "<p>There'll be no difference in performance, since ConfigurationManager.AppSettings just calls GetSection(\"appSettings\") anyway. If you'll need to enumerate all the keys, then a custom section will be nicer than enumerating all of appSettings and looking for some prefix on the keys, but otherwise it's easier to stick to appSettings unless you need something more complex than a NameValueCollection.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3018/" ]
I'm writing a page that can use a couple of different themes, and I'm going to store some information about each theme in the web.config. Is it more efficient to create a new sectionGroup and store everything together, or just put everything in appSettings? **configSection solution** ``` <configSections> <sectionGroup name="SchedulerPage"> <section name="Providers" type="System.Configuration.NameValueSectionHandler"/> <section name="Themes" type="System.Configuration.NameValueSectionHandler"/> </sectionGroup> </configSections> <SchedulerPage> <Themes> <add key="PI" value="PISchedulerForm"/> <add key="UB" value="UBSchedulerForm"/> </Themes> </SchedulerPage> ``` To access values in the configSection, I am using this code: ``` NameValueCollection themes = ConfigurationManager.GetSection("SchedulerPage/Themes") as NameValueCollection; String SchedulerTheme = themes["UB"]; ``` **appSettings solution** ``` <appSettings> <add key="PITheme" value="PISchedulerForm"/> <add key="UBTheme" value="UBSchedulerForm"/> </appSettings> ``` To access values in appSettings, I am using this code ``` String SchedulerTheme = ConfigurationManager.AppSettings["UBSchedulerForm"].ToString(); ```
For more complex configuration setup, I would use a custom configuration section that clearly defines the roles of each section for example ``` <appMonitoring enabled="true" smtpServer="xxx"> <alertRecipients> <add name="me" email="[email protected]"/> </alertRecipient> </appMonitoring> ``` In your configuration class you can expose your properties with something like ``` public class MonitoringConfig : ConfigurationSection { [ConfigurationProperty("smtp", IsRequired = true)] public string Smtp { get { return this["smtp"] as string; } } public static MonitoringConfig GetConfig() { return ConfigurationManager.GetSection("appMonitoring") as MonitoringConfig } } ``` You can then access configuration properties in the following way from your code ``` string smtp = MonitoringConfig.GetConfig().Smtp; ```
204,711
<p>Of the two methods below, which do you prefer to read?<br> Is there another (better?) way to check if a flag is set?</p> <pre><code> bool CheckFlag(FooFlag fooFlag) { return fooFlag == (this.Foo &amp; fooFlag); } </code></pre> <p>And</p> <pre><code> bool CheckFlag(FooFlag fooFlag) { return (this.Foo &amp; fooFlag) != 0; } </code></pre> <p><hr/> Please vote up the method you prefer.</p>
[ { "answer_id": 204723, "author": "Enrico Murru", "author_id": 68336, "author_profile": "https://Stackoverflow.com/users/68336", "pm_score": 2, "selected": false, "text": "<p>i prefer the first one because it's more readable.</p>\n" }, { "answer_id": 204725, "author": "coder1", "author_id": 3018, "author_profile": "https://Stackoverflow.com/users/3018", "pm_score": 1, "selected": false, "text": "<p>I prefer the first one. I use !=0 sparingly in boolean expressions.</p>\n" }, { "answer_id": 204726, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": false, "text": "<pre><code>bool CheckFlag(FooFlag fooFlag)\n{\n return fooFlag == (this.Foo &amp; fooFlag);\n}\n</code></pre>\n" }, { "answer_id": 204727, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 2, "selected": false, "text": "<pre><code>bool CheckFlag(FooFlag fooFlag)\n{\n return (this.Foo &amp; fooFlag) != 0;\n}\n</code></pre>\n" }, { "answer_id": 204728, "author": "Phil Reif", "author_id": 20244, "author_profile": "https://Stackoverflow.com/users/20244", "pm_score": -1, "selected": false, "text": "<p>I'm a positive thinker:</p>\n\n<pre><code>bool CheckFlag(FooFlag fooFlag)\n{\n return this.Foo &amp; fooFlag == 1;\n}\n</code></pre>\n" }, { "answer_id": 204772, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 4, "selected": true, "text": "<p>The two expressions do different things (if fooFlag has more than one bit set), so which one is better really depends on the behavior you want:</p>\n\n<pre><code>fooFlag == (this.Foo &amp; fooFlag) // result is true iff all bits in fooFlag are set\n\n\n(this.Foo &amp; fooFlag) != 0 // result is true if any bits in fooFlag are set\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14484/" ]
Of the two methods below, which do you prefer to read? Is there another (better?) way to check if a flag is set? ``` bool CheckFlag(FooFlag fooFlag) { return fooFlag == (this.Foo & fooFlag); } ``` And ``` bool CheckFlag(FooFlag fooFlag) { return (this.Foo & fooFlag) != 0; } ``` --- Please vote up the method you prefer.
The two expressions do different things (if fooFlag has more than one bit set), so which one is better really depends on the behavior you want: ``` fooFlag == (this.Foo & fooFlag) // result is true iff all bits in fooFlag are set (this.Foo & fooFlag) != 0 // result is true if any bits in fooFlag are set ```
204,733
<p>I am constructing a search page with a textbox and a button for now, and probably a dropdown to filter results later on. I have my button's PostBackUrl set to my search page (~/search.aspx). Is there an easy way to pass the value in the text box to the search page?</p>
[ { "answer_id": 204776, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 0, "selected": false, "text": "<p>you may be able to use useSubmitBehavior=\"true\" and put a method=\"get\" on the form. that way it will use the browsers submit behavior and will append the values of the textbox's to the query string</p>\n" }, { "answer_id": 204816, "author": "Andy May", "author_id": 12367, "author_profile": "https://Stackoverflow.com/users/12367", "pm_score": 0, "selected": false, "text": "<p>You could also use some JavaScript to accomplish this by catching the Enter key keypress event in the textbox field. You could expand this to perform validation of the text in the textbox as well. (This example is using <a href=\"http://jquery.com\" rel=\"nofollow noreferrer\">jQuery</a>)</p>\n\n<pre><code>$(document).ready(function(){\n // Event Handlers to allow searching after pressing Enter key\n $(\"#myTextBoxID\").bind(\"keypress\", function(e){\n switch (e.keyCode){\n case (13):\n // Execute code here ...\n break;\n default:\n break;\n }\n });\n});\n</code></pre>\n" }, { "answer_id": 204917, "author": "Adam Nofsinger", "author_id": 18524, "author_profile": "https://Stackoverflow.com/users/18524", "pm_score": 4, "selected": true, "text": "<p>If you have the PostBackUrl set on your button, then the search box field on your first page, and any other form fields on that page, are already being posted to your search page. The trick is getting access to them in the code-behind for your search.aspx page.</p>\n\n<pre><code>if (Page.PreviousPage != null)\n{\n TextBox SourceTextBox = \n (TextBox)Page.PreviousPage.FindControl(\"TextBox1\");\n if (SourceTextBox != null)\n {\n Label1.Text = SourceTextBox.Text;\n }\n}\n</code></pre>\n\n<p>That is one way. There are some shortcuts too, such as using the PreviousPageType directive at the top of your search.aspx page:</p>\n\n<pre><code>&lt;%@ PreviousPageType VirtualPath=\"~/SourcePage.aspx\" %&gt; \n</code></pre>\n\n<p>More details on how to use that, as well as the first method, can be found here:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms178139.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms178139.aspx</a></p>\n" }, { "answer_id": 204960, "author": "Anders", "author_id": 25515, "author_profile": "https://Stackoverflow.com/users/25515", "pm_score": 0, "selected": false, "text": "<p>Solved the issue, the previous page is \"default.aspx\", however the control doesn't reside on that page. Since I use master pages, I have to select <strong>Master</strong> rather than <strong>PreviousPage</strong>.</p>\n\n<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n If PreviousPage IsNot Nothing Then\n Dim txtBoxSrc As New TextBox\n txtBoxSrc = CType(Master.FindControl(\"searchbox\"), TextBox)\n If txtBoxSrc IsNot Nothing Then\n MsgBox(txtBoxSrc.Text)\n End If\n End If\nEnd Sub\n\n&lt;div class=\"gsSearch\"&gt;\n &lt;asp:TextBox ID=\"searchbox\" runat=\"server\"&gt;&lt;/asp:TextBox&gt;\n &lt;asp:Button ID=\"searchbutton\" runat=\"server\" Text=\"search\" \n UseSubmitBehavior=\"true\" PostBackUrl=\"~/search.aspx\" /&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 205052, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 0, "selected": false, "text": "<p>I have no idea why you would get a null reference in that code, bare with my VB non-knowledge, but I'm going to try to make a slight modification you might be able to try. </p>\n\n<p>I know that the FindControl returns the type Control.. maybe you can wait to box it into a specific type.</p>\n\n<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n If PreviousPage IsNot Nothing Then\n Dim txtBoxSrc As New Control\n txtBoxSrc = PreviousPage.FindControl(\"searchbox\")\n If txtBoxSrc IsNot Nothing Then\n MsgBox((CType(txtBoxSrc, TextBox)).Text)\n End If\n End If\nEnd Sub\n\n&lt;div class=\"gsSearch\"&gt;\n &lt;asp:TextBox ID=\"searchbox\" runat=\"server\"&gt;&lt;/asp:TextBox&gt;\n &lt;asp:Button ID=\"searchbutton\" runat=\"server\" Text=\"search\" \n UseSubmitBehavior=\"true\" PostBackUrl=\"~/search.aspx\" /&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 10466356, "author": "bgmCoder", "author_id": 1038866, "author_profile": "https://Stackoverflow.com/users/1038866", "pm_score": 0, "selected": false, "text": "<p>What about, this (vb, sorry):</p>\n\n<p>Get the value from the text box via codebehind, and simply set the postbackurl on the control like this:</p>\n\n<pre><code>dim textval = SourceTextBox.text\ndim myparam = \"George\"\n\nsearchbutton.PostBackUrl = \"~/search.aspx?myparam=\" &amp; myparam\n</code></pre>\n\n<p>You can just put that in the function that handles the button click, no?</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
I am constructing a search page with a textbox and a button for now, and probably a dropdown to filter results later on. I have my button's PostBackUrl set to my search page (~/search.aspx). Is there an easy way to pass the value in the text box to the search page?
If you have the PostBackUrl set on your button, then the search box field on your first page, and any other form fields on that page, are already being posted to your search page. The trick is getting access to them in the code-behind for your search.aspx page. ``` if (Page.PreviousPage != null) { TextBox SourceTextBox = (TextBox)Page.PreviousPage.FindControl("TextBox1"); if (SourceTextBox != null) { Label1.Text = SourceTextBox.Text; } } ``` That is one way. There are some shortcuts too, such as using the PreviousPageType directive at the top of your search.aspx page: ``` <%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %> ``` More details on how to use that, as well as the first method, can be found here: <http://msdn.microsoft.com/en-us/library/ms178139.aspx>
204,737
<p>I have a lot of castle xml configs where properties like connectionstring are also held under .Net configuration sections.</p> <p>I'd like to be able to read out the properties using the container but can't see a mechanism to do it.</p> <p>ie </p> <pre><code>&lt;castle&gt; &lt;configuration&gt; &lt;properties&gt; &lt;connectionString&gt;Data Source=MyServer;Initial Catalog=YadaYada;User ID=me;Password=IAmGod&lt;/connectionString&gt; &lt;/properties&gt; &lt;components&gt; </code></pre> <p>...</p> <p>Obviously the properties are there as there are component dependencies on them. I can resolve the components but not the properties.</p> <p>Sure I could new up a component just to read out the property castle injected it, or I could wrap all the properties in a component specialised simply to hold name/val pairs. But I would have thought there be a simple container.resolve("property.connectionstring") notation.</p> <p>*Edit Not very good with markdown, above was meant to be a xml section.</p>
[ { "answer_id": 204835, "author": "Ronnie", "author_id": 193, "author_profile": "https://Stackoverflow.com/users/193", "pm_score": 1, "selected": false, "text": "<p>Aren't you thinking about this the wrong way round?</p>\n\n<p>Surely the object that is using the connection string should have a ConnectionString property in the constructor and the dependency pushed in there with something in the components section of config like:</p>\n\n<pre><code>&lt;component type=\"SessionManager\"&gt;\n &lt;parameters&gt;\n &lt;connectionString&gt;#{connectionString}&lt;/connectionString&gt;\n &lt;/parameters&gt;\n&lt;/component&gt;\n</code></pre>\n\n<p>That way the connection string will automatically be passed in and your component won't need to know about the container at all - decoupled and cohesive!!!</p>\n" }, { "answer_id": 232273, "author": "Bittercoder", "author_id": 4843, "author_profile": "https://Stackoverflow.com/users/4843", "pm_score": 2, "selected": false, "text": "<p>You could do this a few different ways - for a strongly typed solution the obvious approach would be to implement a custom configuration class, then wire up the properties of the class with the properties in the windsor config (read-only properties with a bunch of constructor arguments would probably be best, so other dev's don't think they can update them) - there's a little bit of work in keeping the two in sync as you pointed out. Maybe write a small tool to parse the configuration files to generate the windsor config / class definition for this component, so you don't need to maintain it.</p>\n\n<p>Another alternative would be to take the existing configuration interpreter and expose the properties that are collected while parsing the configuration - there would be a little bit of work (but not too much) to get at these .. I think you could do this by:</p>\n\n<ul>\n<li>Creating a decorator implementing IXmlProcessorEngine that captures calls to AddProperty(XmlElement element) and stores the elements in it's own private dictionary.</li>\n<li>Replace XmlProcessor with your own implementation (i.e. copy the source code for the class, then alter the constructor so that you wrap the decorator around the DefaultXmlProcessorEngine instance which is doing the actual work, so the various add-property calls are recorded).</li>\n<li>Inherit from XmlInterpreter and override the ProcessResource method so that it calls your XmlProcessor replacement.</li>\n<li>Decide how you want to get at the properties being stored by your decorator, perhaps it's configured with a dictionary that's passed in via constructor from the XmlInterpreter and XmlProcessor in turn..</li>\n</ul>\n\n<p>Unfortunately AFAIK those properties aren't passed on to the configuration store, because they're only used during the interpretation stage - plus I don't believe the type converters are invoked at this stage of the parsing, so the values will be strings, but at least the if/else etc. condition statements will be evaluated correctly, as well as includes.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a lot of castle xml configs where properties like connectionstring are also held under .Net configuration sections. I'd like to be able to read out the properties using the container but can't see a mechanism to do it. ie ``` <castle> <configuration> <properties> <connectionString>Data Source=MyServer;Initial Catalog=YadaYada;User ID=me;Password=IAmGod</connectionString> </properties> <components> ``` ... Obviously the properties are there as there are component dependencies on them. I can resolve the components but not the properties. Sure I could new up a component just to read out the property castle injected it, or I could wrap all the properties in a component specialised simply to hold name/val pairs. But I would have thought there be a simple container.resolve("property.connectionstring") notation. \*Edit Not very good with markdown, above was meant to be a xml section.
You could do this a few different ways - for a strongly typed solution the obvious approach would be to implement a custom configuration class, then wire up the properties of the class with the properties in the windsor config (read-only properties with a bunch of constructor arguments would probably be best, so other dev's don't think they can update them) - there's a little bit of work in keeping the two in sync as you pointed out. Maybe write a small tool to parse the configuration files to generate the windsor config / class definition for this component, so you don't need to maintain it. Another alternative would be to take the existing configuration interpreter and expose the properties that are collected while parsing the configuration - there would be a little bit of work (but not too much) to get at these .. I think you could do this by: * Creating a decorator implementing IXmlProcessorEngine that captures calls to AddProperty(XmlElement element) and stores the elements in it's own private dictionary. * Replace XmlProcessor with your own implementation (i.e. copy the source code for the class, then alter the constructor so that you wrap the decorator around the DefaultXmlProcessorEngine instance which is doing the actual work, so the various add-property calls are recorded). * Inherit from XmlInterpreter and override the ProcessResource method so that it calls your XmlProcessor replacement. * Decide how you want to get at the properties being stored by your decorator, perhaps it's configured with a dictionary that's passed in via constructor from the XmlInterpreter and XmlProcessor in turn.. Unfortunately AFAIK those properties aren't passed on to the configuration store, because they're only used during the interpretation stage - plus I don't believe the type converters are invoked at this stage of the parsing, so the values will be strings, but at least the if/else etc. condition statements will be evaluated correctly, as well as includes.
204,739
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword">Why does C# not provide the C++ style ‘friend’ keyword?</a> </p> </blockquote> <p>I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes. </p> <p>In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example?</p>
[ { "answer_id": 204744, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "<p>There's no direct equivalent of \"friend\" - the closest that's available (and it isn't very close) is <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx\" rel=\"noreferrer\">InternalsVisibleTo</a>. I've only ever used this attribute for testing - where it's very handy!</p>\n\n<p><strong>Example:</strong> To be placed in <code>AssemblyInfo.cs</code></p>\n\n<pre><code>[assembly: InternalsVisibleTo(\"OtherAssembly\")]\n</code></pre>\n" }, { "answer_id": 204782, "author": "RobG", "author_id": 28232, "author_profile": "https://Stackoverflow.com/users/28232", "pm_score": 4, "selected": false, "text": "<p>There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.</p>\n\n<p>Given a class with this definition:</p>\n\n<pre><code>public class Class1\n{\n private int CallMe()\n {\n return 1;\n }\n}\n</code></pre>\n\n<p>You can invoke it using this code:</p>\n\n<pre><code>Class1 c = new Class1();\nType class1Type = c.GetType();\nMethodInfo callMeMethod = class1Type.GetMethod(\"CallMe\", BindingFlags.Instance | BindingFlags.NonPublic);\n\nint result = (int)callMeMethod.Invoke(c, null);\n\nConsole.WriteLine(result);\n</code></pre>\n\n<p>If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting \"Create Unit Tests...\"</p>\n" }, { "answer_id": 6969249, "author": "Freddy mac", "author_id": 636037, "author_profile": "https://Stackoverflow.com/users/636037", "pm_score": 6, "selected": false, "text": "<p>Take a very common pattern. Class Factory makes Widgets. The Factory class needs to muck about with the internals, because, it is the Factory. Both are implemented in the same file and are, by design and desire and nature, tightly coupled classes -- in fact, Widget is really just an output type from factory.</p>\n\n<p>In C++, make the Factory a friend of Widget class.</p>\n\n<p>In C#, what can we do? The only decent solution that has occurred to me is to invent an interface, IWidget, which only exposes the public methods, and have the Factory return IWidget interfaces.</p>\n\n<p>This involves a fair amount of tedium - exposing all the naturally public properties again in the interface.</p>\n" }, { "answer_id": 10507130, "author": "sjp", "author_id": 1383194, "author_profile": "https://Stackoverflow.com/users/1383194", "pm_score": 7, "selected": false, "text": "<p>The closet equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:</p>\n<pre><code>class Outer\n{\n class Inner\n {\n // This class can access Outer's private members\n }\n}\n</code></pre>\n<p>or if you prefer to put the Inner class in another file:</p>\n<pre><code>Outer.cs\npartial class Outer\n{\n}\n\n\nInner.cs\npartial class Outer\n{\n class Inner\n {\n // This class can access Outer's private members\n }\n}\n</code></pre>\n" }, { "answer_id": 12350279, "author": "smartmobili", "author_id": 1659923, "author_profile": "https://Stackoverflow.com/users/1659923", "pm_score": 3, "selected": false, "text": "<p>You can simulate a friend access if the class that is given the right to access is inside another package and if the methods you are exposing are marked as internal or internal protected. You have to modify the assembly you want to share and add the following settings to AssemblyInfo.cs :</p>\n\n<pre><code>// Expose the internal members to the types in the My.Tester assembly\n[assembly: InternalsVisibleTo(\"My.Tester, PublicKey=\" +\n\"012700000480000094000000060200000024000052534131000400000100010091ab9\" +\n\"ba23e07d4fb7404041ec4d81193cfa9d661e0e24bd2c03182e0e7fc75b265a092a3f8\" +\n\"52c672895e55b95611684ea090e787497b0d11b902b1eccd9bc9ea3c9a56740ecda8e\" +\n\"961c93c3960136eefcdf106955a4eb8fff2a97f66049cd0228854b24709c0c945b499\" +\n\"413d29a2801a39d4c4c30bab653ebc8bf604f5840c88\")]\n</code></pre>\n\n<p>The public key is optional, depending on your needs.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22185/" ]
> > **Possible Duplicate:** > > [Why does C# not provide the C++ style ‘friend’ keyword?](https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword) > > > I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes. In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example?
There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is [InternalsVisibleTo](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx). I've only ever used this attribute for testing - where it's very handy! **Example:** To be placed in `AssemblyInfo.cs` ``` [assembly: InternalsVisibleTo("OtherAssembly")] ```
204,742
<p>Right now I'm working on a web application that receives a significant amount of data from a database that has a potential to return null results. When going through the cyclomatic complexity for the application a number of functions are weighing in between 10 - 30. For the most part the majority of the functions with the high numbers have a lot of lines similar to the following:</p> <pre><code>If Not oraData.IsDBNull(4) Then row("Field") = oraData.GetString(4) </code></pre> <p>Which leads me to my question, what is the best way to go about trying to bring these numbers down? Right now I'm looking at having the majority of the functions below 10. </p>
[ { "answer_id": 204769, "author": "jim", "author_id": 27628, "author_profile": "https://Stackoverflow.com/users/27628", "pm_score": 2, "selected": false, "text": "<p>The first question is: Why are you \"hung\" up on CC ? It's a tool to evaluate how dense the code is and a rule of thumb should be \"not too high of a cc number\".</p>\n\n<p>It's probably hitting all those \"IF\"s and bringing up that number - so reduce the number of ifs by calling a wrap function that extracts the data from the result set which handles the null or change the query so it doesn't return nulls.</p>\n\n<p>Keep in mind that nulls do provide information and are not useless. For example Republican or Democrat ? using null says neither choice.</p>\n" }, { "answer_id": 204783, "author": "Barry Carr", "author_id": 51820, "author_profile": "https://Stackoverflow.com/users/51820", "pm_score": 2, "selected": false, "text": "<p>Decompose into functions, perhaps something like this:</p>\n\n<pre><code>//Object Pascal\nprocedure UpdateIfNotNull( const fldName: String; fldIndex : integer );\nbegin\n if oraData.IsDBNull( fldIndex ) then\n row( fldName ) := oraData.GetString(fldIndex);\nend;\n</code></pre>\n\n<p>Of course you can extend the procedures signature so that \"oraData\" and \"row\" can passed as parameters.</p>\n" }, { "answer_id": 204795, "author": "Tom Carter", "author_id": 2839, "author_profile": "https://Stackoverflow.com/users/2839", "pm_score": 0, "selected": false, "text": "<p>It is possible to refactor the <strong>if</strong> into a separate utility function to reduce your CC. A number of functions or a function relying on type differentiation might be required to handle the different database types ( string, int etc ..)</p>\n\n<p>However, I would argue that any solution would result in less maintainable or readable code (i.e. you might worsen other metrics!) and would as QA allow it to pass according to this justification.</p>\n" }, { "answer_id": 204857, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": true, "text": "<p>What about using <a href=\"http://msdn.microsoft.com/en-us/library/bb384936.aspx\" rel=\"nofollow noreferrer\">Extension Methods</a>.</p>\n\n<pre><code>Imports System.Runtime.CompilerServices\n\nModule Extensions\n\n &lt;Extension()&gt; _\n Public Function TryGetString(ByVal row As IDataRecord, i As Integer) As String\n If row.IsDBNull(i) Then\n Return null\n End If\n Return row.GetString(i);\n End Function\n\nEnd Module\n</code></pre>\n\n<p>Then you can simply write:</p>\n\n<pre><code>row(\"Field\") = oraData.TryGetString(4)\n</code></pre>\n\n<p>This reads smoothly and reduces cyclomatic complexity on your functions.</p>\n" }, { "answer_id": 204925, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 1, "selected": false, "text": "<p>Did you see <a href=\"https://stackoverflow.com/questions/204369/seeking-clarifications-about-structuring-code-to-reduce-cyclomatic-complexity\">this question</a>? He's asking something similar (but I think at a more basic level) ... but then that means the answers there may not be much help here. </p>\n\n<p>I would definitely agree with the other suggestions here: if there are repeated statements that can be neatly packaged into functions/procedures, that might be one approach to take, as long as you're not just shifting CC around. I'm not sure you've gained too much if you move from one proc with a CC of 35 to three procs with CCs of 15, 10, and 10. (It's not a bad first step, but ideally you'd be able to simplify something on a larger scope to reduce total CC in that area of your system.)</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1185/" ]
Right now I'm working on a web application that receives a significant amount of data from a database that has a potential to return null results. When going through the cyclomatic complexity for the application a number of functions are weighing in between 10 - 30. For the most part the majority of the functions with the high numbers have a lot of lines similar to the following: ``` If Not oraData.IsDBNull(4) Then row("Field") = oraData.GetString(4) ``` Which leads me to my question, what is the best way to go about trying to bring these numbers down? Right now I'm looking at having the majority of the functions below 10.
What about using [Extension Methods](http://msdn.microsoft.com/en-us/library/bb384936.aspx). ``` Imports System.Runtime.CompilerServices Module Extensions <Extension()> _ Public Function TryGetString(ByVal row As IDataRecord, i As Integer) As String If row.IsDBNull(i) Then Return null End If Return row.GetString(i); End Function End Module ``` Then you can simply write: ``` row("Field") = oraData.TryGetString(4) ``` This reads smoothly and reduces cyclomatic complexity on your functions.
204,746
<p>For a web application, I want to build a WHERE clause AND submit it to the server. There I will append it to a query. The clause will be something like</p> <pre><code>LASTNAME LIKE 'Pep%' AND (DOB BETWEEN '19600101' AND '19601231 OR SALARY&lt;35000) </code></pre> <p>Can you propose a regular expression to validate the clause before submitting it to SQL Server?</p> <p>(Yes, of course, I would like a regex for the ORDER clause)</p>
[ { "answer_id": 204750, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 4, "selected": false, "text": "<p>This is a monumentally bad idea. I would suggest you build a filter system instead where the user can select all kinds of options in a form, and then you build the correct sql server-side instead of opening yourself up to all kinds of injection attacks.</p>\n\n<p>As an example of what might go wrong, consider this:</p>\n\n<pre><code>LASTNAME LIKE 'Pep%'--\nDROP TABLE People\n--\n</code></pre>\n\n<p>This will inject a DROP TABLE command into your SQL, which will be hard to detect. You can of course remove things like -- and /*, but I guarantee that someone can find a way in if you do this.</p>\n" }, { "answer_id": 204845, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 0, "selected": false, "text": "<p>The number of possibilities of elements in a where clause is immense. Obviously you've got your ANDs and ORs and BETWEENs and IN lists and other operators, plus parens, but you could also be calling system procedures, user-defined functions, and depending on the RDBMS you're working with, entire subqueries. Then there are queries that may be syntactically correct but are still illegal.</p>\n\n<p>A single regular expression to cover this would (a) be insanely big and (b) probably not cover all the cases. Not only do you <em>really</em> not want to do this, but it's likely not even possible.</p>\n" }, { "answer_id": 204903, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 0, "selected": false, "text": "<p>As has already been suggested, a regex is the wrong tool for the job, what you really need is an SQL parser. I don't know of any .Net SQL parsers, but I'm sure a Google search will turn up a few.</p>\n" }, { "answer_id": 204974, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 3, "selected": false, "text": "<p>You don't build </p>\n\n<pre><code>LASTNAME LIKE 'Pep%' AND (DOB BETWEEN '19600101' AND '19601231 OR SALARY&lt;35000)\n</code></pre>\n\n<p>you build</p>\n\n<pre><code>LASTNAME LIKE @LastName AND (DOB BETWEEN @dobStart AND @dobEnd OR SALARY&lt;@MaxSalary)\n</code></pre>\n\n<p>and pass in those guys as parameters. No Regex, no fuss.</p>\n" }, { "answer_id": 205017, "author": "Slapout", "author_id": 19072, "author_profile": "https://Stackoverflow.com/users/19072", "pm_score": 0, "selected": false, "text": "<p>You might want to take a look at <a href=\"http://subsonicproject.com/\" rel=\"nofollow noreferrer\">Subsonic</a>. Its designed to generate a data layer for you and let you use objects to build your where clauses. </p>\n" }, { "answer_id": 205388, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>I want to expand on Jimmy's answer a bit.</p>\n\n<pre><code>LASTNAME LIKE 'Pep%' \n</code></pre>\n\n<p>That's just <strong>EVIL</strong>. NEVER do it. The SQL string should look like this instead:</p>\n\n<pre><code>LASTNAME LIKE @LastName + '%'\n</code></pre>\n\n<p>Now the problem is that in your case you don't know if you need to do a lastname check at all. All you have are SELECT and FROM clauses and a textbox for the lastname column that may or may not have a value in it. Fine. That's still no excuse for doing it like in the first example. What you need to do instead is build your query like this (using C# for now since you didn't supply a client langauge):</p>\n\n<pre><code>//create a place to keep parameters until we can construct the SqlCommand object\nList&lt;SqlParameter&gt; params = new List&lt;SqlParameter&gt;();\nSqlParameter p;\n\n// the StringBuilder is MUCH more efficient the concatenating strings\n// the 1=1 is a placeholder so you can always just append \" AND whatever\"\nStringBuilder sql = new StringBuilder(\"SELECT ... \\nFROM .... \\nWHERE 1=1\\n\");\n\n// Check and add a parameter for the LastName column if needed\nif (!String.IsNullOrEmpty(txtLastName.Text))\n{\n sql.AppendLine(\"AND LASTNAME LIKE @LastName + '%'\");\n p = new SqlParameter(\"@LastName\", SqlDbType.VarChar, 50); // use the actual datatype here\n p.Value = txtLastName.Text;\n params.Add(p); \n}\n\n// Check and add a parameter for another field if needed\nif (!String.IsNullOrEmpty(txtSomeOtherField.Text))\n{\n sql.AppendLine(\"AND OtherField LIKE @OtherParam + '%'\");\n p = new SqlParameter(\"@OtherParam\", SqlDbType.VarChar, 255);\n p.Value = txtSomeOtherField.Text;\n params.Add(p);\n}\n\n// ... You could also write a method to abstract the code in the if blocks ...\n\n// you haven't told us _how_ the user will specify the order, so I'm leaving that implementation detail out for now\nsql.Append(\" ORDER BY LastName, OtherField\"); \n\n// now we can finally get our SQL String and build the (SAFE!) SqlCommand object:\nSqlCommand cmd = new SqlCommand(sql.ToString(), YourSqlConnectionObjectHere);\ncmd.Parameters.AddRange(params.ToArray());\n</code></pre>\n\n<p>Now you have a dynamically generated where clause with no possibility for injection. It works because <em>every</em> part of the string sent to the database is an exact literal in your code, even if those literals are assembled over a number of steps. The values used in the parameters are never substituted into the string, but instead sent to the server separately as data.</p>\n\n<p>Of course this was C# (.Net), but just about every modern platform has some form of parameterized query/prepared statement feature you should be using.</p>\n" }, { "answer_id": 205536, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "<p>Several other commenters have addressed the point that allowing user input to determine SQL syntax is a bad idea and created SQL injection vulnerabilities. </p>\n\n<p>Please take note that the commenters are unanimous in this opinion and have a total StackOverflow \"reputation\" exceeding 14,000!</p>\n\n<p>But leaving aside that point, you asked how to write a regular expression to match arbitrary SQL syntax. The answer is that <strong>you can't do that with regular expressions</strong>. </p>\n\n<p>\"Regular\" in this context means the expression can match a certain class of input language, which can also be represented by a <a href=\"http://en.wikipedia.org/wiki/Deterministic_finite-state_machine\" rel=\"nofollow noreferrer\">deterministic finite state-machine</a> (sort of like a flow-chart).</p>\n\n<p>For example, one simple thing you'd need to match an SQL expression is the ability to match nested parentheses. You can't design a finite state-machine to match nested parentheses, because it would require the ability to count how many levels deep in nested parentheses you are at any given point. For that you need the parser to implement a stack, but this is something a regular expression can't do.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28207/" ]
For a web application, I want to build a WHERE clause AND submit it to the server. There I will append it to a query. The clause will be something like ``` LASTNAME LIKE 'Pep%' AND (DOB BETWEEN '19600101' AND '19601231 OR SALARY<35000) ``` Can you propose a regular expression to validate the clause before submitting it to SQL Server? (Yes, of course, I would like a regex for the ORDER clause)
This is a monumentally bad idea. I would suggest you build a filter system instead where the user can select all kinds of options in a form, and then you build the correct sql server-side instead of opening yourself up to all kinds of injection attacks. As an example of what might go wrong, consider this: ``` LASTNAME LIKE 'Pep%'-- DROP TABLE People -- ``` This will inject a DROP TABLE command into your SQL, which will be hard to detect. You can of course remove things like -- and /\*, but I guarantee that someone can find a way in if you do this.
204,759
<p>Is there a way to perform an HTTP GET request within a Visual Basic script? I need to get the contents of the response from a particular URL for processing.</p>
[ { "answer_id": 204851, "author": "Svante Svenson", "author_id": 19707, "author_profile": "https://Stackoverflow.com/users/19707", "pm_score": 7, "selected": true, "text": "<pre><code>Dim o\nSet o = CreateObject(\"MSXML2.XMLHTTP\")\no.open \"GET\", \"http://www.example.com\", False\no.send\n' o.responseText now holds the response as a string.\n</code></pre>\n" }, { "answer_id": 208913, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 5, "selected": false, "text": "<p>You haven't at time of writing described what you are going to do with the response or what its content type is. An answer already contains a very basic usage of <code>MSXML2.XMLHTTP</code> (I recommend the more explicit <code>MSXML2.XMLHTTP.3.0</code> progID) however you may need to do different things with the response, it may not be text.</p>\n\n<p>The XMLHTTP also has a <code>responseBody</code> property which is a byte array version of the reponse and there is a <code>responseStream</code> which is an <code>IStream</code> wrapper for the response.</p>\n\n<p>Note that in a server-side requirement (e.g., VBScript hosted in ASP) you would use <code>MSXML.ServerXMLHTTP.3.0</code> or <code>WinHttp.WinHttpRequest.5.1</code> (which has a near identical interface).</p>\n\n<p>Here is an example of using XmlHttp to fetch a PDF file and store it:-</p>\n\n<pre><code>Dim oXMLHTTP\nDim oStream\n\nSet oXMLHTTP = CreateObject(\"MSXML2.XMLHTTP.3.0\")\n\noXMLHTTP.Open \"GET\", \"http://someserver/folder/file.pdf\", False\noXMLHTTP.Send\n\nIf oXMLHTTP.Status = 200 Then\n Set oStream = CreateObject(\"ADODB.Stream\")\n oStream.Open\n oStream.Type = 1\n oStream.Write oXMLHTTP.responseBody\n oStream.SaveToFile \"c:\\somefolder\\file.pdf\"\n oStream.Close\nEnd If\n</code></pre>\n" }, { "answer_id": 9338465, "author": "Jamie", "author_id": 1217583, "author_profile": "https://Stackoverflow.com/users/1217583", "pm_score": 2, "selected": false, "text": "<p>If you are using the GET request to actually SEND data...</p>\n\n<p>check:\n<a href=\"http://techhelplist.com/index.php/tech-tutorials/37-windows-troubles/60-vbscript-sending-get-request\" rel=\"nofollow\">http://techhelplist.com/index.php/tech-tutorials/37-windows-troubles/60-vbscript-sending-get-request</a></p>\n\n<p>The problem with MSXML2.XMLHTTP is that there are several versions of it, with different names depending on the windows os version and patches.</p>\n\n<p>this explains it:\n<a href=\"http://support.microsoft.com/kb/269238\" rel=\"nofollow\">http://support.microsoft.com/kb/269238</a></p>\n\n<p>i have had more luck using vbscript to call </p>\n\n<pre><code>set ID = CreateObject(\"InternetExplorer.Application\")\nIE.visible = 0\nIE.navigate \"http://example.com/parser.php?key=\" &amp; value &amp; \"key2=\" &amp; value2 \ndo while IE.Busy.... \n</code></pre>\n\n<p>....and more stuff but just to let the request go thru.</p>\n" }, { "answer_id": 37813009, "author": "Rajkumar Joshua M", "author_id": 6464616, "author_profile": "https://Stackoverflow.com/users/6464616", "pm_score": 0, "selected": false, "text": "<pre><code> strRequest = \"&lt;soap:Envelope xmlns:soap=\"\"http://www.w3.org/2003/05/soap-envelope\"\" \" &amp;_\n \"xmlns:tem=\"\"http://tempuri.org/\"\"&gt;\" &amp;_\n \"&lt;soap:Header/&gt;\" &amp;_\n \"&lt;soap:Body&gt;\" &amp;_\n \"&lt;tem:Authorization&gt;\" &amp;_\n \"&lt;tem:strCC&gt;\"&amp;1234123412341234&amp;\"&lt;/tem:strCC&gt;\" &amp;_\n \"&lt;tem:strEXPMNTH&gt;\"&amp;11&amp;\"&lt;/tem:strEXPMNTH&gt;\" &amp;_\n \"&lt;tem:CVV2&gt;\"&amp;123&amp;\"&lt;/tem:CVV2&gt;\" &amp;_\n \"&lt;tem:strYR&gt;\"&amp;23&amp;\"&lt;/tem:strYR&gt;\" &amp;_\n \"&lt;tem:dblAmount&gt;\"&amp;1235&amp;\"&lt;/tem:dblAmount&gt;\" &amp;_\n \"&lt;/tem:Authorization&gt;\" &amp;_\n \"&lt;/soap:Body&gt;\" &amp;_\n \"&lt;/soap:Envelope&gt;\"\n\n EndPointLink = \"http://www.trainingrite.net/trainingrite_epaysystem\" &amp;_\n \"/trainingrite_epaysystem/tr_epaysys.asmx\"\n\n\n\ndim http\nset http=createObject(\"Microsoft.XMLHTTP\")\nhttp.open \"POST\",EndPointLink,false\nhttp.setRequestHeader \"Content-Type\",\"text/xml\"\n\nmsgbox \"REQUEST : \" &amp; strRequest\nhttp.send strRequest\n\nIf http.Status = 200 Then\n'msgbox \"RESPONSE : \" &amp; http.responseXML.xml\nmsgbox \"RESPONSE : \" &amp; http.responseText\nresponseText=http.responseText\nelse\nmsgbox \"ERRCODE : \" &amp; http.status\nEnd If\n\nCall ParseTag(responseText,\"AuthorizationResult\")\n\nCall CreateXMLEvidence(responseText,strRequest)\n\n'Function to fetch the required message from a TAG\nFunction ParseTag(ResponseXML,SearchTag)\n\n ResponseMessage=split(split(split(ResponseXML,SearchTag)(1),\"&lt;/\")(0),\"&gt;\")(1)\n Msgbox ResponseMessage\n\nEnd Function\n\n'Function to create XML test evidence files\nFunction CreateXMLEvidence(ResponseXML,strRequest)\n\n Set fso=createobject(\"Scripting.FileSystemObject\")\n Set qfile=fso.CreateTextFile(\"C:\\Users\\RajkumarJoshua\\Desktop\\DCIM\\SampleResponse.xml\",2)\n Set qfile1=fso.CreateTextFile(\"C:\\Users\\RajkumarJoshua\\Desktop\\DCIM\\SampleReuest.xml\",2)\n\n qfile.write ResponseXML\n qfile.close\n\n qfile1.write strRequest\n qfile1.close\n\nEnd Function\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/271/" ]
Is there a way to perform an HTTP GET request within a Visual Basic script? I need to get the contents of the response from a particular URL for processing.
``` Dim o Set o = CreateObject("MSXML2.XMLHTTP") o.open "GET", "http://www.example.com", False o.send ' o.responseText now holds the response as a string. ```
204,765
<p>For debugging purposes, I need to recursively search a directory for all files which start with a UTF-8 byte order mark (BOM). My current solution is a simple shell script:</p> <pre><code>find -type f | while read file do if [ "`head -c 3 -- "$file"`" == $'\xef\xbb\xbf' ] then echo "found BOM in: $file" fi done</code></pre> <p>Or, if you prefer short, unreadable one-liners:</p> <pre><code>find -type f|while read file;do [ "`head -c3 -- "$file"`" == $'\xef\xbb\xbf' ] && echo "found BOM in: $file";done</code></pre> <p>It doesn't work with filenames that contain a line break, but such files are not to be expected anyway.</p> <p>Is there any shorter or more elegant solution?</p> <p>Are there any interesting text editors or macros for text editors?</p>
[ { "answer_id": 211855, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 3, "selected": false, "text": "<p>If you accept some false positives (in case there are non-text files, or in the unlikely case there is a ZWNBSP in the middle of a file), you can use grep:</p>\n\n<pre><code>fgrep -rl `echo -ne '\\xef\\xbb\\xbf'` .\n</code></pre>\n" }, { "answer_id": 212214, "author": "Jonathan Wright", "author_id": 28840, "author_profile": "https://Stackoverflow.com/users/28840", "pm_score": 2, "selected": false, "text": "<pre><code>find -type f -print0 | xargs -0 grep -l `printf '^\\xef\\xbb\\xbf'` | sed 's/^/found BOM in: /'\n</code></pre>\n\n<ul>\n<li><code>find -print0</code> puts a null \\0 between each file name instead of using new lines</li>\n<li><code>xargs -0</code> expects null separated arguments instead of line separated</li>\n<li><code>grep -l</code> lists the files which match the regex</li>\n<li>The regex <code>^\\xeff\\xbb\\xbf</code> isn't entirely correct, as it will match non-BOMed UTF-8 files if they have zero width spaces at the start of a line</li>\n</ul>\n" }, { "answer_id": 212312, "author": "Marcus Griep", "author_id": 28645, "author_profile": "https://Stackoverflow.com/users/28645", "pm_score": 3, "selected": false, "text": "<p>I would use something like:</p>\n\n<pre><code>grep -orHbm1 \"^`echo -ne '\\xef\\xbb\\xbf'`\" . | sed '/:0:/!d;s/:0:.*//'\n</code></pre>\n\n<p>Which will ensure that the BOM occurs starting at the first byte of the file.</p>\n" }, { "answer_id": 2858757, "author": "Denis", "author_id": 344192, "author_profile": "https://Stackoverflow.com/users/344192", "pm_score": 9, "selected": true, "text": "<p>What about this one simple command which not just finds but clears the nasty BOM? :)</p>\n\n<pre><code>find . -type f -exec sed '1s/^\\xEF\\xBB\\xBF//' -i {} \\;\n</code></pre>\n\n<p>I love \"find\" :)</p>\n\n<p><strong>Warning</strong> The above will <strong>modify</strong> binary files which contain those three characters.</p>\n\n<p>If you want just to show BOM files, use this one:</p>\n\n<pre><code>grep -rl $'\\xEF\\xBB\\xBF' .\n</code></pre>\n" }, { "answer_id": 2884935, "author": "Aron Griffis", "author_id": 347386, "author_profile": "https://Stackoverflow.com/users/347386", "pm_score": 4, "selected": false, "text": "<pre><code>find . -type f -print0 | xargs -0r awk '\n /^\\xEF\\xBB\\xBF/ {print FILENAME}\n {nextfile}'\n</code></pre>\n\n<p>Most of the solutions given above test more than the first line of the file, even if some (such as Marcus's solution) then filter the results. This solution only tests the first line of each file so it should be a bit quicker.</p>\n" }, { "answer_id": 7478330, "author": "Jan Przybylo", "author_id": 953660, "author_profile": "https://Stackoverflow.com/users/953660", "pm_score": 5, "selected": false, "text": "<p>The best and easiest way to do this on Windows:</p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Total_Commander\" rel=\"noreferrer\">Total Commander</a> &rarr; go to project's root dir &rarr; find files (<kbd>Alt</kbd> + <kbd>F7</kbd>) &rarr; file types *.* &rarr; Find text \"EF BB BF\" &rarr; check 'Hex' checkbox &rarr; search</p>\n\n<p>And you get the list :)</p>\n" }, { "answer_id": 7992682, "author": "julien", "author_id": 1027342, "author_profile": "https://Stackoverflow.com/users/1027342", "pm_score": 2, "selected": false, "text": "<p>For a Windows user, see <a href=\"https://github.com/emrahgunduz/BomCleaner\" rel=\"nofollow\">this</a> (good PHP script for finding the <code>BOM</code> in your project).</p>\n" }, { "answer_id": 8584233, "author": "mario", "author_id": 345031, "author_profile": "https://Stackoverflow.com/users/345031", "pm_score": 2, "selected": false, "text": "<p>An overkill solution to this is <a href=\"http://freecode.com/projects/phptags\" rel=\"nofollow\"><code>phptags</code></a> (not the <code>vi</code> tool with the same name), which specifically looks for PHP scripts:</p>\n\n<pre><code>phptags --warn ./\n</code></pre>\n\n<p>Will output something like:</p>\n\n<pre><code>./invalid.php: TRAILING whitespace (\"?&gt;\\n\")\n./invalid.php: UTF-8 BOM alone (\"\\xEF\\xBB\\xBF\")\n</code></pre>\n\n<p>And the <code>--whitespace</code> mode will automatically fix such issues (recursively, but asserts that it only rewrites .php scripts.)</p>\n" }, { "answer_id": 9990179, "author": "LLub", "author_id": 945548, "author_profile": "https://Stackoverflow.com/users/945548", "pm_score": 2, "selected": false, "text": "<p>I used this to correct only JavaScript files:</p>\n\n<pre><code>find . -iname *.js -type f -exec sed 's/^\\xEF\\xBB\\xBF//' -i.bak {} \\; -exec rm {}.bak \\;\n</code></pre>\n" }, { "answer_id": 17624128, "author": "theory", "author_id": 79202, "author_profile": "https://Stackoverflow.com/users/79202", "pm_score": 3, "selected": false, "text": "<p>You can use <code>grep</code> to find them and Perl to strip them out like so:</p>\n\n<pre><code>grep -rl $'\\xEF\\xBB\\xBF' . | xargs perl -i -pe 's{\\xEF\\xBB\\xBF}{}'\n</code></pre>\n" }, { "answer_id": 26406896, "author": "Mike Dotterer", "author_id": 188452, "author_profile": "https://Stackoverflow.com/users/188452", "pm_score": 1, "selected": false, "text": "<p>If you are looking for UTF files, the <a href=\"http://unixhelp.ed.ac.uk/CGI/man-cgi?file\" rel=\"nofollow\">file command</a> works. It will tell you what the encoding of the file is. If there are any non ASCII characters in there it will come up with UTF.</p>\n\n<pre><code>file *.php | grep UTF\n</code></pre>\n\n<p>That won't work recursively though. You can probably rig up some fancy command to make it recursive, but I just searched each level individually like the following, until I ran out of levels.</p>\n\n<pre><code>file */*.php | grep UTF\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19163/" ]
For debugging purposes, I need to recursively search a directory for all files which start with a UTF-8 byte order mark (BOM). My current solution is a simple shell script: ``` find -type f | while read file do if [ "`head -c 3 -- "$file"`" == $'\xef\xbb\xbf' ] then echo "found BOM in: $file" fi done ``` Or, if you prefer short, unreadable one-liners: ``` find -type f|while read file;do [ "`head -c3 -- "$file"`" == $'\xef\xbb\xbf' ] && echo "found BOM in: $file";done ``` It doesn't work with filenames that contain a line break, but such files are not to be expected anyway. Is there any shorter or more elegant solution? Are there any interesting text editors or macros for text editors?
What about this one simple command which not just finds but clears the nasty BOM? :) ``` find . -type f -exec sed '1s/^\xEF\xBB\xBF//' -i {} \; ``` I love "find" :) **Warning** The above will **modify** binary files which contain those three characters. If you want just to show BOM files, use this one: ``` grep -rl $'\xEF\xBB\xBF' . ```
204,779
<p>I'm VERY new to WPF, and still trying to wrap my head around binding in XAML.</p> <p>I'd like to populate a combobox with the values of a string collection in my.settings. I can do it in code like this:</p> <p>Me.ComboBox1.ItemsSource = My.Settings.MyCollectionOfStrings</p> <p>...and it works.</p> <p>How can I do this in my XAML? is it possible?</p> <p>Thanks</p>
[ { "answer_id": 204855, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 5, "selected": true, "text": "<p><strong>Yes</strong>, you can (and should for the most part) declare bindings in XAML, since that's one of the most powerful features in WPF.</p>\n\n<p>In your case, to bind the ComboBox to one of your custom settings you would use the following XAML:</p>\n\n<pre><code>&lt;Window x:Class=\"WpfApplication1.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:p=\"clr-namespace:WpfApplication1.Properties\"\n Title=\"Window1\"&gt;\n &lt;StackPanel&gt;\n &lt;ComboBox\n ItemsSource=\"{Binding Source={x:Static p:Settings.Default}, Path=MyCollectionOfStrings}\" /&gt;\n &lt;/StackPanel&gt;\n&lt;/Window&gt;\n</code></pre>\n\n<p>Notice the following aspects:</p>\n\n<ul>\n<li>We declared an XML namespace with the prefix 'p' that points to the .NET namespace where the 'Settings' class lives in order to refer to it in XAML</li>\n<li>We used the markup extension '{Binding}' in order to declare a binding in XAML</li>\n<li>We used the markup extension 'Static' in order to indicate that we want to refer to a static ('shared' in VB) class member in XAML</li>\n</ul>\n" }, { "answer_id": 204856, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>It is possible. In C#, I do it like this (for a simple bool):</p>\n\n<pre><code>IsExpanded=\"{Binding Source={StaticResource Settings}, Mode=TwoWay, Path=Default.ASettingValue}\"\n</code></pre>\n\n<p>I define the static resource \"Settings\" in my App.xaml's Application.Resources thusly:</p>\n\n<pre><code>&lt;!-- other namespaces removed for clarity --&gt;\n&lt;Application xmlns:settings=\"clr-namespace:DefaultNamespace.Properties\" &gt;\n &lt;Application.Resources&gt;\n &lt;ResourceDictionary&gt;\n &lt;settings:Settings x:Key=\"Settings\" /&gt;\n &lt;!--stuff removed--&gt;\n &lt;/ResourceDictionary&gt;\n &lt;/Application.Resources&gt;\n&lt;/Application&gt;\n</code></pre>\n\n<p>Your path may be different; in C#, you access app settings in your application via</p>\n\n<pre><code>DefaultNamespace.Properties.Settings.Default.ASettingValue\n</code></pre>\n" }, { "answer_id": 205366, "author": "Ben Brandt", "author_id": 641985, "author_profile": "https://Stackoverflow.com/users/641985", "pm_score": 1, "selected": false, "text": "<p>Got it!</p>\n\n<pre><code>&lt;Window x:Class=\"Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:p=\"clr-namespace:WpfApplication1\"\n Title=\"Window1\" Height=\"90\" Width=\"462\" Name=\"Window1\"&gt;\n &lt;Grid&gt;\n &lt;ComboBox ItemsSource=\"{Binding Source={x:Static p:Settings.Default}, Path=MyCollectionOfStrings}\" /&gt;\n &lt;/Grid&gt;\n&lt;/Window&gt;\n</code></pre>\n\n<p>Thank you all for helping me reach a great \"Aha!\" moment :-) ...hopefully after I spend some more time in WPF I'll understand why this works.</p>\n" }, { "answer_id": 807799, "author": "Thomas Levesque", "author_id": 98713, "author_profile": "https://Stackoverflow.com/users/98713", "pm_score": 2, "selected": false, "text": "<p>I have a simpler solution for doing that, using a custom markup extension. In your case it could be used like this :</p>\n\n<pre><code>&lt;Window x:Class=\"Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:my=\"clr-namespace:WpfApplication1\"\n Title=\"Window1\" Height=\"90\" Width=\"462\" Name=\"Window1\"&gt;\n &lt;Grid&gt;\n &lt;ComboBox ItemsSource=\"{my:SettingBinding MyCollectionOfStrings}\" /&gt;\n &lt;/Grid&gt;\n&lt;/Window&gt;\n</code></pre>\n\n<p>You can find the C# code for this markup extension on my blog here :\n<a href=\"http://www.thomaslevesque.com/2008/11/18/wpf-binding-to-application-settings-using-a-markup-extension/\" rel=\"nofollow noreferrer\">http://www.thomaslevesque.com/2008/11/18/wpf-binding-to-application-settings-using-a-markup-extension/</a></p>\n" }, { "answer_id": 1689281, "author": "Echilon", "author_id": 30512, "author_profile": "https://Stackoverflow.com/users/30512", "pm_score": 0, "selected": false, "text": "<p>You could also store the list as a delimited string in settings then use a converter.</p>\n\n<pre><code>&lt;ComboBox ItemsSource=\"{Binding Default.ImportHistory,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay,Converter={StaticResource StringToListConverter},ConverterParameter=|}\" IsEditable=\"True\"&gt;\n/// &lt;summary&gt;\n/// Converts a delimited set of strings to a list and back again. The parameter defines the delimiter\n/// &lt;/summary&gt;\npublic class StringToListConverter : IValueConverter {\n /// &lt;summary&gt;\n /// Takes a string, returns a list seperated by {parameter}\n /// &lt;/summary&gt;\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {\n string serializedList = (value ?? string.Empty).ToString(),\n splitter = (parameter ?? string.Empty).ToString();\n if(serializedList.Trim().Length == 0) {\n return value;\n }\n return serializedList.Split(new[] { splitter }, StringSplitOptions.RemoveEmptyEntries);\n }\n /// &lt;summary&gt;\n /// Takes a list, returns a string seperated by {parameter}\n /// &lt;/summary&gt;\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {\n var items = value as IEnumerable;\n var splitter = (parameter ?? string.Empty).ToString();\n if(value == null || items == null) {\n return value;\n }\n StringBuilder buffer = new StringBuilder();\n foreach(var itm in items) {\n buffer.Append(itm.ToString()).Append(splitter);\n }\n return buffer.ToString(0, splitter.Length &gt; 0 ? buffer.Length - splitter.Length : buffer.Length);\n }\n}\n</code></pre>\n\n<p>Then when a browse button is clicked, you can add to the list:</p>\n\n<pre><code>var items = Settings.Default.ImportHistory.Split('|');\nif(!items.Contains(dlgOpen.FileNames[0])) {\n Settings.Default.ImportHistory += (\"|\" + dlgOpen.FileNames[0]);\n}\ncboFilename.SelectedValue = dlgOpen.FileNames[0];\nSettings.Default.Save();\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/641985/" ]
I'm VERY new to WPF, and still trying to wrap my head around binding in XAML. I'd like to populate a combobox with the values of a string collection in my.settings. I can do it in code like this: Me.ComboBox1.ItemsSource = My.Settings.MyCollectionOfStrings ...and it works. How can I do this in my XAML? is it possible? Thanks
**Yes**, you can (and should for the most part) declare bindings in XAML, since that's one of the most powerful features in WPF. In your case, to bind the ComboBox to one of your custom settings you would use the following XAML: ``` <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:p="clr-namespace:WpfApplication1.Properties" Title="Window1"> <StackPanel> <ComboBox ItemsSource="{Binding Source={x:Static p:Settings.Default}, Path=MyCollectionOfStrings}" /> </StackPanel> </Window> ``` Notice the following aspects: * We declared an XML namespace with the prefix 'p' that points to the .NET namespace where the 'Settings' class lives in order to refer to it in XAML * We used the markup extension '{Binding}' in order to declare a binding in XAML * We used the markup extension 'Static' in order to indicate that we want to refer to a static ('shared' in VB) class member in XAML
204,784
<p>Given two absolute paths, e.g.</p> <pre><code>/var/data/stuff/xyz.dat /var/data </code></pre> <p>How can one create a relative path that uses the second path as its base? In the example above, the result should be: <code>./stuff/xyz.dat</code></p>
[ { "answer_id": 204847, "author": "Keeg", "author_id": 21059, "author_profile": "https://Stackoverflow.com/users/21059", "pm_score": 3, "selected": false, "text": "<p>If you know the second string is part of the first:</p>\n\n<pre><code>String s1 = \"/var/data/stuff/xyz.dat\";\nString s2 = \"/var/data\";\nString s3 = s1.substring(s2.length());\n</code></pre>\n\n<p>or if you really want the period at the beginning as in your example:</p>\n\n<pre><code>String s3 = \".\".concat(s1.substring(s2.length()));\n</code></pre>\n" }, { "answer_id": 205495, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": -1, "selected": false, "text": "<p>Psuedo-code:</p>\n\n<ol>\n<li>Split the strings by the path seperator (\"/\")</li>\n<li>Find the greatest common path by iterating thru the result of the split string (so you'd end up with \"/var/data\" or \"/a\" in your two examples)</li>\n<li><code>return \".\" + whicheverPathIsLonger.substring(commonPath.length);</code></li>\n</ol>\n" }, { "answer_id": 205592, "author": "Steve Armstrong", "author_id": 28038, "author_profile": "https://Stackoverflow.com/users/28038", "pm_score": 2, "selected": false, "text": "<p>I'm assuming you have <strong>fromPath</strong> (an absolute path for a folder), and <strong>toPath</strong> (an absolute path for a folder/file), and your're looking for a path that with represent the file/folder in <strong>toPath</strong> as a relative path from <strong>fromPath</strong> (your current working directory is <strong>fromPath</strong>) then something like this should work:</p>\n\n<pre><code>public static String getRelativePath(String fromPath, String toPath) {\n\n // This weirdness is because a separator of '/' messes with String.split()\n String regexCharacter = File.separator;\n if (File.separatorChar == '\\\\') {\n regexCharacter = \"\\\\\\\\\";\n }\n\n String[] fromSplit = fromPath.split(regexCharacter);\n String[] toSplit = toPath.split(regexCharacter);\n\n // Find the common path\n int common = 0;\n while (fromSplit[common].equals(toSplit[common])) {\n common++;\n }\n\n StringBuffer result = new StringBuffer(\".\");\n\n // Work your way up the FROM path to common ground\n for (int i = common; i &lt; fromSplit.length; i++) {\n result.append(File.separatorChar).append(\"..\");\n }\n\n // Work your way down the TO path\n for (int i = common; i &lt; toSplit.length; i++) {\n result.append(File.separatorChar).append(toSplit[i]);\n }\n\n return result.toString();\n}\n</code></pre>\n" }, { "answer_id": 205621, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 2, "selected": false, "text": "<p>Actually my other answer didn't work if the target path wasn't a child of the base path.</p>\n\n<p>This should work.</p>\n\n<pre><code>public class RelativePathFinder {\n\n public static String getRelativePath(String targetPath, String basePath, \n String pathSeparator) {\n\n // find common path\n String[] target = targetPath.split(pathSeparator);\n String[] base = basePath.split(pathSeparator);\n\n String common = \"\";\n int commonIndex = 0;\n for (int i = 0; i &lt; target.length &amp;&amp; i &lt; base.length; i++) {\n\n if (target[i].equals(base[i])) {\n common += target[i] + pathSeparator;\n commonIndex++;\n }\n }\n\n\n String relative = \"\";\n // is the target a child directory of the base directory?\n // i.e., target = /a/b/c/d, base = /a/b/\n if (commonIndex == base.length) {\n relative = \".\" + pathSeparator + targetPath.substring(common.length());\n }\n else {\n // determine how many directories we have to backtrack\n for (int i = 1; i &lt;= commonIndex; i++) {\n relative += \"..\" + pathSeparator;\n }\n relative += targetPath.substring(common.length());\n }\n\n return relative;\n }\n\n public static String getRelativePath(String targetPath, String basePath) {\n return getRelativePath(targetPath, basePath, File.pathSeparator);\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>public class RelativePathFinderTest extends TestCase {\n\n public void testGetRelativePath() {\n assertEquals(\"./stuff/xyz.dat\", RelativePathFinder.getRelativePath(\n \"/var/data/stuff/xyz.dat\", \"/var/data/\", \"/\"));\n assertEquals(\"../../b/c\", RelativePathFinder.getRelativePath(\"/a/b/c\",\n \"/a/x/y/\", \"/\"));\n }\n\n}\n</code></pre>\n" }, { "answer_id": 205655, "author": "Adam Crume", "author_id": 25498, "author_profile": "https://Stackoverflow.com/users/25498", "pm_score": 9, "selected": true, "text": "<p>It's a little roundabout, but why not use URI? It has a relativize method which does all the necessary checks for you.</p>\n\n<pre><code>String path = \"/var/data/stuff/xyz.dat\";\nString base = \"/var/data\";\nString relative = new File(base).toURI().relativize(new File(path).toURI()).getPath();\n// relative == \"stuff/xyz.dat\"\n</code></pre>\n\n<p>Please note that for file path there's <code>java.nio.file.Path#relativize</code> since Java 1.7, as pointed out by <a href=\"https://stackoverflow.com/users/1113396/jirka-meluzin\">@Jirka Meluzin</a> in <a href=\"https://stackoverflow.com/a/25743823/537554\">the other answer</a>.</p>\n" }, { "answer_id": 705963, "author": "Christian K.", "author_id": 61588, "author_profile": "https://Stackoverflow.com/users/61588", "pm_score": 5, "selected": false, "text": "<p>When using java.net.URI.relativize you should be aware of Java bug:\n<a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6226081\" rel=\"noreferrer\">JDK-6226081 (URI should be able to relativize paths with partial roots)</a></p>\n\n<blockquote>\n <p>At the moment, the <code>relativize()</code> method of <code>URI</code> will only relativize URIs when one is a prefix of the other.</p>\n</blockquote>\n\n<p>Which essentially means <code>java.net.URI.relativize</code> will not create \"..\"'s for you.</p>\n" }, { "answer_id": 1269907, "author": "Gili", "author_id": 14731, "author_profile": "https://Stackoverflow.com/users/14731", "pm_score": 3, "selected": false, "text": "<p>My version is loosely based on <a href=\"https://stackoverflow.com/a/205621/14731\">Matt</a> and <a href=\"https://stackoverflow.com/a/205592/14731\">Steve</a>'s versions:</p>\n\n<pre><code>/**\n * Returns the path of one File relative to another.\n *\n * @param target the target directory\n * @param base the base directory\n * @return target's path relative to the base directory\n * @throws IOException if an error occurs while resolving the files' canonical names\n */\n public static File getRelativeFile(File target, File base) throws IOException\n {\n String[] baseComponents = base.getCanonicalPath().split(Pattern.quote(File.separator));\n String[] targetComponents = target.getCanonicalPath().split(Pattern.quote(File.separator));\n\n // skip common components\n int index = 0;\n for (; index &lt; targetComponents.length &amp;&amp; index &lt; baseComponents.length; ++index)\n {\n if (!targetComponents[index].equals(baseComponents[index]))\n break;\n }\n\n StringBuilder result = new StringBuilder();\n if (index != baseComponents.length)\n {\n // backtrack to base directory\n for (int i = index; i &lt; baseComponents.length; ++i)\n result.append(\"..\" + File.separator);\n }\n for (; index &lt; targetComponents.length; ++index)\n result.append(targetComponents[index] + File.separator);\n if (!target.getPath().endsWith(\"/\") &amp;&amp; !target.getPath().endsWith(\"\\\\\"))\n {\n // remove final path separator\n result.delete(result.length() - File.separator.length(), result.length());\n }\n return new File(result.toString());\n }\n</code></pre>\n" }, { "answer_id": 1288584, "author": "Matuszek", "author_id": 155876, "author_profile": "https://Stackoverflow.com/users/155876", "pm_score": 2, "selected": false, "text": "<p>Matt B's solution gets the number of directories to backtrack wrong -- it should be the length of the base path minus the number of common path elements, minus one (for the last path element, which is either a filename or a trailing <code>\"\"</code> generated by <code>split</code>). It happens to work with <code>/a/b/c/</code> and <code>/a/x/y/</code>, but replace the arguments with <code>/m/n/o/a/b/c/</code> and <code>/m/n/o/a/x/y/</code> and you will see the problem. </p>\n\n<p>Also, it needs an <code>else break</code> inside the first for loop, or it will mishandle paths that happen to have matching directory names, such as <code>/a/b/c/d/</code> and <code>/x/y/c/z</code> -- the <code>c</code> is in the same slot in both arrays, but is not an actual match. </p>\n\n<p>All these solutions lack the ability to handle paths that cannot be relativized to one another because they have incompatible roots, such as <code>C:\\foo\\bar</code> and <code>D:\\baz\\quux</code>. Probably only an issue on Windows, but worth noting.</p>\n\n<p>I spent far longer on this than I intended, but that's okay. I actually needed this for work, so thank you to everyone who has chimed in, and I'm sure there will be corrections to this version too!</p>\n\n<pre><code>public static String getRelativePath(String targetPath, String basePath, \n String pathSeparator) {\n\n // We need the -1 argument to split to make sure we get a trailing \n // \"\" token if the base ends in the path separator and is therefore\n // a directory. We require directory paths to end in the path\n // separator -- otherwise they are indistinguishable from files.\n String[] base = basePath.split(Pattern.quote(pathSeparator), -1);\n String[] target = targetPath.split(Pattern.quote(pathSeparator), 0);\n\n // First get all the common elements. Store them as a string,\n // and also count how many of them there are. \n String common = \"\";\n int commonIndex = 0;\n for (int i = 0; i &lt; target.length &amp;&amp; i &lt; base.length; i++) {\n if (target[i].equals(base[i])) {\n common += target[i] + pathSeparator;\n commonIndex++;\n }\n else break;\n }\n\n if (commonIndex == 0)\n {\n // Whoops -- not even a single common path element. This most\n // likely indicates differing drive letters, like C: and D:. \n // These paths cannot be relativized. Return the target path.\n return targetPath;\n // This should never happen when all absolute paths\n // begin with / as in *nix. \n }\n\n String relative = \"\";\n if (base.length == commonIndex) {\n // Comment this out if you prefer that a relative path not start with ./\n //relative = \".\" + pathSeparator;\n }\n else {\n int numDirsUp = base.length - commonIndex - 1;\n // The number of directories we have to backtrack is the length of \n // the base path MINUS the number of common path elements, minus\n // one because the last element in the path isn't a directory.\n for (int i = 1; i &lt;= (numDirsUp); i++) {\n relative += \"..\" + pathSeparator;\n }\n }\n relative += targetPath.substring(common.length());\n\n return relative;\n}\n</code></pre>\n\n<p>And here are tests to cover several cases:</p>\n\n<pre><code>public void testGetRelativePathsUnixy() \n{ \n assertEquals(\"stuff/xyz.dat\", FileUtils.getRelativePath(\n \"/var/data/stuff/xyz.dat\", \"/var/data/\", \"/\"));\n assertEquals(\"../../b/c\", FileUtils.getRelativePath(\n \"/a/b/c\", \"/a/x/y/\", \"/\"));\n assertEquals(\"../../b/c\", FileUtils.getRelativePath(\n \"/m/n/o/a/b/c\", \"/m/n/o/a/x/y/\", \"/\"));\n}\n\npublic void testGetRelativePathFileToFile() \n{\n String target = \"C:\\\\Windows\\\\Boot\\\\Fonts\\\\chs_boot.ttf\";\n String base = \"C:\\\\Windows\\\\Speech\\\\Common\\\\sapisvr.exe\";\n\n String relPath = FileUtils.getRelativePath(target, base, \"\\\\\");\n assertEquals(\"..\\\\..\\\\..\\\\Boot\\\\Fonts\\\\chs_boot.ttf\", relPath);\n}\n\npublic void testGetRelativePathDirectoryToFile() \n{\n String target = \"C:\\\\Windows\\\\Boot\\\\Fonts\\\\chs_boot.ttf\";\n String base = \"C:\\\\Windows\\\\Speech\\\\Common\";\n\n String relPath = FileUtils.getRelativePath(target, base, \"\\\\\");\n assertEquals(\"..\\\\..\\\\Boot\\\\Fonts\\\\chs_boot.ttf\", relPath);\n}\n\npublic void testGetRelativePathDifferentDriveLetters() \n{\n String target = \"D:\\\\sources\\\\recovery\\\\RecEnv.exe\";\n String base = \"C:\\\\Java\\\\workspace\\\\AcceptanceTests\\\\Standard test data\\\\geo\\\\\";\n\n // Should just return the target path because of the incompatible roots.\n String relPath = FileUtils.getRelativePath(target, base, \"\\\\\");\n assertEquals(target, relPath);\n}\n</code></pre>\n" }, { "answer_id": 1290311, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 4, "selected": false, "text": "<p>The bug referred to in <a href=\"https://stackoverflow.com/a/705963/\">another answer</a> is addressed by <a href=\"https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URIUtils.html#resolve%28java.net.URI,%20java.lang.String%29\" rel=\"nofollow noreferrer\">URIUtils</a> in <a href=\"https://hc.apache.org/httpcomponents-client-ga/httpclient/project-info.html\" rel=\"nofollow noreferrer\">Apache HttpComponents</a></p>\n\n<pre><code>public static URI resolve(URI baseURI,\n String reference)\n</code></pre>\n\n<blockquote>\n <p>Resolves a URI reference against a\n base URI. Work-around for bug in\n java.net.URI ()</p>\n</blockquote>\n" }, { "answer_id": 1915729, "author": "Rachel", "author_id": 233101, "author_profile": "https://Stackoverflow.com/users/233101", "pm_score": 2, "selected": false, "text": "<p>Cool!! I need a bit of code like this but for comparing directory paths on Linux machines. I found that this wasn't working in situations where a parent directory was the target.</p>\n\n<p>Here is a directory friendly version of the method:</p>\n\n<pre><code> public static String getRelativePath(String targetPath, String basePath, \n String pathSeparator) {\n\n boolean isDir = false;\n {\n File f = new File(targetPath);\n isDir = f.isDirectory();\n }\n // We need the -1 argument to split to make sure we get a trailing \n // \"\" token if the base ends in the path separator and is therefore\n // a directory. We require directory paths to end in the path\n // separator -- otherwise they are indistinguishable from files.\n String[] base = basePath.split(Pattern.quote(pathSeparator), -1);\n String[] target = targetPath.split(Pattern.quote(pathSeparator), 0);\n\n // First get all the common elements. Store them as a string,\n // and also count how many of them there are. \n String common = \"\";\n int commonIndex = 0;\n for (int i = 0; i &lt; target.length &amp;&amp; i &lt; base.length; i++) {\n if (target[i].equals(base[i])) {\n common += target[i] + pathSeparator;\n commonIndex++;\n }\n else break;\n }\n\n if (commonIndex == 0)\n {\n // Whoops -- not even a single common path element. This most\n // likely indicates differing drive letters, like C: and D:. \n // These paths cannot be relativized. Return the target path.\n return targetPath;\n // This should never happen when all absolute paths\n // begin with / as in *nix. \n }\n\n String relative = \"\";\n if (base.length == commonIndex) {\n // Comment this out if you prefer that a relative path not start with ./\n relative = \".\" + pathSeparator;\n }\n else {\n int numDirsUp = base.length - commonIndex - (isDir?0:1); /* only subtract 1 if it is a file. */\n // The number of directories we have to backtrack is the length of \n // the base path MINUS the number of common path elements, minus\n // one because the last element in the path isn't a directory.\n for (int i = 1; i &lt;= (numDirsUp); i++) {\n relative += \"..\" + pathSeparator;\n }\n }\n //if we are comparing directories then we \n if (targetPath.length() &gt; common.length()) {\n //it's OK, it isn't a directory\n relative += targetPath.substring(common.length());\n }\n\n return relative;\n}\n</code></pre>\n" }, { "answer_id": 3054692, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 6, "selected": false, "text": "<p>At the time of writing (June 2010), this was the only solution that passed my test cases. I can't guarantee that this solution is bug-free, but it does pass the included test cases. The method and tests I've written depend on the <a href=\"https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FilenameUtils.html\" rel=\"noreferrer\"><code>FilenameUtils</code></a> class from <a href=\"http://commons.apache.org/io/\" rel=\"noreferrer\">Apache commons IO</a>.</p>\n\n<p>The solution was tested with Java 1.4. If you're using Java 1.5 (or higher) you should consider replacing <code>StringBuffer</code> with <code>StringBuilder</code> (if you're still using Java 1.4 you should consider a change of employer instead).</p>\n\n<pre><code>import java.io.File;\nimport java.util.regex.Pattern;\n\nimport org.apache.commons.io.FilenameUtils;\n\npublic class ResourceUtils {\n\n /**\n * Get the relative path from one file to another, specifying the directory separator. \n * If one of the provided resources does not exist, it is assumed to be a file unless it ends with '/' or\n * '\\'.\n * \n * @param targetPath targetPath is calculated to this file\n * @param basePath basePath is calculated from this file\n * @param pathSeparator directory separator. The platform default is not assumed so that we can test Unix behaviour when running on Windows (for example)\n * @return\n */\n public static String getRelativePath(String targetPath, String basePath, String pathSeparator) {\n\n // Normalize the paths\n String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);\n String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);\n\n // Undo the changes to the separators made by normalization\n if (pathSeparator.equals(\"/\")) {\n normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);\n normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);\n\n } else if (pathSeparator.equals(\"\\\\\")) {\n normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);\n normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);\n\n } else {\n throw new IllegalArgumentException(\"Unrecognised dir separator '\" + pathSeparator + \"'\");\n }\n\n String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));\n String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));\n\n // First get all the common elements. Store them as a string,\n // and also count how many of them there are.\n StringBuffer common = new StringBuffer();\n\n int commonIndex = 0;\n while (commonIndex &lt; target.length &amp;&amp; commonIndex &lt; base.length\n &amp;&amp; target[commonIndex].equals(base[commonIndex])) {\n common.append(target[commonIndex] + pathSeparator);\n commonIndex++;\n }\n\n if (commonIndex == 0) {\n // No single common path element. This most\n // likely indicates differing drive letters, like C: and D:.\n // These paths cannot be relativized.\n throw new PathResolutionException(\"No common path element found for '\" + normalizedTargetPath + \"' and '\" + normalizedBasePath\n + \"'\");\n } \n\n // The number of directories we have to backtrack depends on whether the base is a file or a dir\n // For example, the relative path from\n //\n // /foo/bar/baz/gg/ff to /foo/bar/baz\n // \n // \"..\" if ff is a file\n // \"../..\" if ff is a directory\n //\n // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because\n // the resource referred to by this path may not actually exist, but it's the best I can do\n boolean baseIsFile = true;\n\n File baseResource = new File(normalizedBasePath);\n\n if (baseResource.exists()) {\n baseIsFile = baseResource.isFile();\n\n } else if (basePath.endsWith(pathSeparator)) {\n baseIsFile = false;\n }\n\n StringBuffer relative = new StringBuffer();\n\n if (base.length != commonIndex) {\n int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;\n\n for (int i = 0; i &lt; numDirsUp; i++) {\n relative.append(\"..\" + pathSeparator);\n }\n }\n relative.append(normalizedTargetPath.substring(common.length()));\n return relative.toString();\n }\n\n\n static class PathResolutionException extends RuntimeException {\n PathResolutionException(String msg) {\n super(msg);\n }\n } \n}\n</code></pre>\n\n<p>The test cases that this passes are</p>\n\n<pre><code>public void testGetRelativePathsUnix() {\n assertEquals(\"stuff/xyz.dat\", ResourceUtils.getRelativePath(\"/var/data/stuff/xyz.dat\", \"/var/data/\", \"/\"));\n assertEquals(\"../../b/c\", ResourceUtils.getRelativePath(\"/a/b/c\", \"/a/x/y/\", \"/\"));\n assertEquals(\"../../b/c\", ResourceUtils.getRelativePath(\"/m/n/o/a/b/c\", \"/m/n/o/a/x/y/\", \"/\"));\n}\n\npublic void testGetRelativePathFileToFile() {\n String target = \"C:\\\\Windows\\\\Boot\\\\Fonts\\\\chs_boot.ttf\";\n String base = \"C:\\\\Windows\\\\Speech\\\\Common\\\\sapisvr.exe\";\n\n String relPath = ResourceUtils.getRelativePath(target, base, \"\\\\\");\n assertEquals(\"..\\\\..\\\\Boot\\\\Fonts\\\\chs_boot.ttf\", relPath);\n}\n\npublic void testGetRelativePathDirectoryToFile() {\n String target = \"C:\\\\Windows\\\\Boot\\\\Fonts\\\\chs_boot.ttf\";\n String base = \"C:\\\\Windows\\\\Speech\\\\Common\\\\\";\n\n String relPath = ResourceUtils.getRelativePath(target, base, \"\\\\\");\n assertEquals(\"..\\\\..\\\\Boot\\\\Fonts\\\\chs_boot.ttf\", relPath);\n}\n\npublic void testGetRelativePathFileToDirectory() {\n String target = \"C:\\\\Windows\\\\Boot\\\\Fonts\";\n String base = \"C:\\\\Windows\\\\Speech\\\\Common\\\\foo.txt\";\n\n String relPath = ResourceUtils.getRelativePath(target, base, \"\\\\\");\n assertEquals(\"..\\\\..\\\\Boot\\\\Fonts\", relPath);\n}\n\npublic void testGetRelativePathDirectoryToDirectory() {\n String target = \"C:\\\\Windows\\\\Boot\\\\\";\n String base = \"C:\\\\Windows\\\\Speech\\\\Common\\\\\";\n String expected = \"..\\\\..\\\\Boot\";\n\n String relPath = ResourceUtils.getRelativePath(target, base, \"\\\\\");\n assertEquals(expected, relPath);\n}\n\npublic void testGetRelativePathDifferentDriveLetters() {\n String target = \"D:\\\\sources\\\\recovery\\\\RecEnv.exe\";\n String base = \"C:\\\\Java\\\\workspace\\\\AcceptanceTests\\\\Standard test data\\\\geo\\\\\";\n\n try {\n ResourceUtils.getRelativePath(target, base, \"\\\\\");\n fail();\n\n } catch (PathResolutionException ex) {\n // expected exception\n }\n}\n</code></pre>\n" }, { "answer_id": 8555628, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 8, "selected": false, "text": "<p>Since Java 7 you can use the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html#relativize%28java.nio.file.Path%29\" rel=\"noreferrer\">relativize</a> method:</p>\n\n<pre><code>import java.nio.file.Path;\nimport java.nio.file.Paths;\n\npublic class Test {\n\n public static void main(String[] args) {\n Path pathAbsolute = Paths.get(\"/var/data/stuff/xyz.dat\");\n Path pathBase = Paths.get(\"/var/data\");\n Path pathRelative = pathBase.relativize(pathAbsolute);\n System.out.println(pathRelative);\n }\n\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>stuff/xyz.dat\n</code></pre>\n" }, { "answer_id": 11215226, "author": "Burn L.", "author_id": 1483867, "author_profile": "https://Stackoverflow.com/users/1483867", "pm_score": 3, "selected": false, "text": "<p>Recursion produces a smaller solution. This throws an exception if the result is impossible (e.g. different Windows disk) or impractical (root is only common directory.) </p>\n\n<pre><code>/**\n * Computes the path for a file relative to a given base, or fails if the only shared \n * directory is the root and the absolute form is better.\n * \n * @param base File that is the base for the result\n * @param name File to be \"relativized\"\n * @return the relative name\n * @throws IOException if files have no common sub-directories, i.e. at best share the\n * root prefix \"/\" or \"C:\\\"\n */\n\npublic static String getRelativePath(File base, File name) throws IOException {\n File parent = base.getParentFile();\n\n if (parent == null) {\n throw new IOException(\"No common directory\");\n }\n\n String bpath = base.getCanonicalPath();\n String fpath = name.getCanonicalPath();\n\n if (fpath.startsWith(bpath)) {\n return fpath.substring(bpath.length() + 1);\n } else {\n return (\"..\" + File.separator + getRelativePath(parent, name));\n }\n}\n</code></pre>\n" }, { "answer_id": 19332145, "author": "NateS", "author_id": 187883, "author_profile": "https://Stackoverflow.com/users/187883", "pm_score": 1, "selected": false, "text": "<p>Lots of answers already here, but I found they didn't handle all cases, such as the base and target being the same. This function takes a base <em>directory</em> and a target path and returns the relative path. If no relative path exists, the target path is returned. File.separator is unnecessary.</p>\n\n<pre><code>public static String getRelativePath (String baseDir, String targetPath) {\n String[] base = baseDir.replace('\\\\', '/').split(\"\\\\/\");\n targetPath = targetPath.replace('\\\\', '/');\n String[] target = targetPath.split(\"\\\\/\");\n\n // Count common elements and their length.\n int commonCount = 0, commonLength = 0, maxCount = Math.min(target.length, base.length);\n while (commonCount &lt; maxCount) {\n String targetElement = target[commonCount];\n if (!targetElement.equals(base[commonCount])) break;\n commonCount++;\n commonLength += targetElement.length() + 1; // Directory name length plus slash.\n }\n if (commonCount == 0) return targetPath; // No common path element.\n\n int targetLength = targetPath.length();\n int dirsUp = base.length - commonCount;\n StringBuffer relative = new StringBuffer(dirsUp * 3 + targetLength - commonLength + 1);\n for (int i = 0; i &lt; dirsUp; i++)\n relative.append(\"../\");\n if (commonLength &lt; targetLength) relative.append(targetPath.substring(commonLength));\n return relative.toString();\n}\n</code></pre>\n" }, { "answer_id": 21368806, "author": "Kristel", "author_id": 3182397, "author_profile": "https://Stackoverflow.com/users/3182397", "pm_score": -1, "selected": false, "text": "<p>org.apache.ant has a FileUtils class with a getRelativePath method. Haven't tried it myself yet, but could be worthwhile to check it out.</p>\n\n<p><a href=\"http://javadoc.haefelinger.it/org.apache.ant/1.7.1/org/apache/tools/ant/util/FileUtils.html#getRelativePath(java.io.File\" rel=\"nofollow\">http://javadoc.haefelinger.it/org.apache.ant/1.7.1/org/apache/tools/ant/util/FileUtils.html#getRelativePath(java.io.File</a>, java.io.File)</p>\n" }, { "answer_id": 23950069, "author": "pedromateo", "author_id": 260981, "author_profile": "https://Stackoverflow.com/users/260981", "pm_score": 0, "selected": false, "text": "<p>Here a method that resolves a relative path from a base path regardless they are in the same or in a different root:</p>\n\n<pre><code>public static String GetRelativePath(String path, String base){\n\n final String SEP = \"/\";\n\n // if base is not a directory -&gt; return empty\n if (!base.endsWith(SEP)){\n return \"\";\n }\n\n // check if path is a file -&gt; remove last \"/\" at the end of the method\n boolean isfile = !path.endsWith(SEP);\n\n // get URIs and split them by using the separator\n String a = \"\";\n String b = \"\";\n try {\n a = new File(base).getCanonicalFile().toURI().getPath();\n b = new File(path).getCanonicalFile().toURI().getPath();\n } catch (IOException e) {\n e.printStackTrace();\n }\n String[] basePaths = a.split(SEP);\n String[] otherPaths = b.split(SEP);\n\n // check common part\n int n = 0;\n for(; n &lt; basePaths.length &amp;&amp; n &lt; otherPaths.length; n ++)\n {\n if( basePaths[n].equals(otherPaths[n]) == false )\n break;\n }\n\n // compose the new path\n StringBuffer tmp = new StringBuffer(\"\");\n for(int m = n; m &lt; basePaths.length; m ++)\n tmp.append(\"..\"+SEP);\n for(int m = n; m &lt; otherPaths.length; m ++)\n {\n tmp.append(otherPaths[m]);\n tmp.append(SEP);\n }\n\n // get path string\n String result = tmp.toString();\n\n // remove last \"/\" if path is a file\n if (isfile &amp;&amp; result.endsWith(SEP)){\n result = result.substring(0,result.length()-1);\n }\n\n return result;\n}\n</code></pre>\n" }, { "answer_id": 25743823, "author": "Jirka Meluzin", "author_id": 1113396, "author_profile": "https://Stackoverflow.com/users/1113396", "pm_score": 3, "selected": false, "text": "<p>Here is a solution other library free:</p>\n\n<pre><code>Path sourceFile = Paths.get(\"some/common/path/example/a/b/c/f1.txt\");\nPath targetFile = Paths.get(\"some/common/path/example/d/e/f2.txt\"); \nPath relativePath = sourceFile.relativize(targetFile);\nSystem.out.println(relativePath);\n</code></pre>\n\n<p>Outputs</p>\n\n<pre><code>..\\..\\..\\..\\d\\e\\f2.txt\n</code></pre>\n\n<p>[EDIT] actually it outputs on more ..\\ because of the source is file not a directory. Correct solution for my case is:</p>\n\n<pre><code>Path sourceFile = Paths.get(new File(\"some/common/path/example/a/b/c/f1.txt\").parent());\nPath targetFile = Paths.get(\"some/common/path/example/d/e/f2.txt\"); \nPath relativePath = sourceFile.relativize(targetFile);\nSystem.out.println(relativePath);\n</code></pre>\n" }, { "answer_id": 31742504, "author": "terensu", "author_id": 4429268, "author_profile": "https://Stackoverflow.com/users/4429268", "pm_score": -1, "selected": false, "text": "<pre><code>private String relative(String left, String right){\n String[] lefts = left.split(\"/\");\n String[] rights = right.split(\"/\");\n int min = Math.min(lefts.length, rights.length);\n int commonIdx = -1;\n for(int i = 0; i &lt; min; i++){\n if(commonIdx &lt; 0 &amp;&amp; !lefts[i].equals(rights[i])){\n commonIdx = i - 1;\n break;\n }\n }\n if(commonIdx &lt; 0){\n return null;\n }\n StringBuilder sb = new StringBuilder(Math.max(left.length(), right.length()));\n sb.append(left).append(\"/\");\n for(int i = commonIdx + 1; i &lt; lefts.length;i++){\n sb.append(\"../\");\n }\n for(int i = commonIdx + 1; i &lt; rights.length;i++){\n sb.append(rights[i]).append(\"/\");\n }\n\n return sb.deleteCharAt(sb.length() -1).toString();\n}\n</code></pre>\n" }, { "answer_id": 36477801, "author": "rmuller", "author_id": 868941, "author_profile": "https://Stackoverflow.com/users/868941", "pm_score": 4, "selected": false, "text": "<p>In <strong>Java 7</strong> and later you can simply use (and in contrast to <code>URI</code>, it is bug free):</p>\n\n<pre><code>Path#relativize(Path)\n</code></pre>\n" }, { "answer_id": 41411138, "author": "Mike", "author_id": 448078, "author_profile": "https://Stackoverflow.com/users/448078", "pm_score": 0, "selected": false, "text": "<p>Passes Dónal's tests, the only change - if no common root it returns target path (it could be already relative)</p>\n\n<pre><code>import static java.util.Arrays.asList;\nimport static java.util.Collections.nCopies;\nimport static org.apache.commons.io.FilenameUtils.normalizeNoEndSeparator;\nimport static org.apache.commons.io.FilenameUtils.separatorsToUnix;\nimport static org.apache.commons.lang3.StringUtils.getCommonPrefix;\nimport static org.apache.commons.lang3.StringUtils.isBlank;\nimport static org.apache.commons.lang3.StringUtils.isNotEmpty;\nimport static org.apache.commons.lang3.StringUtils.join;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ResourceUtils {\n\n public static String getRelativePath(String targetPath, String basePath, String pathSeparator) {\n File baseFile = new File(basePath);\n if (baseFile.isFile() || !baseFile.exists() &amp;&amp; !basePath.endsWith(\"/\") &amp;&amp; !basePath.endsWith(\"\\\\\"))\n basePath = baseFile.getParent();\n\n String target = separatorsToUnix(normalizeNoEndSeparator(targetPath));\n String base = separatorsToUnix(normalizeNoEndSeparator(basePath));\n\n String commonPrefix = getCommonPrefix(target, base);\n if (isBlank(commonPrefix))\n return targetPath.replaceAll(\"/\", pathSeparator);\n\n target = target.replaceFirst(commonPrefix, \"\");\n base = base.replaceFirst(commonPrefix, \"\");\n\n List&lt;String&gt; result = new ArrayList&lt;&gt;();\n if (isNotEmpty(base))\n result.addAll(nCopies(base.split(\"/\").length, \"..\"));\n result.addAll(asList(target.replaceFirst(\"^/\", \"\").split(\"/\")));\n\n return join(result, pathSeparator);\n }\n}\n</code></pre>\n" }, { "answer_id": 43308179, "author": "Ben Hutchison", "author_id": 979493, "author_profile": "https://Stackoverflow.com/users/979493", "pm_score": 0, "selected": false, "text": "<p>If you're writing a Maven plugin, you can use <a href=\"https://codehaus-plexus.github.io/plexus-utils/apidocs/org/codehaus/plexus/util/PathTool.html\" rel=\"nofollow noreferrer\">Plexus' <code>PathTool</code></a>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import org.codehaus.plexus.util.PathTool;\n\nString relativeFilePath = PathTool.getRelativeFilePath(file1, file2);\n</code></pre>\n" }, { "answer_id": 47494646, "author": "alftank", "author_id": 8603796, "author_profile": "https://Stackoverflow.com/users/8603796", "pm_score": 0, "selected": false, "text": "<p>If Paths is not available for JRE 1.5 runtime or maven plugin</p>\n\n<pre><code>package org.afc.util;\n\nimport java.io.File;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class FileUtil {\n\n public static String getRelativePath(String basePath, String filePath) {\n return getRelativePath(new File(basePath), new File(filePath));\n }\n\n public static String getRelativePath(File base, File file) {\n\n List&lt;String&gt; bases = new LinkedList&lt;String&gt;();\n bases.add(0, base.getName());\n for (File parent = base.getParentFile(); parent != null; parent = parent.getParentFile()) {\n bases.add(0, parent.getName());\n }\n\n List&lt;String&gt; files = new LinkedList&lt;String&gt;();\n files.add(0, file.getName());\n for (File parent = file.getParentFile(); parent != null; parent = parent.getParentFile()) {\n files.add(0, parent.getName());\n }\n\n int overlapIndex = 0;\n while (overlapIndex &lt; bases.size() &amp;&amp; overlapIndex &lt; files.size() &amp;&amp; bases.get(overlapIndex).equals(files.get(overlapIndex))) {\n overlapIndex++;\n }\n\n StringBuilder relativePath = new StringBuilder();\n for (int i = overlapIndex; i &lt; bases.size(); i++) {\n relativePath.append(\"..\").append(File.separatorChar);\n }\n\n for (int i = overlapIndex; i &lt; files.size(); i++) {\n relativePath.append(files.get(i)).append(File.separatorChar);\n }\n\n relativePath.deleteCharAt(relativePath.length() - 1);\n return relativePath.toString();\n }\n\n}\n</code></pre>\n" }, { "answer_id": 65433687, "author": "nullsector76", "author_id": 12715384, "author_profile": "https://Stackoverflow.com/users/12715384", "pm_score": 0, "selected": false, "text": "<p>I know this is a bit late but, I created a solution that works with any java version.</p>\n<pre><code> public static String getRealtivePath(File root, File file) \n {\n String path = file.getPath();\n String rootPath = root.getPath();\n boolean plus1 = path.contains(File.separator);\n return path.substring(path.indexOf(rootPath) + rootPath.length() + (plus1 ? 1 : 0));\n }\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23424/" ]
Given two absolute paths, e.g. ``` /var/data/stuff/xyz.dat /var/data ``` How can one create a relative path that uses the second path as its base? In the example above, the result should be: `./stuff/xyz.dat`
It's a little roundabout, but why not use URI? It has a relativize method which does all the necessary checks for you. ``` String path = "/var/data/stuff/xyz.dat"; String base = "/var/data"; String relative = new File(base).toURI().relativize(new File(path).toURI()).getPath(); // relative == "stuff/xyz.dat" ``` Please note that for file path there's `java.nio.file.Path#relativize` since Java 1.7, as pointed out by [@Jirka Meluzin](https://stackoverflow.com/users/1113396/jirka-meluzin) in [the other answer](https://stackoverflow.com/a/25743823/537554).
204,801
<p>I believe the following VB.Net code is the equivalent of the proceeding C# code; however the VB.Net test fails - the event handling Lambda is never called.</p> <p>What is going on?</p> <p>VB.Net version - fails:</p> <pre class="lang-vb prettyprint-override"><code>&lt;TestFixture()&gt; _ Public Class TestClass &lt;Test()&gt; _ Public Sub EventTest() Dim eventClass As New EventClass Dim eventRaised As Boolean = False AddHandler eventClass.AnEvent, Function() (eventRaised = True) eventClass.RaiseIt() Assert.IsTrue(eventRaised) End Sub End Class Public Class EventClass Public Event AnEvent() Public Sub RaiseIt() RaiseEvent AnEvent() End Sub End Class </code></pre> <p>C# version - passes:</p> <pre><code>[TestFixture] public class TestClass { [Test] public void EventTest() { var eventClass = new EventClass(); var eventRaised = false; eventClass.AnEvent += () =&gt; { eventRaised = true; }; eventClass.RaiseIt(); Assert.IsTrue(eventRaised); } } public class EventClass { public delegate void EventHandler(); public event EventHandler AnEvent; public void RaiseIt() { AnEvent(); } } </code></pre>
[ { "answer_id": 204992, "author": "Gareth D", "author_id": 3580, "author_profile": "https://Stackoverflow.com/users/3580", "pm_score": 5, "selected": true, "text": "<blockquote>\n <p><strong>Note:</strong> This relates to older versions of VB.net Prior to Visual Studio 2010 and VB.net 10</p>\n</blockquote>\n\n<p>The difference is that in VB.Net a lambda expression must return a value i.e. they must be functions not subs. The lambda expression <code>eventRaised = true</code> is being interpreted as a boolean expression rather than an assignment i.e. is evaluating to false rather than setting to true.</p>\n\n<p>Further details on <a href=\"http://msdn.microsoft.com/en-us/library/bb531253.aspx\" rel=\"noreferrer\">MSDN</a>.</p>\n\n<p>I'm don't think the c# pattern for testing events used in the example can be done in VB.Net without introducing another function e.g.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>&lt;TestFixture()&gt; _\nPublic Class Test\n &lt;Test()&gt; _\n Public Sub EventTest()\n Dim eventClass As New EventClass\n Dim eventRaised As Boolean = False\n AddHandler eventClass.AnEvent, Function() (SetValueToTrue(eventRaised))\n eventClass.RaiseIt()\n Assert.IsTrue(eventRaised)\n End Sub\n\n Private Function SetValueToTrue(ByRef value As Boolean) As Boolean\n value = True\n Return True\n End Function\n\nEnd Class\n\nPublic Class EventClass\n Public Event AnEvent()\n Public Sub RaiseIt()\n RaiseEvent AnEvent()\n End Sub\nEnd Class\n</code></pre>\n" }, { "answer_id": 216036, "author": "Denis Troller", "author_id": 29336, "author_profile": "https://Stackoverflow.com/users/29336", "pm_score": 2, "selected": false, "text": "<p>Long story short, you cannot do that in VB for the time being (it is on the list of features considered for next release). You have to use a declared method and the AddressOf operator.</p>\n\n<p>The VB team did not have the time to include anonymous delegates in the language (which is what you are trying to use, technically not a lambda expression).</p>\n\n<p>Lambda expressions they had to implement so that Linq can actually work. Anonymous delegates are not required by anything (but would be quite useful). I guess they spent more time on wrapping up things like Linq To XML and XML litterals and integrating more query operators in the syntax...</p>\n" }, { "answer_id": 14182962, "author": "svick", "author_id": 41071, "author_profile": "https://Stackoverflow.com/users/41071", "pm_score": 5, "selected": false, "text": "<p>For those finding this question now: since Visual Basic 2010 (VB 10.0), anonymous <code>Sub</code>s do work, so you can write something like:</p>\n\n<pre><code>Sub() eventRaised = True\n</code></pre>\n" }, { "answer_id": 62450550, "author": "Ahmed_mag", "author_id": 11241728, "author_profile": "https://Stackoverflow.com/users/11241728", "pm_score": 0, "selected": false, "text": "<p>WPF controls that have popups require an instance of the WPF Application Object. In a WPF application, this is automatically created. This is not the case in a WinForm application. For this reason, this object must be created manually. The Application also must be set to remain open until it is shut down through code, otherwise it will shut automatically when the WinForm applications determines it is no longer needed. The following code will open the Application object in a WinForm and keep it open until it is closed. Shutting down the Application object when the WinForm closes is the recommended approach.</p>\n\n<pre><code> Dim app As System.Windows.Application = New System.Windows.Application With {\n .ShutdownMode = Windows.ShutdownMode.OnExplicitShutdown\n }\n AddHandler Closed, Sub()\n app.Shutdown()\n End Sub\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3580/" ]
I believe the following VB.Net code is the equivalent of the proceeding C# code; however the VB.Net test fails - the event handling Lambda is never called. What is going on? VB.Net version - fails: ```vb <TestFixture()> _ Public Class TestClass <Test()> _ Public Sub EventTest() Dim eventClass As New EventClass Dim eventRaised As Boolean = False AddHandler eventClass.AnEvent, Function() (eventRaised = True) eventClass.RaiseIt() Assert.IsTrue(eventRaised) End Sub End Class Public Class EventClass Public Event AnEvent() Public Sub RaiseIt() RaiseEvent AnEvent() End Sub End Class ``` C# version - passes: ``` [TestFixture] public class TestClass { [Test] public void EventTest() { var eventClass = new EventClass(); var eventRaised = false; eventClass.AnEvent += () => { eventRaised = true; }; eventClass.RaiseIt(); Assert.IsTrue(eventRaised); } } public class EventClass { public delegate void EventHandler(); public event EventHandler AnEvent; public void RaiseIt() { AnEvent(); } } ```
> > **Note:** This relates to older versions of VB.net Prior to Visual Studio 2010 and VB.net 10 > > > The difference is that in VB.Net a lambda expression must return a value i.e. they must be functions not subs. The lambda expression `eventRaised = true` is being interpreted as a boolean expression rather than an assignment i.e. is evaluating to false rather than setting to true. Further details on [MSDN](http://msdn.microsoft.com/en-us/library/bb531253.aspx). I'm don't think the c# pattern for testing events used in the example can be done in VB.Net without introducing another function e.g. ```vb <TestFixture()> _ Public Class Test <Test()> _ Public Sub EventTest() Dim eventClass As New EventClass Dim eventRaised As Boolean = False AddHandler eventClass.AnEvent, Function() (SetValueToTrue(eventRaised)) eventClass.RaiseIt() Assert.IsTrue(eventRaised) End Sub Private Function SetValueToTrue(ByRef value As Boolean) As Boolean value = True Return True End Function End Class Public Class EventClass Public Event AnEvent() Public Sub RaiseIt() RaiseEvent AnEvent() End Sub End Class ```
204,813
<p>In the past people used to wrap HTML comment tags around blocks of JavaScript in order to prevent "older" browsers from displaying the script. Even Lynx is smart enough to ignore JavaScript, so why do some people keep doing this? Are there any valid reasons these days?</p> <pre><code>&lt;script type="text/javascript"&gt; &lt;!-- //some js code //--&gt; &lt;/script&gt; </code></pre> <p>Edit: There is ONE situation I did encounter. Some code editors, such as Dreamweaver, get confused by quoted HTML inside a JavaScript string when in "design view" and try to display it as part of your page.</p>
[ { "answer_id": 204825, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 7, "selected": true, "text": "<p>No, absolutely not. Any user agent, search engine spider, or absolutely anything else these days is smart enough to ignore Javascript if it can't execute it.</p>\n\n<p>There was only a very brief period when this was at all helpful, and it was around 1996.</p>\n" }, { "answer_id": 204895, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 4, "selected": false, "text": "<p>There isn't a good reason to do this anymore, as the browsers which required this have by and large disappeared from the web.</p>\n\n<p>In fact, doing this can actually cause unintended problems with certain older browsers' attempts to interpret the page if it uses XHTML - from <a href=\"http://developer.mozilla.org/en/Properly_Using_CSS_and_JavaScript_in_XHTML_Documents#Use_of_Comments_Inside_Inline_style_and_script\" rel=\"noreferrer\">developer.mozilla.org</a>:</p>\n\n<blockquote>\n <ul>\n <li><p>Mozilla 1.1+/Opera 7</p>\n \n <p>Do not apply CSS or execute the JavaScript. </p></li>\n <li><p>Netscape 7.0x/Mozilla 1.0.x</p>\n \n <p>Do not apply CSS but does execute the JavaScript. </p></li>\n <li><p>Internet Explorer 5.5+</p>\n \n <p>Can not display the document.</p></li>\n </ul>\n</blockquote>\n\n<p>That site also links to examples of the <a href=\"http://developer.mozilla.org/en/Properly_Using_CSS_and_JavaScript_in_XHTML_Documents/Examples#Problem_2\" rel=\"noreferrer\">several</a> <a href=\"http://developer.mozilla.org/en/Properly_Using_CSS_and_JavaScript_in_XHTML_Documents/Examples#Problem_3\" rel=\"noreferrer\">problems</a> mentioned above.</p>\n" }, { "answer_id": 207749, "author": "Ionuț Staicu", "author_id": 23810, "author_profile": "https://Stackoverflow.com/users/23810", "pm_score": 4, "selected": false, "text": "<p>You should use CDATA though...</p>\n\n<pre><code>&lt;script type=\"text/javascript\" charset=\"utf-8\"&gt;\n/* &lt;![CDATA[ */\n\n/* ]]&gt; */\n&lt;/script&gt;\n</code></pre>\n\n<p>Because if you have '&lt;', '>', '&amp;', etc in your code, the code won't validate :)</p>\n" }, { "answer_id": 251722, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 1, "selected": false, "text": "<p>Not having to use CDATA blocks is one of the reasons I prefer to use HTML 4.01 Strict as my docttype, but, Staicu, I thought it used the following syntax:</p>\n\n<pre><code>&lt;script charset=\"utf-8\"&gt;\n//&lt;![CDATA[\n\n//]]&gt;\n&lt;/script&gt;\n</code></pre>\n\n<p>Maybe the two are equivalent? Anyone know if there is an advantage to one over the other?</p>\n" }, { "answer_id": 677725, "author": "Tim Büthe", "author_id": 60518, "author_profile": "https://Stackoverflow.com/users/60518", "pm_score": 4, "selected": false, "text": "<p>Hell no, nobody needs this anymore and if you do, you have some more problems to care about. When you really want to support browsers that need that, you have to watch out for a lot more things. Not even talking about the lack of css!</p>\n\n<p>However, the bigger problem is, that people do this wrong. Actually your example is wrong, because the line </p>\n\n<pre><code>--&gt;\n</code></pre>\n\n<p>should read</p>\n\n<pre><code>//--&gt;\n</code></pre>\n\n<p>secondly, you type attribute says \"text/JavaScript\" what is wrong too. It has been \"text/javascript\" (all lower case) but this is obsolete (see the <a href=\"http://www.iana.org/assignments/media-types/text/\" rel=\"noreferrer\">IANA List</a>) and now it should be \"application/javascript\" (see <a href=\"http://www.iana.org/assignments/media-types/application/\" rel=\"noreferrer\">another IANA List</a>. However, Douglas Crockford, the JS Guru, said you just should leave it out.</p>\n\n<p>Another Problem nobody mentioned already is this: Within HTML comments, \"--\" is not allowed and that means you can't use \"x--\" to decrement x by one.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12579/" ]
In the past people used to wrap HTML comment tags around blocks of JavaScript in order to prevent "older" browsers from displaying the script. Even Lynx is smart enough to ignore JavaScript, so why do some people keep doing this? Are there any valid reasons these days? ``` <script type="text/javascript"> <!-- //some js code //--> </script> ``` Edit: There is ONE situation I did encounter. Some code editors, such as Dreamweaver, get confused by quoted HTML inside a JavaScript string when in "design view" and try to display it as part of your page.
No, absolutely not. Any user agent, search engine spider, or absolutely anything else these days is smart enough to ignore Javascript if it can't execute it. There was only a very brief period when this was at all helpful, and it was around 1996.
204,814
<p>Wow, I just got back a huge project in C# from outsourced developers and while going through my code review my analysis tool revealed bunches of what it considered bad stuff. One of the more discouraging messages was:</p> <pre><code>Exceptions.DontSwallowErrorsCatchingNonspecificExceptionsRule : 2106 defects </code></pre> <p>The developers assure me they had good reason for all the empty catch blocks, that sometimes the try with empty catch blocks are just there to ignore useless exceptions and keep the application from crashing. I feel this is a cop out and complete BS. Some of the examples I actually looked up were database calls where the record was being saved to the database, and in this case, if an exception was ignored, the user would get back an okay prompt, think everything was okay, and continue on with their work. In reality, their work was never saved. I think this is absolutely the most horrible kind of error. In this case, they are completely wrong in throwing that code in a try with an empty catch block. But my question is, "Is this EVER acceptable in ANY situation?" I think not, but I've been known to be wrong. </p>
[ { "answer_id": 204826, "author": "Maxime Rouiller", "author_id": 24975, "author_profile": "https://Stackoverflow.com/users/24975", "pm_score": 4, "selected": false, "text": "<p>I sometimes use a WebControl that is not compulsory for a page to display. If it fails, I don't want to prevent the page from displaying. An example of a non-critical WebControl would be one that displays an advertisement.</p>\n\n<p>However, I do log the error. I just don't rethrow it.</p>\n" }, { "answer_id": 204827, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>It depends on the framework. Badly implemented frameworks might actually require this. I recall a hack in VB6 where there was no way to determine whether a collection contained an element. The only way was to try to retrieve the element and swallow the error.</p>\n" }, { "answer_id": 204832, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 4, "selected": false, "text": "<p>I don't catch exceptions unless I plan to do something about them. Ignoring them isn't doing something about them.</p>\n" }, { "answer_id": 204838, "author": "Dustin Getz", "author_id": 20003, "author_profile": "https://Stackoverflow.com/users/20003", "pm_score": 3, "selected": false, "text": "<p>in critical code, probably not, because the state of the program must always be exactly defined. like your database call example.</p>\n\n<p>in noncritical code, sure, we do it too (we just display caught exceptions in a message box and keep running). maybe a plugin or module is failing, but the main program isn't affected. maybe a lexical_cast failed and there's a text glitch rendered to the screen. No need to halt the process.</p>\n" }, { "answer_id": 204844, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "<p>Yes, its acceptable (unavoidable, necessary) in certain circumstances per Maxim's post. That doesnt mean you have to like it. 2106 violations is probably WAY too many and at the least they should have added a comment in the catch block as to why it was ok to swallow this exception.</p>\n\n<p>@Dustin\nIts bad practice to show any exception details to a public user (stack traces, line numbers, etc). You should probably log the exception and display a generic error.</p>\n" }, { "answer_id": 204858, "author": "Kena", "author_id": 8027, "author_profile": "https://Stackoverflow.com/users/8027", "pm_score": 3, "selected": false, "text": "<p>One example of where I'd consider this acceptable is in some non-critical module of a critical application (say, in the sound feedback module of the space shuttle navigation system), for exceptions that should never happen, and cannot be handled more cleanly. </p>\n\n<p>In those cases, you would not want to let that exception propagate and cause the whole application to fail (Sorry guys, no more navigation system, our beeping module crashed, and there was really nothing we could do about it). </p>\n\n<p>Edited to say that in any of these cases, you'd at least want to log the event somewhere. </p>\n" }, { "answer_id": 204861, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 1, "selected": false, "text": "<p>That's a really bad thing to be doing.</p>\n\n<p>While there <em>are</em> valid reasons you might want to ignore exceptions - if it's expected in some way, and there's no need to do anything about it - however doing it 2000 times seems like they just want to sweep their exceptions under the rug.</p>\n\n<p>Examples of where it's OK to swallow exceptions might be probing for things... you send off a message to some device or module, but you don't care if it actually gets there.</p>\n" }, { "answer_id": 204870, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 7, "selected": true, "text": "<p>While there are some reasonable reasons for ignoring exceptions; however, generally it is only specific exceptions that you are able to safely ignore. As noted by <a href=\"https://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception#204827\">Konrad Rudolph</a>, you might have to catch and swallow an error as part of a framework; and as noted by <a href=\"https://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception#204873\">osp70</a>, there might be an exception generated by a framework that you know you can ignore.</p>\n\n<p>In both of these cases though, you will likely know the exception type and if you know the type then you should have code similar to the following:</p>\n\n<pre><code>try {\n // Do something that might generate an exception\n} catch (System.InvalidCastException ex) {\n // This exception is safe to ignore due to...\n} catch (System.Exception ex) {\n // Exception handling\n}\n</code></pre>\n\n<p>In the case of your application, is sounds like something similar might apply in some cases; but the example you give of a database save returning an \"OK\" even when there is an exception is not a very good sign.</p>\n" }, { "answer_id": 204873, "author": "osp70", "author_id": 2357, "author_profile": "https://Stackoverflow.com/users/2357", "pm_score": 3, "selected": false, "text": "<p>I think that if you have an empty catch block you need to document why it is empty so that the next developer will know. For example on server.transfer a web exception is sometimes thrown. I catch that and comment that we can ignore it because of the transfer call. </p>\n" }, { "answer_id": 204884, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 3, "selected": false, "text": "<p>Generally no, in fact no in 99% of all cases, BUT</p>\n\n<p>There are exceptions. One one project I worked on we used a third party library to handle a TWAIN device. It was buggy and under some hardware combinations would throw a null pointer error. However we never found any circumstances when it didn't actually manage to scan the document before it did that - so catching the exception was entirely rational.</p>\n\n<p>So I think if it's your code that's throwing the exception then you should always check it, but if you're stuck with third party code then in some circumstances you may be forced to eat the exception and move on.</p>\n" }, { "answer_id": 204888, "author": "Clayton", "author_id": 22201, "author_profile": "https://Stackoverflow.com/users/22201", "pm_score": 4, "selected": false, "text": "<p>My feeling is that any empty Catch Block needs a comment.</p>\n\n<p>Possibly it's valid to ignore certain errors, but you need to document your reasons.</p>\n\n<p>Also, you wouldn't want to make it a generic \"catch (Exception e) { }\".</p>\n\n<p>You should catch only the specific error type that's expected there and is known to be safely ignored.</p>\n" }, { "answer_id": 204915, "author": "Even Mien", "author_id": 73794, "author_profile": "https://Stackoverflow.com/users/73794", "pm_score": 2, "selected": false, "text": "<p>When it comes to Exceptions, <em>there are always exceptions</em>.</p>\n" }, { "answer_id": 204972, "author": "Davy8", "author_id": 23822, "author_profile": "https://Stackoverflow.com/users/23822", "pm_score": 0, "selected": false, "text": "<p>I think the best rule of thumb is only ignore an exception if you're completely aware of what the exception means and the possible ramifications of it. In the case of some isolated module that doesn't affect the rest of your system I think it would be okay to just catch the generic Exception as long as you know nothing bad happens to anything else.</p>\n\n<p>IMO it's easier to know the ramifications in Java since each method is required to declare all exceptions it can throw so you know what to expect, but in C# an exception can be thrown even if it isn't documented, so it's hard to know all the possible exceptions that can be thrown by a method, and lacking that knowledge it is usually a bad idea to catch all.</p>\n" }, { "answer_id": 205022, "author": "belugabob", "author_id": 13397, "author_profile": "https://Stackoverflow.com/users/13397", "pm_score": 3, "selected": false, "text": "<p>The other case where you can be excused for catching and ignoring exceptions is when you're unit testing.</p>\n\n<pre><code>public void testSomething(){\n try{\n fooThatThrowsAnException(parameterThatCausesTheException);\n fail(\"The method didn't throw the exception that we expected it to\");\n } catch(SomeException e){\n // do nothing, as we would expect this to happen, if the code works OK.\n }\n}\n</code></pre>\n\n<p>Note that, even though the catch block does nothing, it explains why.</p>\n\n<p>Having said this, more recent testing frameworks (Junit4 &amp; TestNG) allow you to specify the exception that is expected - which leads to somthing like this...</p>\n\n<pre><code>@Test(expected = SomeException.class)\npublic void testSomething(){\n fooThatThrowsAnException(parameterThatCausesTheException);\n fail(\"The method didn't throw the exception that we expected it to\");\n}\n</code></pre>\n" }, { "answer_id": 205086, "author": "user28205", "author_id": 28205, "author_profile": "https://Stackoverflow.com/users/28205", "pm_score": 1, "selected": false, "text": "<p>The following only applies to languages that have checked exceptions, e.g. Java:</p>\n\n<p>Sometimes a method throws a checked Exception that you <em>know</em> won't happen, e.g. some java APIs expect an encoding name as a string and throw a UnsupportedEncodingException if the given encoding isn't supported. But usually i pass a literal \"UTF-8\" that i know is supported so I could theoretically write an empty catch there.</p>\n\n<p>Instead of doing that (empty catch) I usually throw a generic unchecked exception wrapping the \"impossible\" exception, or I even declare a class ImpossibleException that i throw. Because my theory about that error condition being impossible might be wrong and in that case I wouldn't want the exception to be swallowed.</p>\n" }, { "answer_id": 205163, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 3, "selected": false, "text": "<p>I guess from what I gather the best answer is that it can be somewhat acceptable but should be limited. You should try to use another alternative, and if you can't find another alternative, you should know enough about how the code works that you can expect specific exception types and not just use the blanket catch all \"Exception\". Documentation of the reason why this exception is ignored should be included in the form of an understandable comment. </p>\n" }, { "answer_id": 205392, "author": "Aaron Palmer", "author_id": 24908, "author_profile": "https://Stackoverflow.com/users/24908", "pm_score": 1, "selected": false, "text": "<p>I like to let almost all of my exceptions bubble up to an application handler where they are logged and a generic error message is displayed to the end user. But the caveat here is that there should not be very many exceptions that actually occur. If your application is throwing many exceptions, then there's probably something wrong or something that could have been coded better. For the most part, I try to make sure that my code checks for exceptional cases in advanced because generating exceptions is expensive. </p>\n\n<p>As an aside, outsourcing coding is generally a bad idea. From my experience, usually they are consultants who are only in it for the paycheck and have no stake in the success of the project. Also, you surrender to their -lack of- coding standards (unless you included that in the contract). </p>\n" }, { "answer_id": 205718, "author": "Clayton", "author_id": 22201, "author_profile": "https://Stackoverflow.com/users/22201", "pm_score": 2, "selected": false, "text": "<p>I think the original question has been well answered, but one thing I'd like to add is that if you think these outsourced/contracted developers produced poor quality work, you should make sure the right people at your company know about it.</p>\n\n<p>There may be a chance that it can be sent back for rework, that payment can be partially withheld, or that the same firm won't be used again. If your company uses contractors again, they might find a way to build quality requirements into the agreements, assuming that's not alredy there.</p>\n\n<p>If this was in-house work, there would be consequences to the team/individual that produced substandard work. Maybe that would just mean that they have to work nights and weekends to fix it, but they'd be on the hook for it one way or another. The same should apply to contractors, possibly even more so.</p>\n\n<p>Just be careful to explain your position professionally and with a focus on what's best for the company/product. You don't want it to seem like you're just complaining, or that you have some kind of political objection to outsourcing. Don't make it about you. Make it about cost, time to market, customer satisfaction, etc. You know, all those things that management types care about.</p>\n" }, { "answer_id": 205883, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>I wonder about this specific one a lot.</p>\n\n<pre><code>Connection con = DriverManager.getConnection(url, \"***\", \"***\");\n\ntry {\n PreparedStatement pStmt = con.prepareStatement(\"your query here\");\n\n ... // query the database and get the results\n}\ncatch(ClassNotFoundException cnfe) {\n // real exception handling goes here\n}\ncatch(SQLException sqle) {\n // real exception handling goes here\n}\nfinally {\n try {\n con.close();\n }\n catch {\n // What do you do here?\n }\n}\n</code></pre>\n\n<p>I never know what to do in that last catch in the finally block. I've never seen close() throw an exception before, and it's so unlikely that I don't worry about it. I just log the exception and move on.</p>\n" }, { "answer_id": 205888, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 3, "selected": false, "text": "<p>There are certainly circumstances where it's OK to catch a specific exception and do nothing. Here's a trivial example:</p>\n\n<pre><code> public FileStream OpenFile(string path)\n {\n FileStream f = null;\n try\n {\n f = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);\n }\n catch (FileNotFoundException)\n {\n }\n return f;\n }\n</code></pre>\n\n<p>You could also write the method this way:</p>\n\n<pre><code> public FileStream OpenFile(string path)\n {\n FileStream f = null;\n FileInfo fi = new FileInfo(path);\n if (fi.Exists)\n {\n f = new FileStream(path, FileMode.Open, FileAccess.ReadWrite); \n }\n return f;\n }\n</code></pre>\n\n<p>In this case, catching the exception is (very) marginally safer, as the file could get deleted between the time you check for its existence and the time you open it.</p>\n\n<p>There are reasons <em>not</em> to do this, sure. In .NET, exceptions are computationally expensive, so you want to avoid anything that throws a lot of them. (In Python, where exceptions are cheap, it's a common idiom to use exceptions to do things like break out of loops.)</p>\n\n<p>But that's ignoring a <em>specific</em> exception. This code:</p>\n\n<pre><code>catch\n{\n}\n</code></pre>\n\n<p>is inexcusable. </p>\n\n<p>There's no good reason not to catch the specific typed exception that the code in the <code>try</code> block is going to throw. The first reason that the naive developer gives for catching exceptions irrespective of type, \"But I don't know what type of exception might get thrown,\" is kind of the answer to the question. </p>\n\n<p>If you don't know what type of exception might get thrown, you don't know how your code can fail. If you don't know how your code can fail, you have no basis for assuming that it's OK to just continue processing if it does.</p>\n" }, { "answer_id": 205922, "author": "David Robbins", "author_id": 19799, "author_profile": "https://Stackoverflow.com/users/19799", "pm_score": 1, "selected": false, "text": "<p>Think of it this way - if you are expending the CPU cycles to catch the exception but then swallowing, you are ignoring a potential issue and wasting CPU. As many have said the application should not be throwing that many exceptions unless you have something poorly constructed.</p>\n" }, { "answer_id": 207543, "author": "bashmohandes", "author_id": 28120, "author_profile": "https://Stackoverflow.com/users/28120", "pm_score": 2, "selected": false, "text": "<p>Unless your catch code will either </p>\n\n<ol>\n<li>Log the exception</li>\n<li>Repackage the exception into another exception that matches the same abstraction. and throw again</li>\n<li>Handles the exception <em>the way you see suitable</em></li>\n</ol>\n\n<p>You can ignore the exception, but at least mention the expected exception in the method docs, so the consumer can expect and handle if necessary</p>\n" }, { "answer_id": 207919, "author": "Jon Bright", "author_id": 1813, "author_profile": "https://Stackoverflow.com/users/1813", "pm_score": 2, "selected": false, "text": "<p>To take an example from the Java world where it's OK to ignore an exception:</p>\n\n<pre><code>String foo=\"foobar\";\nbyte[] foobytes;\n\ntry\n{\n foobytes=foo.getBytes(\"UTF-8\");\n}\ncatch (UnsupportedEncodingException uee)\n{\n // This is guaranteed by the Java Language Specification not to occur, \n // since every Java implementation is required to support UTF-8.\n}\n</code></pre>\n\n<p>That said, even in situations like this, I'll often instead use</p>\n\n<pre><code>...\ncatch (UnsupportedEncodingException uee)\n{\n // This is guaranteed by the Java Language Specification not to occur, \n // since every Java implementation is required to support UTF-8.\n uee.printStackTrace();\n}\n</code></pre>\n\n<p>If the virtual machine is going to be mad/spec-breaking, there's little I can do about it, but with the stack trace, I at least get to notice when it started its descent into madness...</p>\n" }, { "answer_id": 357635, "author": "GWLlosa", "author_id": 18071, "author_profile": "https://Stackoverflow.com/users/18071", "pm_score": 1, "selected": false, "text": "<p>We have an application that does a lot of processing on behalf of other applications, where you insert some job (collection of config) into a database and the app will take it and run it at the appropriate time. We tend to swallow a lot of exceptions in that application, because even if Job1 dies in a horrifying fashion with a catastrophic error, we want the app to stay alive to take a stab at processing Job2.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18893/" ]
Wow, I just got back a huge project in C# from outsourced developers and while going through my code review my analysis tool revealed bunches of what it considered bad stuff. One of the more discouraging messages was: ``` Exceptions.DontSwallowErrorsCatchingNonspecificExceptionsRule : 2106 defects ``` The developers assure me they had good reason for all the empty catch blocks, that sometimes the try with empty catch blocks are just there to ignore useless exceptions and keep the application from crashing. I feel this is a cop out and complete BS. Some of the examples I actually looked up were database calls where the record was being saved to the database, and in this case, if an exception was ignored, the user would get back an okay prompt, think everything was okay, and continue on with their work. In reality, their work was never saved. I think this is absolutely the most horrible kind of error. In this case, they are completely wrong in throwing that code in a try with an empty catch block. But my question is, "Is this EVER acceptable in ANY situation?" I think not, but I've been known to be wrong.
While there are some reasonable reasons for ignoring exceptions; however, generally it is only specific exceptions that you are able to safely ignore. As noted by [Konrad Rudolph](https://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception#204827), you might have to catch and swallow an error as part of a framework; and as noted by [osp70](https://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception#204873), there might be an exception generated by a framework that you know you can ignore. In both of these cases though, you will likely know the exception type and if you know the type then you should have code similar to the following: ``` try { // Do something that might generate an exception } catch (System.InvalidCastException ex) { // This exception is safe to ignore due to... } catch (System.Exception ex) { // Exception handling } ``` In the case of your application, is sounds like something similar might apply in some cases; but the example you give of a database save returning an "OK" even when there is an exception is not a very good sign.
204,823
<p>I'm required to write documentation for my current project that lists all .c files and for each one lists every .h file which is directly or indirectly included by that file.</p> <p>This is a large project, and although we have Makefiles which theoretically have this information, those Makefiles are sometimes incorrect (we inherited this project from another company). We've often had to do a <code>make clean ; make</code> for our changes to actually be reflected in the recompilation, so I don't want to rely on these Makefiles.</p> <p>So is there a tool which lets us give it the name of a .c file and an include path and have it tell us all of the .h files which are directly or indirectly included by the .c file? We don't have anything weird like</p> <pre><code>#define my_include "some_file.h" #include my_include </code></pre> <p>so the tool doesn't need to be perfect. Anything that searched .c and .h files in an include path for regular includes would be good enough.</p>
[ { "answer_id": 204893, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p><code>gcc -M file.c</code> does what you need.</p>\n" }, { "answer_id": 204930, "author": "Mark Baker", "author_id": 11815, "author_profile": "https://Stackoverflow.com/users/11815", "pm_score": 5, "selected": true, "text": "<p>What I do in my Makefile is</p>\n\n<pre><code>SRCS=$(wildcard *.c)\n\ndepend: $(SRCS)\n gcc -M $(CFLAGS) $(SRCS) &gt;depend\n\ninclude depend\n</code></pre>\n\n<p>This means that if any of the source files are updated, the depend rule will run, and use gcc -M to update the file called depend. This is then included in the makefile to provide the dependency rules for all the source files.</p>\n\n<p>Make will check that a file is up to date before including it, so this depend rule will run if necessary whenever you run make without you needing to do a \"make depend\".</p>\n\n<p>This will run any time any file has changed. I've never found this a problem, but if you had a huge number of files in the directory you might find it took too long, in which case you could try having one dependency file per source file, like this:</p>\n\n<pre><code>SRCS=$(wildcard *.c)\nDEPS=$(SRCS:.c=.dep)\n\n%.dep : %.c\n gcc -M $(CFLAGS) $&lt; &gt;$@\n\ninclude $(DEPS)\n</code></pre>\n\n<p>Note that you can use -MM instead of -M to not include system headers.</p>\n" }, { "answer_id": 204951, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 1, "selected": false, "text": "<p>In MSVC (2005 and 2008 at least, possibly other versions as well but not VC6) you can get the compiler to tell you all the files that were included during compilation. The output is quite verbose, but complete and fairly easy to parse with human eyes.</p>\n\n<p>In Project Settings, go to the C/C++>Advanced tab, and toggle \"Show Includes,\" then rebuild your project from the ground up.</p>\n" }, { "answer_id": 211749, "author": "Jonathan Wright", "author_id": 28840, "author_profile": "https://Stackoverflow.com/users/28840", "pm_score": 2, "selected": false, "text": "<p>An alternative to gcc -M is <a href=\"https://fastdep.louislivi.com/#/en/\" rel=\"nofollow noreferrer\">fastdep</a>. Fastdep's author reports fastdep to be ten times faster than gcc's -M. If the project takes a while to build, fastdep may be worth a look.</p>\n" }, { "answer_id": 244341, "author": "humble_guru", "author_id": 23961, "author_profile": "https://Stackoverflow.com/users/23961", "pm_score": 2, "selected": false, "text": "<p>Use SCons</p>\n\n<pre><code>$ scons --tree=all\nscons: Reading SConscript files ...\n\nscons: done reading SConscript files.\nscons: Building targets ...\nscons: `.' is up to date.\n+-.\n +-SConstruct\n +-app\n | +-test.o\n | | +-test.c\n | | +-/include/PCI_1149_1.h\n | | +-/include/Pci.h\n | | +-/usr/bin/gcc\n | +-/usr/bin/gcc\n | +-/lib/libpci1149_64.a\n ...\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694/" ]
I'm required to write documentation for my current project that lists all .c files and for each one lists every .h file which is directly or indirectly included by that file. This is a large project, and although we have Makefiles which theoretically have this information, those Makefiles are sometimes incorrect (we inherited this project from another company). We've often had to do a `make clean ; make` for our changes to actually be reflected in the recompilation, so I don't want to rely on these Makefiles. So is there a tool which lets us give it the name of a .c file and an include path and have it tell us all of the .h files which are directly or indirectly included by the .c file? We don't have anything weird like ``` #define my_include "some_file.h" #include my_include ``` so the tool doesn't need to be perfect. Anything that searched .c and .h files in an include path for regular includes would be good enough.
What I do in my Makefile is ``` SRCS=$(wildcard *.c) depend: $(SRCS) gcc -M $(CFLAGS) $(SRCS) >depend include depend ``` This means that if any of the source files are updated, the depend rule will run, and use gcc -M to update the file called depend. This is then included in the makefile to provide the dependency rules for all the source files. Make will check that a file is up to date before including it, so this depend rule will run if necessary whenever you run make without you needing to do a "make depend". This will run any time any file has changed. I've never found this a problem, but if you had a huge number of files in the directory you might find it took too long, in which case you could try having one dependency file per source file, like this: ``` SRCS=$(wildcard *.c) DEPS=$(SRCS:.c=.dep) %.dep : %.c gcc -M $(CFLAGS) $< >$@ include $(DEPS) ``` Note that you can use -MM instead of -M to not include system headers.
204,829
<p>Situation:</p> <ul> <li>text: a string</li> <li>R: a regex that matches part of the string. This might be expensive to calculate. </li> </ul> <p>I want to both delete the R-matches from the text, and see what they actually contain. Currently, I do this like:</p> <pre><code>import re ab_re = re.compile("[ab]") text="abcdedfe falijbijie bbbb laifsjelifjl" ab_re.findall(text) # ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a'] ab_re.sub('',text) # 'cdedfe flijijie lifsjelifjl' </code></pre> <p>This runs the regex twice, near as I can tell. Is there a technique to do it all on pass, perhaps using re.split? It seems like with split based solutions I'd need to do the regex at least twice as well. </p>
[ { "answer_id": 204961, "author": "Hamish Downer", "author_id": 3189, "author_profile": "https://Stackoverflow.com/users/3189", "pm_score": 0, "selected": false, "text": "<p>You could use split with capturing parantheses. If you do, then the text of all groups in the pattern are also returned as part of the resulting list (from <a href=\"http://www.python.org/doc/2.5.2/lib/node46.html\" rel=\"nofollow noreferrer\">python doc</a>).</p>\n\n<p>So the code would be </p>\n\n<pre><code>import re\nab_re = re.compile(\"([ab])\")\ntext=\"abcdedfe falijbijie bbbb laifsjelifjl\"\nmatches = ab_re.split(text)\n# matches = ['', 'a', '', 'b', 'cdedfe f', 'a', 'lij', 'b', 'ijie ', 'b', '', 'b', '', 'b', '', 'b', ' l', 'a', 'ifsjelifjl']\n\n# now extract the matches\nRmatches = []\nremaining = []\nfor i in range(1, len(matches), 2):\n Rmatches.append(matches[i])\n# Rmatches = ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']\n\nfor i in range(0, len(matches), 2):\n remaining.append(matches[i])\nremainingtext = ''.join(remaining)\n# remainingtext = 'cdedfe flijijie lifsjelifjl'\n</code></pre>\n" }, { "answer_id": 204981, "author": "Deestan", "author_id": 6848, "author_profile": "https://Stackoverflow.com/users/6848", "pm_score": 3, "selected": true, "text": "<pre><code>import re\n\nr = re.compile(\"[ab]\")\ntext = \"abcdedfe falijbijie bbbb laifsjelifjl\"\n\nmatches = []\nreplaced = []\npos = 0\nfor m in r.finditer(text):\n matches.append(m.group(0))\n replaced.append(text[pos:m.start()])\n pos = m.end()\nreplaced.append(text[pos:])\n\nprint matches\nprint ''.join(replaced)\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']\ncdedfe flijijie lifsjelifjl\n</code></pre>\n" }, { "answer_id": 205056, "author": "Gregg Lind", "author_id": 15842, "author_profile": "https://Stackoverflow.com/users/15842", "pm_score": 2, "selected": false, "text": "<p>My revised answer, using <strong>re.split()</strong>, which does things in one regex pass:</p>\n\n<pre><code>import re\ntext=\"abcdedfe falijbijie bbbb laifsjelifjl\"\nab_re = re.compile(\"([ab])\")\ntokens = ab_re.split(text)\nnon_matches = tokens[0::2]\nmatches = tokens[1::2]\n</code></pre>\n\n<p>(edit: here is a complete function version)</p>\n\n<pre><code>def split_matches(text,compiled_re):\n ''' given a compiled re, split a text \n into matching and nonmatching sections\n returns m, n_m, two lists\n '''\n tokens = compiled_re.split(text)\n matches = tokens[1::2]\n non_matches = tokens[0::2]\n return matches,non_matches\n\nm,nm = split_matches(text,ab_re)\n''.join(nm) # equivalent to ab_re.sub('',text)\n</code></pre>\n" }, { "answer_id": 205072, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 2, "selected": false, "text": "<p>What about this:</p>\n\n<pre><code>import re\n\ntext = \"abcdedfe falijbijie bbbb laifsjelifjl\"\nmatches = []\n\nab_re = re.compile( \"[ab]\" )\n\ndef verboseTest( m ):\n matches.append( m.group(0) )\n return ''\n\ntextWithoutMatches = ab_re.sub( verboseTest, text )\n\nprint matches\n# ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']\nprint textWithoutMatches\n# cdedfe flijijie lifsjelifjl\n</code></pre>\n\n<p>The 'repl' argument of the <strong>re.sub</strong> function can be a function so you can report or save the matches from there and whatever the function returns is what 'sub' will substitute.</p>\n\n<p>The function could easily be modified to do a lot more too! Check out <a href=\"http://docs.python.org/library/re.html#module-contents\" rel=\"nofollow noreferrer\">the re module documentation</a> on docs.python.org for more information on what else is possible.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15842/" ]
Situation: * text: a string * R: a regex that matches part of the string. This might be expensive to calculate. I want to both delete the R-matches from the text, and see what they actually contain. Currently, I do this like: ``` import re ab_re = re.compile("[ab]") text="abcdedfe falijbijie bbbb laifsjelifjl" ab_re.findall(text) # ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a'] ab_re.sub('',text) # 'cdedfe flijijie lifsjelifjl' ``` This runs the regex twice, near as I can tell. Is there a technique to do it all on pass, perhaps using re.split? It seems like with split based solutions I'd need to do the regex at least twice as well.
``` import re r = re.compile("[ab]") text = "abcdedfe falijbijie bbbb laifsjelifjl" matches = [] replaced = [] pos = 0 for m in r.finditer(text): matches.append(m.group(0)) replaced.append(text[pos:m.start()]) pos = m.end() replaced.append(text[pos:]) print matches print ''.join(replaced) ``` Outputs: ``` ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a'] cdedfe flijijie lifsjelifjl ```
204,852
<p>I have an xsd like this </p> <pre><code>&lt;xsd:complexType name="A"&gt; &lt;xsd:complexContent&gt; &lt;xsd:sequence&gt; &lt;xsd:element name="options"&gt; &lt;xsd:complexType&gt; &lt;xsd:sequence&gt; &lt;xsd:element name="Day"&gt; ... &lt;/xsd:element&gt; &lt;/xsd:sequence&gt; &lt;/xsd:complexType&gt; &lt;/xsd:element&gt; &lt;/xsd:sequence&gt; &lt;/xsd:complexContent&gt; &lt;/xsd:complexType&gt; &lt;xsd:complexType name="B"&gt; &lt;xsd:complexContent&gt; &lt;xsd:extension base="A"&gt; ...What would go here... &lt;/xsd:extension&gt; &lt;/xsd:complexContent&gt; &lt;/xsd:complexType&gt; </code></pre> <p>So basically I want class A to have a sequence of options (Day, Week for example) then I want B to inherit from A and have all of A's options and an additional 2 or 3 options like hours, seconds.</p>
[ { "answer_id": 205247, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 3, "selected": false, "text": "<p>Simply add an <code>&lt;xsd:sequence&gt;</code> with the required elements:</p>\n\n<pre><code>&lt;xsd:complexType name=\"B\"&gt; \n &lt;xsd:complexContent&gt;\n &lt;xsd:extension base=\"A\"&gt;\n &lt;xsd:sequence&gt;\n &lt;xsd:element name=\"Hours\"&gt;\n ...\n &lt;/xsd:element&gt;\n &lt;/xsd:sequence&gt;\n &lt;/xsd:extension&gt;\n &lt;/xsd:complexContent&gt;\n&lt;/xsd:complexType&gt;\n</code></pre>\n" }, { "answer_id": 207449, "author": "tunaranch", "author_id": 27708, "author_profile": "https://Stackoverflow.com/users/27708", "pm_score": 0, "selected": false, "text": "<p>You'll need to create a type for options, which contains hours etc, and then add options instead of hours in csgero's answer.</p>\n" }, { "answer_id": 207487, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": 6, "selected": true, "text": "<p>Here's the schema I came up with:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;xs:schema id=\"inheritance\"\n targetNamespace=\"http://test.com\"\n elementFormDefault=\"qualified\"\n xmlns=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:test=\"http://test.com\"\n&gt;\n &lt;xs:element name=\"Time\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"First\" type=\"test:A\" /&gt;\n &lt;xs:element name=\"Second\" type=\"test:B\" /&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n\n &lt;xs:complexType name=\"shortOptions\"&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"Day\" /&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n\n &lt;xs:complexType name=\"longOptions\"&gt;\n &lt;xs:complexContent&gt;\n &lt;xs:extension base=\"test:shortOptions\"&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"Week\" /&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:extension&gt;\n &lt;/xs:complexContent&gt;\n &lt;/xs:complexType&gt;\n\n &lt;xs:complexType name=\"A\"&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"options\" type=\"test:shortOptions\" /&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n\n &lt;xs:complexType name=\"B\"&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"options\" type=\"test:longOptions\" /&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n\n&lt;/xs:schema&gt;\n</code></pre>\n\n<p>Which seems to fit this xml:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;Time xmlns=\"http://test.com\"&gt;\n &lt;First&gt;\n &lt;options&gt;\n &lt;Day&gt;Today&lt;/Day&gt;\n &lt;/options&gt;\n &lt;/First&gt;\n &lt;Second&gt;\n &lt;options&gt;\n &lt;Day&gt;Tomorrow&lt;/Day&gt;\n &lt;Week&gt;This Week&lt;/Week&gt;\n &lt;/options&gt;\n &lt;/Second&gt;\n&lt;/Time&gt;\n</code></pre>\n" }, { "answer_id": 207528, "author": "nedruod", "author_id": 5504, "author_profile": "https://Stackoverflow.com/users/5504", "pm_score": 1, "selected": false, "text": "<p>You will need to define options as a complex type of it's own, then use extension on that to create a new options complex type and use substitution instead of extension.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22763/" ]
I have an xsd like this ``` <xsd:complexType name="A"> <xsd:complexContent> <xsd:sequence> <xsd:element name="options"> <xsd:complexType> <xsd:sequence> <xsd:element name="Day"> ... </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexContent> </xsd:complexType> <xsd:complexType name="B"> <xsd:complexContent> <xsd:extension base="A"> ...What would go here... </xsd:extension> </xsd:complexContent> </xsd:complexType> ``` So basically I want class A to have a sequence of options (Day, Week for example) then I want B to inherit from A and have all of A's options and an additional 2 or 3 options like hours, seconds.
Here's the schema I came up with: ``` <?xml version="1.0" encoding="utf-8"?> <xs:schema id="inheritance" targetNamespace="http://test.com" elementFormDefault="qualified" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:test="http://test.com" > <xs:element name="Time"> <xs:complexType> <xs:sequence> <xs:element name="First" type="test:A" /> <xs:element name="Second" type="test:B" /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="shortOptions"> <xs:sequence> <xs:element name="Day" /> </xs:sequence> </xs:complexType> <xs:complexType name="longOptions"> <xs:complexContent> <xs:extension base="test:shortOptions"> <xs:sequence> <xs:element name="Week" /> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="A"> <xs:sequence> <xs:element name="options" type="test:shortOptions" /> </xs:sequence> </xs:complexType> <xs:complexType name="B"> <xs:sequence> <xs:element name="options" type="test:longOptions" /> </xs:sequence> </xs:complexType> </xs:schema> ``` Which seems to fit this xml: ``` <?xml version="1.0" encoding="utf-8" ?> <Time xmlns="http://test.com"> <First> <options> <Day>Today</Day> </options> </First> <Second> <options> <Day>Tomorrow</Day> <Week>This Week</Week> </options> </Second> </Time> ```
204,877
<p>What does the following mean?</p> <pre><code>Class.Function(variable := 1 + 1) </code></pre> <p>What is this operator called, and what does it do? </p>
[ { "answer_id": 204902, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 0, "selected": false, "text": "<p>It assigns the optional parameter \"variable\" the value 2.</p>\n" }, { "answer_id": 204935, "author": "Ikke", "author_id": 20261, "author_profile": "https://Stackoverflow.com/users/20261", "pm_score": 5, "selected": true, "text": "<p>It is used to assign optional variables, without assigning the previous ones.</p>\n\n<pre><code>sub test(optional a as string = \"\", optional b as string = \"\")\n msgbox(a &amp; b)\nend sub\n</code></pre>\n\n<p>you can now do</p>\n\n<pre><code>test(b:= \"blaat\")\n'in stead of\ntest(\"\", \"blaat\")\n</code></pre>\n" }, { "answer_id": 204947, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 0, "selected": false, "text": "<p>VB.NET supports this syntax for named (optional) parameters in method calls. This particular syntax informs <code>Class.Function</code> that its parameter <code>variable</code> is to be set to 2 (1 + 1).</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40/" ]
What does the following mean? ``` Class.Function(variable := 1 + 1) ``` What is this operator called, and what does it do?
It is used to assign optional variables, without assigning the previous ones. ``` sub test(optional a as string = "", optional b as string = "") msgbox(a & b) end sub ``` you can now do ``` test(b:= "blaat") 'in stead of test("", "blaat") ```
204,886
<p>you can request the http header to check if a web page has been edited by looking at its date but how about dynamic pages such as - php, aspx- which grabs its data from a database?</p>
[ { "answer_id": 204898, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 0, "selected": false, "text": "<p>You can if it uses the http response headers correctly but it's often overlooked.</p>\n\n<p>Otherwise storing a local md5-hash of the content might be useful to you (unless there's an easier in-content string you could hook out). It's not ideal (because it's quite a slow process) but it's an option.</p>\n" }, { "answer_id": 204946, "author": "Jon Adams", "author_id": 2291, "author_profile": "https://Stackoverflow.com/users/2291", "pm_score": 0, "selected": false, "text": "<p>Yes, you can and should use HTTP headers to mark pages as unexpired. If they are dynamic though (PHP, ASPX, etc.) and/or database driven, you'll need to manually control setting the Expires header/sending HTTP Not Modified appropriately. ASP.NET has some SqlDependency objects for this, but they still need to be configured and managed. (Not sure if PHP has something just like it, but there's probably something in PEAR if not...)</p>\n" }, { "answer_id": 204953, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 1, "selected": false, "text": "<p>This is the exact purpose of the <em><a href=\"http://en.wikipedia.org/wiki/HTTP_ETag\" rel=\"nofollow noreferrer\">ETag</a></em> header, but it has to be supported by your web framework or you need to take care that your application responds properly to requests with headers <em>If-Match</em>, <em>If-Not-Match</em> and <em>If-Range</em> (see <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11\" rel=\"nofollow noreferrer\">HTTP Ch 3.11</a>).</p>\n" }, { "answer_id": 204971, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 0, "selected": false, "text": "<p>The <code>Last-Modified</code> header will only be of use to you if the programmer of the site has explicitly set it to be returned.</p>\n\n<p>For a regular, static page <code>Last-Modified</code> is the timestamp of the last modification of the HTML file. For a dynamically generated page the server can't reliably assign a <code>Last-Modified</code> value as it has no real way of knowing how the content has changed depending on request, so many servers don't generate the header at all.</p>\n\n<p>If you have control over the page, then ensuring the Last Modified header is being set will ensure a check on <code>Last-Modified</code> is successful. Otherwise you may have to fetch the page and either perform a regex to find a changed section (e.g. date/time in the header of a news site). If no such obvious marker exists, then I'd second <a href=\"https://stackoverflow.com/questions/204886/can-i-use-http-header-to-check-if-a-dynamic-page-has-been-changed#204898\">Oli's suggestion</a> of an MD5 on the page content as a way to be sure it has changed.</p>\n" }, { "answer_id": 236380, "author": "Leandro López", "author_id": 22695, "author_profile": "https://Stackoverflow.com/users/22695", "pm_score": 2, "selected": false, "text": "<p>Even though you might think it's outdated I've always found Simon Willison's article on <a href=\"http://simonwillison.net/2003/Apr/23/conditionalGet/\" rel=\"nofollow noreferrer\">Conditional GET</a> to be more than useful. The example is in PHP but it is so simple that you can adapt it to other languages. Here it is the example:</p>\n\n<pre><code>function doConditionalGet($timestamp) {\n // A PHP implementation of conditional get, see \n // http://fishbowl.pastiche.org/archives/001132.html\n $last_modified = substr(date('r', $timestamp), 0, -5).'GMT';\n $etag = '\"'.md5($last_modified).'\"';\n\n // Send the headers\n header(\"Last-Modified: $last_modified\");\n header(\"ETag: $etag\");\n\n // See if the client has provided the required headers\n $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ?\n stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) :\n false;\n\n $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ?\n stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : \n false;\n\n if (!$if_modified_since &amp;&amp; !$if_none_match) {\n return;\n }\n\n // At least one of the headers is there - check them\n if ($if_none_match &amp;&amp; $if_none_match != $etag) {\n return; // etag is there but doesn't match\n }\n\n if ($if_modified_since &amp;&amp; $if_modified_since != $last_modified) {\n return; // if-modified-since is there but doesn't match\n }\n\n // Nothing has changed since their last request - serve a 304 and exit\n header('HTTP/1.0 304 Not Modified');\n exit;\n}\n</code></pre>\n\n<p>With this you can use HTTP verbs <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3\" rel=\"nofollow noreferrer\">GET</a> or <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4\" rel=\"nofollow noreferrer\">HEAD</a> (I think it's also possible with the <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9\" rel=\"nofollow noreferrer\">others</a>, but I can't see the reason to use them). All you need to do is adding either <code>If-Modified-Since</code> or <code>If-None-Match</code> with the respective values of headers <code>Last-Modified</code> or <code>ETag</code> sent by a previous version of the page. As of HTTP version 1.1 it's recommended <code>ETag</code> over <code>Last-Modified</code>, but both will do the work.</p>\n\n<p>This is a very simple example of how a conditional GET works. First we need to retrieve the page the usual way:</p>\n\n<pre>GET /some-page.html HTTP/1.1\nHost: example.org</pre>\n\n<p>First response with conditional headers and contents:</p>\n\n<pre>200 OK\nETag: YourETagHere</pre>\n\n<p>Now the conditional get request:</p>\n\n<pre>GET /some-page.html HTTP/1.1\nHost: example.org\nIf-None-Match: YourETagHere</pre>\n\n<p>And the response indicating you can use the cached version of the page, as only the headers are going to be delivered:</p>\n\n<pre>304 Not Modified\nETag: YourETagHere</pre>\n\n<p>With this the server notified you there was no modification to the page.</p>\n\n<p>I can also recommend you another article about conditional GET: <a href=\"http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers/\" rel=\"nofollow noreferrer\">HTTP conditional GET for RSS hackers</a>.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459737/" ]
you can request the http header to check if a web page has been edited by looking at its date but how about dynamic pages such as - php, aspx- which grabs its data from a database?
Even though you might think it's outdated I've always found Simon Willison's article on [Conditional GET](http://simonwillison.net/2003/Apr/23/conditionalGet/) to be more than useful. The example is in PHP but it is so simple that you can adapt it to other languages. Here it is the example: ``` function doConditionalGet($timestamp) { // A PHP implementation of conditional get, see // http://fishbowl.pastiche.org/archives/001132.html $last_modified = substr(date('r', $timestamp), 0, -5).'GMT'; $etag = '"'.md5($last_modified).'"'; // Send the headers header("Last-Modified: $last_modified"); header("ETag: $etag"); // See if the client has provided the required headers $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) : false; $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : false; if (!$if_modified_since && !$if_none_match) { return; } // At least one of the headers is there - check them if ($if_none_match && $if_none_match != $etag) { return; // etag is there but doesn't match } if ($if_modified_since && $if_modified_since != $last_modified) { return; // if-modified-since is there but doesn't match } // Nothing has changed since their last request - serve a 304 and exit header('HTTP/1.0 304 Not Modified'); exit; } ``` With this you can use HTTP verbs [GET](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3) or [HEAD](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4) (I think it's also possible with the [others](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9), but I can't see the reason to use them). All you need to do is adding either `If-Modified-Since` or `If-None-Match` with the respective values of headers `Last-Modified` or `ETag` sent by a previous version of the page. As of HTTP version 1.1 it's recommended `ETag` over `Last-Modified`, but both will do the work. This is a very simple example of how a conditional GET works. First we need to retrieve the page the usual way: ``` GET /some-page.html HTTP/1.1 Host: example.org ``` First response with conditional headers and contents: ``` 200 OK ETag: YourETagHere ``` Now the conditional get request: ``` GET /some-page.html HTTP/1.1 Host: example.org If-None-Match: YourETagHere ``` And the response indicating you can use the cached version of the page, as only the headers are going to be delivered: ``` 304 Not Modified ETag: YourETagHere ``` With this the server notified you there was no modification to the page. I can also recommend you another article about conditional GET: [HTTP conditional GET for RSS hackers](http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers/).
204,933
<p>I read an excel sheet into a datagrid.From there , I have managed to read the grid's rows into a DataTable object.The DataTable object has data because when I make equal a grid's datasource to that table object , the grid is populated.</p> <p>My Problem : I want to use the table object and manipulate its values using SQL server,(i.e. I want to store it as a temporary table and manipulate it using SQL queries from within C# code and , I want it to return a different result inte a grid.(I don't know how to work with temporary tables in C#)</p> <p>Here's code to execute when clicking button....</p> <pre><code> SqlConnection conn = new SqlConnection("server = localhost;integrated security = SSPI"); //is connection string incorrect? SqlCommand cmd = new SqlCommand(); //!!The method ConvertFPSheetDataTable Returns a DataTable object// cmd.Parameters.AddWithValue("#table",ConvertFPSheetDataTable(12,false,fpSpread2_Sheet1)); //I am trying to create temporary table //Here , I do a query cmd.CommandText = "Select col1,col2,SUM(col7) From #table group by col1,col2 Drop #table"; SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText,conn); DataTable dt = new DataTable(); da.Fill(dt); ***// I get an error here 'Invalid object name '#table'.'*** fpDataSet_Sheet1.DataSource = dt; //**NOTE:** fpDataSet_Sheet1 is the grid control </code></pre>
[ { "answer_id": 204964, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>Putting the data into a database will take time - since you already have it in memory, perhaps LINQ-to-Objects (with DataSetExtensions) is your friend? Replace &lt;int&gt; etc with the correct types...</p>\n\n<pre><code> var query = from row in table.Rows.Cast&lt;DataRow&gt;()\n group row by new\n {\n Col1 = row.Field&lt;int&gt;(1),\n Col2 = row.Field&lt;int&gt;(2)\n } into grp\n select new\n {\n Col1 = grp.Key.Col1,\n Col2 = grp.Key.Col2,\n SumCol7 = grp.Sum(x =&gt; x.Field&lt;int&gt;(7))\n };\n foreach (var item in query)\n {\n Console.WriteLine(\"{0},{1}: {2}\",\n item.Col1, item.Col2, item.SumCol7);\n }\n</code></pre>\n" }, { "answer_id": 204997, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 0, "selected": false, "text": "<p>Pardon me, if I have not understood what you exactly want.<br>\nIf you want to perform SQL query on excel sheet, you could do it directly.</p>\n\n<p>Alternatively, you can use SQL Server to query excel (OPENROWSET or a function which I dont remember right away). Using this, you can join a sql server table with excel sheet<br></p>\n\n<p>Marc's suggestion is one more way to look at it.</p>\n" }, { "answer_id": 205312, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 0, "selected": false, "text": "<p>Perhaps you could use a DataView. You create that from a DataTable, which you already have.</p>\n\n<pre><code>dv = new DataView(dataTableName);\n</code></pre>\n\n<p>Then, you can filter (apply a SQL WHERE clause) or sort the data using the DataView's methods. You can also use Find to find a matching row, or FindRows to find all matching rows.</p>\n\n<p>Some filters: </p>\n\n<pre><code>dv.RowFilter = \"Country = 'USA'\";\ndv.RowFilter = \"EmployeeID &gt;5 AND Birthdate &lt; #1/31/82#\"\ndv.RowFilter = \"Description LIKE '*product*'\"\ndv.RowFilter = \"employeeID IN (2,4,5)\"\n</code></pre>\n\n<p>Sorting:</p>\n\n<pre><code>dv.Sort = \"City\"\n</code></pre>\n\n<p>Finding a row: Find the customer named \"John Smith\".</p>\n\n<pre><code> vals(0)= \"John\"\n vals(1) = \"Smith\"\n i = dv.Find(vals)\n</code></pre>\n\n<p>where i is the index of the row containing the customer.</p>\n\n<p>Once you've applied these to the DataView, you can bind your grid to the DataView.</p>\n" }, { "answer_id": 205383, "author": "Ryan Abbott", "author_id": 27908, "author_profile": "https://Stackoverflow.com/users/27908", "pm_score": 2, "selected": false, "text": "<p>I don't think you can make a temp table in SQL the way you are thinking, since it only exists within the scope of the query/stored procedure that creates it.</p>\n\n<p>If the spreadsheet is a standard format - meaning you know the columns and they are always the same, you would want to create a Table in SQL to put this file into. There is a very fast way to do this called SqlBulkCopy</p>\n\n<pre><code>// Load the reports in bulk\nSqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString);\n// Map the columns\nforeach(DataColumn col in dataTable.Columns)\n bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);\nbulkCopy.DestinationTableName = \"SQLTempTable\";\nbulkCopy.WriteToServer(dataTable);\n</code></pre>\n\n<p>But, if I'm understanding your problem correctly, you don't need to use SQL server to modify the data in the DataTable. You c an use the JET engine to grab the data for you.</p>\n\n<pre><code> // For CSV\n connStr = string.Format(\"Provider=Microsoft.JET.OLEDB.4.0;Data Source={0};Extended Properties='Text;HDR=Yes;FMT=Delimited;IMEX=1'\", Folder);\n cmdStr = string.Format(\"SELECT * FROM [{0}]\", FileName);\n // For XLS\n connStr = string.Format(\"Provider=Microsoft.JET.OLEDB.4.0;Data Source={0}{1};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'\", Folder, FileName);\n cmdStr = \"select * from [Sheet1$]\";\nOleDbConnection oConn = new OleDbConnection(connStr);\n OleDbCommand cmd = new OleDbCommand(cmdStr, oConn);\n OleDbDataAdapter da = new OleDbDataAdapter(cmd);\n oConn.Open();\n da.Fill(dataTable);\n oConn.Close();\n</code></pre>\n\n<p>Also, in your code you ask if your connection string is correct. I don't think it is (but I could be wrong). If yours isn't working try this.</p>\n\n<pre><code>connectionString=\"Data Source=localhost\\&lt;instance&gt;;database=&lt;yourDataBase&gt;;Integrated Security=SSPI\" providerName=\"System.Data.SqlClient\"\n</code></pre>\n" }, { "answer_id": 252277, "author": "user32957", "author_id": 32957, "author_profile": "https://Stackoverflow.com/users/32957", "pm_score": 3, "selected": false, "text": "<p>Change your temp table from #table to ##table in both places.</p>\n\n<p>Using ## means a global temp table that stays around. You'll need to Drop it after you have completed your task.</p>\n\n<p>Command = \" Drop Table ##table\"</p>\n" }, { "answer_id": 18109049, "author": "Al Option", "author_id": 2024420, "author_profile": "https://Stackoverflow.com/users/2024420", "pm_score": 0, "selected": false, "text": "<p>Change the command text from</p>\n\n<pre><code>Select col1,col2,SUM(col7) From #table group by col1,col2\n</code></pre>\n\n<p>to</p>\n\n<pre><code>Select col1,col2,SUM(col7) From @#table group by col1,col2\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I read an excel sheet into a datagrid.From there , I have managed to read the grid's rows into a DataTable object.The DataTable object has data because when I make equal a grid's datasource to that table object , the grid is populated. My Problem : I want to use the table object and manipulate its values using SQL server,(i.e. I want to store it as a temporary table and manipulate it using SQL queries from within C# code and , I want it to return a different result inte a grid.(I don't know how to work with temporary tables in C#) Here's code to execute when clicking button.... ``` SqlConnection conn = new SqlConnection("server = localhost;integrated security = SSPI"); //is connection string incorrect? SqlCommand cmd = new SqlCommand(); //!!The method ConvertFPSheetDataTable Returns a DataTable object// cmd.Parameters.AddWithValue("#table",ConvertFPSheetDataTable(12,false,fpSpread2_Sheet1)); //I am trying to create temporary table //Here , I do a query cmd.CommandText = "Select col1,col2,SUM(col7) From #table group by col1,col2 Drop #table"; SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText,conn); DataTable dt = new DataTable(); da.Fill(dt); ***// I get an error here 'Invalid object name '#table'.'*** fpDataSet_Sheet1.DataSource = dt; //**NOTE:** fpDataSet_Sheet1 is the grid control ```
Change your temp table from #table to ##table in both places. Using ## means a global temp table that stays around. You'll need to Drop it after you have completed your task. Command = " Drop Table ##table"
204,942
<p>We have an application that installs SQL Server Express from the command line and specifies the service account as the LocalSystem account via the parameter SQLACCOUNT="NT AUTHORITY\SYSTEM".</p> <p>This doesn't work with different languages because the account name for LocalSystem is different. There's a table listing the differences here:</p> <p><a href="http://forums.microsoft.com/MSR/ShowPost.aspx?PostID=685354&amp;SiteID=37" rel="nofollow noreferrer">http://forums.microsoft.com/MSR/ShowPost.aspx?PostID=685354&amp;SiteID=37</a></p> <p>This doesn't seem to be complete (the Swedish version isn't listed). So I'd like to be able to determine the name programmatically, perhaps using the SID?</p> <p>I've found some VB Script to do this:</p> <pre><code>Set objWMI = GetObject("winmgmts:root\cimv2") Set objSid = objWMI.Get("Win32_SID.SID='S-1-5-18'") MsgBox objSid.ReferencedDomainName &amp; "\" &amp; objSid.AccountName </code></pre> <p>Does anyone know the equivalent code that can be used in C#?</p>
[ { "answer_id": 204955, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 1, "selected": false, "text": "<p>This should do something similar to what you posted. I'm not sure how to get specific properties of WMI objects offhand, but this will get you started with the syntax:</p>\n\n<pre><code>ManagementObject m = new ManagementObject(\"winmgmts:root\\cimv2\");\nm.Get();\nMessageBox.Show(m[\"Win32_SID.SID='S-1-5-18'\"].ToString());\n</code></pre>\n" }, { "answer_id": 205012, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 4, "selected": true, "text": "<p>You can use .NET's built-in <a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.securityidentifier.aspx\" rel=\"noreferrer\">System.Security.Principal.SecurityIdentifier</a> class for this purpose: by translating it into an instance of <a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.ntaccount.aspx\" rel=\"noreferrer\">NtAccount</a> you can obtain the account name:</p>\n\n<pre><code>using System.Security.Principal;\n\n\nSecurityIdentifier sid = new SecurityIdentifier(\"S-1-5-18\");\nNTAccount acct = (NTAccount)sid.Translate(typeof(NTAccount));\nConsole.WriteLine(acct.Value);\n</code></pre>\n\n<p>Later edit, in response to question in comments: you do not need any special privileges to do SID-to-name lookups on the local machine -- for example, even if the user account you're running under is only in the Guests group, this code should work. Things are a little bit different if the SID resolves to a domain account, but even that should work correctly in most cases, as long as you're logged on to the domain (and a domain controller is available at the time of the lookup).</p>\n" }, { "answer_id": 1159563, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The problem with the accepted answer is that the account name must be resolvable by the local machine running the code. </p>\n\n<p>If you are reading the ACLs on a remote machine you may well not be able to resolve Domain SIDs / local SIDs on the remote box. The following uses WMI and takes the parameter of the remote machine and the SID you want the remote machine to resolve.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Returns the Account name for the specified SID \n// using WMI against the specified remote machine\n/// &lt;/summary&gt;\nprivate string RemoteSID2AccountName(String MachineName, String SIDString)\n{\n ManagementScope oScope = new ManagementScope(@\"\\\\\" + MachineName + \n @\"\\root\\cimv2\");\n ManagementPath oPath = new ManagementPath(\"Win32_SID.SID='\" + SIDString + \"'\");\n ManagementObject oObject = new ManagementObject(oScope, oPath, null);\n return oObject[\"AccountName\"].ToString();\n}\n</code></pre>\n" }, { "answer_id": 15926564, "author": "Vinicius Ottoni", "author_id": 1160608, "author_profile": "https://Stackoverflow.com/users/1160608", "pm_score": 2, "selected": false, "text": "<p>Or you can use:</p>\n\n<pre><code>string localSystem = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null).Translate(typeof(NTAccount)).Value;\n</code></pre>\n\n<p>With <code>WellKnownSidType</code> you can look for other accounts, as <code>NetworkService</code> for example.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5449/" ]
We have an application that installs SQL Server Express from the command line and specifies the service account as the LocalSystem account via the parameter SQLACCOUNT="NT AUTHORITY\SYSTEM". This doesn't work with different languages because the account name for LocalSystem is different. There's a table listing the differences here: <http://forums.microsoft.com/MSR/ShowPost.aspx?PostID=685354&SiteID=37> This doesn't seem to be complete (the Swedish version isn't listed). So I'd like to be able to determine the name programmatically, perhaps using the SID? I've found some VB Script to do this: ``` Set objWMI = GetObject("winmgmts:root\cimv2") Set objSid = objWMI.Get("Win32_SID.SID='S-1-5-18'") MsgBox objSid.ReferencedDomainName & "\" & objSid.AccountName ``` Does anyone know the equivalent code that can be used in C#?
You can use .NET's built-in [System.Security.Principal.SecurityIdentifier](http://msdn.microsoft.com/en-us/library/system.security.principal.securityidentifier.aspx) class for this purpose: by translating it into an instance of [NtAccount](http://msdn.microsoft.com/en-us/library/system.security.principal.ntaccount.aspx) you can obtain the account name: ``` using System.Security.Principal; SecurityIdentifier sid = new SecurityIdentifier("S-1-5-18"); NTAccount acct = (NTAccount)sid.Translate(typeof(NTAccount)); Console.WriteLine(acct.Value); ``` Later edit, in response to question in comments: you do not need any special privileges to do SID-to-name lookups on the local machine -- for example, even if the user account you're running under is only in the Guests group, this code should work. Things are a little bit different if the SID resolves to a domain account, but even that should work correctly in most cases, as long as you're logged on to the domain (and a domain controller is available at the time of the lookup).
204,950
<p>I have just installed the Krypton Toolkit 3.0.6 from component Factory. I find that in the create new Project Dialog Box , Krypton Form does not show up as an option. I am sure it used to show up ( and I have actually used it in an earlier version of krypton toolkit).But after the new install it does not.</p>
[ { "answer_id": 205039, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 1, "selected": false, "text": "<p>The \"New Krypton Form\" used to show up not inside the \"new project\" dialog, but inside the \"new item\" dialog. (e.g. right-click on project, Add New Item)</p>\n\n<p>But I don't see it there either. Phil may have removed this from the installer.</p>\n\n<p>In any case, just add a regular Form, then make it derive from KryptonForm rather than Form, and voila, you have yourself a KryptonForm.</p>\n" }, { "answer_id": 208226, "author": "dezkev", "author_id": 28291, "author_profile": "https://Stackoverflow.com/users/28291", "pm_score": 2, "selected": false, "text": "<p>For the sake of completeness and accuracy , I am posting the actual code for inheriting from a krypton form.</p>\n\n<pre><code>public partial class Form1 : ComponentFactory.Krypton.Toolkit.KryptonForm\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have just installed the Krypton Toolkit 3.0.6 from component Factory. I find that in the create new Project Dialog Box , Krypton Form does not show up as an option. I am sure it used to show up ( and I have actually used it in an earlier version of krypton toolkit).But after the new install it does not.
For the sake of completeness and accuracy , I am posting the actual code for inheriting from a krypton form. ``` public partial class Form1 : ComponentFactory.Krypton.Toolkit.KryptonForm ```
204,963
<p>I'm quite confused by something. I've got 2 select lists, and if you choose an option in the first, I then load the 2nd with a certain set of options. I clear this out and repopulate it every time you change the selection in the first select element. Now, on postback, I need to know the value of the option that was selected in the 2nd select element, but it is always showing up as -1.</p> <p>I'm sure I'm missing something fundamental and dumb on my part, but can anyone point me in the right direction?</p>
[ { "answer_id": 205039, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 1, "selected": false, "text": "<p>The \"New Krypton Form\" used to show up not inside the \"new project\" dialog, but inside the \"new item\" dialog. (e.g. right-click on project, Add New Item)</p>\n\n<p>But I don't see it there either. Phil may have removed this from the installer.</p>\n\n<p>In any case, just add a regular Form, then make it derive from KryptonForm rather than Form, and voila, you have yourself a KryptonForm.</p>\n" }, { "answer_id": 208226, "author": "dezkev", "author_id": 28291, "author_profile": "https://Stackoverflow.com/users/28291", "pm_score": 2, "selected": false, "text": "<p>For the sake of completeness and accuracy , I am posting the actual code for inheriting from a krypton form.</p>\n\n<pre><code>public partial class Form1 : ComponentFactory.Krypton.Toolkit.KryptonForm\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232/" ]
I'm quite confused by something. I've got 2 select lists, and if you choose an option in the first, I then load the 2nd with a certain set of options. I clear this out and repopulate it every time you change the selection in the first select element. Now, on postback, I need to know the value of the option that was selected in the 2nd select element, but it is always showing up as -1. I'm sure I'm missing something fundamental and dumb on my part, but can anyone point me in the right direction?
For the sake of completeness and accuracy , I am posting the actual code for inheriting from a krypton form. ``` public partial class Form1 : ComponentFactory.Krypton.Toolkit.KryptonForm ```
204,970
<p>Suppose I have following string:</p> <pre><code>String asd = "this is test ass this is test" </code></pre> <p>and I want to split the string using "ass" character sequence.</p> <p>I used:</p> <pre><code>asd.split("ass"); </code></pre> <p>It doesn't work. What do I need to do?</p>
[ { "answer_id": 205004, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>It seems to work fine for me:</p>\n\n<pre><code>public class Test\n{\n public static void main(String[] args) {\n String asd = \"this is test ass this is test\";\n String[] bits = asd.split(\"ass\");\n for (String bit : bits) {\n System.out.println(\"'\" + bit + \"'\");\n }\n }\n}\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>'this is test '\n' this is test'\n</code></pre>\n\n<p>Is your real delimiter different perhaps? Don't forget that split uses its parameter as a regular expression...</p>\n" }, { "answer_id": 205023, "author": "johnstok", "author_id": 27929, "author_profile": "https://Stackoverflow.com/users/27929", "pm_score": 1, "selected": true, "text": "<pre><code>public class Splitter {\n\n public static void main(final String[] args) {\n final String asd = \"this is test ass this is test\";\n final String[] parts = asd.split(\"ass\");\n for (final String part : parts) {\n System.out.println(part);\n }\n }\n}\n</code></pre>\n\n<p>Prints:</p>\n\n<pre><code>this is test \n this is test\n</code></pre>\n\n<p>Under Java 6. What output were you expecting?</p>\n" }, { "answer_id": 38609312, "author": "Bhimreddy", "author_id": 6634977, "author_profile": "https://Stackoverflow.com/users/6634977", "pm_score": 1, "selected": false, "text": "<pre><code>String asd = \"this is test foo this is test\";\nString[] parts = asd.split(\"foo\");\n</code></pre>\n\n<p>Try this it will work </p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25778/" ]
Suppose I have following string: ``` String asd = "this is test ass this is test" ``` and I want to split the string using "ass" character sequence. I used: ``` asd.split("ass"); ``` It doesn't work. What do I need to do?
``` public class Splitter { public static void main(final String[] args) { final String asd = "this is test ass this is test"; final String[] parts = asd.split("ass"); for (final String part : parts) { System.out.println(part); } } } ``` Prints: ``` this is test this is test ``` Under Java 6. What output were you expecting?
204,983
<p>If you want to associate some constant value with a class, here are two ways to accomplish the same goal:</p> <pre><code>class Foo { public: static const size_t Life = 42; }; class Bar { public: enum {Life = 42}; }; </code></pre> <p>Syntactically and semantically they appear to be identical from the client's point of view:</p> <pre><code>size_t fooLife = Foo::Life; size_t barLife = Bar::Life; </code></pre> <p>Is there any reason other than just pure style concerns why one would be preferable to another?</p>
[ { "answer_id": 204999, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>They're not identical:</p>\n\n<pre><code>size_t *pLife1 = &amp;Foo::Life;\nsize_t *pLife2 = &amp;Bar::Life;\n</code></pre>\n" }, { "answer_id": 205000, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 7, "selected": true, "text": "<p>The <code>enum</code> hack used to be necessary because many compilers didn't support in-place initialization of the value. Since this is no longer an issue, go for the other option. Modern compilers are also capable of optimizing this constant so that no storage space is required for it.</p>\n\n<p>The only reason for not using the <code>static const</code> variant is if you want to <em>forbid</em> taking the address of the value: you can't take an address of an <code>enum</code> value while you can take the address of a constant (and this would prompt the compiler to reserve space for the value after all, but only <em>if</em> its address is really taken).</p>\n\n<p>Additionally, the taking of the address will yield a link-time error unless the constant is explicitly <em>defined</em> as well. Notice that it can still be initialized at the site of declaration:</p>\n\n<pre><code>struct foo {\n static int const bar = 42; // Declaration, initialization.\n};\n\nint const foo::bar; // Definition.\n</code></pre>\n" }, { "answer_id": 205007, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<p>Well, if needed, you can take the address of a static const Member Value. You've have to declare a separate member variable of enum type to take the address of it.</p>\n" }, { "answer_id": 205016, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 3, "selected": false, "text": "<p>One difference is that the enum defines a type that can be used as a method parameter, for example, to get better type checking. Both are treated as compile time constants by the compiler, so they should generate identical code.</p>\n" }, { "answer_id": 206776, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 3, "selected": false, "text": "<h2>Another third solution?</h2>\n<p>One subtle difference is that the enum must be defined in the header, and visible for all. When you are avoiding dependencies, this is a pain. For example, in a PImpl, adding an enum is somewhat counter-productive:</p>\n<pre><code>// MyPImpl.hpp\n\nclass MyImpl ;\n\nclass MyPimpl\n{\n public :\n enum { Life = 42 } ;\n private :\n MyImpl * myImpl ;\n}\n</code></pre>\n<p>Another <strong>third solution</strong> would be a variation on the &quot;const static&quot; alternative proposed in the question: Declaring the variable in the header, but defining it in the source:</p>\n<pre><code>// MyPImpl.hpp\n\nclass MyImpl ;\n\nclass MyPimpl\n{\n public :\n static const int Life ;\n private :\n MyImpl * myImpl ;\n}\n</code></pre>\n<p>.</p>\n<pre><code>// MyPImpl.cpp\nconst int MyPImpl::Life = 42 ;\n</code></pre>\n<p>Note that the value of MyPImpl::Life is hidden from the user of MyPImpl (who includes MyPImpl.hpp).</p>\n<p>This will enable the MyPimpl author to change the value of &quot;Life&quot; as needed, without needing the MyPImpl user to recompile, as is the overall aim of the PImpl.</p>\n" }, { "answer_id": 211180, "author": "deft_code", "author_id": 28817, "author_profile": "https://Stackoverflow.com/users/28817", "pm_score": 3, "selected": false, "text": "<p><code>static const</code> values are treated as r-values just like <code>enum</code> in 99% of code you'll see. Constant r-values never have memory generated for them. The advantage <code>enum</code> constants is they can't become l-values in that other 1%. The <code>static const</code> values are type safe and allow for floats, c-strings, etc.</p>\n\n<p>The compiler will make <code>Foo::Life</code> an l-value if it has memory associated with it. The usual way to do that is to take its address. e.g. <code>&amp;Foo::Life;</code></p>\n\n<p>Here is a subtle example where GCC will use the address:</p>\n\n<pre><code>int foo = rand()? Foo::Life: Foo::Everthing;\n</code></pre>\n\n<p>The compiler generated code uses the addresses of <code>Life</code> and <code>Everything</code>. Worse, this only produces a linker error about the missing addresses for <code>Foo::Life</code> and <code>Foo::Everything</code>. This behavior is completely standard conforming, though obviously undesirable. There are other compiler specific ways that this can happen, and all standard conforming.</p>\n\n<p>Once you have a conforming c++11 compiler the correct code will be</p>\n\n<pre><code>class Foo {\n public:\n constexpr size_t Life = 42;\n};\n</code></pre>\n\n<p>This is guaranteed to always be an l-value and it's type-safe, the best of both worlds.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241536/" ]
If you want to associate some constant value with a class, here are two ways to accomplish the same goal: ``` class Foo { public: static const size_t Life = 42; }; class Bar { public: enum {Life = 42}; }; ``` Syntactically and semantically they appear to be identical from the client's point of view: ``` size_t fooLife = Foo::Life; size_t barLife = Bar::Life; ``` Is there any reason other than just pure style concerns why one would be preferable to another?
The `enum` hack used to be necessary because many compilers didn't support in-place initialization of the value. Since this is no longer an issue, go for the other option. Modern compilers are also capable of optimizing this constant so that no storage space is required for it. The only reason for not using the `static const` variant is if you want to *forbid* taking the address of the value: you can't take an address of an `enum` value while you can take the address of a constant (and this would prompt the compiler to reserve space for the value after all, but only *if* its address is really taken). Additionally, the taking of the address will yield a link-time error unless the constant is explicitly *defined* as well. Notice that it can still be initialized at the site of declaration: ``` struct foo { static int const bar = 42; // Declaration, initialization. }; int const foo::bar; // Definition. ```
204,991
<p>I'm not quite sure how this happened, but somehow a completely empty hierarchy of directories has ended up in my repository:</p> <pre><code>com/ com/companyname/ com/companyname/blah/ com/sun/ com/sun/java/ com/sun/java/jax_rpc_ri/ </code></pre> <p>I think what happened was that these directories did have files in them, but then a developer realized he/she shouldn't have checked them in in the first place since these are by-products of the build process, so he/she removed the files but somehow the empty directories are left in the repository as ancient relics.</p> <p>How can I remove this from CVS? The only results I seem to be able to find on google say that there shouldn't be a need to remove empty directories as CVS won't keep them around in the first place, and that the <code>-P</code> (prune) options to <code>cvs update</code> should remove them from the working directory - which is zero help if you actually have empty directories in your repository.</p> <p>A <code>cvs remove</code> and <code>cvs commit</code> doesn't seem to take care of this situation:</p> <pre><code>$ cvs remove -Rf com cvs remove: Removing com cvs remove: Removing com/companyname cvs remove: Removing com/companyname/blah cvs remove: Removing com/sun cvs remove: Removing com/sun/java cvs remove: Removing com/sun/java/jax_rpc_ri $ cvs commit com cvs commit: Examining com cvs commit: Examining com/companyname cvs commit: Examining com/companyname/blah cvs commit: Examining com/sun cvs commit: Examining com/sun/java cvs commit: Examining com/sun/java/jax_rpc_ri $ ls -l com total 24 drwxrwxr-x 2 matt matt 4096 Oct 15 14:38 CVS drwxrwxr-x 9 matt matt 4096 Oct 15 14:38 companyname drwxrwxr-x 4 matt matt 4096 Oct 15 14:38 sun </code></pre> <p>It's still there!</p> <p>Does SVN have this weird behavior too?</p>
[ { "answer_id": 205038, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 6, "selected": true, "text": "<p>AFAIK the CVS protocol does not allow to remove directories. You should go to the server console and remove them from the real physical repository.</p>\n\n<hr>\n\n<p><a href=\"http://www.network-theory.co.uk/docs/cvsmanual/Removingdirectories.html\" rel=\"noreferrer\">http://www.network-theory.co.uk/docs/cvsmanual/Removingdirectories.html</a></p>\n\n<blockquote>\n <p><strong>You don't remove the directory itself;\n there is no way to do that.</strong></p>\n</blockquote>\n" }, { "answer_id": 205042, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 5, "selected": false, "text": "<p>CVS checkout and update will always check out empty directories; that's just the way CVS is built. Do an update with \"-P\" -- \"prune\" -- to remove empty directories:</p>\n\n<pre><code>cvs update -dP\n</code></pre>\n\n<p>(Adding \"-d\" will update new directories that have appeared since your last update; otherwise, CVS will ignore them.)</p>\n" }, { "answer_id": 205081, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 1, "selected": false, "text": "<p>cvs tends to work on a two phase approach regarding directories that's why there is a -P option for many cvs commands to \"Prune empty directories\".</p>\n\n<p>When this has happened, e.g. want to rename a directory I've just added, I delete the directory, delete the entry for the directory in the CVS/Entries file, it'll be a line prepended with a \"D\".</p>\n\n<p>Job done.</p>\n\n<p>If I've committed, I make sure my current working area that contains the empty directory/ies is all checked in. Then I blow away the part of the work area that I have added the directories to.</p>\n\n<p>For example, in</p>\n\n<pre><code>~/Sandbox/my_project/some_stuff_i_want\n~/Sandbox/my_project/empty_dir_1\n~/Sandbox/my_project/other_stuff_i_want\n</code></pre>\n\n<p>I make sure everything is up to date in both directories containing the stuff I want to keep. I then blow away my_project from within my sandbox.</p>\n\n<p>Then I delete the empty directories <strong>from the repository itself</strong>.</p>\n\n<p>Going back and checking out the same work area, e.g. my_project will give me the work area without the empty dirs.</p>\n\n<p>Or just leave everything as is and use the -P option to get CVS check everything out (or update everything), then prune out the empty dirs.</p>\n\n<p>HTH</p>\n\n<p>cheers,</p>\n\n<p>Rob </p>\n" }, { "answer_id": 205157, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 2, "selected": false, "text": "<p>CVS has a number of design flaws, never being able to get rid of a directory without losing history is one. Difficulty renaming files and directories without losing history is another.</p>\n\n<p>Consider graduating to <a href=\"http://subversion.tigris.org/\" rel=\"nofollow noreferrer\">Subversion</a>. <a href=\"http://cvs2svn.tigris.org/\" rel=\"nofollow noreferrer\">cvs2svn</a> does a very good job converting repositories including all branches and tags. The CVS and SVN command sets are very similar and require minimal adjustment. (And to head off this becoming a \"what version control should you use\" war) once you're using SVN you can move to any number of more advanced version control systems such as <a href=\"http://git.or.cz/\" rel=\"nofollow noreferrer\">git</a> or <a href=\"http://svk.bestpractical.com/view/HomePage\" rel=\"nofollow noreferrer\">SVK</a>.</p>\n" }, { "answer_id": 1673930, "author": "Ljubomir Josifovski", "author_id": 202629, "author_profile": "https://Stackoverflow.com/users/202629", "pm_score": 3, "selected": false, "text": "<p>Just did</p>\n\n<ol>\n<li>rm -rvf /localCopy/project/emptyDirectory</li>\n<li>edit /localCopy/project/CVS/Entries, delete line D/emptyDirectory////, save file</li>\n<li>rmdir -v /CVSROOT/project/emptyDirectory</li>\n</ol>\n\n<p>to get rid of emptyDirectory in project. Admit not legit to mess with internal CVS data, but seems to have worked (cvs version 1.12.13).</p>\n" }, { "answer_id": 3890599, "author": "Pramod Jaiswal", "author_id": 470235, "author_profile": "https://Stackoverflow.com/users/470235", "pm_score": 2, "selected": false, "text": "<p>This worked for me. Basically When you do</p>\n\n<p><strong>rmdir -v /CVSROOT/project/emptyDirectory</strong> # We are deleting directory from CVS repository directory.</p>\n\n<p>If you have repository unix server login access, you can travel to the path and can delete the directory,or raise the same concern with unix team.</p>\n" }, { "answer_id": 21379077, "author": "SteveScm", "author_id": 1531757, "author_profile": "https://Stackoverflow.com/users/1531757", "pm_score": 1, "selected": false, "text": "<p>You cannot delete directory from your workspace , you need to delete it from going to server where actual repository is kept. but you can delete files from the directory with cvs remove command.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/204991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
I'm not quite sure how this happened, but somehow a completely empty hierarchy of directories has ended up in my repository: ``` com/ com/companyname/ com/companyname/blah/ com/sun/ com/sun/java/ com/sun/java/jax_rpc_ri/ ``` I think what happened was that these directories did have files in them, but then a developer realized he/she shouldn't have checked them in in the first place since these are by-products of the build process, so he/she removed the files but somehow the empty directories are left in the repository as ancient relics. How can I remove this from CVS? The only results I seem to be able to find on google say that there shouldn't be a need to remove empty directories as CVS won't keep them around in the first place, and that the `-P` (prune) options to `cvs update` should remove them from the working directory - which is zero help if you actually have empty directories in your repository. A `cvs remove` and `cvs commit` doesn't seem to take care of this situation: ``` $ cvs remove -Rf com cvs remove: Removing com cvs remove: Removing com/companyname cvs remove: Removing com/companyname/blah cvs remove: Removing com/sun cvs remove: Removing com/sun/java cvs remove: Removing com/sun/java/jax_rpc_ri $ cvs commit com cvs commit: Examining com cvs commit: Examining com/companyname cvs commit: Examining com/companyname/blah cvs commit: Examining com/sun cvs commit: Examining com/sun/java cvs commit: Examining com/sun/java/jax_rpc_ri $ ls -l com total 24 drwxrwxr-x 2 matt matt 4096 Oct 15 14:38 CVS drwxrwxr-x 9 matt matt 4096 Oct 15 14:38 companyname drwxrwxr-x 4 matt matt 4096 Oct 15 14:38 sun ``` It's still there! Does SVN have this weird behavior too?
AFAIK the CVS protocol does not allow to remove directories. You should go to the server console and remove them from the real physical repository. --- <http://www.network-theory.co.uk/docs/cvsmanual/Removingdirectories.html> > > **You don't remove the directory itself; > there is no way to do that.** > > >
205,001
<p>What's the best way to remove a page frame automatically?</p> <p>I've used this type of code before:</p> <pre><code>&lt;script language="JavaScript"&gt; setTimeout ("changePage()", 3000); function changePage() { if (self.parent.frames.length != 0) self.parent.location="http://www.example.com"; } &lt;/script&gt; </code></pre>
[ { "answer_id": 205055, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 0, "selected": false, "text": "<p>Do it this way if you want the frame-breaking step to not appear in the history</p>\n\n<pre><code>if ( self.location !== top.location )\n{\n top.location.replace( self.location );\n}\n</code></pre>\n" }, { "answer_id": 205057, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 1, "selected": false, "text": "<p>Here's an alternative that's more generic in that it doesn't name the parent URL, nor use the separate function call:</p>\n\n<pre><code>// is the current page at the top of the browser window hierarchy?\nif (top.location != self.location) \n{\n // it isn't, so force this page to be at \n // the top of the hierarchy, in its own window\n top.location = self.location \n}\n</code></pre>\n" }, { "answer_id": 205065, "author": "Remy Sharp", "author_id": 22617, "author_profile": "https://Stackoverflow.com/users/22617", "pm_score": 4, "selected": true, "text": "<p>Do you mean if someone has put a frame around your content? If so, you need the following any where in your HTML page to jump out of the iframe:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nif (window.top.location != window.location) {\n window.top.location = window.location;\n}\n&lt;/script&gt;\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28260/" ]
What's the best way to remove a page frame automatically? I've used this type of code before: ``` <script language="JavaScript"> setTimeout ("changePage()", 3000); function changePage() { if (self.parent.frames.length != 0) self.parent.location="http://www.example.com"; } </script> ```
Do you mean if someone has put a frame around your content? If so, you need the following any where in your HTML page to jump out of the iframe: ``` <script type="text/javascript"> if (window.top.location != window.location) { window.top.location = window.location; } </script> ```
205,040
<p>In my SQL database, I have a one-to-many relationship, something like this:</p> <pre> Teacher Student John Alex John Mike John Sean Bob Jack Gary George Gary Paul </pre> <p>I'd like to display a table listing each teacher, with their students as a comma-delimited list, like this:</p> <pre> Teacher Students John Alex, Mike, Sean Bob Jack Gary George, Paul </pre> <p><a href="https://stackoverflow.com/questions/180032/how-can-i-combine-multiple-rows-into-a-comma-delimited-list-in-sql-server-2005">This question</a> describes how to do this on the SQL Server end, but is there a way to do this on the SSRS side of things?</p>
[ { "answer_id": 207440, "author": "gbn", "author_id": 27535, "author_profile": "https://Stackoverflow.com/users/27535", "pm_score": 1, "selected": false, "text": "<p>Add a grouping on teacher, and use the .net Join to append the detail rows</p>\n\n<p>Join is demonstrated for multi-value parameters in BOL... so in theory it can be used for the result dataset</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/b65z3h4h.aspx\" rel=\"nofollow noreferrer\">Join</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa337292(SQL.90).aspx\" rel=\"nofollow noreferrer\">Join and multi-value parameters</a></p>\n" }, { "answer_id": 209669, "author": "AaronSieb", "author_id": 16911, "author_profile": "https://Stackoverflow.com/users/16911", "pm_score": 0, "selected": false, "text": "<p>This StackOverflow answer presents one technique for accomplishing this:</p>\n\n<p><a href=\"https://stackoverflow.com/a/977763/16911\">String aggregation in SSRS 2005</a></p>\n\n<p>The downside to this technique is that it uses shared variables in a code module, which may cause concurrency issues if the report is hosted on a network.</p>\n\n<p>I've also come across another work-around:</p>\n\n<p>Create a custom function, such as GetStudentList(TeacherId As Integer, ConnectionString As String), which is intended to return the list of students based on the specified teacher.</p>\n\n<p>This function can then be written to open a connection to the database, run a query, process the results, and then return them. But that means opening the connection and running the query for every row, which seems like a lot of overhead for this type of formatting (not to mention the need to pass in a Connection String).</p>\n\n<p>This is based largely on an <a href=\"http://www.google.com/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-US%3Aofficial&amp;hs=vTB&amp;q=site%3Aexperts-exchange.com+%22Reporting+Services%2C+access+dataset+from+RDL+custom+code+module%22&amp;btnG=Search\" rel=\"nofollow noreferrer\">Experts' Exchange article</a>.</p>\n" }, { "answer_id": 30518651, "author": "Jerry", "author_id": 53531, "author_profile": "https://Stackoverflow.com/users/53531", "pm_score": 4, "selected": true, "text": "<p>I've found a simpler, straight-forward method to do this -- add an expression as follows:</p>\n\n<pre><code>=Join(LookUpSet(Fields!TeacherName.Value, \n Fields!TeacherName.Value, \n Fields!StudentName.Value, \n \"YourTeacherDataSet\"), \",\")\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16911/" ]
In my SQL database, I have a one-to-many relationship, something like this: ``` Teacher Student John Alex John Mike John Sean Bob Jack Gary George Gary Paul ``` I'd like to display a table listing each teacher, with their students as a comma-delimited list, like this: ``` Teacher Students John Alex, Mike, Sean Bob Jack Gary George, Paul ``` [This question](https://stackoverflow.com/questions/180032/how-can-i-combine-multiple-rows-into-a-comma-delimited-list-in-sql-server-2005) describes how to do this on the SQL Server end, but is there a way to do this on the SSRS side of things?
I've found a simpler, straight-forward method to do this -- add an expression as follows: ``` =Join(LookUpSet(Fields!TeacherName.Value, Fields!TeacherName.Value, Fields!StudentName.Value, "YourTeacherDataSet"), ",") ```
205,064
<p>On Unix, is there any way that one process can change another's environment variables (assuming they're all being run by the same user)? A general solution would be best, but if not, what about the specific case where one is a child of the other?</p> <p>Edit: How about via gdb?</p>
[ { "answer_id": 205074, "author": "Mike G.", "author_id": 18901, "author_profile": "https://Stackoverflow.com/users/18901", "pm_score": 1, "selected": false, "text": "<p>If your unix supports the /proc filesystem, then it's trivial to READ the env - you can read the environment, commandline, and many other attributes of any process you own that way. Changing it... Well, I can think of a way, but it's a BAD idea.</p>\n\n<p>The more general case... I don't know, but I doubt there's a portable answer.</p>\n\n<p>(Edited: my original answer assumed the OP wanted to READ the env, not change it)</p>\n" }, { "answer_id": 205082, "author": "Davide", "author_id": 25891, "author_profile": "https://Stackoverflow.com/users/25891", "pm_score": 3, "selected": false, "text": "<p>Quoting Jerry Peek:</p>\n\n<blockquote>\n <p>You can't teach an old dog new tricks.</p>\n</blockquote>\n\n<p>The only thing you can do is to change the environment variable of the child process <strong>before</strong> starting it: it gets the copy of the parent environment, sorry.</p>\n\n<p>See <a href=\"http://www.unix.com.ua/orelly/unix/upt/ch06_02.htm\" rel=\"noreferrer\">http://www.unix.com.ua/orelly/unix/upt/ch06_02.htm</a> for details.</p>\n\n<p>Just a comment on the answer about using /proc. Under linux /proc is supported but, it does not work, you <strong>cannot</strong> change the <code>/proc/${pid}/environ</code> file, even if you are root: it is <strong>absolutely</strong> read-only.</p>\n" }, { "answer_id": 205090, "author": "Stephen Darlington", "author_id": 2998, "author_profile": "https://Stackoverflow.com/users/2998", "pm_score": 2, "selected": false, "text": "<p>Not as far as I know. Really you're trying to communicate from one process to another which calls for one of the IPC methods (shared memory, semaphores, sockets, etc.). Having received data by one of these methods you could then set environment variables or perform other actions more directly.</p>\n" }, { "answer_id": 205091, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 2, "selected": false, "text": "<p>Or get your process to update a config file for the new process and then either:</p>\n\n<ul>\n<li>perform a kill -HUP on the new process to reread the updated config file, or</li>\n<li>have the process check the config file for updates every now and then. If changes are found, then reread the config file.</li>\n</ul>\n" }, { "answer_id": 205276, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 3, "selected": false, "text": "<p>I could think of the rather contrived way to do that, and it will not work for arbitrary processes.</p>\n\n<p>Suppose that you write your own shared library which implements 'char *getenv'. Then, you set up 'LD_PRELOAD' or 'LD_LIBRARY_PATH' env. vars so that both your processes are run with your shared library preloaded.</p>\n\n<p>This way, you will essentially have a control over the code of the 'getenv' function. Then, you could do all sorts of nasty tricks. Your 'getenv' could consult external config file or SHM segment for alternate values of env vars. Or you could do regexp search/replace on the requested values. Or ... </p>\n\n<p>I can't think of an easy way to do that for arbitrary running processes (even if you are root), short of rewriting dynamic linker (ld-linux.so).</p>\n" }, { "answer_id": 209589, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 4, "selected": false, "text": "<p>Substantially, no. If you had sufficient privileges (root, or thereabouts) and poked around /dev/kmem (kernel memory), and you made changes to the process's environment, and if the process actually re-referenced the environment variable afterwards (that is, the process had not already taken a copy of the env var and was not using just that copy), then maybe, if you were lucky and clever, and the wind was blowing in the right direction, and the phase of the moon was correct, perhaps, you might achieve something. </p>\n" }, { "answer_id": 211064, "author": "An̲̳̳drew", "author_id": 17035, "author_profile": "https://Stackoverflow.com/users/17035", "pm_score": 8, "selected": true, "text": "<p>Via gdb:</p>\n\n<pre><code>(gdb) attach process_id\n\n(gdb) call putenv (\"env_var_name=env_var_value\")\n\n(gdb) detach\n</code></pre>\n\n<p>This is quite a nasty hack and should only be done in the context of a debugging scenario, of course.</p>\n" }, { "answer_id": 594122, "author": "sleske", "author_id": 43681, "author_profile": "https://Stackoverflow.com/users/43681", "pm_score": 5, "selected": false, "text": "<p>You probably can do it technically (see other answers), but it might not help you.</p>\n\n<p>Most programs will expect that env vars cannot be changed from the outside after startup, hence most will probably just read the vars they are interested in at startup and initialize based on that. So changing them afterwards will not make a difference, since the program will never re-read them.</p>\n\n<p>If you posted this as a concrete problem, you should probably take a different approach. If it was just out of curiosity: Nice question :-).</p>\n" }, { "answer_id": 594140, "author": "Ruben Bartelink", "author_id": 11635, "author_profile": "https://Stackoverflow.com/users/11635", "pm_score": 1, "selected": false, "text": "<p>Not a direct answer but... <a href=\"https://devblogs.microsoft.com/oldnewthing/20090223-00/?p=19063\" rel=\"nofollow noreferrer\">Raymond Chen had a [Windows-based] rationale around this only the other day</a> :-</p>\n<blockquote>\n<p>... Although there are certainly unsupported ways of doing it or ways that work with the assistance of a debugger, there’s nothing that is supported for programmatic access to another process’s command line, at least nothing provided by the kernel. ...</p>\n<p>That there isn’t is a consequence of the principle of not keeping track of information which you don’t need. The kernel has no need to obtain the command line of another process. It takes the command line passed to the <code>CreateProcess</code> function and copies it into the address space of the process being launched, in a location where the <code>GetCommandLine</code> function can retrieve it. Once the process can access its own command line, the kernel’s responsibilities are done.</p>\n<p>Since the command line is copied into the process’s address space, the process might even write to the memory that holds the command line and modify it. If that happens, then the original command line is lost forever; the only known copy got overwritten.</p>\n</blockquote>\n<p>In other words, any such kernel facilities would be</p>\n<ul>\n<li>difficult to implement</li>\n<li>potentially a security concern</li>\n</ul>\n<p>However the most likely reason is simply that there's limited use cases for such a facility.</p>\n" }, { "answer_id": 6187857, "author": "dvd", "author_id": 777604, "author_profile": "https://Stackoverflow.com/users/777604", "pm_score": 1, "selected": false, "text": "<p>UNIX is full of Inter-process communication. Check if your target instance has some. Dbus is becoming a standard in \"desktop\" IPC.</p>\n\n<p>I change environment variables inside of Awesome window manager using <em>awesome-client</em> with is a Dbus \"sender\" of lua code.</p>\n" }, { "answer_id": 61801422, "author": "Kakash1hatake", "author_id": 1822868, "author_profile": "https://Stackoverflow.com/users/1822868", "pm_score": 2, "selected": false, "text": "<p>It seems that <em>putenv</em> doesn't work now, but <em>setenv</em> does.\nI was testing the accepted answer while trying to set the variable in the current shell with no success</p>\n\n<pre><code>$] sudo gdb -p $$\n(gdb) call putenv(\"TEST=1234\")\n$1 = 0\n(gdb) call (char*) getenv(\"TEST\")\n$2 = 0x0\n(gdb) detach\n(gdb) quit\n$] echo \"TEST=$TEST\"\nTEST=\n</code></pre>\n\n<p>and the variant how it works:</p>\n\n<pre><code>$] sudo gdb -p $$\n(gdb) call (int) setenv(\"TEST\", \"1234\", 1)\n$1 = 0\n(gdb) call (char*) getenv(\"TEST\")\n$2 = 0x55f19ff5edc0 \"1234\"\n(gdb) detach\n(gdb) quit\n$] echo \"TEST=$TEST\"\nTEST=1234\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
On Unix, is there any way that one process can change another's environment variables (assuming they're all being run by the same user)? A general solution would be best, but if not, what about the specific case where one is a child of the other? Edit: How about via gdb?
Via gdb: ``` (gdb) attach process_id (gdb) call putenv ("env_var_name=env_var_value") (gdb) detach ``` This is quite a nasty hack and should only be done in the context of a debugging scenario, of course.
205,073
<p>This is probably a simple answer but I can't find it. I have a table with a column of integers and I want to ensure that when a row is inserted that the value in this column is greater than zero. I could do this on the code side but thought it would be best to enforce it on the table.</p> <p>Thanks!</p> <p>I was in error with my last comment all is good now.</p>
[ { "answer_id": 205093, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 3, "selected": false, "text": "<p>Create a database constraint:</p>\n\n<pre><code>ALTER TABLE Table1 ADD CONSTRAINT Constraint1 CHECK (YourCol &gt; 0)\n</code></pre>\n\n<p>You can have pretty sophisticated constraints, too, involving multiple columns. For example:</p>\n\n<pre><code>ALTER TABLE Table1 ADD CONSTRAINT Constraint2 CHECK (StartDate&lt;EndDate OR EndDate IS NULL)\n</code></pre>\n" }, { "answer_id": 205095, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 5, "selected": true, "text": "<p>You can use a check constraint on the column. IIRC the syntax for this looks like:</p>\n\n<pre><code>create table foo (\n [...]\n ,Foobar int not null check (Foobar &gt; 0)\n [...]\n)\n</code></pre>\n\n<p>As the poster below says (thanks Constantin), you should create the check constraint outside the table definition and give it a meaningful name so it is obvious which column it applies to.</p>\n\n<pre><code>alter table foo\n add constraint Foobar_NonNegative\n check (Foobar &gt; 0)\n</code></pre>\n\n<p>You can get out the text of check constraints from the system data dictionary in <code>sys.check_constraints</code>:</p>\n\n<pre><code>select name\n ,description\n from sys.check_constraints\n where name = 'Foobar_NonNegative'\n</code></pre>\n" }, { "answer_id": 205102, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 0, "selected": false, "text": "<p>Add a <code>CHECK</code> constraint when creating your table</p>\n\n<pre><code>CREATE TABLE Test(\n [ID] [int] NOT NULL,\n [MyCol] [int] NOT NULL CHECK (MyCol &gt; 1)\n)\n</code></pre>\n" }, { "answer_id": 205103, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 0, "selected": false, "text": "<p>I believe you want to add a CONSTRAINT to the table field:</p>\n\n<pre><code>ALTER TABLE tableName WITH NOCHECK\nADD CONSTRAINT constraintName CHECK (columnName &gt; 0)\n</code></pre>\n\n<p>That optional NOCHECK is used to keep the constraint from being applied to existing rows of data (which could contain invalid data) &amp; to allow the constraint to be added.</p>\n" }, { "answer_id": 65052922, "author": "Hamid Jolany", "author_id": 555078, "author_profile": "https://Stackoverflow.com/users/555078", "pm_score": 0, "selected": false, "text": "<p>you can alter your table and add new constraint like bellow.</p>\n<pre><code>BEGIN TRANSACTION\n GO\n ALTER TABLE dbo.table1 ADD CONSTRAINT\n CK_table1_field1 CHECK (field1&gt;0)\n GO\n ALTER TABLE dbo.table1 SET (LOCK_ESCALATION = TABLE)\n GO\nCOMMIT\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2357/" ]
This is probably a simple answer but I can't find it. I have a table with a column of integers and I want to ensure that when a row is inserted that the value in this column is greater than zero. I could do this on the code side but thought it would be best to enforce it on the table. Thanks! I was in error with my last comment all is good now.
You can use a check constraint on the column. IIRC the syntax for this looks like: ``` create table foo ( [...] ,Foobar int not null check (Foobar > 0) [...] ) ``` As the poster below says (thanks Constantin), you should create the check constraint outside the table definition and give it a meaningful name so it is obvious which column it applies to. ``` alter table foo add constraint Foobar_NonNegative check (Foobar > 0) ``` You can get out the text of check constraints from the system data dictionary in `sys.check_constraints`: ``` select name ,description from sys.check_constraints where name = 'Foobar_NonNegative' ```
205,087
<p>We are using jQuery <a href="http://jquery.com/demo/thickbox/" rel="noreferrer">thickbox</a> to dynamically display an iframe when someone clicks on a picture. In this iframe, we are using <a href="http://devkick.com/lab/galleria/demo_01.htm" rel="noreferrer">galleria</a> a javascript library to display multiple pictures.</p> <p>The problem seems to be that <code>$(document).ready</code> in the iframe seems to be fired too soon and the iframe content isn't even loaded yet, so galleria code is not applied properly on the DOM elements. <code>$(document).ready</code> seems to use the iframe parent ready state to decide if the iframe is ready.</p> <p>If we extract the function called by document ready in a separate function and call it after a timeout of 100&nbsp;ms. It works, but we can't take the chance in production with a slow computer.</p> <pre><code>$(document).ready(function() { setTimeout(ApplyGalleria, 100); }); </code></pre> <p>My question: which jQuery event should we bind to to be able to execute our code when the dynamic iframe is ready and not just it's a parent?</p>
[ { "answer_id": 205221, "author": "Pier Luigi", "author_id": 27789, "author_profile": "https://Stackoverflow.com/users/27789", "pm_score": 9, "selected": true, "text": "<p>I answered a similar question (see <a href=\"https://stackoverflow.com/questions/164085/javascript-callback-when-iframe-is-finished-loading\">Javascript callback when IFRAME is finished loading?</a>).\nYou can obtain control over the iframe load event with the following code:</p>\n\n<pre><code>function callIframe(url, callback) {\n $(document.body).append('&lt;IFRAME id=\"myId\" ...&gt;');\n $('iframe#myId').attr('src', url);\n\n $('iframe#myId').load(function() {\n callback(this);\n });\n}\n</code></pre>\n\n<p>In dealing with iframes I found good enough to use load event instead of document ready event.</p>\n" }, { "answer_id": 205280, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 4, "selected": false, "text": "<p>In IFrames I usually solve this problem by putting a small script to the very end of the block:</p>\n\n<pre><code>&lt;body&gt;\nThe content of your IFrame\n&lt;script type=\"text/javascript\"&gt;\n//&lt;![CDATA[\n fireOnReadyEvent();\n parent.IFrameLoaded();\n//]]&gt;\n&lt;/script&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>This work most of the time for me. Sometimes the simplest and most naive solution is the most appropriate.</p>\n" }, { "answer_id": 205539, "author": "EtienneT", "author_id": 9140, "author_profile": "https://Stackoverflow.com/users/9140", "pm_score": 2, "selected": false, "text": "<p>Found the solution to the problem.</p>\n\n<p>When you click on a thickbox link that open a iframe, it insert an iframe with an id of TB_iframeContent.</p>\n\n<p>Instead of relying on the <code>$(document).ready</code> event in the iframe code, I just have to bind to the load event of the iframe in the parent document:</p>\n\n<pre><code>$('#TB_iframeContent', top.document).load(ApplyGalleria);\n</code></pre>\n\n<p>This code is in the iframe but binds to an event of a control in the parent document. It works in FireFox and IE.</p>\n" }, { "answer_id": 735199, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Using jQuery 1.3.2 the following worked for me:</p>\n\n<pre><code>$('iframe').ready(function() {\n $('body', $('iframe').contents()).html('Hello World!');\n});\n</code></pre>\n\n<p>REVISION:!\nActually the above code sometimes looks like it works in Firefox, never looks like it works in Opera.</p>\n\n<p>Instead I implemented a polling solution for my purposes. Simplified down it looks like this:</p>\n\n<pre><code>$(function() {\n function manipIframe() {\n el = $('body', $('iframe').contents());\n if (el.length != 1) {\n setTimeout(manipIframe, 100);\n return;\n }\n el.html('Hello World!');\n }\n manipIframe();\n});\n</code></pre>\n\n<p>This doesn't require code in the called iframe pages. All code resides and executes from the parent frame/window.</p>\n" }, { "answer_id": 1555751, "author": "Danny G", "author_id": 76302, "author_profile": "https://Stackoverflow.com/users/76302", "pm_score": 1, "selected": false, "text": "<p>Try this,</p>\n\n<pre><code>&lt;iframe id=\"testframe\" src=\"about:blank\" onload=\"if (testframe.location.href != 'about:blank') testframe_loaded()\"&gt;&lt;/iframe&gt;\n</code></pre>\n\n<p>All you need to do then is create the JavaScript function testframe_loaded().</p>\n" }, { "answer_id": 11989472, "author": "Pavel Savara", "author_id": 129124, "author_profile": "https://Stackoverflow.com/users/129124", "pm_score": 1, "selected": false, "text": "<p>I'm loading the PDF with jQuery ajax into browser cache. Then I create embedded element with data already in browser cache. I guess it will work with iframe too.</p>\n\n<pre><code>\nvar url = \"http://example.com/my.pdf\";\n// show spinner\n$.mobile.showPageLoadingMsg('b', note, false);\n$.ajax({\n url: url,\n cache: true,\n mimeType: 'application/pdf',\n success: function () {\n // display cached data\n $(scroller).append('&lt;embed type=\"application/pdf\" src=\"' + url + '\" /&gt;');\n // hide spinner\n $.mobile.hidePageLoadingMsg();\n }\n});\n</code></pre>\n\n<p>You have to set your http headers correctly as well.</p>\n\n<pre><code>\nHttpContext.Response.Expires = 1;\nHttpContext.Response.Cache.SetNoServerCaching();\nHttpContext.Response.Cache.SetAllowResponseInBrowserHistory(false);\nHttpContext.Response.CacheControl = \"Private\";\n</code></pre>\n" }, { "answer_id": 16290979, "author": "Ricardo Freitas", "author_id": 689223, "author_profile": "https://Stackoverflow.com/users/689223", "pm_score": 3, "selected": false, "text": "<p>Following DrJokepu's and David Murdoch idea I implemented a more complete version.\nIt <strong>requires</strong> jQuery on both the parent and iframe and the iframe to be in your control.</p>\n\n<p><strong>iframe code:</strong></p>\n\n<pre><code>var iframe = window.frameElement;\n\nif (iframe){\n iframe.contentDocument = document;//normalization: some browsers don't set the contentDocument, only the contentWindow\n\n var parent = window.parent;\n $(parent.document).ready(function(){//wait for parent to make sure it has jQuery ready\n var parent$ = parent.jQuery;\n\n parent$(iframe).trigger(\"iframeloading\");\n\n $(function(){\n parent$(iframe).trigger(\"iframeready\");\n });\n\n $(window).load(function(){//kind of unnecessary, but here for completion\n parent$(iframe).trigger(\"iframeloaded\");\n });\n\n $(window).unload(function(e){//not possible to prevent default\n parent$(iframe).trigger(\"iframeunloaded\");\n });\n\n $(window).on(\"beforeunload\",function(){\n parent$(iframe).trigger(\"iframebeforeunload\");\n });\n });\n}\n</code></pre>\n\n<p><strong>parent test code:</strong></p>\n\n<pre><code>$(function(){\n $(\"iframe\").on(\"iframeloading iframeready iframeloaded iframebeforeunload iframeunloaded\", function(e){\n console.log(e.type);\n });\n});\n</code></pre>\n" }, { "answer_id": 35317607, "author": "Jon Freynik", "author_id": 2109714, "author_profile": "https://Stackoverflow.com/users/2109714", "pm_score": 1, "selected": false, "text": "<p>This was the exact issue I ran into with our client. I created a little jquery plugin that seems to work for iframe readiness. It uses polling to check the iframe document readyState combined with the inner document url combined with the iframe source to make sure the iframe is in fact \"ready\".</p>\n\n<p>The issue with \"onload\" is that you need access to the actual iframe being added to the DOM, if you don't then you need to try to catch the iframe loading which if it is cached then you may not. What I needed was a script that could be called anytime, and determine whether or not the iframe was \"ready\" or not.</p>\n\n<p>Here's the question: </p>\n\n<p><a href=\"https://stackoverflow.com/questions/35227469/holy-grail-for-determining-whether-or-not-local-iframe-has-loaded\">Holy grail for determining whether or not local iframe has loaded</a></p>\n\n<p>and here's the jsfiddle I eventually came up with.</p>\n\n<p><a href=\"https://jsfiddle.net/q0smjkh5/10/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/q0smjkh5/10/</a></p>\n\n<p>In the jsfiddle above, I am waiting for onload to append an iframe to the dom, then checking iframe's inner document's ready state - which should be cross domain because it's pointed to wikipedia - but Chrome seems to report \"complete\". The plug-in's iready method then gets called when the iframe is in fact ready. The callback tries to check the inner document's ready state again - this time reporting a cross domain request (which is correct) - anyway it seems to work for what I need and hope it helps others.</p>\n\n<pre><code>&lt;script&gt;\n (function($, document, undefined) {\n $.fn[\"iready\"] = function(callback) {\n var ifr = this.filter(\"iframe\"),\n arg = arguments,\n src = this,\n clc = null, // collection\n lng = 50, // length of time to wait between intervals\n ivl = -1, // interval id\n chk = function(ifr) {\n try {\n var cnt = ifr.contents(),\n doc = cnt[0],\n src = ifr.attr(\"src\"),\n url = doc.URL;\n switch (doc.readyState) {\n case \"complete\":\n if (!src || src === \"about:blank\") {\n // we don't care about empty iframes\n ifr.data(\"ready\", \"true\");\n } else if (!url || url === \"about:blank\") {\n // empty document still needs loaded\n ifr.data(\"ready\", undefined);\n } else {\n // not an empty iframe and not an empty src\n // should be loaded\n ifr.data(\"ready\", true);\n }\n\n break;\n case \"interactive\":\n ifr.data(\"ready\", \"true\");\n break;\n case \"loading\":\n default:\n // still loading\n break; \n }\n } catch (ignore) {\n // as far as we're concerned the iframe is ready\n // since we won't be able to access it cross domain\n ifr.data(\"ready\", \"true\");\n }\n\n return ifr.data(\"ready\") === \"true\";\n };\n\n if (ifr.length) {\n ifr.each(function() {\n if (!$(this).data(\"ready\")) {\n // add to collection\n clc = (clc) ? clc.add($(this)) : $(this);\n }\n });\n if (clc) {\n ivl = setInterval(function() {\n var rd = true;\n clc.each(function() {\n if (!$(this).data(\"ready\")) {\n if (!chk($(this))) {\n rd = false;\n }\n }\n });\n\n if (rd) {\n clearInterval(ivl);\n clc = null;\n callback.apply(src, arg);\n }\n }, lng);\n } else {\n clc = null;\n callback.apply(src, arg);\n }\n } else {\n clc = null;\n callback.apply(this, arguments);\n }\n return this;\n };\n }(jQuery, document));\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 45440415, "author": "udondan", "author_id": 2753241, "author_profile": "https://Stackoverflow.com/users/2753241", "pm_score": 2, "selected": false, "text": "<p>Basically what others have already posted but IMHO a bit cleaner:</p>\n\n<pre><code>$('&lt;iframe/&gt;', {\n src: 'https://example.com/',\n load: function() {\n alert(\"loaded\")\n }\n}).appendTo('body');\n</code></pre>\n" }, { "answer_id": 61968548, "author": "Crashalot", "author_id": 144088, "author_profile": "https://Stackoverflow.com/users/144088", "pm_score": 2, "selected": false, "text": "<p>This function from <a href=\"https://stackoverflow.com/a/36155560/144088\">this answer</a> is the best way to handle this as <code>$.ready</code> explicitly fails for iframes. <a href=\"https://bugs.jquery.com/ticket/1124\" rel=\"nofollow noreferrer\">Here's the decision</a> not to support this.</p>\n\n<p>The <code>load</code> event also doesn't fire if the iframe has already loaded. Very frustrating that this remains a problem in 2020!</p>\n\n<pre><code>function onIframeReady($i, successFn, errorFn) {\n try {\n const iCon = $i.first()[0].contentWindow,\n bl = \"about:blank\",\n compl = \"complete\";\n const callCallback = () =&gt; {\n try {\n const $con = $i.contents();\n if($con.length === 0) { // https://git.io/vV8yU\n throw new Error(\"iframe inaccessible\");\n }\n\n\n successFn($con);\n } catch(e) { // accessing contents failed\n errorFn();\n }\n };\n const observeOnload = () =&gt; {\n $i.on(\"load.jqueryMark\", () =&gt; {\n try {\n const src = $i.attr(\"src\").trim(),\n href = iCon.location.href;\n if(href !== bl || src === bl || src === \"\") {\n $i.off(\"load.jqueryMark\");\n callCallback();\n }\n } catch(e) {\n errorFn();\n }\n });\n };\n if(iCon.document.readyState === compl) {\n const src = $i.attr(\"src\").trim(),\n href = iCon.location.href;\n if(href === bl &amp;&amp; src !== bl &amp;&amp; src !== \"\") {\n observeOnload();\n } else {\n callCallback();\n }\n } else {\n observeOnload();\n }\n} catch(e) {\n errorFn();\n}\n</code></pre>\n\n<p>}</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9140/" ]
We are using jQuery [thickbox](http://jquery.com/demo/thickbox/) to dynamically display an iframe when someone clicks on a picture. In this iframe, we are using [galleria](http://devkick.com/lab/galleria/demo_01.htm) a javascript library to display multiple pictures. The problem seems to be that `$(document).ready` in the iframe seems to be fired too soon and the iframe content isn't even loaded yet, so galleria code is not applied properly on the DOM elements. `$(document).ready` seems to use the iframe parent ready state to decide if the iframe is ready. If we extract the function called by document ready in a separate function and call it after a timeout of 100 ms. It works, but we can't take the chance in production with a slow computer. ``` $(document).ready(function() { setTimeout(ApplyGalleria, 100); }); ``` My question: which jQuery event should we bind to to be able to execute our code when the dynamic iframe is ready and not just it's a parent?
I answered a similar question (see [Javascript callback when IFRAME is finished loading?](https://stackoverflow.com/questions/164085/javascript-callback-when-iframe-is-finished-loading)). You can obtain control over the iframe load event with the following code: ``` function callIframe(url, callback) { $(document.body).append('<IFRAME id="myId" ...>'); $('iframe#myId').attr('src', url); $('iframe#myId').load(function() { callback(this); }); } ``` In dealing with iframes I found good enough to use load event instead of document ready event.
205,112
<p>Is there any way to print in memory collection or variable size in WPF? </p> <p>I am using the following code in which I print the ListView control. But when the content is larger than the vertical scroll bar takes over and cuts the content. </p> <pre><code> PrintDialog printDialog = new PrintDialog(); printDialog.ShowDialog(); printDialog.PrintVisual(lvDocumentSummary, "testing printing!"); </code></pre>
[ { "answer_id": 205148, "author": "Artur Carvalho", "author_id": 1013, "author_profile": "https://Stackoverflow.com/users/1013", "pm_score": -1, "selected": false, "text": "<p>Interesting, Is the ListView virtualized? If it is, the object are not drawn, that is a possibility. Take a look at the Printing <a href=\"http://www.charlespetzold.com/blog/2006/02/PrintaBunchaButtons.cs\" rel=\"nofollow noreferrer\">example</a> from Petzold.</p>\n" }, { "answer_id": 206421, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": -1, "selected": false, "text": "<p>Here is my solution to this problem. It is kinda shaky but works for my scenario. </p>\n\n<p>I read my collection and transform it into a string. The whole collection now resides in a StringBuilder object. Next, I saw the text/string into a file on the client's machine and then run the notepad process with /p to print the contents of the file. </p>\n\n<p>It works and it prints the contents successfully. </p>\n\n<p>Finally, there is a timer which is called after 5 seconds and which removes the file. Basically within 5 seconds the request is already sent to the printer queue. But a better solution will be to make sure that the print job has been processed this way you will be 100% sure that the job has been performed. </p>\n" }, { "answer_id": 207991, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 0, "selected": false, "text": "<p>If you want nice printing from WPF you need to build a FixedDocument and print that, unfortunately it can be very complex depending on what you are trying to print.</p>\n\n<p>There's some example code that creates a FixedDocument here: <a href=\"http://www.ericsink.com/wpf3d/B_Printing.html\" rel=\"nofollow noreferrer\">http://www.ericsink.com/wpf3d/B_Printing.html</a></p>\n" }, { "answer_id": 208010, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 2, "selected": false, "text": "<p>FixedDocument supports DataBinding (other than FlowDocument) like any other xaml document. just host the listview in a fixeddocument and display it in a DocumentViewer (which has built-in print support).</p>\n\n<p>however, if your list is too long for one page, FixedDocument does not automatically generate a new page (like flowdocument does). therefore you have to create a new page maually with code, as this cannot be done in pure xaml.</p>\n" }, { "answer_id": 380522, "author": "Ifeanyi Echeruo", "author_id": 47702, "author_profile": "https://Stackoverflow.com/users/47702", "pm_score": 4, "selected": true, "text": "<p>To print multiple pages you just need to use a class that implements DocumentPaginator FixedDocument is one of the more complex implementations, FlowDocument is a simpler one.</p>\n\n<pre><code>FlowDocument fd = new FlowDocument();\n\nforeach(object item in items)\n{\n fd.Blocks.Add(new Paragraph(new Run(item.ToString())));\n}\n\nfd.Print();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>PrintDialog pd = new PrintDialog();\npd.PrintDocument(fd);\n</code></pre>\n" }, { "answer_id": 56609431, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Here's a 2019 answer. Some of the old answers don't work anymore, eg. FlowDocumentReader doesn't have a <code>Print</code> method. </p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> private void Button_Click(object sender, RoutedEventArgs e)\n {\n FlowDocument fd = new FlowDocument();\n foreach (var item in COLLECTION) //&lt;- put your collection here\n {\n fd.Blocks.Add(new Paragraph(new Run(item.ToString())));\n }\n\n PrintDialog pd = new PrintDialog();\n if (pd.ShowDialog() != true) return;\n\n fd.PageHeight = pd.PrintableAreaHeight;\n fd.PageWidth = pd.PrintableAreaWidth;\n\n IDocumentPaginatorSource idocument = fd as IDocumentPaginatorSource;\n\n pd.PrintDocument(idocument.DocumentPaginator, \"Printing Flow Document...\");\n }\n }\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3797/" ]
Is there any way to print in memory collection or variable size in WPF? I am using the following code in which I print the ListView control. But when the content is larger than the vertical scroll bar takes over and cuts the content. ``` PrintDialog printDialog = new PrintDialog(); printDialog.ShowDialog(); printDialog.PrintVisual(lvDocumentSummary, "testing printing!"); ```
To print multiple pages you just need to use a class that implements DocumentPaginator FixedDocument is one of the more complex implementations, FlowDocument is a simpler one. ``` FlowDocument fd = new FlowDocument(); foreach(object item in items) { fd.Blocks.Add(new Paragraph(new Run(item.ToString()))); } fd.Print(); ``` or ``` PrintDialog pd = new PrintDialog(); pd.PrintDocument(fd); ```
205,114
<p>I have an asp.net 2.0 page that contains 2 <code>UpdatePanels</code>.</p> <p>The first panel contains a <code>TreeView</code> control, when I select a node in the three view control it triggers an update of the second <code>UpdatePanel</code> only. This much is behaving correctly.</p> <p>There are two buttons on the page outside of an update panel (previous/next). These buttons trigger an update of both panels. The behaviour of the buttons is to select the adjacent node in the tree. The first time I click on one of these buttons I get the expected behaviour, and adjacent node is selected and the both panels are updated to reflect this change.</p> <p>The problem happens when I click any of these buttons again. The selected node of the treeview seems to remember the previously selected node and the buttons act on this node. So the behaviour of the previous/next buttons is to do nothing or jump back two.</p> <p><strong>Edit</strong> - Sample code that demonstrates my problem</p> <p>The markup</p> <pre><code> &lt;asp:UpdatePanel ID="myTreeViewPanel" runat="server"&gt; &lt;ContentTemplate&gt; &lt;asp:TreeView runat="server" ID="myTreeView" OnSelectedNodeChanged="myTreeView_SelectedNodeChanged"&gt; &lt;SelectedNodeStyle BackColor="#FF8000" /&gt; &lt;/asp:TreeView&gt; &lt;/ContentTemplate&gt; &lt;Triggers&gt; &lt;asp:AsyncPostBackTrigger ControlID="myButton" EventName="Click" /&gt; &lt;/Triggers&gt; &lt;/asp:UpdatePanel&gt; &lt;asp:UpdatePanel ID="myLabelPanel" runat="server"&gt; &lt;ContentTemplate&gt; &lt;asp:Label runat="server" ID="myLabel" Text="myLabel"&gt;&lt;/asp:Label&gt; &lt;/ContentTemplate&gt; &lt;Triggers&gt; &lt;asp:AsyncPostBackTrigger ControlID="myTreeView" EventName="SelectedNodeChanged" /&gt; &lt;asp:AsyncPostBackTrigger ControlID="myButton" EventName="Click" /&gt; &lt;/Triggers&gt; &lt;/asp:UpdatePanel&gt; &lt;asp:Button runat="server" ID="myButton" Text="myButton" OnClick="myButton_Click" /&gt; </code></pre> <p>The code behind</p> <pre><code> protected void Page_Load ( object sender, EventArgs e ) { if ( !IsPostBack ) { myTreeView.Nodes.Add( new TreeNode( "Test 1", "Test One" ) ); myTreeView.Nodes.Add( new TreeNode( "Test 2", "Test two" ) ); myTreeView.Nodes.Add( new TreeNode( "Test 3", "Test three" ) ); myTreeView.Nodes.Add( new TreeNode( "Test 4", "Test four" ) ); myTreeView.Nodes.Add( new TreeNode( "Test 5", "Test five" ) ); myTreeView.Nodes.Add( new TreeNode( "Test 6", "Test size" ) ); } } protected void myTreeView_SelectedNodeChanged ( object sender, EventArgs e ) { UpdateLabel( ); } protected void myButton_Click ( object sender, EventArgs e ) { // here we just select the next node in the three int index = myTreeView.Nodes.IndexOf( myTreeView.SelectedNode ); myTreeView.Nodes[ index + 1 ].Select( ); UpdateLabel( ); } private void UpdateLabel ( ) { myLabel.Text = myTreeView.SelectedNode.Value; } </code></pre> <p>It is like the viewstate of the tree is not being saved?</p>
[ { "answer_id": 205464, "author": "Dave Anderson", "author_id": 371, "author_profile": "https://Stackoverflow.com/users/371", "pm_score": 0, "selected": false, "text": "<p>I think you're right about the AJAX partial page postback that it doesn't update the hidden input __ViewState.</p>\n\n<p>I have the same thing with my update panels when a user navigates back to the pages in my website application form. The normal inputs have updated the viewstate and so their values are repopulated but the state of the controls that were updated with AJAX isn't recorded and so they revert to the default state.</p>\n" }, { "answer_id": 206077, "author": "tpower", "author_id": 18107, "author_profile": "https://Stackoverflow.com/users/18107", "pm_score": 0, "selected": false, "text": "<p>I can fix this problem by saving and restoring the selected node in the pages own view state, by just added these two functions.</p>\n\n<pre><code>protected override object SaveViewState()\n{\n ViewState[\"SelectedNodePath\"] = myTreeView.SelectedNode.ValuePath;\n return base.SaveViewState();\n}\n\nprotected void Page_PreLoad(object sender, EventArgs e)\n{\n if (ViewState[\"SelectedNodePath\"] != null)\n {\n TreeNode node = myTreeView.FindNode(ViewState[\"SelectedNodePath\"].ToString());\n if (node != null)\n node.Select();\n }\n}\n</code></pre>\n\n<p>I can't load the selected the node inside LoadViewState() because the tree doesn't have any nodes at that point. So I do it in PreLoad.</p>\n\n<p>It just feels wrong that I have to do this. Am I missing something?</p>\n" }, { "answer_id": 217245, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 3, "selected": true, "text": "<p>From <a href=\"http://www.asp.net/ajax/documentation/live/overview/UpdatePanelOverview.aspx\" rel=\"nofollow noreferrer\">UpdatePanel Control Overview [asp.net]</a></p>\n<blockquote>\n<h3>Controls that Are Not Compatible with UpdatePanel Controls</h3>\n<p>The following ASP.NET controls are not compatible with partial-page updates, and are therefore not supported inside an UpdatePanel control:</p>\n<ul>\n<li>TreeView and Menu controls.</li>\n<li>...</li>\n</ul>\n</blockquote>\n" }, { "answer_id": 1091395, "author": "Kangkan", "author_id": 118500, "author_profile": "https://Stackoverflow.com/users/118500", "pm_score": 0, "selected": false, "text": "<p>I am facing almost a similar issue. I lose the CheckedNodes collection. I doubt the same technique will solve my issues. Any idea?</p>\n\n<p>Update: I solved the issue to a great extent and used some workarounds. See the details here: <a href=\"http://www.geekays.net/post/TreeView-control-postbacks-on-check-and-uncheck-of-the-nodes-Checkbox.aspx\" rel=\"nofollow noreferrer\">TreeView inside UpdatePanel issue - postbacks on check and uncheck of the node's Checkbox</a> and <a href=\"http://www.geekays.net/post/Using-TreeView-inside-AJAX-UpdatePanel.aspx\" rel=\"nofollow noreferrer\">Using TreeView inside AJAX UpdatePanel</a></p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18107/" ]
I have an asp.net 2.0 page that contains 2 `UpdatePanels`. The first panel contains a `TreeView` control, when I select a node in the three view control it triggers an update of the second `UpdatePanel` only. This much is behaving correctly. There are two buttons on the page outside of an update panel (previous/next). These buttons trigger an update of both panels. The behaviour of the buttons is to select the adjacent node in the tree. The first time I click on one of these buttons I get the expected behaviour, and adjacent node is selected and the both panels are updated to reflect this change. The problem happens when I click any of these buttons again. The selected node of the treeview seems to remember the previously selected node and the buttons act on this node. So the behaviour of the previous/next buttons is to do nothing or jump back two. **Edit** - Sample code that demonstrates my problem The markup ``` <asp:UpdatePanel ID="myTreeViewPanel" runat="server"> <ContentTemplate> <asp:TreeView runat="server" ID="myTreeView" OnSelectedNodeChanged="myTreeView_SelectedNodeChanged"> <SelectedNodeStyle BackColor="#FF8000" /> </asp:TreeView> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="myButton" EventName="Click" /> </Triggers> </asp:UpdatePanel> <asp:UpdatePanel ID="myLabelPanel" runat="server"> <ContentTemplate> <asp:Label runat="server" ID="myLabel" Text="myLabel"></asp:Label> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="myTreeView" EventName="SelectedNodeChanged" /> <asp:AsyncPostBackTrigger ControlID="myButton" EventName="Click" /> </Triggers> </asp:UpdatePanel> <asp:Button runat="server" ID="myButton" Text="myButton" OnClick="myButton_Click" /> ``` The code behind ``` protected void Page_Load ( object sender, EventArgs e ) { if ( !IsPostBack ) { myTreeView.Nodes.Add( new TreeNode( "Test 1", "Test One" ) ); myTreeView.Nodes.Add( new TreeNode( "Test 2", "Test two" ) ); myTreeView.Nodes.Add( new TreeNode( "Test 3", "Test three" ) ); myTreeView.Nodes.Add( new TreeNode( "Test 4", "Test four" ) ); myTreeView.Nodes.Add( new TreeNode( "Test 5", "Test five" ) ); myTreeView.Nodes.Add( new TreeNode( "Test 6", "Test size" ) ); } } protected void myTreeView_SelectedNodeChanged ( object sender, EventArgs e ) { UpdateLabel( ); } protected void myButton_Click ( object sender, EventArgs e ) { // here we just select the next node in the three int index = myTreeView.Nodes.IndexOf( myTreeView.SelectedNode ); myTreeView.Nodes[ index + 1 ].Select( ); UpdateLabel( ); } private void UpdateLabel ( ) { myLabel.Text = myTreeView.SelectedNode.Value; } ``` It is like the viewstate of the tree is not being saved?
From [UpdatePanel Control Overview [asp.net]](http://www.asp.net/ajax/documentation/live/overview/UpdatePanelOverview.aspx) > > ### Controls that Are Not Compatible with UpdatePanel Controls > > > The following ASP.NET controls are not compatible with partial-page updates, and are therefore not supported inside an UpdatePanel control: > > > * TreeView and Menu controls. > * ... > > >
205,154
<p>I'm exploring git to see how it might work for my company. I've got git installed and I need to know a couple things:</p> <ul> <li>How can I set up a git server on my computer to act as my central repo?</li> <li>I'm trying to figure out how to manage my workflow with just the GUI on Windows (using the GUI is a requirement). How do I take a bunch of files in a folder and get them into my GIT repo?</li> </ul> <p>If there's a good tutorial for each item I'm plenty happy looking there instead if you can point me in the right direction. Thanks!</p>
[ { "answer_id": 205295, "author": "Grant Limberg", "author_id": 27314, "author_profile": "https://Stackoverflow.com/users/27314", "pm_score": 2, "selected": false, "text": "<p>In order to get started, you're going to have to use the command line. </p>\n\n<p>First you'll want to initialize a local repo in place. cd to the folder your files that you want under version control and issue:</p>\n\n<pre><code>git init\n</code></pre>\n\n<p>You've now initialized a git repository in that foleder. Now you need to add all of the files to it:</p>\n\n<pre><code>git add .\ngit commit -m \"Initial Import\"\n</code></pre>\n\n<p>Now cd to the parent folder of your local repository. You're going to want to make a \"Bare\" clone of the repository to act as your central repo. Issue the following command:</p>\n\n<pre><code>git clone projectFolder/ ProjectName.git\n</code></pre>\n\n<p>ProjectName.git will be created with only the version control repository. Move this folder to wherever you want to act as your central repository. From there on out, you can clone and pull from the central repository and push to the central repository.</p>\n\n<p>To clone from a central repository via SSH:</p>\n\n<pre><code>git clone [user@]host.xz:/path/to/repo.git/\n</code></pre>\n\n<p>Or, if your repo is on a network share</p>\n\n<pre><code>git clone D:/path/to/repo.git/\n</code></pre>\n\n<p>This is also doable from the GUI client for checking out and pushing changes back to the repo.</p>\n" }, { "answer_id": 205322, "author": "Edwin Jarvis", "author_id": 18623, "author_profile": "https://Stackoverflow.com/users/18623", "pm_score": 0, "selected": false, "text": "<p>If using a GUI is a requirement you'll have some problems with git. Even on command line git isn't as good as it is on other unixes. </p>\n\n<p>The only thing that support git on a GUI is the git <a href=\"http://git.or.cz/gitwiki/EclipsePlugin\" rel=\"nofollow noreferrer\">plugin</a> for Eclipse, but it's far away from the real thing. I like git very much but for that heavy Windows usage I would recommend Subversion.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9401/" ]
I'm exploring git to see how it might work for my company. I've got git installed and I need to know a couple things: * How can I set up a git server on my computer to act as my central repo? * I'm trying to figure out how to manage my workflow with just the GUI on Windows (using the GUI is a requirement). How do I take a bunch of files in a folder and get them into my GIT repo? If there's a good tutorial for each item I'm plenty happy looking there instead if you can point me in the right direction. Thanks!
In order to get started, you're going to have to use the command line. First you'll want to initialize a local repo in place. cd to the folder your files that you want under version control and issue: ``` git init ``` You've now initialized a git repository in that foleder. Now you need to add all of the files to it: ``` git add . git commit -m "Initial Import" ``` Now cd to the parent folder of your local repository. You're going to want to make a "Bare" clone of the repository to act as your central repo. Issue the following command: ``` git clone projectFolder/ ProjectName.git ``` ProjectName.git will be created with only the version control repository. Move this folder to wherever you want to act as your central repository. From there on out, you can clone and pull from the central repository and push to the central repository. To clone from a central repository via SSH: ``` git clone [user@]host.xz:/path/to/repo.git/ ``` Or, if your repo is on a network share ``` git clone D:/path/to/repo.git/ ``` This is also doable from the GUI client for checking out and pushing changes back to the repo.
205,158
<p>Sorry, that title just hurts. I'm wondering if there is a Linq to collections extension method that collapses the following code segment into a single line:</p> <pre><code>public IEnumerable&lt;Child&gt; GetAllChildren(IEnumerable&lt;Parent&gt; parents){ var result = new List&lt;Child&gt;(); foreach(Parent parent in parents) foreach(Child child in parent.Children) result.Add(child); return result; } </code></pre> <p>If you can collapse that into a single statement, try it on insane difficulty:</p> <pre><code>public IEnumerable&lt;Child&gt; GetAllChildren(IEnumerable&lt;Grandparent&gt; nanas){ var result = new List&lt;Child&gt;(); foreach(Grandparent papa in nanas) foreach(Parent parent in papa.Children) foreach(Child child in parent.Children) result.Add(child); return result; } </code></pre>
[ { "answer_id": 205169, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 3, "selected": false, "text": "<p>This will work:</p>\n\n<pre><code>public IEnumerable&lt;Child&gt; GetAllChildren(IEnumerable&lt;Parent&gt; parents)\n{\n return from parent in parents\n from child in parent.Children\n select child;\n}\n</code></pre>\n\n<p>and then this:</p>\n\n<pre><code>public IEnumerable&lt;Child&gt; GetAllChildren(IEnumerable&lt;Grandparent&gt; nanas)\n{\n return from papa in nanas\n from parent in papa.Children\n from child in parent.Children\n select child;\n}\n</code></pre>\n\n<p>Note, in this example I'm not actually returning a list, I'm returning an IEnumerable data source that until you start to foreach over it, or similar, won't actually do any processing.</p>\n\n<p>If you need to return a list, modify each return statement as follows:</p>\n\n<pre><code> return (from .....\n ...\n select child).ToList();\n</code></pre>\n" }, { "answer_id": 205309, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 4, "selected": true, "text": "<p>Here's the obligatory method form.</p>\n\n<pre><code>return parents\n .SelectMany(p =&gt; p.Children);\n</code></pre>\n\n<p>And for two levels:</p>\n\n<pre><code>return oldies\n .SelectMany(grand =&gt; grand.Children)\n .SelectMany(parent =&gt; parent.Children);\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Sorry, that title just hurts. I'm wondering if there is a Linq to collections extension method that collapses the following code segment into a single line: ``` public IEnumerable<Child> GetAllChildren(IEnumerable<Parent> parents){ var result = new List<Child>(); foreach(Parent parent in parents) foreach(Child child in parent.Children) result.Add(child); return result; } ``` If you can collapse that into a single statement, try it on insane difficulty: ``` public IEnumerable<Child> GetAllChildren(IEnumerable<Grandparent> nanas){ var result = new List<Child>(); foreach(Grandparent papa in nanas) foreach(Parent parent in papa.Children) foreach(Child child in parent.Children) result.Add(child); return result; } ```
Here's the obligatory method form. ``` return parents .SelectMany(p => p.Children); ``` And for two levels: ``` return oldies .SelectMany(grand => grand.Children) .SelectMany(parent => parent.Children); ```
205,159
<p>I would like to execute <code>ls</code> in a Perl program as part of a CGI script. For this I used <code>exec(ls)</code>, but this does not return from the <code>exec</code> call.</p> <p>Is there a better way to get a listing of a directory in Perl?</p>
[ { "answer_id": 205168, "author": "holli", "author_id": 18606, "author_profile": "https://Stackoverflow.com/users/18606", "pm_score": 3, "selected": false, "text": "<p>In order to get the output of a system command you need to use backticks.</p>\n\n<pre><code>$listing = `ls`;\n</code></pre>\n\n<p>However, Perl is good in dealing with directories for itself. I'd recommend using File::Find::Rule.</p>\n" }, { "answer_id": 205172, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 7, "selected": true, "text": "<p>Exec doesn't return at all. If you wanted that, use system.</p>\n\n<p>If you just want to read a directory, open/read/close-dir may be more appropriate.</p>\n\n<pre><code>opendir my($dh), $dirname or die \"Couldn't open dir '$dirname': $!\";\nmy @files = readdir $dh;\nclosedir $dh;\n#print files...\n</code></pre>\n" }, { "answer_id": 205181, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 3, "selected": false, "text": "<p><strong>exec</strong> does not give control back to the perl program.\n<strong>system</strong> will, but it does not return the results of an ls, it returns a status code.\ntick marks <strong>``</strong> will give you the output of our command, but is considered by some as unsafe.</p>\n\n<p>Use the built in dir functions.\nopendir, readdir, and so on.</p>\n\n<p><a href=\"http://perldoc.perl.org/functions/opendir.html\" rel=\"nofollow noreferrer\">http://perldoc.perl.org/functions/opendir.html</a></p>\n\n<p><a href=\"http://perldoc.perl.org/functions/readdir.html\" rel=\"nofollow noreferrer\">http://perldoc.perl.org/functions/readdir.html</a></p>\n" }, { "answer_id": 205629, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 0, "selected": false, "text": "<p>I would recommend you have a look at <a href=\"http://perldoc.perl.org/IPC/Open3.html\" rel=\"nofollow noreferrer\">IPC::Open3</a>. It allows for far more control over the spawned process than system or the backticks do.</p>\n" }, { "answer_id": 206646, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 4, "selected": false, "text": "<p>Everyone else seems stuck on the exec portion of the question.</p>\n\n<p>If you want a directory listing, use Perl's built-in <code>glob</code> or <code>opendir</code>. You don't need a separate process.</p>\n" }, { "answer_id": 210841, "author": "JDrago", "author_id": 28758, "author_profile": "https://Stackoverflow.com/users/28758", "pm_score": 0, "selected": false, "text": "<p>On Linux, I prefer find:</p>\n\n<pre><code>my @files = map { chomp; $_ } `find`;\n</code></pre>\n" }, { "answer_id": 3361544, "author": "dynax60", "author_id": 368067, "author_profile": "https://Stackoverflow.com/users/368067", "pm_score": 3, "selected": false, "text": "<p>Yet another example:</p>\n\n<pre><code>chdir $dir or die \"Cannot chroot to $dir: $!\\n\";\nmy @files = glob(\"*.txt\");\n</code></pre>\n" }, { "answer_id": 3458794, "author": "Octoberdan", "author_id": 189491, "author_profile": "https://Stackoverflow.com/users/189491", "pm_score": 3, "selected": false, "text": "<p>EDIT: Whoops! I thought you just wanted a listing of the directories... remove the 'directory' call to make this script do what you want it to... </p>\n\n<p>Playing with filehandles is the wrong way to go in my opinion. The following is an example of using File::Find::Rule to find all the directories in a specified directory. It may seem like over kill for what you're doing, but later down the line it may be worth it.</p>\n\n<p>First, my one line solution:</p>\n\n<pre><code>File::Find::Rule-&gt;maxdepth(1)-&gt;directory-&gt;in($base_dir);\n</code></pre>\n\n<p>Now a more drawn out version with comments. If you have File::Find::Rule installed you should be able to run this no problem. Don't fear the CPAN.</p>\n\n<pre><code>#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\n# See http://search.cpan.org/~rclamp/File-Find-Rule-0.32/README\nuse File::Find::Rule;\n\n# If a base directory was not past to the script, assume current working director\nmy $base_dir = shift // '.';\nmy $find_rule = File::Find::Rule-&gt;new;\n\n# Do not descend past the first level\n$find_rule-&gt;maxdepth(1);\n\n# Only return directories\n$find_rule-&gt;directory;\n\n# Apply the rule and retrieve the subdirectories\nmy @sub_dirs = $find_rule-&gt;in($base_dir);\n\n# Print out the name of each directory on its own line\nprint join(\"\\n\", @sub_dirs);\n</code></pre>\n" }, { "answer_id": 6587372, "author": "Greg", "author_id": 830252, "author_profile": "https://Stackoverflow.com/users/830252", "pm_score": 3, "selected": false, "text": "<p>Use Perl Globbing:</p>\n\n<pre><code>my $dir = &lt;/dir/path/*&gt; \n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28280/" ]
I would like to execute `ls` in a Perl program as part of a CGI script. For this I used `exec(ls)`, but this does not return from the `exec` call. Is there a better way to get a listing of a directory in Perl?
Exec doesn't return at all. If you wanted that, use system. If you just want to read a directory, open/read/close-dir may be more appropriate. ``` opendir my($dh), $dirname or die "Couldn't open dir '$dirname': $!"; my @files = readdir $dh; closedir $dh; #print files... ```
205,182
<p>Is there a way of reusing the same resultMap multiple times in a single query.</p> <p>For example, suppose I have a "foo" resultMap:</p> <pre><code>&lt;resultMap id="foo" class="Foo"&gt; &lt;result property="Bar" column="bar" /&gt; &lt;/resultMap&gt; </code></pre> <p>Is there a way to define another resultMap that reuses the above for different columns? Something like...</p> <pre><code>&lt;resultMap id="fizz"class="Fizz"&gt; &lt;result property="Foo1" column="bar=bar1" resultMapping="foo" /&gt; &lt;result property="Foo2" column="bar=bar2" resultMapping="foo" /&gt; &lt;result property="Foo3" column="bar=bar3" resultMapping="foo" /&gt; &lt;/resultMap&gt; </code></pre>
[ { "answer_id": 205257, "author": "James Rose", "author_id": 9703, "author_profile": "https://Stackoverflow.com/users/9703", "pm_score": 3, "selected": true, "text": "<p>Almost. If you select the ID of the Foo in your query, you can have the Fizz result map execute a SELECT for that ID, which will use the Foo result map.</p>\n\n<p><code>&lt;result property=\"Foo1\" column=\"bar1Id\" select=\"selectFoo\"/&gt;</code></p>\n\n<p>(Assuming you have a <code>selectFoo</code> query defined.) But that's extremely slow with large result sets, since it does an additional SELECT for every row.</p>\n\n<p>iBATIS has a solution to this problem for the typical case, where you have a composite object that contains various other objects. First, you define a query that joins your tables, then you can use <code>fooMap</code> to populate a <code>Foo</code>:</p>\n\n<p><code>&lt;result property=\"Foo1\" resultMap=\"fooMap\"/&gt;</code></p>\n\n<p>But you can't use that result map twice for two different <code>Foos</code> because the result map specifies certain column names. You can use another technique, though:</p>\n\n<p><code>&lt;result property=\"foo1.bar\" column=\"foo1bar\"/&gt;</code><br>\n<code>&lt;result property=\"foo2.bar\" column=\"foo2bar\"/&gt;</code></p>\n\n<p>More detail in page 35 of the iBatis Datamapper manual.</p>\n" }, { "answer_id": 11127823, "author": "duffy356", "author_id": 1358430, "author_profile": "https://Stackoverflow.com/users/1358430", "pm_score": 1, "selected": false, "text": "<p>you could use resultmaps, which extend another resultmap\ne.g.</p>\n\n<pre><code>&lt;resultMap id=\"document\" class=\"Document\"&gt; \n &lt;result property=\"Id\" column=\"Document_ID\"/&gt;\n &lt;result property=\"Title\" column=\"Document_Title\"/&gt;\n &lt;discriminator column=\"Document_Type\" type=\"string\"/&gt;\n &lt;subMap value=\"Book\" resultMapping=\"book\"/&gt;\n &lt;subMap value=\"Newspaper\" resultMapping=\"newspaper\"/&gt;\n&lt;/resultMap&gt;\n\n&lt;resultMap id=\"book\" class=\"Book\" extends=\"document\"&gt; \n &lt;property=\"PageNumber\" column=\"Document_PageNumber\"/&gt;\n&lt;/resultMap&gt;\n</code></pre>\n\n<p>more info: <a href=\"http://ibatis.apache.org/docs/dotnet/datamapper/ch03s05.html\" rel=\"nofollow\">http://ibatis.apache.org/docs/dotnet/datamapper/ch03s05.html</a></p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4094/" ]
Is there a way of reusing the same resultMap multiple times in a single query. For example, suppose I have a "foo" resultMap: ``` <resultMap id="foo" class="Foo"> <result property="Bar" column="bar" /> </resultMap> ``` Is there a way to define another resultMap that reuses the above for different columns? Something like... ``` <resultMap id="fizz"class="Fizz"> <result property="Foo1" column="bar=bar1" resultMapping="foo" /> <result property="Foo2" column="bar=bar2" resultMapping="foo" /> <result property="Foo3" column="bar=bar3" resultMapping="foo" /> </resultMap> ```
Almost. If you select the ID of the Foo in your query, you can have the Fizz result map execute a SELECT for that ID, which will use the Foo result map. `<result property="Foo1" column="bar1Id" select="selectFoo"/>` (Assuming you have a `selectFoo` query defined.) But that's extremely slow with large result sets, since it does an additional SELECT for every row. iBATIS has a solution to this problem for the typical case, where you have a composite object that contains various other objects. First, you define a query that joins your tables, then you can use `fooMap` to populate a `Foo`: `<result property="Foo1" resultMap="fooMap"/>` But you can't use that result map twice for two different `Foos` because the result map specifies certain column names. You can use another technique, though: `<result property="foo1.bar" column="foo1bar"/>` `<result property="foo2.bar" column="foo2bar"/>` More detail in page 35 of the iBatis Datamapper manual.
205,188
<p>There seems to be lots of different ways to register assemblies with the GAC, as in, they 'work'. However, what's the "proper" way of doing it?</p> <p>In response to Lou Franco (and gacutil):</p> <p>I'm using Gacutil for development, but it seems to me to be not the proper way to install it, since gacutil isn't included in the basic .NET utilities past .NET 1.1 - it's only a developer tool.</p> <p>Additional: Gacutil (as seen in responses below) is not redistributable, and therefore should not be used in any app that you intend to give to people who are not developers. AKA, customers. See <a href="http://blogs.msdn.com/astebner/archive/2006/11/04/why-to-not-use-gacutil-exe-in-an-application-setup.aspx" rel="noreferrer">This blog post (and comments) by Aaron Stebner</a>.</p> <p>In response to using WIX:</p> <p>WIX might be great and all, but how does it work under the hood? What details makes the way WIX installs the assembly the right way to install it? How does it look it up? Is it a system/.NET call? Is there some call in a dll buried somewhere in System32 that needs to be made? </p> <p>(Edit: it looks like WIX uses MSI under the hood. See my comments in the accepted answer.)</p> <p>Final edit: It looks like the correct way to install an assembly to the GAC is using windows installer, and nothing else. I'm going to give Wix a try. Thanks all!</p>
[ { "answer_id": 205192, "author": "Robert P", "author_id": 18097, "author_profile": "https://Stackoverflow.com/users/18097", "pm_score": 0, "selected": false, "text": "<p>use gacutil. </p>\n\n<p>Advantages: seems to always work.\nDisadvantages:</p>\n\n<ul>\n<li>must package an additional executable with your installer.</li>\n<li>As a development utility, seems to have additional side effects (like forcing the install no matter what).</li>\n<li>Should NOT be included in any redistributable given to customers.</li>\n</ul>\n" }, { "answer_id": 205193, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>Doesn't your installer maker have a way of installing an assembly into the GAC? On your own, I'd say GACUTIL:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ex0ss12c(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ex0ss12c(VS.80).aspx</a></p>\n" }, { "answer_id": 205194, "author": "Robert P", "author_id": 18097, "author_profile": "https://Stackoverflow.com/users/18097", "pm_score": -1, "selected": false, "text": "<p>copy directly to %WINDIR%\\Assembly.</p>\n\n<p>Advantage: Straightforward.</p>\n\n<p>Disadvantage: AFAIK, %WINDIR%\\Assembly just <em>happens</em> to be where it is right now, and it's location is subject to change. This would make it break in future versions of windows or if that folder's behavior chaneges. This probably isn't the right way.</p>\n\n<p>Extreme Disadvantage: As said by madmath:</p>\n\n<blockquote>just copying your assembly into c:\\windows\\assembly won't work. Explorer only shows a simplified view of the folder, which contains in fact lots of different folders for different kinds of assemblies. Doing a copy in it from an installer won't trigger all the operations done by explorer on a drag-and-drop. (written here because I don't have enough reputation yet to comment on other posts).</blockquote>\n" }, { "answer_id": 205207, "author": "coder1", "author_id": 3018, "author_profile": "https://Stackoverflow.com/users/3018", "pm_score": 0, "selected": false, "text": "<p>If you don't want to handle the gacutil stuff yourself, you can always create a setup project in visual studio. </p>\n\n<p>But I'd stick with gacutil myself.</p>\n" }, { "answer_id": 205212, "author": "Robert P", "author_id": 18097, "author_profile": "https://Stackoverflow.com/users/18097", "pm_score": 2, "selected": false, "text": "<p>Use <code>System.EnterpriseServices.Internal.Publish</code>'s <code>GacInstall</code> method.</p>\n\n<p>Advantages: Seems to be an internal tool. Probably does all the right stuff.</p>\n\n<p>Disadvantages: As part of an installer, you'd still need to make and run an app that calls this (unless the installer you make is a custom app that does it anyway).</p>\n" }, { "answer_id": 205223, "author": "Mathieu Garstecki", "author_id": 22078, "author_profile": "https://Stackoverflow.com/users/22078", "pm_score": -1, "selected": false, "text": "<p>The best way is to use <code>gacutil -i Library.dll</code>.</p>\n\n<p>The only problem with gacutil is that it is not in the default PATH of the system. It is however in a fixed location relative to the windows directory, for a given .Net Framework version. So you can use the following command line to execute it from anywhere:</p>\n\n<pre><code>%SystemRoot%\\Microsoft.Net\\Framework\\v1.1.4322\\gacutil -i\n</code></pre>\n\n<p>PS: just copying your assembly into c:\\windows\\assembly won't work. Explorer only shows a simplified view of the folder, which contains in fact lots of different folders for different kinds of assemblies. Doing a copy in it from an installer won't trigger all the operations done by explorer on a drag-and-drop. (written here because I don't have enough reputation yet to comment on other posts).</p>\n" }, { "answer_id": 205243, "author": "CheGueVerra", "author_id": 17787, "author_profile": "https://Stackoverflow.com/users/17787", "pm_score": 5, "selected": true, "text": "<p>With Wix I would do something like this:</p>\n\n<pre>\n\n&lt;DirectoryRef Id=\"MyDirectory\" &gt;\n &lt;Component Id=\"MyComponent\" Guid=\"PUT-GUID-HERE\" DiskId=\"1\"&gt;\n &lt;File Id=\"MyAssembly\" Name=\"MyAssembly.dll\" Assembly=\".net\" KeyPath=\"yes\" Source=\"MyAssembly.dll\" /&gt;\n &lt;/Component&gt;\n&lt;/DirectoryRef&gt;\n\n</pre>\n\n<p>When you use the attribute Assembly=\".net\" for a file in WiX, it will create entries in the MsiAssembly and MsiAssemblyName table for this component and mark it as a GAC component.</p>\n" }, { "answer_id": 206731, "author": "Robert P", "author_id": 18097, "author_profile": "https://Stackoverflow.com/users/18097", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://blogs.msdn.com/astebner/archive/2006/11/04/why-to-not-use-gacutil-exe-in-an-application-setup.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/astebner/archive/2006/11/04/why-to-not-use-gacutil-exe-in-an-application-setup.aspx</a></p>\n\n<p>It looks like the gacutil should be avoided; it's not a redistributable app. Instead, the 'proper' way of installing them seems to be using MSI, one way being WIX, as posted by CheGueVerra or another script.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18097/" ]
There seems to be lots of different ways to register assemblies with the GAC, as in, they 'work'. However, what's the "proper" way of doing it? In response to Lou Franco (and gacutil): I'm using Gacutil for development, but it seems to me to be not the proper way to install it, since gacutil isn't included in the basic .NET utilities past .NET 1.1 - it's only a developer tool. Additional: Gacutil (as seen in responses below) is not redistributable, and therefore should not be used in any app that you intend to give to people who are not developers. AKA, customers. See [This blog post (and comments) by Aaron Stebner](http://blogs.msdn.com/astebner/archive/2006/11/04/why-to-not-use-gacutil-exe-in-an-application-setup.aspx). In response to using WIX: WIX might be great and all, but how does it work under the hood? What details makes the way WIX installs the assembly the right way to install it? How does it look it up? Is it a system/.NET call? Is there some call in a dll buried somewhere in System32 that needs to be made? (Edit: it looks like WIX uses MSI under the hood. See my comments in the accepted answer.) Final edit: It looks like the correct way to install an assembly to the GAC is using windows installer, and nothing else. I'm going to give Wix a try. Thanks all!
With Wix I would do something like this: ``` <DirectoryRef Id="MyDirectory" > <Component Id="MyComponent" Guid="PUT-GUID-HERE" DiskId="1"> <File Id="MyAssembly" Name="MyAssembly.dll" Assembly=".net" KeyPath="yes" Source="MyAssembly.dll" /> </Component> </DirectoryRef> ``` When you use the attribute Assembly=".net" for a file in WiX, it will create entries in the MsiAssembly and MsiAssemblyName table for this component and mark it as a GAC component.
205,190
<p>Clearly the following is incorrect.</p> <pre><code>INSERT INTO `aTable` (`A`,`B`) VALUES((SELECT MAX(`A`) FROM `aTable`)*2),'name'); </code></pre> <p>I get the value:</p> <p>SQL query: </p> <pre><code>INSERT INTO `aTable` (`A`, `B` ) VALUES ( ( SELECT MAX(`A`) FROM `aTable` ) *2 , 'name' ) </code></pre> <p>MySQL said:</p> <p>1093 - You can't specify target table 'aTable' for update in FROM clause </p> <p>So, I'm trying to make a bitmap table, each row corresponds to one Bit, and has a 'map' value.</p> <p>To insert in the table, I don't want to do two queries, I want to do one. How should I do this?</p> <p>No one commented on this, but since I am trying to make a bitmap, it should be * 2 not ^ 2, my mistake, please note that is why the comments often say ^ 2, it was an error in the version that the commenters read.</p>
[ { "answer_id": 205195, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 2, "selected": false, "text": "<p>I think you need to drop the \"VALUES\", and have a valid select statement.</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html\" rel=\"nofollow noreferrer\">see this link</a></p>\n\n<p>I'm not particularly a mySQL guy, I use MSSQL mostly. But If you format the select statement correctly, It should work. </p>\n" }, { "answer_id": 205234, "author": "Enrico Murru", "author_id": 68336, "author_profile": "https://Stackoverflow.com/users/68336", "pm_score": -1, "selected": false, "text": "<p>as soon as the Select is correct you can do this.</p>\n" }, { "answer_id": 205256, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 3, "selected": false, "text": "<p>I take it that <a href=\"http://dev.mysql.com/doc/refman/5.0/en/insert-select.html\" rel=\"noreferrer\">INSERT ... SELECT</a> isn't working? I see this in the documentation for it:</p>\n\n<blockquote>\n <p>The target table of the INSERT\n statement may appear in the FROM\n clause of the SELECT part of the\n query. (This was not possible in some\n older versions of MySQL.) In this\n case, MySQL creates a temporary table\n to hold the rows from the SELECT and\n then inserts those rows into the\n target table.</p>\n</blockquote>\n\n<p>Out of curiosity, which version of MySQL are you using?</p>\n" }, { "answer_id": 205844, "author": "Leonel Martins", "author_id": 26673, "author_profile": "https://Stackoverflow.com/users/26673", "pm_score": 5, "selected": true, "text": "<p>try:</p>\n\n<pre><code>insert into aTable select max(a)^2, 'name' from aTable;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>insert into aTable select max(a)^2, 'name' from aTable group by B;\n</code></pre>\n\n<p>If you need a join, you can do this:</p>\n\n<pre><code>insert into aTable select max(a)^2, 'name' from aTable, bTable;\n</code></pre>\n\n<p>My \"Server version\" is \"5.0.51b-community-nt MySQL Community Edition (GPL)\"</p>\n" }, { "answer_id": 7960671, "author": "Hoser", "author_id": 1022818, "author_profile": "https://Stackoverflow.com/users/1022818", "pm_score": 4, "selected": false, "text": "<p>Actually, you can alias the table on the insert. I've seen this question all over the place, but no one seems to have tried that. Use a subquery to get the max from the table, but alias the table in the subquery.</p>\n\n<pre><code>INSERT INTO tableA SET fieldA = (SELECT max(x.fieldA) FROM tableA x)+1;\n</code></pre>\n\n<p>A more complex example, where you have a corresponding secondary key and might be inserting the FIRST record for the corresponding secondary key:</p>\n\n<pre><code>INSERT INTO tableA SET secondaryKey = 123, fieldA = COALESCE((SELECT max(x.fieldA) FROM tableA x WHERE x.secondaryKey = 123)+1,1);\n</code></pre>\n\n<p>By aliasing the table, it doesn't throw the error and seems to work. I just did this while coding something, although I can't see if there area any silly syntax errors above, I would try that type of syntax.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144/" ]
Clearly the following is incorrect. ``` INSERT INTO `aTable` (`A`,`B`) VALUES((SELECT MAX(`A`) FROM `aTable`)*2),'name'); ``` I get the value: SQL query: ``` INSERT INTO `aTable` (`A`, `B` ) VALUES ( ( SELECT MAX(`A`) FROM `aTable` ) *2 , 'name' ) ``` MySQL said: 1093 - You can't specify target table 'aTable' for update in FROM clause So, I'm trying to make a bitmap table, each row corresponds to one Bit, and has a 'map' value. To insert in the table, I don't want to do two queries, I want to do one. How should I do this? No one commented on this, but since I am trying to make a bitmap, it should be \* 2 not ^ 2, my mistake, please note that is why the comments often say ^ 2, it was an error in the version that the commenters read.
try: ``` insert into aTable select max(a)^2, 'name' from aTable; ``` or ``` insert into aTable select max(a)^2, 'name' from aTable group by B; ``` If you need a join, you can do this: ``` insert into aTable select max(a)^2, 'name' from aTable, bTable; ``` My "Server version" is "5.0.51b-community-nt MySQL Community Edition (GPL)"
205,239
<p>Consider the following interface in Java:</p> <pre><code>public interface I { public final String KEY = "a"; } </code></pre> <p>And the following class:</p> <pre><code>public class A implements I { public String KEY = "b"; public String getKey() { return KEY; } } </code></pre> <p>Why is it possible for class A to come along and override interface I's final constant?</p> <p>Try for yourself:</p> <pre><code>A a = new A(); String s = a.getKey(); // returns "b"!!! </code></pre>
[ { "answer_id": 205249, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 5, "selected": false, "text": "<p>You are hiding it, it's a feature of \"Scope\". Any time you are in a smaller scope, you can redefine all the variables you like and the outer scope variables will be \"Shadowed\"</p>\n\n<p>By the way, you can scope it again if you like:</p>\n\n<pre><code>public class A implements I {\n public String KEY = \"b\";\n\n public String getKey() {\n String KEY = \"c\";\n return KEY;\n }\n}\n</code></pre>\n\n<p>Now KEY will return \"c\";</p>\n\n<p>Edited because the original sucked upon re-reading.</p>\n" }, { "answer_id": 205268, "author": "Steve B.", "author_id": 19479, "author_profile": "https://Stackoverflow.com/users/19479", "pm_score": 2, "selected": false, "text": "<p>It looks like your class is simply hiding the variable, not overwriting it: </p>\n\n<pre><code>public class A implements I {\n public String KEY = \"B\";\n\n public static void main(String args[])\n {\n A t = new A();\n System.out.println(t.KEY);\n System.out.println(((I) t).KEY);\n }\n}\n</code></pre>\n\n<p>This will print \"B\", and \"A\", as you found. You can even assign to it, as the A.KEY variable is not defined as final. </p>\n\n<pre><code> A.KEY=\"C\" &lt;-- this compiles.\n</code></pre>\n\n<p>But - </p>\n\n<pre><code>public class C implements I{\n\n public static void main (String args[])\n {\n C t = new C();\n c.KEY=\"V\"; &lt;--- compiler error ! can't assign to final\n\n }\n}\n</code></pre>\n" }, { "answer_id": 205292, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 1, "selected": false, "text": "<p>Static fields and methods are attached to the class/interface declaring them (though interfaces cannot declare static methods as they are wholly abstract classes which need to be implemented).</p>\n\n<p>So, if you have an interface with a public static (vartype) (varname),\nthat field is attached to that interface.</p>\n\n<p>If you have a class implement that interface, the compiler trick transforms (this.)varname into InterfaceName.varname. But, if your class redefines varname, a new constant named varname is attached to your class, and the compiler knows to now translate (this.)varname into NewClass.varname. The same applies for methods: if the new class does not re-define the method, (this.)methodName is translated into SuperClass.methodName, otherwise, (this.)methodName is translated into CurrentClass.methodName.</p>\n\n<p>This is why you will encounter the warning \"x field/method should be accessed in a static way\". The compiler is telling you that, although it may use the trick, it would prefer that you used ClassName.method/fieldName, because it is more explicit for readability purposes.</p>\n" }, { "answer_id": 205358, "author": "Jorn", "author_id": 8681, "author_profile": "https://Stackoverflow.com/users/8681", "pm_score": 2, "selected": false, "text": "<p>You should not access your constant in this way, use the static reference instead:</p>\n\n<pre><code>I.KEY //returns \"a\"\nB.KEY //returns \"b\"\n</code></pre>\n" }, { "answer_id": 205427, "author": "André", "author_id": 9683, "author_profile": "https://Stackoverflow.com/users/9683", "pm_score": 5, "selected": true, "text": "<p>Despite the fact that you are shadowing the variable it's quite interesting to know that you can change final fields in java as you can read <a href=\"http://www.javaspecialists.co.za/archive/Issue096.html\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<blockquote>\n <p><strong>Java 5 - \"final\" is not final anymore</strong></p>\n \n <p>Narve Saetre from Machina Networks in Norway sent me a note yesterday,\n mentioning that it was a pity that we could change the handle to a\n final array. I misunderstood him, and started patiently explaining\n that we could not make an array constant, and that there was no way of\n protecting the contents of an array. \"No\", said he, \"we can change a\n final handle using reflection.\"</p>\n \n <p>I tried Narve's sample code, and unbelievably, Java 5 allowed me to\n modify a final handle, even a handle to a primitive field! I knew that\n it used to be allowed at some point, but that it was then disallowed,\n so I ran some tests with older versions of Java. First, we need a\n class with final fields:</p>\n\n<pre><code>public class Person {\n private final String name;\n private final int age;\n private final int iq = 110;\n private final Object country = \"South Africa\";\n\n public Person(String name, int age) {\n this.name = name;\n this.age = age;\n }\n\n public String toString() {\n return name + \", \" + age + \" of IQ=\" + iq + \" from \" + country;\n }\n}\n</code></pre>\n \n <p><strong>JDK 1.1.x</strong></p>\n \n <p>In JDK 1.1.x, we were not able to access private fields using\n reflection. We could, however, create another Person with public\n fields, then compile our class against that, and swap the Person\n classes. There was no access checking at runtime if we were running\n against a different class to the one that we compiled against.\n However, we could not rebind final fields at runtime using either\n class swapping or reflection.</p>\n \n <p>The JDK 1.1.8 JavaDocs for java.lang.reflect.Field had the following\n to say:</p>\n \n <ul>\n <li>If this Field object enforces Java language access control, and the underlying field is inaccessible, the method throws an\n IllegalAccessException.</li>\n <li>If the underlying field is final, the method throws an IllegalAccessException.</li>\n </ul>\n \n <p><strong>JDK 1.2.x</strong></p>\n \n <p>In JDK 1.2.x, this changed a bit. We could now make private fields\n accessible with the setAccessible(true) method. Access of fields was\n now checked at runtime, so we could not use the class swapping trick\n to access private fields. However, we could now suddenly rebind final\n fields! Look at this code:</p>\n\n<pre><code>import java.lang.reflect.Field;\n\npublic class FinalFieldChange {\n private static void change(Person p, String name, Object value)\n throws NoSuchFieldException, IllegalAccessException {\n Field firstNameField = Person.class.getDeclaredField(name);\n firstNameField.setAccessible(true);\n firstNameField.set(p, value);\n }\n public static void main(String[] args) throws Exception {\n Person heinz = new Person(\"Heinz Kabutz\", 32);\n change(heinz, \"name\", \"Ng Keng Yap\");\n change(heinz, \"age\", new Integer(27));\n change(heinz, \"iq\", new Integer(150));\n change(heinz, \"country\", \"Malaysia\");\n System.out.println(heinz);\n }\n}\n</code></pre>\n \n <p>When I ran this in JDK 1.2.2_014, I got the following result:</p>\n\n<pre><code>Ng Keng Yap, 27 of IQ=110 from Malaysia Note, no exceptions, no complaints, and an incorrect IQ result. It seems that if we set a\n</code></pre>\n \n <p>final field of a primitive at declaration time, the value is inlined,\n if the type is primitive or a String.</p>\n \n <p><strong>JDK 1.3.x and 1.4.x</strong></p>\n \n <p>In JDK 1.3.x, Sun tightened up the access a bit, and prevented us from\n modifying a final field with reflection. This was also the case with\n JDK 1.4.x. If we tried running the FinalFieldChange class to rebind\n the final fields at runtime using reflection, we would get:</p>\n \n <blockquote>\n <p>java version \"1.3.1_12\": Exception thread \"main\"\n IllegalAccessException: field is final\n at java.lang.reflect.Field.set(Native Method)\n at FinalFieldChange.change(FinalFieldChange.java:8)\n at FinalFieldChange.main(FinalFieldChange.java:12)</p>\n \n <p>java version \"1.4.2_05\" Exception thread \"main\"\n IllegalAccessException: Field is final\n at java.lang.reflect.Field.set(Field.java:519)\n at FinalFieldChange.change(FinalFieldChange.java:8)\n at FinalFieldChange.main(FinalFieldChange.java:12)</p>\n </blockquote>\n \n <p><strong>JDK 5.x</strong></p>\n \n <p>Now we get to JDK 5.x. The FinalFieldChange class has the same output\n as in JDK 1.2.x:</p>\n\n<pre><code>Ng Keng Yap, 27 of IQ=110 from Malaysia When Narve Saetre mailed me that he managed to change a final field in JDK 5 using\n</code></pre>\n \n <p>reflection, I was hoping that a bug had crept into the JDK. However,\n we both felt that to be unlikely, especially such a fundamental bug.\n After some searching, I found the JSR-133: Java Memory Model and\n Thread Specification. Most of the specification is hard reading, and\n reminds me of my university days (I used to write like that ;-)\n However, JSR-133 is so important that it should be required reading\n for all Java programmers. (Good luck)</p>\n \n <p>Start with chapter 9 Final Field Semantics, on page 25. Specifically,\n read section 9.1.1 Post-Construction Modification of Final Fields. It\n makes sense to allow updates to final fields. For example, we could\n relax the requirement to have fields non-final in JDO.</p>\n \n <p>If we read section 9.1.1 carefully, we see that we should only modify\n final fields as part of our construction process. The use case is\n where we deserialize an object, and then once we have constructed the\n object, we initialise the final fields, before passing it on. Once we\n have made the object available to another thread, we should not change\n final fields using reflection. The result would not be predictable.</p>\n \n <p>It even says this: If a final field is initialized to a compile-time\n constant in the field declaration, changes to the final field may not\n be observed, since uses of that final field are replaced at compile\n time with the compile-time constant. This explains why our iq field\n stays the same, but country changes.</p>\n \n <p>Strangely, JDK 5 differs slightly from JDK 1.2.x, in that you cannot\n modify a static final field.</p>\n\n<pre><code>import java.lang.reflect.Field;\n\npublic class FinalStaticFieldChange {\n /** Static fields of type String or primitive would get inlined */\n private static final String stringValue = \"original value\";\n private static final Object objValue = stringValue;\n\n private static void changeStaticField(String name)\n throws NoSuchFieldException, IllegalAccessException {\n Field statFinField = FinalStaticFieldChange.class.getDeclaredField(name);\n statFinField.setAccessible(true);\n statFinField.set(null, \"new Value\");\n }\n\n public static void main(String[] args) throws Exception {\n changeStaticField(\"stringValue\");\n changeStaticField(\"objValue\");\n System.out.println(\"stringValue = \" + stringValue);\n System.out.println(\"objValue = \" + objValue);\n System.out.println();\n }\n}\n</code></pre>\n \n <p>When we run this with JDK 1.2.x and JDK 5.x, we get the following\n output:</p>\n \n <blockquote>\n <p>java version \"1.2.2_014\": stringValue = original value objValue = new\n Value</p>\n \n <p>java version \"1.5.0\" Exception thread \"main\" IllegalAccessException:\n Field is final at java.lang.reflect.Field.set(Field.java:656) at\n FinalStaticFieldChange.changeStaticField(12) at\n FinalStaticFieldChange.main(16)</p>\n </blockquote>\n \n <p>So, JDK 5 is like JDK 1.2.x, just different?</p>\n \n <p><strong>Conclusion</strong></p>\n \n <p>Do you know when JDK 1.3.0 was released? I struggled to find out, so I\n downloaded and installed it. The readme.txt file has the date\n 2000/06/02 13:10. So, it is more than 4 years old (goodness me, it\n feels like yesterday). JDK 1.3.0 was released several months before I\n started writing The Java(tm) Specialists' Newsletter! I think it would\n be safe to say that very few Java developers can remember the details\n of pre-JDK1.3.0. Ahh, nostalgia isn't what it used to be! Do you\n remember running Java for the first time and getting this error:\n \"Unable to initialize threads: cannot find class java/lang/Thread\"?</p>\n</blockquote>\n" }, { "answer_id": 14690836, "author": "Arnaldo Ignacio Gaspar Véjar", "author_id": 1843385, "author_profile": "https://Stackoverflow.com/users/1843385", "pm_score": 2, "selected": false, "text": "<p>As a design consideration, </p>\n\n<pre><code>public interface I {\n public final String KEY = \"a\";\n}\n</code></pre>\n\n<p>The static methods always returns the parent key.</p>\n\n<pre><code>public class A implements I {\n public String KEY = \"b\";\n\n public String getKey() {\n return KEY; // returns \"b\"\n }\n\n public static String getParentKey(){\n return KEY; // returns \"a\"\n }\n}\n</code></pre>\n\n<p>Just like Jom has noticed. The design of static methods using re-defined interface members could be a heavy problem. In general, try to avoid use the same name for the constant.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24545/" ]
Consider the following interface in Java: ``` public interface I { public final String KEY = "a"; } ``` And the following class: ``` public class A implements I { public String KEY = "b"; public String getKey() { return KEY; } } ``` Why is it possible for class A to come along and override interface I's final constant? Try for yourself: ``` A a = new A(); String s = a.getKey(); // returns "b"!!! ```
Despite the fact that you are shadowing the variable it's quite interesting to know that you can change final fields in java as you can read [here](http://www.javaspecialists.co.za/archive/Issue096.html): > > **Java 5 - "final" is not final anymore** > > > Narve Saetre from Machina Networks in Norway sent me a note yesterday, > mentioning that it was a pity that we could change the handle to a > final array. I misunderstood him, and started patiently explaining > that we could not make an array constant, and that there was no way of > protecting the contents of an array. "No", said he, "we can change a > final handle using reflection." > > > I tried Narve's sample code, and unbelievably, Java 5 allowed me to > modify a final handle, even a handle to a primitive field! I knew that > it used to be allowed at some point, but that it was then disallowed, > so I ran some tests with older versions of Java. First, we need a > class with final fields: > > > > ``` > public class Person { > private final String name; > private final int age; > private final int iq = 110; > private final Object country = "South Africa"; > > public Person(String name, int age) { > this.name = name; > this.age = age; > } > > public String toString() { > return name + ", " + age + " of IQ=" + iq + " from " + country; > } > } > > ``` > > **JDK 1.1.x** > > > In JDK 1.1.x, we were not able to access private fields using > reflection. We could, however, create another Person with public > fields, then compile our class against that, and swap the Person > classes. There was no access checking at runtime if we were running > against a different class to the one that we compiled against. > However, we could not rebind final fields at runtime using either > class swapping or reflection. > > > The JDK 1.1.8 JavaDocs for java.lang.reflect.Field had the following > to say: > > > * If this Field object enforces Java language access control, and the underlying field is inaccessible, the method throws an > IllegalAccessException. > * If the underlying field is final, the method throws an IllegalAccessException. > > > **JDK 1.2.x** > > > In JDK 1.2.x, this changed a bit. We could now make private fields > accessible with the setAccessible(true) method. Access of fields was > now checked at runtime, so we could not use the class swapping trick > to access private fields. However, we could now suddenly rebind final > fields! Look at this code: > > > > ``` > import java.lang.reflect.Field; > > public class FinalFieldChange { > private static void change(Person p, String name, Object value) > throws NoSuchFieldException, IllegalAccessException { > Field firstNameField = Person.class.getDeclaredField(name); > firstNameField.setAccessible(true); > firstNameField.set(p, value); > } > public static void main(String[] args) throws Exception { > Person heinz = new Person("Heinz Kabutz", 32); > change(heinz, "name", "Ng Keng Yap"); > change(heinz, "age", new Integer(27)); > change(heinz, "iq", new Integer(150)); > change(heinz, "country", "Malaysia"); > System.out.println(heinz); > } > } > > ``` > > When I ran this in JDK 1.2.2\_014, I got the following result: > > > > ``` > Ng Keng Yap, 27 of IQ=110 from Malaysia Note, no exceptions, no complaints, and an incorrect IQ result. It seems that if we set a > > ``` > > final field of a primitive at declaration time, the value is inlined, > if the type is primitive or a String. > > > **JDK 1.3.x and 1.4.x** > > > In JDK 1.3.x, Sun tightened up the access a bit, and prevented us from > modifying a final field with reflection. This was also the case with > JDK 1.4.x. If we tried running the FinalFieldChange class to rebind > the final fields at runtime using reflection, we would get: > > > > > > > java version "1.3.1\_12": Exception thread "main" > > IllegalAccessException: field is final > > at java.lang.reflect.Field.set(Native Method) > > at FinalFieldChange.change(FinalFieldChange.java:8) > > at FinalFieldChange.main(FinalFieldChange.java:12) > > > > > > java version "1.4.2\_05" Exception thread "main" > > IllegalAccessException: Field is final > > at java.lang.reflect.Field.set(Field.java:519) > > at FinalFieldChange.change(FinalFieldChange.java:8) > > at FinalFieldChange.main(FinalFieldChange.java:12) > > > > > > > > > **JDK 5.x** > > > Now we get to JDK 5.x. The FinalFieldChange class has the same output > as in JDK 1.2.x: > > > > ``` > Ng Keng Yap, 27 of IQ=110 from Malaysia When Narve Saetre mailed me that he managed to change a final field in JDK 5 using > > ``` > > reflection, I was hoping that a bug had crept into the JDK. However, > we both felt that to be unlikely, especially such a fundamental bug. > After some searching, I found the JSR-133: Java Memory Model and > Thread Specification. Most of the specification is hard reading, and > reminds me of my university days (I used to write like that ;-) > However, JSR-133 is so important that it should be required reading > for all Java programmers. (Good luck) > > > Start with chapter 9 Final Field Semantics, on page 25. Specifically, > read section 9.1.1 Post-Construction Modification of Final Fields. It > makes sense to allow updates to final fields. For example, we could > relax the requirement to have fields non-final in JDO. > > > If we read section 9.1.1 carefully, we see that we should only modify > final fields as part of our construction process. The use case is > where we deserialize an object, and then once we have constructed the > object, we initialise the final fields, before passing it on. Once we > have made the object available to another thread, we should not change > final fields using reflection. The result would not be predictable. > > > It even says this: If a final field is initialized to a compile-time > constant in the field declaration, changes to the final field may not > be observed, since uses of that final field are replaced at compile > time with the compile-time constant. This explains why our iq field > stays the same, but country changes. > > > Strangely, JDK 5 differs slightly from JDK 1.2.x, in that you cannot > modify a static final field. > > > > ``` > import java.lang.reflect.Field; > > public class FinalStaticFieldChange { > /** Static fields of type String or primitive would get inlined */ > private static final String stringValue = "original value"; > private static final Object objValue = stringValue; > > private static void changeStaticField(String name) > throws NoSuchFieldException, IllegalAccessException { > Field statFinField = FinalStaticFieldChange.class.getDeclaredField(name); > statFinField.setAccessible(true); > statFinField.set(null, "new Value"); > } > > public static void main(String[] args) throws Exception { > changeStaticField("stringValue"); > changeStaticField("objValue"); > System.out.println("stringValue = " + stringValue); > System.out.println("objValue = " + objValue); > System.out.println(); > } > } > > ``` > > When we run this with JDK 1.2.x and JDK 5.x, we get the following > output: > > > > > > > java version "1.2.2\_014": stringValue = original value objValue = new > > Value > > > > > > java version "1.5.0" Exception thread "main" IllegalAccessException: > > Field is final at java.lang.reflect.Field.set(Field.java:656) at > > FinalStaticFieldChange.changeStaticField(12) at > > FinalStaticFieldChange.main(16) > > > > > > > > > So, JDK 5 is like JDK 1.2.x, just different? > > > **Conclusion** > > > Do you know when JDK 1.3.0 was released? I struggled to find out, so I > downloaded and installed it. The readme.txt file has the date > 2000/06/02 13:10. So, it is more than 4 years old (goodness me, it > feels like yesterday). JDK 1.3.0 was released several months before I > started writing The Java(tm) Specialists' Newsletter! I think it would > be safe to say that very few Java developers can remember the details > of pre-JDK1.3.0. Ahh, nostalgia isn't what it used to be! Do you > remember running Java for the first time and getting this error: > "Unable to initialize threads: cannot find class java/lang/Thread"? > > >
205,240
<p>Is it possible with Axis2 and Eclipse to generate a Web Service client and have it use java types that you already have in packages instead of creating it's own types. Reason being of course if I have type A already created and it creates it's own Type A I can't just assign variable of type A to variable of type B.</p> <p>The wsdl is being generated from a Web Service deployed to an application server. If it's not possible to generate it from that would it be possible to generate a client from the already existing java files.</p>
[ { "answer_id": 205356, "author": "Michael Sharek", "author_id": 1958, "author_profile": "https://Stackoverflow.com/users/1958", "pm_score": 1, "selected": false, "text": "<p>You are generating the web service client from wsdl, correct?</p>\n\n<p>The only thing that the wsdl2java tool knows about is the information in the wsdl, so it won't know about any types that you have already created.</p>\n\n<p>If you can get the type information into the wsdl you may get it to work, although I have never tried.</p>\n\n<p>If you want an easy way to copy from Type A to Type B then you could try <a href=\"http://commons.apache.org/beanutils/api/org/apache/commons/beanutils/BeanUtils.html#copyProperties(java.lang.Object,%20java.lang.Object)\" rel=\"nofollow noreferrer\">BeanUtils.copyProperties</a>, as long as the setters and getters of Type A and Type B match.</p>\n" }, { "answer_id": 206157, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<p>pretty much most java webservices projects go through this. I don't know if the .NET/C# world have a more elegant solution. </p>\n\n<p>It makes sense, as Mike mentioned, to use BeanUtils.copyProperties.</p>\n\n<p>BR,<BR>\n~A</p>\n" }, { "answer_id": 206188, "author": "Michael Sharek", "author_id": 1958, "author_profile": "https://Stackoverflow.com/users/1958", "pm_score": 3, "selected": true, "text": "<p>If you really want to reuse existing classes, you can call the Axis2 API directly without generating a client using wsdl2java. Below is some relatively simple code to call a web service. You just need to fill in the web service endpoint, method QName, expected return Class(es), and arguments to the service. You could reuse your existing classes as the return values or arguments.</p>\n\n<p>If your web service is pretty complicated then you may find that you have to go deeper into the API to get this approach to work.</p>\n\n<pre><code>serviceClient = new RPCServiceClient();\nOptions options = serviceClient.getOptions();\n\nEndpointReference targetEPR = new EndpointReference(\"http://myservice\");\n\noptions.setTo(targetEPR);\n\nQName methodName = new QName(\"ns\",\"methodName\");\n\nClass&lt;?&gt;[] returnTypes = new Class[] { String.class };\n\nObject[] args = new Object[] { \"parameter\" };\n\nObject[] response = serviceClient.invokeBlocking(methodName, args,\n returnTypes);\n</code></pre>\n" }, { "answer_id": 300377, "author": "Red33mer", "author_id": 38721, "author_profile": "https://Stackoverflow.com/users/38721", "pm_score": 0, "selected": false, "text": "<p>If you use eclipse as your ide, that is waht you need: <a href=\"http://www.eclipse.org/webtools/\" rel=\"nofollow noreferrer\">http://www.eclipse.org/webtools/</a>. It does beyond other things exactly what you want.</p>\n" }, { "answer_id": 2872633, "author": "Parth", "author_id": 344993, "author_profile": "https://Stackoverflow.com/users/344993", "pm_score": 0, "selected": false, "text": "<p>You can directly use ServiceClient class to call web service, which provides call using XML only and returns XML response. For different methods of web service, you have to convert the XML response to some java POJO to use it. Only Response handling needs to be done at your end. that you can do like from XML to Map etc...</p>\n\n<p>So you won't need any other stub classes to call any web service, only needs to handle response XML. You can convert XML to POJO using Castor or JAXB libs.</p>\n\n<p>This is the way you don't need to modify your client every time for diff. web services. You can develop like providing a response handler to client externally. So that for every different web service you will have diff. response handler class which is implementation of you interface.</p>\n\n<pre><code>//common interface for response handlers...\n//implement this for diff. web service/methods\npublic interface WSRespHandler{\n public Object getMeResp(Object respData);\n}\n\n\n//pass particular handler to client when you call some WS\npublic class WebServiceClient {\n public Object getResp(WSRespHandler respHandler) {\n ..\n\n return repHandler.getMeResp(xmlData);\n }\n}\n</code></pre>\n\n<p>reference:</p>\n\n<p><a href=\"http://www.developer.com/java/web/article.php/3863416/Using-Axis2-and-Java-for-Asynchronous-Web-Service-Invocation-on-the-Client-Side.htm\" rel=\"nofollow noreferrer\">http://www.developer.com/java/web/article.php/3863416/Using-Axis2-and-Java-for-Asynchronous-Web-Service-Invocation-on-the-Client-Side.htm</a></p>\n\n<p><a href=\"http://www.devdaily.com/blog/post/java/java-web-service-client-read-array-list/\" rel=\"nofollow noreferrer\">http://www.devdaily.com/blog/post/java/java-web-service-client-read-array-list/</a></p>\n\n<p>thanks.</p>\n\n<p>www.techlads.com</p>\n" }, { "answer_id": 14460708, "author": "davidfm", "author_id": 1732156, "author_profile": "https://Stackoverflow.com/users/1732156", "pm_score": 0, "selected": false, "text": "<p>In case this post is still of any use to someone I read the axis2 generating clients guide: <a href=\"http://axis.apache.org/axis2/java/core/docs/userguide-creatingclients.html\" rel=\"nofollow\">http://axis.apache.org/axis2/java/core/docs/userguide-creatingclients.html</a>. </p>\n\n<p>It seems that the Axis2 Eclipse plugin is configured to call ADB code generation in integrated mode (see <a href=\"http://axis.apache.org/axis2/java/core/docs/adb/adb-howto.html\" rel=\"nofollow\">http://axis.apache.org/axis2/java/core/docs/adb/adb-howto.html</a>), thus creating inner classes in the Web service stub. I don't know if changing the generation mode to expanded mode (generate data classes out of the stub class) is possible, but you can do it command line using Wsdl2Java:</p>\n\n<pre><code> %AXIS2_HOME%\\bin\\WSDL2Java -uri &lt;wsdl file path&gt; -p &lt;package name&gt; -u\n</code></pre>\n\n<p>The -u option tells the ADB code generator to create data classes as separate classes and not inner classes in the stub.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28288/" ]
Is it possible with Axis2 and Eclipse to generate a Web Service client and have it use java types that you already have in packages instead of creating it's own types. Reason being of course if I have type A already created and it creates it's own Type A I can't just assign variable of type A to variable of type B. The wsdl is being generated from a Web Service deployed to an application server. If it's not possible to generate it from that would it be possible to generate a client from the already existing java files.
If you really want to reuse existing classes, you can call the Axis2 API directly without generating a client using wsdl2java. Below is some relatively simple code to call a web service. You just need to fill in the web service endpoint, method QName, expected return Class(es), and arguments to the service. You could reuse your existing classes as the return values or arguments. If your web service is pretty complicated then you may find that you have to go deeper into the API to get this approach to work. ``` serviceClient = new RPCServiceClient(); Options options = serviceClient.getOptions(); EndpointReference targetEPR = new EndpointReference("http://myservice"); options.setTo(targetEPR); QName methodName = new QName("ns","methodName"); Class<?>[] returnTypes = new Class[] { String.class }; Object[] args = new Object[] { "parameter" }; Object[] response = serviceClient.invokeBlocking(methodName, args, returnTypes); ```
205,270
<p>My MFC application using the "ESRI MapObjects LT2" ActiveX plugin throws an ASSERT at me when closing it. The error occurs in <code>cmdtarg.cpp</code>:</p> <pre><code>CCmdTarget::~CCmdTarget() { #ifndef _AFX_NO_OLE_SUPPORT if (m_xDispatch.m_vtbl != 0) ((COleDispatchImpl*)&amp;m_xDispatch)-&gt;Disconnect(); ASSERT(m_dwRef &lt;= 1); //&lt;--- Fails because m_dwRef is 3 #endif m_pModuleState = NULL; } </code></pre> <p>I built the (native C++) application with VC9. When I compile the application with VC6, it behaves nicely.</p> <p>What could be the reason for this?</p>
[ { "answer_id": 205449, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 2, "selected": false, "text": "<p>That looks like a reference count. Could this \"target\" be referenced by something else, something that's not releasing it?</p>\n" }, { "answer_id": 205639, "author": "Alessandro Jacopson", "author_id": 15485, "author_profile": "https://Stackoverflow.com/users/15485", "pm_score": 2, "selected": false, "text": "<p>You can trace the Addref and Release calls defining <code>_ATL_DEBUG_INTERFACES</code> </p>\n\n<p>from <a href=\"http://msdn.microsoft.com/en-us/library/sycfy8ec(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/sycfy8ec(VS.80).aspx</a></p>\n\n<pre><code>_ATL_DEBUG_INTERFACES\n</code></pre>\n\n<p>Define this macro before including any ATL header files to trace all AddRef and Release calls on your components' interfaces to the output window.</p>\n" }, { "answer_id": 205890, "author": "foraidt", "author_id": 27596, "author_profile": "https://Stackoverflow.com/users/27596", "pm_score": 1, "selected": false, "text": "<p>Using <code>_ATL_DEBUG_INTERFACES</code> did not yield any additional output...\nI defined it on the first line of <code>stdafx.</code>h, directly after <code>#pragma once</code> so I guess this is early enough.</p>\n\n<p>Maybe the reason is how I am using the ActiveX control:<br>\nI'm not calling <code>AddRef()</code> or <code>Release()</code> by myself.<br>\nThe MapObjects Installer comes with sample code with lots of wrapper classes which must have been generated by VC6 or something earlier.<br>\nI tried to generate wrapper classes myself with VC9 but there occured errors which I wasn't able to fix.\nI use the control by letting one of my windows have a member of type <code>CMap1</code> (derived from <code>CWnd</code>), which is one of those generated wrapper classes. In <code>CMyWnd::OnCreate()</code> I also call <code>CMap1::Create()</code> and that's it, I'm finished: I can add a layer and the control displays a world map.<br>\nI have pretty much no idea what the reference-count stuff is about as I have not added or released any references. At least not knowingly...</p>\n\n<p>The control is pretty old: The .OCX file has the year 2000 in its version information.<br>\nIt's also not officially supported anymore but I don't have any substitue.</p>\n" }, { "answer_id": 785307, "author": "foraidt", "author_id": 27596, "author_profile": "https://Stackoverflow.com/users/27596", "pm_score": 2, "selected": true, "text": "<p>The following solved it for me:\nIn the window that contains the control, add an OnDestroy() handler:</p>\n\n<pre><code>void CMyWnd::OnDestroy()\n{\n // Apparently we have to disconnect the (ActiveX) Map control manually\n // with this undocumented method.\n COleControlSite* pSite = GetOleControlSite(MY_DIALOG_CONTROL_ID);\n if(NULL != pSite)\n {\n pSite-&gt;ExternalDisconnect();\n }\n\n CWnd::OnDestroy();\n}\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27596/" ]
My MFC application using the "ESRI MapObjects LT2" ActiveX plugin throws an ASSERT at me when closing it. The error occurs in `cmdtarg.cpp`: ``` CCmdTarget::~CCmdTarget() { #ifndef _AFX_NO_OLE_SUPPORT if (m_xDispatch.m_vtbl != 0) ((COleDispatchImpl*)&m_xDispatch)->Disconnect(); ASSERT(m_dwRef <= 1); //<--- Fails because m_dwRef is 3 #endif m_pModuleState = NULL; } ``` I built the (native C++) application with VC9. When I compile the application with VC6, it behaves nicely. What could be the reason for this?
The following solved it for me: In the window that contains the control, add an OnDestroy() handler: ``` void CMyWnd::OnDestroy() { // Apparently we have to disconnect the (ActiveX) Map control manually // with this undocumented method. COleControlSite* pSite = GetOleControlSite(MY_DIALOG_CONTROL_ID); if(NULL != pSite) { pSite->ExternalDisconnect(); } CWnd::OnDestroy(); } ```
205,287
<p>I am writing an XML document in C#.</p> <p>I have something like this...</p> <pre><code>string output = "REAPP DUE NO OF M CASE NBR APPL NBR DATE GRPS M CASE NBR APPL NBR DATE GRPS _ _ _"; </code></pre> <p>and I do this...</p> <pre><code> objXmlTextWriter.WriteStartElement("Case"); objXmlTextWriter.WriteString(record); objXmlTextWriter.WriteEndElement(); </code></pre> <p>and the xml element turns out like this...</p> <pre><code>&lt;Case&gt;REAPP DUE NO OF REAPP DUE NO OF M CASE NBR APPL NBR DATE GRPS M CASE NBR APPL NBR DATE GRPS _ _ _ &lt;/Case&gt; </code></pre> <p>It has basically converted white space with length greater than 1 to 1 character of white space.</p> <p>How do I prevent this?</p>
[ { "answer_id": 205298, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 3, "selected": true, "text": "<p>GridView has a DataKeyNames property. When you bind a data source to the grid, you set the DataKeyNames (usually with just one name, your PK field). You don't show the PK, but you can get to it from code-behind.</p>\n" }, { "answer_id": 205305, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>Visible=false means don't render on the page. What you want is either to make it a template field and use a HiddenField to hold the value or set the style on the control to \"display: none;\". This would be the case if the client side code needed access to the value for an Ajax call or something.</p>\n\n<p>Otherwise use the DataKeyNames property as @Eric Z Beard suggests.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6161/" ]
I am writing an XML document in C#. I have something like this... ``` string output = "REAPP DUE NO OF M CASE NBR APPL NBR DATE GRPS M CASE NBR APPL NBR DATE GRPS _ _ _"; ``` and I do this... ``` objXmlTextWriter.WriteStartElement("Case"); objXmlTextWriter.WriteString(record); objXmlTextWriter.WriteEndElement(); ``` and the xml element turns out like this... ``` <Case>REAPP DUE NO OF REAPP DUE NO OF M CASE NBR APPL NBR DATE GRPS M CASE NBR APPL NBR DATE GRPS _ _ _ </Case> ``` It has basically converted white space with length greater than 1 to 1 character of white space. How do I prevent this?
GridView has a DataKeyNames property. When you bind a data source to the grid, you set the DataKeyNames (usually with just one name, your PK field). You don't show the PK, but you can get to it from code-behind.
205,299
<p>I tried the following code in LINQPad and got the results given below:</p> <pre><code>List&lt;string&gt; listFromSplit = new List&lt;string&gt;("a, b".Split(",".ToCharArray())).Dump(); listFromSplit.ForEach(delegate(string s) { s.Trim(); }); listFromSplit.Dump(); </code></pre> <blockquote> <p>"a" and " b"</p> </blockquote> <p>so the letter b didn't get the white-space removed as I was expecting...?</p> <p>Anyone have any ideas</p> <p>[NOTE: the .Dump() method is an extension menthod in LINQPad that prints out the contents of any object in a nice intelligently formatted way]</p>
[ { "answer_id": 205306, "author": "Sciolist", "author_id": 16045, "author_profile": "https://Stackoverflow.com/users/16045", "pm_score": 4, "selected": false, "text": "<p>you're just creating a trimmed string, not assigning anything to it.</p>\n\n<pre><code>var s = \" asd \";\ns.Trim();\n</code></pre>\n\n<p>won't update s, while..</p>\n\n<pre><code>var s = \" asd \";\ns = s.Trim();\n</code></pre>\n\n<p>will.. </p>\n\n<pre><code>var listFromSplit = \"a, b\".Split(',').Select(s=&gt;s.Trim());\n</code></pre>\n\n<p>would, i suppose, be how i'd go about it.</p>\n" }, { "answer_id": 205310, "author": "pezi_pink_squirrel", "author_id": 24757, "author_profile": "https://Stackoverflow.com/users/24757", "pm_score": 1, "selected": false, "text": "<p>You are not assigning the trimmed result to anything. This is a classic error, I've only just got out of the habit of making this mistake with string.Replace :)</p>\n" }, { "answer_id": 205319, "author": "Pablo Marambio", "author_id": 18552, "author_profile": "https://Stackoverflow.com/users/18552", "pm_score": 2, "selected": false, "text": "<p>The string instances are immutable. Anything that seems to modify one, creates a new instance instead.</p>\n" }, { "answer_id": 205339, "author": "akmad", "author_id": 1314, "author_profile": "https://Stackoverflow.com/users/1314", "pm_score": 4, "selected": true, "text": "<p>The String.Trim() method returns a string representing the updated string. It does not update the string object itself, but rather creates a new one.</p>\n\n<p>You could do this:</p>\n\n<pre><code>s = s.Trim();\n</code></pre>\n\n<p>However you cannot update a collection while enumerating through it so you'd want to either fill a new List while enumerating over the existing one or populate the List manually using the string array returned by String.Split.</p>\n\n<p>Filling a new list:</p>\n\n<pre><code>List&lt;string&gt; temp = new List&lt;string&gt;(\"a, b\".Split(\",\".ToCharArray()));\nList&lt;string&gt; listFromSplit = new List&lt;string&gt;();\n\ntemp.ForEach(delegate(string s) \n{ \n listFromSplit.Add(s.Trim()); \n});\n\nlistFromSplit.Dump();\n</code></pre>\n\n<p>Populating Manually:</p>\n\n<pre><code>string[] temp = \"a, b\".Split(\",\".ToCharArray());\nList&lt;string&gt; listFromSplit = new List&lt;string&gt;();\n\nforeach (string s in temp)\n{\n listFromSplit.Add(s.Trim()); \n};\n\nlistFromSplit.Dump();\n</code></pre>\n" }, { "answer_id": 205342, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>Split on both spaces and commas and remove any empty entries. All nice and trimmed. Assumes that your strings don't contain spaces, though.</p>\n\n<pre><code>List&lt;string&gt; listFromSplit =\n new List&lt;string&gt;( \"a , b \".Split( new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries ));\n</code></pre>\n" }, { "answer_id": 205509, "author": "akuhn", "author_id": 24468, "author_profile": "https://Stackoverflow.com/users/24468", "pm_score": 1, "selected": false, "text": "<p>I have no IDE up and running, but this should get the job done (unless I am wrong):</p>\n\n<pre><code>var result = from each in listFromSplit select each.Trim();\n</code></pre>\n" }, { "answer_id": 584385, "author": "mezoid", "author_id": 39532, "author_profile": "https://Stackoverflow.com/users/39532", "pm_score": 2, "selected": false, "text": "<p>Further to the answer posted by <a href=\"https://stackoverflow.com/questions/205299/why-does-my-attempt-to-trim-strings-in-a-liststring-not-appear-to-work/205509#205509\">Adrian Kuhn</a> you could do the following:</p>\n\n<pre><code>var result = listFromSplit.Select(s =&gt; s.Trim());\n</code></pre>\n" }, { "answer_id": 11904279, "author": "frax", "author_id": 1552658, "author_profile": "https://Stackoverflow.com/users/1552658", "pm_score": 0, "selected": false, "text": "<p>The linq options others have provided should work well. As another option, here is an extension method using a for loop:</p>\n\n<pre><code> public static void TrimCollection(this IList&lt;string&gt; stringCollection) {\n\n for (int i = 0; i &lt;= stringCollection.Count() - 1; i++)\n stringCollection[i] = stringCollection[i].Trim();\n\n }\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5351/" ]
I tried the following code in LINQPad and got the results given below: ``` List<string> listFromSplit = new List<string>("a, b".Split(",".ToCharArray())).Dump(); listFromSplit.ForEach(delegate(string s) { s.Trim(); }); listFromSplit.Dump(); ``` > > "a" and " b" > > > so the letter b didn't get the white-space removed as I was expecting...? Anyone have any ideas [NOTE: the .Dump() method is an extension menthod in LINQPad that prints out the contents of any object in a nice intelligently formatted way]
The String.Trim() method returns a string representing the updated string. It does not update the string object itself, but rather creates a new one. You could do this: ``` s = s.Trim(); ``` However you cannot update a collection while enumerating through it so you'd want to either fill a new List while enumerating over the existing one or populate the List manually using the string array returned by String.Split. Filling a new list: ``` List<string> temp = new List<string>("a, b".Split(",".ToCharArray())); List<string> listFromSplit = new List<string>(); temp.ForEach(delegate(string s) { listFromSplit.Add(s.Trim()); }); listFromSplit.Dump(); ``` Populating Manually: ``` string[] temp = "a, b".Split(",".ToCharArray()); List<string> listFromSplit = new List<string>(); foreach (string s in temp) { listFromSplit.Add(s.Trim()); }; listFromSplit.Dump(); ```
205,340
<p>I'm getting odd results from a <code>MySQL SELECT</code> query involving a <code>LEFT JOIN</code>, and I can't understand whether my understanding of <code>LEFT JOIN</code> is wrong or whether I'm seeing a genuinely odd behavior.</p> <p>I have a two tables with a many-to-one relationship: For every record in <code>table 1</code> there are 0 or more records in <code>table 2</code>. I want to select all the records in table 1 with a column that counts the number of related records in table 2. As I understand it, <code>LEFT JOIN</code> should always return all records on the <code>LEFT</code> side of the statement.</p> <p>Here's a test database that exhibits the problem:</p> <pre><code>CREATE DATABASE Test; USE Test; CREATE TABLE Dates ( dateID INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATE NOT NULL, UNIQUE KEY (dateID) ) TYPE=MyISAM; CREATE TABLE Slots ( slotID INT UNSIGNED NOT NULL AUTO_INCREMENT, dateID INT UNSIGNED NOT NULL, UNIQUE KEY (slotID) ) TYPE=MyISAM; INSERT INTO Dates (date) VALUES ('2008-10-12'),('2008-10-13'),('2008-10-14'); INSERT INTO Slots (dateID) VALUES (3); </code></pre> <p>The Dates table has three records, and the Slots 1 - and that record points to the third record in Dates.</p> <p>If I do the following query..</p> <pre><code>SELECT d.date, count(s.slotID) FROM Dates AS d LEFT JOIN Slots AS s ON s.dateID=d.dateID GROUP BY s.dateID; </code></pre> <p>..I expect to see a table with 3 rows in - two with a count of 0, and one with a count of 1. But what I actually see is this:</p> <pre><code>+------------+-----------------+ | date | count(s.slotID) | +------------+-----------------+ | 2008-10-12 | 0 | | 2008-10-14 | 1 | +------------+-----------------+ </code></pre> <p>The first record with a zero count appears, but the later record with a zero count is ignored. </p> <p>Am I doing something wrong, or do I just not understand what LEFT JOIN is supposed to do?</p>
[ { "answer_id": 205365, "author": "thoroughly", "author_id": 8943, "author_profile": "https://Stackoverflow.com/users/8943", "pm_score": 2, "selected": false, "text": "<p>I think you mean to group by d.dateId.</p>\n" }, { "answer_id": 205370, "author": "leif", "author_id": 24563, "author_profile": "https://Stackoverflow.com/users/24563", "pm_score": 1, "selected": false, "text": "<p>Try removing the GROUP BY s.dateID</p>\n" }, { "answer_id": 205372, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 4, "selected": true, "text": "<p>You need to <code>GROUP BY d.dateID</code>. In two of your cases, <code>s.DateID</code> is <code>NULL</code> (<code>LEFT JOIN</code>) and these are combined together.</p>\n\n<p>I think you will also find that this is invalid (ANSI) SQL, because d.date is not part of a <code>GROUP BY</code> or the result of an aggregate operation, and should not be able to be <code>SELECT</code>ed.</p>\n" }, { "answer_id": 205385, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 1, "selected": false, "text": "<p>The dateid for 10-12 and 10-13 are groupd together by you. Since they are 2 null values the count is evaluated to 0</p>\n" }, { "answer_id": 205391, "author": "Veynom", "author_id": 11670, "author_profile": "https://Stackoverflow.com/users/11670", "pm_score": 0, "selected": false, "text": "<p>replace GROUP BY s.dateID with d.dateID.</p>\n" }, { "answer_id": 205578, "author": "John Nilsson", "author_id": 24243, "author_profile": "https://Stackoverflow.com/users/24243", "pm_score": 1, "selected": false, "text": "<p>I don't know if this is valid in MySQL but you could probably void this mistake in the future by using the following syntax instead</p>\n\n<pre><code>SELECT date, count(slotID) as slotCount\nFROM Dates LEFT OUTER JOIN Slots USING (dateID)\nGROUP BY (date)\n</code></pre>\n\n<p>By using the USING clause you don't get two dateID's to keep track of.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28299/" ]
I'm getting odd results from a `MySQL SELECT` query involving a `LEFT JOIN`, and I can't understand whether my understanding of `LEFT JOIN` is wrong or whether I'm seeing a genuinely odd behavior. I have a two tables with a many-to-one relationship: For every record in `table 1` there are 0 or more records in `table 2`. I want to select all the records in table 1 with a column that counts the number of related records in table 2. As I understand it, `LEFT JOIN` should always return all records on the `LEFT` side of the statement. Here's a test database that exhibits the problem: ``` CREATE DATABASE Test; USE Test; CREATE TABLE Dates ( dateID INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATE NOT NULL, UNIQUE KEY (dateID) ) TYPE=MyISAM; CREATE TABLE Slots ( slotID INT UNSIGNED NOT NULL AUTO_INCREMENT, dateID INT UNSIGNED NOT NULL, UNIQUE KEY (slotID) ) TYPE=MyISAM; INSERT INTO Dates (date) VALUES ('2008-10-12'),('2008-10-13'),('2008-10-14'); INSERT INTO Slots (dateID) VALUES (3); ``` The Dates table has three records, and the Slots 1 - and that record points to the third record in Dates. If I do the following query.. ``` SELECT d.date, count(s.slotID) FROM Dates AS d LEFT JOIN Slots AS s ON s.dateID=d.dateID GROUP BY s.dateID; ``` ..I expect to see a table with 3 rows in - two with a count of 0, and one with a count of 1. But what I actually see is this: ``` +------------+-----------------+ | date | count(s.slotID) | +------------+-----------------+ | 2008-10-12 | 0 | | 2008-10-14 | 1 | +------------+-----------------+ ``` The first record with a zero count appears, but the later record with a zero count is ignored. Am I doing something wrong, or do I just not understand what LEFT JOIN is supposed to do?
You need to `GROUP BY d.dateID`. In two of your cases, `s.DateID` is `NULL` (`LEFT JOIN`) and these are combined together. I think you will also find that this is invalid (ANSI) SQL, because d.date is not part of a `GROUP BY` or the result of an aggregate operation, and should not be able to be `SELECT`ed.
205,351
<p>This case arises in a real-life situation where invalid data was in (and continuing to come into) an Oracle database which is extracted into a data processing system in Focus. Focus would choke and die on some rows with invalid time portions. The Oracle DBA would then go and copy the datetime into the affected column from a good column to allow the process to continue (yeah, I know).</p> <p>I assisted troubleshooting the problem and found that in Oracle on an affected row:</p> <pre><code>DUMP(START_TIME) </code></pre> <p>gives:</p> <pre><code>'Typ=12 Len=7: 100,99,255,255,0,0,0' </code></pre> <p>While:</p> <pre><code>TO_CHAR(START_TIME, 'YYYY/MM/DD HH24:MI:SS') </code></pre> <p>gives:</p> <pre><code>ORA-01801: date format is too long for internal buffer </code></pre> <p>Looking at the <code>DUMP()</code> results, <code>'Typ=12 Len=7: 100,99,255,255,0,0,0'</code>, and the <a href="http://www.psoug.org/reference/datatypes.html" rel="nofollow noreferrer">storage conventions</a>, it appears that they are able to bypass the column's semantic limits and insert the equivalent of 0, -1, -1, -1, -1, -1, -1 or <code>0x00 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF</code></p> <p>Which makes "sense", since <code>0xFF = 255 = -1</code> might potentially result in <code>0000/255/255 255:255:255</code> depending on how you interpret the bytes, signs and overflows.</p> <p>Under what conditions (connection mechanism, etc) does Oracle allow invalid data to come into datetime columns?</p>
[ { "answer_id": 205412, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 1, "selected": false, "text": "<p>I cannot seem to find the bug in a quick Metalink search (if you haven't opened a SR with Oracle yet, I'd suggest doing so), but I know there were bugs in the OCI layer (Oracle Call Interface) that allowed buggy code to insert invalid dates. For the most part, those bugs have been corrected for some time, though, so I would tend to wager that if you applied the latest patchset to the client machines that are doing the inserts that the problem would disappear.</p>\n" }, { "answer_id": 297859, "author": "Gary Myers", "author_id": 25714, "author_profile": "https://Stackoverflow.com/users/25714", "pm_score": 3, "selected": false, "text": "<p>Oracle generally doesn't allow it.\nThe OCI layer can bypass the data type validation - Oracle basically trusts that what you put in those seven bytes make up a valid date. Similarly, at the OCI layer, Oracle can pass back seven bytes of 'date' and it is up to the client software to do whatever it wishes with those bytes (leave them as is, convert to a string or an epoch number...)\nMaybe a better approach is to work out what loads the data in there and see what that is doing with the dates.</p>\n\n<p>If you are feeling exceptionally perverse you can use the undocumented REVERSE function on a date and make it invalid.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18255/" ]
This case arises in a real-life situation where invalid data was in (and continuing to come into) an Oracle database which is extracted into a data processing system in Focus. Focus would choke and die on some rows with invalid time portions. The Oracle DBA would then go and copy the datetime into the affected column from a good column to allow the process to continue (yeah, I know). I assisted troubleshooting the problem and found that in Oracle on an affected row: ``` DUMP(START_TIME) ``` gives: ``` 'Typ=12 Len=7: 100,99,255,255,0,0,0' ``` While: ``` TO_CHAR(START_TIME, 'YYYY/MM/DD HH24:MI:SS') ``` gives: ``` ORA-01801: date format is too long for internal buffer ``` Looking at the `DUMP()` results, `'Typ=12 Len=7: 100,99,255,255,0,0,0'`, and the [storage conventions](http://www.psoug.org/reference/datatypes.html), it appears that they are able to bypass the column's semantic limits and insert the equivalent of 0, -1, -1, -1, -1, -1, -1 or `0x00 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF` Which makes "sense", since `0xFF = 255 = -1` might potentially result in `0000/255/255 255:255:255` depending on how you interpret the bytes, signs and overflows. Under what conditions (connection mechanism, etc) does Oracle allow invalid data to come into datetime columns?
Oracle generally doesn't allow it. The OCI layer can bypass the data type validation - Oracle basically trusts that what you put in those seven bytes make up a valid date. Similarly, at the OCI layer, Oracle can pass back seven bytes of 'date' and it is up to the client software to do whatever it wishes with those bytes (leave them as is, convert to a string or an epoch number...) Maybe a better approach is to work out what loads the data in there and see what that is doing with the dates. If you are feeling exceptionally perverse you can use the undocumented REVERSE function on a date and make it invalid.
205,359
<p>This is similar to my previous posting. But this time I want to call a function that exists on the main mxml page.</p> <p>This is my main mxml page:</p> <p>main.mxml</p> <pre><code>&lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:ns1="*"&gt; &lt;mx:Script&gt; &lt;![CDATA[ public function changeText(currentText:String):void{ switch (currentText){ case "changeText": lblOne.text = "More Text"; } } ]]&gt; &lt;/mx:Script&gt; &lt;mx:HBox x="137.5" y="10" width="100%" height="100%"&gt; &lt;ns1:menu id="buttons"&gt; &lt;/ns1:menu&gt; &lt;/mx:HBox&gt; &lt;mx:Canvas x="137" y="88" width="408.5" height="200"&gt; &lt;mx:HBox x="0" y="10" width="388.5" height="190"&gt; &lt;mx:Panel width="388" height="179" layout="absolute"&gt; &lt;mx:Label x="10" y="10" text="Some Text" visible="{buttons.showLabel}" id="lblOne"/&gt; &lt;/mx:Panel&gt; &lt;/mx:HBox&gt; &lt;/mx:Canvas&gt; &lt;/mx:Application&gt; </code></pre> <p>Here is my included page:</p> <p>menu.mxml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300"&gt; &lt;mx:Script&gt; &lt;![CDATA[ [Bindable] public var showLabel:Boolean = true; ]]&gt; &lt;/mx:Script&gt; &lt;mx:MenuBar width="380" height="58"&gt;&lt;/mx:MenuBar&gt; &lt;mx:Button x="10" y="10" width="80" label="Show" id="btnOne" click="this.showLabel=true;" /&gt; &lt;mx:Button x="94" y="10" width="80" label="Hide" id="btnTwo" click="this.showLabel=false;"/&gt; &lt;mx:Button x="181" y="10" width="80" label="Run Function" id="btnThree" click="{changeText('changeText')}"/&gt; &lt;/mx:Canvas&gt; </code></pre> <p>How do I call the changeText function from the button on menu.mxml?</p>
[ { "answer_id": 205462, "author": "Brandon", "author_id": 23133, "author_profile": "https://Stackoverflow.com/users/23133", "pm_score": 3, "selected": true, "text": "<p>Add this to menu: </p>\n\n<pre><code> &lt;mx:Metadata&gt;\n [Event(name=\"buttonClicked\", type=\"flash.events.Event\")]\n &lt;/mx:Metadata&gt;\n\n &lt;mx:Button x=\"10\" y=\"10\" width=\"80\" label=\"Show\" id=\"btnOne\" click=\"this.showLabel=true;dispatchEvent(new Event(\"buttonClicked\"));\"/&gt;\n</code></pre>\n\n<p>Change main to:</p>\n\n<pre><code> &lt;ns1:menu id=\"buttons\" buttonClicked=\"changeText(\"Your Text\");\"&gt;\n</code></pre>\n\n<p>I couldn't tell where current text is coming from but if it is from menu you may have to build your own custom flex event or create a common variable for the two parts to access. The first is usually preferred.</p>\n\n<p>P.S. The event metadata thing could also be achieved by adding the event listener when the creation of the application completes. You would add to main:</p>\n\n<pre><code>buttons.addEventListener(\"buttonClicked\",changeText(\"Your Text\"));\n</code></pre>\n" }, { "answer_id": 1350709, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>there is a simpler way, just use parentDocument.</p>\n\n<p>Change this: </p>\n\n<pre><code>&lt;mx:Button x=\"181\" y=\"10\" width=\"80\" label=\"Run Function\" id=\"btnThree\" click=\"{changeText('changeText')}\"/&gt;\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>&lt;mx:Button x=\"181\" y=\"10\" width=\"80\" label=\"Run Function\" id=\"btnThree\" click=\"{parentDocument*.changeText('changeText')}\"/&gt;**\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24563/" ]
This is similar to my previous posting. But this time I want to call a function that exists on the main mxml page. This is my main mxml page: main.mxml ``` <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:ns1="*"> <mx:Script> <![CDATA[ public function changeText(currentText:String):void{ switch (currentText){ case "changeText": lblOne.text = "More Text"; } } ]]> </mx:Script> <mx:HBox x="137.5" y="10" width="100%" height="100%"> <ns1:menu id="buttons"> </ns1:menu> </mx:HBox> <mx:Canvas x="137" y="88" width="408.5" height="200"> <mx:HBox x="0" y="10" width="388.5" height="190"> <mx:Panel width="388" height="179" layout="absolute"> <mx:Label x="10" y="10" text="Some Text" visible="{buttons.showLabel}" id="lblOne"/> </mx:Panel> </mx:HBox> </mx:Canvas> </mx:Application> ``` Here is my included page: menu.mxml ``` <?xml version="1.0" encoding="utf-8"?> <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300"> <mx:Script> <![CDATA[ [Bindable] public var showLabel:Boolean = true; ]]> </mx:Script> <mx:MenuBar width="380" height="58"></mx:MenuBar> <mx:Button x="10" y="10" width="80" label="Show" id="btnOne" click="this.showLabel=true;" /> <mx:Button x="94" y="10" width="80" label="Hide" id="btnTwo" click="this.showLabel=false;"/> <mx:Button x="181" y="10" width="80" label="Run Function" id="btnThree" click="{changeText('changeText')}"/> </mx:Canvas> ``` How do I call the changeText function from the button on menu.mxml?
Add this to menu: ``` <mx:Metadata> [Event(name="buttonClicked", type="flash.events.Event")] </mx:Metadata> <mx:Button x="10" y="10" width="80" label="Show" id="btnOne" click="this.showLabel=true;dispatchEvent(new Event("buttonClicked"));"/> ``` Change main to: ``` <ns1:menu id="buttons" buttonClicked="changeText("Your Text");"> ``` I couldn't tell where current text is coming from but if it is from menu you may have to build your own custom flex event or create a common variable for the two parts to access. The first is usually preferred. P.S. The event metadata thing could also be achieved by adding the event listener when the creation of the application completes. You would add to main: ``` buttons.addEventListener("buttonClicked",changeText("Your Text")); ```
205,375
<p>I have a String such as: </p> <pre><code>Cerepedia, una apliación web </code></pre> <p>I would like to transform it into something URL valid such as: </p> <pre><code>Cerepedia,unaaplicacionweb </code></pre> <p><strong>Note:</strong> the special character transformation and spaces removal. </p> <p>By the way, are commas allowed in URLs?</p>
[ { "answer_id": 205404, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 2, "selected": false, "text": "<p>Have you looked at <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLEncoder.html\" rel=\"nofollow noreferrer\">URLEncoder</a>? That seems to do what you need it to do. Though the special characters will be transformed to escaped entities and not stripped from their \"special\" properties.</p>\n" }, { "answer_id": 205423, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 2, "selected": false, "text": "<p>Try convertNonAscii() in the class below</p>\n\n<pre><code>public class AsciiUtils {\n\n /**\n * Contains a list of all the characters that map one to one for UNICODE.\n */\n private static final String PLAIN_ASCII = \n \"AaEeIiOoUu\" // grave\n + \"AaEeIiOoUuYy\" // acute\n + \"AaEeIiOoUuYy\" // circumflex\n + \"AaEeIiOoUuYy\" // tilde\n + \"AaEeIiOoUuYy\" // umlaut\n + \"Aa\" // ring\n + \"Cc\" // cedilla\n + \"Nn\" // n tilde (spanish)\n ;\n\n /**\n * Actual accented values, corresponds one to one with ASCII\n */\n private static final String UNICODE =\n \"\\u00C0\\u00E0\\u00C8\\u00E8\\u00CC\\u00EC\\u00D2\\u00F2\\u00D9\\u00F9\" \n +\"\\u00C1\\u00E1\\u00C9\\u00E9\\u00CD\\u00ED\\u00D3\\u00F3\\u00DA\\u00FA\\u00DD\\u00FD\" \n +\"\\u00C2\\u00E2\\u00CA\\u00EA\\u00CE\\u00EE\\u00D4\\u00F4\\u00DB\\u00FB\\u0176\\u0177\" \n +\"\\u00C2\\u00E2\\u00CA\\u00EA\\u00CE\\u00EE\\u00D4\\u00F4\\u00DB\\u00FB\\u0176\\u0177\" \n +\"\\u00C4\\u00E4\\u00CB\\u00EB\\u00CF\\u00EF\\u00D6\\u00F6\\u00DC\\u00FC\\u0178\\u00FF\" \n +\"\\u00C5\\u00E5\" \n +\"\\u00C7\\u00E7\" \n +\"\\u00D1\\u00F1\"\n ;\n\n // private constructor, can't be instanciated!\n private AsciiUtils() { \n }\n\n\n /**\n * Removes accentued from a string and replace with ascii equivalent\n * @param s The string to englishify\n * @return The string without the french and spanish stuff.\n */\n public static String convertNonAscii(String s) {\n\n StringBuilder b = new StringBuilder();\n\n int n = s.length();\n for (int i = 0; i &lt; n; i++) {\n char c = s.charAt(i);\n int pos = UNICODE.indexOf(c);\n if (pos &gt; -1) {\n b.append(PLAIN_ASCII.charAt(pos));\n } else {\n b.append(c);\n }\n }\n\n return b.toString();\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 221627, "author": "Sergio del Amo", "author_id": 2138, "author_profile": "https://Stackoverflow.com/users/2138", "pm_score": 0, "selected": false, "text": "<p>URLEncoder subsitutes spaces with +. The Asccii class posted by Don does not remove spaces but the next function can be used for that propouse: </p>\n\n<pre><code>public static String removeSpaces(String s) {\n StringTokenizer st = new StringTokenizer(s,\" \",false);\n String t=\"\";\n while (st.hasMoreElements()) t += st.nextElement();\n return t;\n}\n</code></pre>\n" }, { "answer_id": 222361, "author": "Sergio del Amo", "author_id": 2138, "author_profile": "https://Stackoverflow.com/users/2138", "pm_score": 0, "selected": false, "text": "<p><strong>Note</strong> Don solution works with strings in code but does not work with strings coming from a file with UTF-8 encoding</p>\n\n<p>This is the best solution i have, using URLEncode and escaping the hexadecimal characters afterwards:</p>\n\n<pre><code>String s = \"Cerepedia, una apliación web\";\nString ENCODING= \"uft-8\";\nString encoded_s = URLEncoder.encode(s,ENCODING); // Cerepedia+una+aplicaci%C3%83%C2%B3n+web\nString s_hexa_free = EncodingTableUtils.replaceHexa(,ENCODING)); // Cerepedia+una+aplicacion+web\n</code></pre>\n\n<p>EncodingTableUtils </p>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Set;\n\npublic class EncodingTableUtils {\n public final static HashMap iso88591 = new HashMap();\n static {\n iso88591.put(\"%C3%A1\", \"a\"); // á\n iso88591.put(\"%C3%81\", \"A\"); // Á\n iso88591.put(\"%C3%A9\", \"e\"); // é\n iso88591.put(\"%C3%89\", \"E\"); // É\n iso88591.put(\"%C3%AD\", \"i\"); // í\n iso88591.put(\"%C3%8D\", \"I\"); // Í\n iso88591.put(\"%C3%93\", \"O\"); // Ó\n iso88591.put(\"%C3%B3\", \"o\"); // ó\n iso88591.put(\"%C3%BA\", \"u\"); // ú\n iso88591.put(\"%C3%9A\", \"U\"); // Ú\n iso88591.put(\"%C3%91\", \"N\"); // Ñ\n iso88591.put(\"%C3%B1\", \"n\"); // ñ\n }\n public final static HashMap utf8 = new HashMap();\n static {\n utf8.put(\"%C3%83%C2%A1\", \"a\"); // á\n utf8.put(\"%C3%83%EF%BF\", \"A\"); // Á\n utf8.put(\"%BD%C3%83%C2\", \"e\"); // é\n utf8.put(\"%A9%C3%83%E2\", \"E\"); // É\n utf8.put(\"%80%B0%C3%83\", \"i\"); // í\n utf8.put(\"%C2%AD%C3%83\", \"I\"); // Í\n utf8.put(\"%EF%BF%BD%C3\", \"O\"); // Ó\n utf8.put(\"%C3%83%C2%B3\", \"o\"); // ó\n utf8.put(\"%83%E2%80%9C\", \"u\"); // ú \n utf8.put(\"%C3%83%C2%BA\", \"U\"); // Ú\n utf8.put(\"%C3%83%C5%A1\", \"N\"); // Ñ\n utf8.put(\"%C3%83%E2%80\", \"n\"); // ñ\n }\n\n public final static HashMap enc_table = new HashMap();\n static {\n enc_table.put(\"iso-8859-1\", iso88591);\n enc_table.put(\"utf-8\", utf8);\n }\n\n\n /**\n * Replace Hexadecimal characters with equivalent english not special ones\n * &lt;p&gt;Example: á Hexa: %C3%A1 gets replaced with a&lt;/p&gt;\n * @param s Usually a string coming from URLEncode.encode\n * @param enc Encoding UTF-8 or ISO-8850-1\n */\n public static String convertHexaDecimal(String s, String enc) {\n HashMap characters = (HashMap) enc_table.get(enc.toLowerCase());\n if(characters==null) return \"\";\n Set keys = characters.keySet();\n Iterator it = keys.iterator();\n while(it.hasNext()) {\n String key = (String) it.next();\n String regex = EscapeChars.forRegex(key);\n String replacement = (String) characters.get(key); \n s = s.replaceAll(regex, replacement); \n }\n return s;\n }\n}\n</code></pre>\n\n<p>EscapeChars Class </p>\n\n<pre><code>public final class EscapeChars {\n/**\n * Replace characters having special meaning in regular expressions\n * with their escaped equivalents, preceded by a '\\' character.\n *\n * &lt;P&gt;The escaped characters include :\n *&lt;ul&gt;\n *&lt;li&gt;.\n *&lt;li&gt;\\\n *&lt;li&gt;?, * , and +\n *&lt;li&gt;&amp;\n *&lt;li&gt;:\n *&lt;li&gt;{ and }\n *&lt;li&gt;[ and ]\n *&lt;li&gt;( and )\n *&lt;li&gt;^ and $\n *&lt;/ul&gt;\n */\n public static String forRegex(String aRegexFragment){\n final StringBuilder result = new StringBuilder();\n\n final StringCharacterIterator iterator = new StringCharacterIterator(aRegexFragment);\n char character = iterator.current();\n while (character != CharacterIterator.DONE ){\n /*\n * All literals need to have backslashes doubled.\n */\n if (character == '.') {\n result.append(\"\\\\.\");\n }\n else if (character == '\\\\') {\n result.append(\"\\\\\\\\\");\n }\n else if (character == '?') {\n result.append(\"\\\\?\");\n }\n else if (character == '*') {\n result.append(\"\\\\*\");\n }\n else if (character == '+') {\n result.append(\"\\\\+\");\n }\n else if (character == '&amp;') {\n result.append(\"\\\\&amp;\");\n }\n else if (character == ':') {\n result.append(\"\\\\:\");\n }\n else if (character == '{') {\n result.append(\"\\\\{\");\n }\n else if (character == '}') {\n result.append(\"\\\\}\");\n }\n else if (character == '[') {\n result.append(\"\\\\[\");\n }\n else if (character == ']') {\n result.append(\"\\\\]\");\n }\n else if (character == '(') {\n result.append(\"\\\\(\");\n }\n else if (character == ')') {\n result.append(\"\\\\)\");\n }\n else if (character == '^') {\n result.append(\"\\\\^\");\n }\n else if (character == '$') {\n result.append(\"\\\\$\");\n }\n else {\n //the char is not a special one\n //add it to the result as is\n result.append(character);\n }\n character = iterator.next();\n }\n return result.toString();\n }\n}\n</code></pre>\n" }, { "answer_id": 38610011, "author": "Bhimreddy", "author_id": 6634977, "author_profile": "https://Stackoverflow.com/users/6634977", "pm_score": -1, "selected": false, "text": "<p>Try this code</p>\n\n<pre><code> public class Test {\n\n public static void main(final String[] args) {\n String str = \"Cerepedia, una apliación web\";\n String[] parts = str.split(\" \");\n int sum=0;\n for (int i=0;i&lt;=parts.length-1;i++) {\n sum = sum+parts[i].length();\n }\n\n int k=0;\n char[] url = new char[25];\n for (int i=0;i&lt;=parts.length-1;i++) {\n char[] temp = parts[i].toCharArray();\n\n\n for(int j=0;j&lt;temp.length;j++){\n\n url[k]=temp[j];\n k++;\n }\n\n }\n System.out.println(url);\n\n }\n}\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
I have a String such as: ``` Cerepedia, una apliación web ``` I would like to transform it into something URL valid such as: ``` Cerepedia,unaaplicacionweb ``` **Note:** the special character transformation and spaces removal. By the way, are commas allowed in URLs?
Have you looked at [URLEncoder](http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLEncoder.html)? That seems to do what you need it to do. Though the special characters will be transformed to escaped entities and not stripped from their "special" properties.
205,382
<p>I have the following C# which simply replaces parts of the input string that look like EQUIP:19d005 into URLs, like this:</p> <pre><code>input = Regex.Replace(input, @"(EQUIP:)(\S+)", @"&lt;a title=""View equipment item $2"" href=""/EquipmentDisplay.asp?eqnum=$2""&gt;$1$2&lt;/a&gt;", RegexOptions.IgnoreCase); </code></pre> <p>The HTML ends up looking like this.</p> <pre><code>&lt;a title="View equipment item 19d005" href="/EquipmentDisplay.asp?eqnum=19d005"&gt;EQUIP:19d005&lt;/a&gt; </code></pre> <p>The only trouble is that the destination page expects the eqnum querystring to be all UPPERCASE so it returns the correct equipment when eqnum=19D005 but fails if it receives eqnum=19d005.</p> <p>I guess I can modify and correct EquipmentDisplay.asp's errant requirement of uppercase values however, if possible I'd like to make the C# code comply with the existing classic ASP page by uppercasing the $2 in the Regex.Replace statement above.</p> <p>Ideally, I'd like the HTML returned to look like this:</p> <pre><code>&lt;a title="View equipment item 19d005" href="/EquipmentDisplay.asp?eqnum=19D005"&gt;EQUIP:19d005&lt;/a&gt; </code></pre> <p><em>Notice although the original string was EQUIP:19d005 (lowercase), only the eqnum= value is uppercased.</em></p> <p>Can it be done and if so, what's the tidiest way to do it?</p>
[ { "answer_id": 205413, "author": "John Fiala", "author_id": 9143, "author_profile": "https://Stackoverflow.com/users/9143", "pm_score": 0, "selected": false, "text": "<p>Assuming that input is a string:</p>\n\n<p><code>input = Regex.Replace(input.ToUpper, @\"(EQUIP:)(\\S+)\", @\"&lt;a title=\"\"View equipment item $2\"\" href=\"\"/EquipmentDisplay.asp?eqnum=$2\"\"&gt;$1$2&lt;/a&gt;\", RegexOptions.IgnoreCase);</code></p>\n\n<p>Changing the case of a string isn't something regex does.</p>\n" }, { "answer_id": 205422, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 2, "selected": false, "text": "<p>Using Regex.Replace directly I do not think there is a way. But you could make this a two step process and get the result you are looking for. </p>\n\n<pre><code>var match = Regex.Match(input, @\"(EQUIP:)(\\S+)\", RegexOptions.IgnoreCase);\nvar input = String.Format( @\"&amp;lt;a title=\"\"View equipment item {1}\"\" href=\"\"/EquipmentDisplay.asp?eqnum={2}\"\"&amp;gt;{0}{1}&amp;lt;/a&amp;gt;\", \nmatch.Groups[1].Value,\nmatch.Groups[2].Value,\nmatch.Groups[2].Value.ToUpper());\n</code></pre>\n" }, { "answer_id": 205445, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>You can use a MatchEvaluator delegate instead of a string in the replacement. You can then embed the delegate as an anonymous function if on recent .NET. The 'old' solution might look like something like this:</p>\n\n<pre><code> static void Main(string[] args)\n {\n string input = \"EQUIP:12312dd23\";\n string output = Regex.Replace(input, @\"(EQUIP:)(\\S+)\", \n new MatchEvaluator(genURL), RegexOptions.IgnoreCase);\n Console.WriteLine(output);\n Console.ReadKey();\n }\n static string genURL(Match m)\n {\n return string.Format(@\"&lt;a title=\"\"View item {0}\"\" \n href=\"\"/EqDisp.asp?eq={2}\"\"&gt;{1}{0}&lt;/a&gt;\",\n m.Groups[2].Value,m.Groups[1].Value,m.Groups[2].Value.ToUpper());\n }\n</code></pre>\n" }, { "answer_id": 205448, "author": "Duncan", "author_id": 25035, "author_profile": "https://Stackoverflow.com/users/25035", "pm_score": 5, "selected": true, "text": "<p>OK, 2 solutions, one inline:</p>\n\n<pre><code>input = Regex.Replace(input, @\"(EQUIP:)(\\S+)\", m =&gt; string.Format(@\"&lt;a title=\"\"View equipment item {1}\"\" href=\"\"/EquipmentDisplay.asp?eqnum={2}\"\"&gt;{0}{1}&lt;/a&gt;\", m.Groups[1].Value, m.Groups[2].Value, m.Groups[2].Value.ToUpper()), RegexOptions.IgnoreCase);\n</code></pre>\n\n<p>The other using a separate function:</p>\n\n<pre><code>var input = Regex.Replace(input, @\"(EQUIP:)(\\S+)\", Evaluator, RegexOptions.IgnoreCase);\n\nprivate static string Evaluator(Match match)\n{\n return string.Format(@\"&lt;a title=\"\"View equipment item {1}\"\" href=\"\"/EquipmentDisplay.asp?eqnum={2}\"\"&gt;{0}{1}&lt;/a&gt;\", match.Groups[1].Value, match.Groups[2].Value, match.Groups[2].Value.ToUpper());\n}\n</code></pre>\n" }, { "answer_id": 205469, "author": "Jesse C. Slicer", "author_id": 3312, "author_profile": "https://Stackoverflow.com/users/3312", "pm_score": 0, "selected": false, "text": "<pre><code>string input = \"EQUIP:19d005\";\nRegex regex = new Regex (@\"(EQUIP:)(\\S+)\", RegexOptions.IgnoreCase);\nstring eqlabel = regex.Replace(input, \"$1\");\nstring eqnum = regex.Replace(input, \"$2\");\nstring eqnumu = eqnum.ToUpperInvariant();\ninput = string.Format(@\"&lt;a title=\"\"View equipment item {1}\"\" href=\"\"/EquipmentDisplay.asp?eqnum={2}\"\"&gt;{0}{1}&lt;/a&gt;\", eqlabel, eqnum, eqnumu);\n</code></pre>\n" }, { "answer_id": 205586, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 0, "selected": false, "text": "<pre><code>public static string FormatToCustomAnchorTag(this string value)\n{\n\n return Regex.Replace(value.ToLower() + value.ToUpper(),\n @\"(?&lt;equiplo&gt;equip:)(?&lt;equipnolo&gt;\\S+)(?&lt;equipup&gt;EQUIP:)(?&lt;equipnoup&gt;\\S+)\",\n @\"&lt;a title=\"\"View equipment item ${equipnolo}\"\" href=\"\"/EquipmentDisplay.asp?eqnum=${equipnoup}\"\"&gt;${equipup}${equipnolo}&lt;/a&gt;\");\n}\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7508/" ]
I have the following C# which simply replaces parts of the input string that look like EQUIP:19d005 into URLs, like this: ``` input = Regex.Replace(input, @"(EQUIP:)(\S+)", @"<a title=""View equipment item $2"" href=""/EquipmentDisplay.asp?eqnum=$2"">$1$2</a>", RegexOptions.IgnoreCase); ``` The HTML ends up looking like this. ``` <a title="View equipment item 19d005" href="/EquipmentDisplay.asp?eqnum=19d005">EQUIP:19d005</a> ``` The only trouble is that the destination page expects the eqnum querystring to be all UPPERCASE so it returns the correct equipment when eqnum=19D005 but fails if it receives eqnum=19d005. I guess I can modify and correct EquipmentDisplay.asp's errant requirement of uppercase values however, if possible I'd like to make the C# code comply with the existing classic ASP page by uppercasing the $2 in the Regex.Replace statement above. Ideally, I'd like the HTML returned to look like this: ``` <a title="View equipment item 19d005" href="/EquipmentDisplay.asp?eqnum=19D005">EQUIP:19d005</a> ``` *Notice although the original string was EQUIP:19d005 (lowercase), only the eqnum= value is uppercased.* Can it be done and if so, what's the tidiest way to do it?
OK, 2 solutions, one inline: ``` input = Regex.Replace(input, @"(EQUIP:)(\S+)", m => string.Format(@"<a title=""View equipment item {1}"" href=""/EquipmentDisplay.asp?eqnum={2}"">{0}{1}</a>", m.Groups[1].Value, m.Groups[2].Value, m.Groups[2].Value.ToUpper()), RegexOptions.IgnoreCase); ``` The other using a separate function: ``` var input = Regex.Replace(input, @"(EQUIP:)(\S+)", Evaluator, RegexOptions.IgnoreCase); private static string Evaluator(Match match) { return string.Format(@"<a title=""View equipment item {1}"" href=""/EquipmentDisplay.asp?eqnum={2}"">{0}{1}</a>", match.Groups[1].Value, match.Groups[2].Value, match.Groups[2].Value.ToUpper()); } ```
205,393
<p>Is it possible to reload a page that was loaded thru link_to_remote? I'm doing this in my controller: <br></p> <pre><code>def create if captchas_verified do_something else render :action=&gt;'new' end </code></pre> <p>But when the captchas is wrong, it do not render a form that is inside of the new template. By the way, in the webserver log, it shows that the templades was rendered.</p> <p>Thanks!</p> <p>UPDATED: Today i changed the render to:</p> <pre><code>render(:update) { |page| page.call 'location.reload' } </code></pre> <p>But it makes me update the page that called the link_to_remote not the page that was opened thru the link_to_remote</p> <p>UPDATED 2: I fixed using page.replace_html "mydiv", :partial => "new" instead of page.call 'location.reload'</p>
[ { "answer_id": 206115, "author": "jdl", "author_id": 9465, "author_profile": "https://Stackoverflow.com/users/9465", "pm_score": 1, "selected": false, "text": "<p>Something like this should do what you want.</p>\n\n<pre><code>render :update do |page| page &lt;&lt; 'window.location.reload()' end\n</code></pre>\n" }, { "answer_id": 206144, "author": "salt.racer", "author_id": 757, "author_profile": "https://Stackoverflow.com/users/757", "pm_score": 3, "selected": true, "text": "<p>You need to <code>render :update</code>, rather than <code>render :action</code>.</p>\n\n<p>I do this sort of thing all the time. Similar to the response from jdl you can use inline rjs (don't know if that's the right term) to render the page.</p>\n\n<pre><code>render(:update) do |page|\n page.replace_html(\"div_to_update\", :partial =&gt; \"name_of_template\", :object =&gt; @object)\n page &lt;&lt; \"alert('javascript can be inserted here as well')\"\nend\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18642/" ]
Is it possible to reload a page that was loaded thru link\_to\_remote? I'm doing this in my controller: ``` def create if captchas_verified do_something else render :action=>'new' end ``` But when the captchas is wrong, it do not render a form that is inside of the new template. By the way, in the webserver log, it shows that the templades was rendered. Thanks! UPDATED: Today i changed the render to: ``` render(:update) { |page| page.call 'location.reload' } ``` But it makes me update the page that called the link\_to\_remote not the page that was opened thru the link\_to\_remote UPDATED 2: I fixed using page.replace\_html "mydiv", :partial => "new" instead of page.call 'location.reload'
You need to `render :update`, rather than `render :action`. I do this sort of thing all the time. Similar to the response from jdl you can use inline rjs (don't know if that's the right term) to render the page. ``` render(:update) do |page| page.replace_html("div_to_update", :partial => "name_of_template", :object => @object) page << "alert('javascript can be inserted here as well')" end ```
205,431
<p>I'm trying to draw images on the iPhone using with rounded corners, a la the contact images in the Contacts app. I've got code that generally work, but it occasionally crashes inside of the UIImage drawing routines with an <code>EXEC_BAD_ACCESS</code> - <code>KERN_INVALID_ADDRESS</code>. I thought this might be related to the <a href="https://stackoverflow.com/questions/158914/cropping-a-uiimage">cropping question</a> I asked a few weeks back, but I believe I'm setting up the clipping path correctly.</p> <p>Here's the code I'm using - when it doesn't crash, the result looks fine and anybody looking to get a similar look is free to borrow the code.</p> <pre><code>- (UIImage *)borderedImageWithRect: (CGRect)dstRect radius:(CGFloat)radius { UIImage *maskedImage = nil; radius = MIN(radius, .5 * MIN(CGRectGetWidth(dstRect), CGRectGetHeight(dstRect))); CGRect interiorRect = CGRectInset(dstRect, radius, radius); UIGraphicsBeginImageContext(dstRect.size); CGContextRef maskedContextRef = UIGraphicsGetCurrentContext(); CGContextSaveGState(maskedContextRef); CGMutablePathRef borderPath = CGPathCreateMutable(); CGPathAddArc(borderPath, NULL, CGRectGetMinX(interiorRect), CGRectGetMinY(interiorRect), radius, PNDegreeToRadian(180), PNDegreeToRadian(270), NO); CGPathAddArc(borderPath, NULL, CGRectGetMaxX(interiorRect), CGRectGetMinY(interiorRect), radius, PNDegreeToRadian(270.0), PNDegreeToRadian(360.0), NO); CGPathAddArc(borderPath, NULL, CGRectGetMaxX(interiorRect), CGRectGetMaxY(interiorRect), radius, PNDegreeToRadian(0.0), PNDegreeToRadian(90.0), NO); CGPathAddArc(borderPath, NULL, CGRectGetMinX(interiorRect), CGRectGetMaxY(interiorRect), radius, PNDegreeToRadian(90.0), PNDegreeToRadian(180.0), NO); CGContextBeginPath(maskedContextRef); CGContextAddPath(maskedContextRef, borderPath); CGContextClosePath(maskedContextRef); CGContextClip(maskedContextRef); [self drawInRect: dstRect]; maskedImage = UIGraphicsGetImageFromCurrentImageContext(); CGContextRestoreGState(maskedContextRef); UIGraphicsEndImageContext(); return maskedImage; } </code></pre> <p>and here's the crash log. It looks the same whenever I get one of these crashes</p> <pre> Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x6e2e6181 Crashed Thread: 0 Thread 0 Crashed: 0 com.apple.CoreGraphics 0x30fe56d8 CGGStateGetRenderingIntent + 4 1 libRIP.A.dylib 0x33c4a7d8 ripc_RenderImage + 104 2 libRIP.A.dylib 0x33c51868 ripc_DrawImage + 3860 3 com.apple.CoreGraphics 0x30fecad4 CGContextDelegateDrawImage + 80 4 com.apple.CoreGraphics 0x30feca40 CGContextDrawImage + 368 5 UIKit 0x30a6a708 -[UIImage drawInRect:blendMode:alpha:] + 1460 6 UIKit 0x30a66904 -[UIImage drawInRect:] + 72 7 MyApp 0x0003f8a8 -[UIImage(PNAdditions) borderedImageWithRect:radius:] (UIImage+PNAdditions.m:187) </pre>
[ { "answer_id": 205643, "author": "Lounges", "author_id": 8918, "author_profile": "https://Stackoverflow.com/users/8918", "pm_score": 2, "selected": false, "text": "<p>I cant offer any insight into your crash, but I thought I would offer another option for rounding the corners. I had a similar problem arise in an application i was working on. Rather than write any code I am overlaying another image which masks off the corners.</p>\n" }, { "answer_id": 206005, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 1, "selected": false, "text": "<p>If it only crashes some of the time, figure out what the crash cases have in common. Is dstRect the same every time? Are the images ever a different size?</p>\n\n<p>Also, you need to <code>CGPathRelease(borderPath)</code>, although I doubt that leak is causing your problem.</p>\n" }, { "answer_id": 373315, "author": "Max Motovilov", "author_id": 43349, "author_profile": "https://Stackoverflow.com/users/43349", "pm_score": 2, "selected": false, "text": "<p>The easiest way is to embed a disabled[!] round-rect [not custom!] button in your view (can even do it all in the Interface Builder) and associate your image with it. The image-setting message is different for UIButton (compared to UIImageView), but the overall kludge works like a charm. Use setImage:forState: if you want a centered icon or setBackgroundImage:forState: if you want the whole image with corners cut (like Contacts). Of course if you want to display lots of these images in your drawRect this isn't the right approach, but more likely an embedded view is exactly what you needed anyway...</p>\n" }, { "answer_id": 452643, "author": "fjoachim", "author_id": 56087, "author_profile": "https://Stackoverflow.com/users/56087", "pm_score": 2, "selected": false, "text": "<p>If you are calling your method (borderedImageWithRect) in a background thread, crashes might occur since UIGraphics-functions are not thread-safe. In such a case, you must create a context using CGBitmapContextCreate() - see the \"Reflection\" sample code from the SDK.</p>\n" }, { "answer_id": 510228, "author": "PCheese", "author_id": 61274, "author_profile": "https://Stackoverflow.com/users/61274", "pm_score": 2, "selected": false, "text": "<p>I would reiterate <a href=\"https://stackoverflow.com/questions/205431/rounded-corners-on-uiimage/452643#452643\">fjoachim's answer</a>: be cautious when attempting to draw while running on a separate thread, or you may get <code>EXC_BAD_ACCESS</code> errors.</p>\n\n<p>My workaround went something like this:</p>\n\n<pre><code>UIImage *originalImage = [UIImage imageNamed:@\"OriginalImage.png\"] \n[self performSelectorOnMainThread:@selector(displayImageWithRoundedCorners:) withObject:originalImage waitUntilDone:YES];\n</code></pre>\n\n<p>(In my case I was resizing / scaling UIImages.)</p>\n" }, { "answer_id": 510760, "author": "Jablair", "author_id": 24168, "author_profile": "https://Stackoverflow.com/users/24168", "pm_score": 2, "selected": false, "text": "<p>I actually had a chance to talk about this with somebody from Apple at the iPhone Tech Talk in New York. When we talked about it, he was pretty sure it wasn't a threading issued. Instead, he thought that I needed to retain the graphics context that was generated when calling <code>UIGraphicsBeginImageContext</code>. This seems to violate the general rules dealing with retain rules and naming schemes, but this fellow was pretty sure he'd seen the issue previously.</p>\n\n<p>If the memory was getting scribbled, perhaps by another thread, that would certainly explain why I was only seeing the issue occasionally.</p>\n\n<p>I haven't had time to revisit the code and test out the fix, but PCheese's comment made me realize I hadn't posted the info here.</p>\n\n<p>...unless I wrote that down wrong and <code>UIGraphicsBeginImageContext</code> should've been <code>CGBitmapContextCreate</code>...</p>\n" }, { "answer_id": 1307717, "author": "MagicSeth", "author_id": 131876, "author_profile": "https://Stackoverflow.com/users/131876", "pm_score": 8, "selected": true, "text": "<p>Here is an even easier method that is available in iPhone 3.0 and up. Every View-based object has an associated layer. Each layer can have a corner radius set, this will give you just what you want:</p>\n\n<pre><code>UIImageView * roundedView = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@\"wood.jpg\"]];\n// Get the Layer of any view\nCALayer * l = [roundedView layer];\n[l setMasksToBounds:YES];\n[l setCornerRadius:10.0];\n\n// You can even add a border\n[l setBorderWidth:4.0];\n[l setBorderColor:[[UIColor blueColor] CGColor]];\n</code></pre>\n" }, { "answer_id": 1462318, "author": "cuasiJoe", "author_id": 138745, "author_profile": "https://Stackoverflow.com/users/138745", "pm_score": 5, "selected": false, "text": "<p>If appIconImage is an UIImageView, then:</p>\n\n<pre><code>appIconImage.image = [UIImage imageWithContentsOfFile:@\"image.png\"]; \nappIconImage.layer.masksToBounds = YES;\nappIconImage.layer.cornerRadius = 10.0;\nappIconImage.layer.borderWidth = 1.0;\nappIconImage.layer.borderColor = [[UIColor grayColor] CGColor];\n</code></pre>\n\n<p>And also remember: </p>\n\n<pre><code>#import &lt;QuartzCore/QuartzCore.h&gt;\n</code></pre>\n" }, { "answer_id": 18585960, "author": "Jonny", "author_id": 129202, "author_profile": "https://Stackoverflow.com/users/129202", "pm_score": 5, "selected": false, "text": "<p>I'm gonna go ahead here and actually answer the question in the title.</p>\n\n<p>Try this category.</p>\n\n<p><strong>UIImage+additions.h</strong></p>\n\n<pre><code>#import &lt;UIKit/UIKit.h&gt;\n\n@interface UIImage (additions)\n-(UIImage*)makeRoundCornersWithRadius:(const CGFloat)RADIUS;\n@end\n</code></pre>\n\n<p><strong>UIImage+additions.m</strong></p>\n\n<pre><code>#import \"UIImage+additions.h\"\n\n@implementation UIImage (additions)\n-(UIImage*)makeRoundCornersWithRadius:(const CGFloat)RADIUS {\n UIImage *image = self;\n\n // Begin a new image that will be the new image with the rounded corners\n // (here with the size of an UIImageView)\n UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);\n\n const CGRect RECT = CGRectMake(0, 0, image.size.width, image.size.height);\n // Add a clip before drawing anything, in the shape of an rounded rect\n [[UIBezierPath bezierPathWithRoundedRect:RECT cornerRadius:RADIUS] addClip];\n // Draw your image\n [image drawInRect:RECT];\n\n // Get the image, here setting the UIImageView image\n //imageView.image\n UIImage* imageNew = UIGraphicsGetImageFromCurrentImageContext();\n\n // Lets forget about that we were drawing\n UIGraphicsEndImageContext();\n\n return imageNew;\n}\n@end\n</code></pre>\n" }, { "answer_id": 24404939, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Set the Image in xib or storyboard (image width and height 41x41).</p>\n\n<p>FirstViewController.h</p>\n\n<pre><code>@interface....\n\nIBOutlet UIImageView *testImg;\n\n@end\n</code></pre>\n\n<p>FirstViewController.m</p>\n\n<pre><code>-(void)viewDidLoad{\n testImg.layer.backgroundColor=[[UIColor clearColor] CGColor];\n testImg.layer.cornerRadius=20;\n testImg.layer.masksToBounds = YES;\n }\n</code></pre>\n" }, { "answer_id": 28317655, "author": "user3536010", "author_id": 3536010, "author_profile": "https://Stackoverflow.com/users/3536010", "pm_score": 0, "selected": false, "text": "<pre><code>UIImage *originalImage = [UIImage imageNamed:@\"OriginalImage.png\"] \n[self performSelectorOnMainThread:@selector(displayImageWithRoundedCorners:) withObject:originalImage waitUntilDone:YES];\n</code></pre>\n" }, { "answer_id": 54476845, "author": "Naresh", "author_id": 8090893, "author_profile": "https://Stackoverflow.com/users/8090893", "pm_score": 0, "selected": false, "text": "<p>In Swift 4.2 and Xcode 10.1</p>\n\n<pre><code>let imgView = UIImageView()\nimgView.frame = CGRect(x: 200, y: 200, width: 200, height: 200)\nimgView.image = UIImage(named: \"yourimagename\")\nimgView.imgViewCorners()\n//If you want complete round shape\n//imgView.imgViewCorners(width: imgView.frame.width)//Pass ImageView width\nview.addSubview(imgView)\n\nextension UIImageView {\n//If you want only round corners\nfunc imgViewCorners() {\n layer.cornerRadius = 10\n layer.borderWidth = 1.0\n layer.borderColor = UIColor.red.cgColor\n layer.masksToBounds = true\n}\n//If you want complete round shape\nfunc imgViewCorners(width:CGFloat) {\n layer.cornerRadius = width/2\n layer.borderWidth = 1.0\n layer.borderColor = UIColor.red.cgColor\n layer.masksToBounds = true\n}\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24168/" ]
I'm trying to draw images on the iPhone using with rounded corners, a la the contact images in the Contacts app. I've got code that generally work, but it occasionally crashes inside of the UIImage drawing routines with an `EXEC_BAD_ACCESS` - `KERN_INVALID_ADDRESS`. I thought this might be related to the [cropping question](https://stackoverflow.com/questions/158914/cropping-a-uiimage) I asked a few weeks back, but I believe I'm setting up the clipping path correctly. Here's the code I'm using - when it doesn't crash, the result looks fine and anybody looking to get a similar look is free to borrow the code. ``` - (UIImage *)borderedImageWithRect: (CGRect)dstRect radius:(CGFloat)radius { UIImage *maskedImage = nil; radius = MIN(radius, .5 * MIN(CGRectGetWidth(dstRect), CGRectGetHeight(dstRect))); CGRect interiorRect = CGRectInset(dstRect, radius, radius); UIGraphicsBeginImageContext(dstRect.size); CGContextRef maskedContextRef = UIGraphicsGetCurrentContext(); CGContextSaveGState(maskedContextRef); CGMutablePathRef borderPath = CGPathCreateMutable(); CGPathAddArc(borderPath, NULL, CGRectGetMinX(interiorRect), CGRectGetMinY(interiorRect), radius, PNDegreeToRadian(180), PNDegreeToRadian(270), NO); CGPathAddArc(borderPath, NULL, CGRectGetMaxX(interiorRect), CGRectGetMinY(interiorRect), radius, PNDegreeToRadian(270.0), PNDegreeToRadian(360.0), NO); CGPathAddArc(borderPath, NULL, CGRectGetMaxX(interiorRect), CGRectGetMaxY(interiorRect), radius, PNDegreeToRadian(0.0), PNDegreeToRadian(90.0), NO); CGPathAddArc(borderPath, NULL, CGRectGetMinX(interiorRect), CGRectGetMaxY(interiorRect), radius, PNDegreeToRadian(90.0), PNDegreeToRadian(180.0), NO); CGContextBeginPath(maskedContextRef); CGContextAddPath(maskedContextRef, borderPath); CGContextClosePath(maskedContextRef); CGContextClip(maskedContextRef); [self drawInRect: dstRect]; maskedImage = UIGraphicsGetImageFromCurrentImageContext(); CGContextRestoreGState(maskedContextRef); UIGraphicsEndImageContext(); return maskedImage; } ``` and here's the crash log. It looks the same whenever I get one of these crashes ``` Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x6e2e6181 Crashed Thread: 0 Thread 0 Crashed: 0 com.apple.CoreGraphics 0x30fe56d8 CGGStateGetRenderingIntent + 4 1 libRIP.A.dylib 0x33c4a7d8 ripc_RenderImage + 104 2 libRIP.A.dylib 0x33c51868 ripc_DrawImage + 3860 3 com.apple.CoreGraphics 0x30fecad4 CGContextDelegateDrawImage + 80 4 com.apple.CoreGraphics 0x30feca40 CGContextDrawImage + 368 5 UIKit 0x30a6a708 -[UIImage drawInRect:blendMode:alpha:] + 1460 6 UIKit 0x30a66904 -[UIImage drawInRect:] + 72 7 MyApp 0x0003f8a8 -[UIImage(PNAdditions) borderedImageWithRect:radius:] (UIImage+PNAdditions.m:187) ```
Here is an even easier method that is available in iPhone 3.0 and up. Every View-based object has an associated layer. Each layer can have a corner radius set, this will give you just what you want: ``` UIImageView * roundedView = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"wood.jpg"]]; // Get the Layer of any view CALayer * l = [roundedView layer]; [l setMasksToBounds:YES]; [l setCornerRadius:10.0]; // You can even add a border [l setBorderWidth:4.0]; [l setBorderColor:[[UIColor blueColor] CGColor]]; ```
205,435
<p>I keep getting an NHibernate.PersistentObjectException when calling session.Save() which is due to an uninitialized proxy passed to save(). If I fiddle with my cascade settings I can make it go away, but then child objects aren't being saved.</p> <p>The only other fix I have found is by adding the following to my DefaultSaveEventListener.</p> <pre><code> protected override bool ReassociateIfUninitializedProxy(object obj, global::NHibernate.Engine.ISessionImplementor source) { if (!NHibernateUtil.IsInitialized(obj)) NHibernateUtil.Initialize(obj); return base.ReassociateIfUninitializedProxy(obj, source); } </code></pre> <p>This is obviously not an ideal solution.</p> <p>Any ideas?</p>
[ { "answer_id": 1126196, "author": "Joe", "author_id": 74776, "author_profile": "https://Stackoverflow.com/users/74776", "pm_score": 2, "selected": false, "text": "<p>Are you trying to work with a child object that is in a list on a root aggregate entity? If you are, you need to work with the root, traverse to the child, make the changes, and save the <em>root</em>, not the child.</p>\n" }, { "answer_id": 2936444, "author": "mathieu", "author_id": 971, "author_profile": "https://Stackoverflow.com/users/971", "pm_score": 2, "selected": false, "text": "<p>I had a similar problem.</p>\n\n<p>The fix was simple : <code>use ISession.Get()</code> and not <code>ISession.Load()</code></p>\n" }, { "answer_id": 3309406, "author": "Rabid", "author_id": 123883, "author_profile": "https://Stackoverflow.com/users/123883", "pm_score": 2, "selected": false, "text": "<p>There mere presence of a custom <code>DefaultSaveEventListener</code> subclass containing no overidden or extended behaviour is enough to trigger this exception for me, using the following configuration Xml:</p>\n\n<pre><code>&lt;event type=\"save-update\"&gt;\n &lt;listener class=\"MyNamespace.MyCustomSaveEventListener, MyAssembly\" /&gt;\n&lt;/event&gt;\n</code></pre>\n\n<p>I am continuing this discussion <a href=\"https://stackoverflow.com/questions/3309390/bizarre-nhibernate-exception-uninitialized-proxy-passed-to-save-caused-by-f\">in this question</a>.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>I had mistakenly derived from <code>DefaultSaveEventListener</code> instead of <code>DefaultSaveOrUpdateEventListener</code>, changing the superclass made this problem go away for me.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4590/" ]
I keep getting an NHibernate.PersistentObjectException when calling session.Save() which is due to an uninitialized proxy passed to save(). If I fiddle with my cascade settings I can make it go away, but then child objects aren't being saved. The only other fix I have found is by adding the following to my DefaultSaveEventListener. ``` protected override bool ReassociateIfUninitializedProxy(object obj, global::NHibernate.Engine.ISessionImplementor source) { if (!NHibernateUtil.IsInitialized(obj)) NHibernateUtil.Initialize(obj); return base.ReassociateIfUninitializedProxy(obj, source); } ``` This is obviously not an ideal solution. Any ideas?
Are you trying to work with a child object that is in a list on a root aggregate entity? If you are, you need to work with the root, traverse to the child, make the changes, and save the *root*, not the child.
205,440
<p>I like to know if there is a way to read the user input inside a batch file, because i have a file named: "fif.bat" that recives two parameters (just call them <strong><em>paramA</em></strong> and <strong><em>paramB</em></strong>) so i execute the file like this:</p> <pre><code>fif paramA paramB </code></pre> <p>I have to change paramA every month, but i call this file lot of times so i like to open a console and have printed this:</p> <pre><code>fif paramA </code></pre> <p>So i only have to write paramB and change paramA when i want it.</p> <p>PD: paramA is very large so it's very helpful if i can have it there instead of writing every time. And i don't want to make another batch file to call fif whit paramA.</p>
[ { "answer_id": 205461, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 0, "selected": false, "text": "<p>You can prompt for user input in a batch file using <code>SET /P</code> for example:</p>\n\n<pre><code>SET /P paramB=\"Prompt String: \"\n</code></pre>\n" }, { "answer_id": 205471, "author": "Jeremy", "author_id": 9266, "author_profile": "https://Stackoverflow.com/users/9266", "pm_score": 4, "selected": true, "text": "<p>I think this might be what you're looking for:</p>\n\n<pre><code>@ECHO OFF\nSET /p paramA=Parameter A:\nECHO you typed %paramA%\nPAUSE\n</code></pre>\n\n<p>Line one stops commands in batch file from being echoed to the console\nLine two prompts the user with \"Parameter A:\" and waits for user to enter a value and press enter. The value goes into a variable called paramA.\nLine three echoes the value of the variable paramA to the console\nLine four waits for the user to hit any key.</p>\n\n<p>Note that the SET /p command does not work on every version of windows, I beleive it was introduced in 2000, but I could be wrong on the version.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20601/" ]
I like to know if there is a way to read the user input inside a batch file, because i have a file named: "fif.bat" that recives two parameters (just call them ***paramA*** and ***paramB***) so i execute the file like this: ``` fif paramA paramB ``` I have to change paramA every month, but i call this file lot of times so i like to open a console and have printed this: ``` fif paramA ``` So i only have to write paramB and change paramA when i want it. PD: paramA is very large so it's very helpful if i can have it there instead of writing every time. And i don't want to make another batch file to call fif whit paramA.
I think this might be what you're looking for: ``` @ECHO OFF SET /p paramA=Parameter A: ECHO you typed %paramA% PAUSE ``` Line one stops commands in batch file from being echoed to the console Line two prompts the user with "Parameter A:" and waits for user to enter a value and press enter. The value goes into a variable called paramA. Line three echoes the value of the variable paramA to the console Line four waits for the user to hit any key. Note that the SET /p command does not work on every version of windows, I beleive it was introduced in 2000, but I could be wrong on the version.
205,447
<p>I've got a model in CakePHP that doesn't have a table, called Upload. I've got a validation in this Model for a field called source_id.</p> <p>I've got a form that builds a nice looking $this-data, giving me a well formated set, including:</p> <pre><code>$this-&gt;data['Upload']['source_id'] </code></pre> <p>However, the validation rule I have set doesn't seem to run at all. I copied this validation rule from another model where it does work, so I'm confident that it works:</p> <pre><code>var $validate = array( 'source_id' =&gt; array( rule' =&gt; 'numeric', 'required' =&gt; true, 'allowEmpty' =&gt; false, 'message' =&gt; 'Error!.' ) ); </code></pre> <p>Can you not validate fields for a model that lacks a database table?</p> <p>The form uses the Upload model, and submits to another controller action method.</p> <p>CakePHP 1.2, PHP/MySQL 5, XAMPP.</p>
[ { "answer_id": 205459, "author": "Justin", "author_id": 43, "author_profile": "https://Stackoverflow.com/users/43", "pm_score": 4, "selected": true, "text": "<p>I'm dumb. You have to trigger a validation check, either with a save() or</p>\n\n<pre><code>$this-&gt;Upload-&gt;set($this-&gt;data);\n$this-&gt;Upload-&gt;validates();\n</code></pre>\n\n<p>Working now.</p>\n" }, { "answer_id": 298222, "author": "Chris Hawes", "author_id": 22776, "author_profile": "https://Stackoverflow.com/users/22776", "pm_score": 2, "selected": false, "text": "<p>You can also <em>fake</em> the database structure by setting the $_schema array, like so:</p>\n\n<pre><code>var $useTable = false;\n\nvar $_schema = array(\n 'name' =&gt;array('type'=&gt;'string', 'length'=&gt;100), \n 'email' =&gt;array('type'=&gt;'string', 'length'=&gt;255), \n 'phone' =&gt;array('type'=&gt;'string', 'length'=&gt;20),\n 'subject' =&gt;array('type'=&gt;'string', 'length'=&gt;255),\n 'message' =&gt;array('type'=&gt;'text')\n);\n</code></pre>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43/" ]
I've got a model in CakePHP that doesn't have a table, called Upload. I've got a validation in this Model for a field called source\_id. I've got a form that builds a nice looking $this-data, giving me a well formated set, including: ``` $this->data['Upload']['source_id'] ``` However, the validation rule I have set doesn't seem to run at all. I copied this validation rule from another model where it does work, so I'm confident that it works: ``` var $validate = array( 'source_id' => array( rule' => 'numeric', 'required' => true, 'allowEmpty' => false, 'message' => 'Error!.' ) ); ``` Can you not validate fields for a model that lacks a database table? The form uses the Upload model, and submits to another controller action method. CakePHP 1.2, PHP/MySQL 5, XAMPP.
I'm dumb. You have to trigger a validation check, either with a save() or ``` $this->Upload->set($this->data); $this->Upload->validates(); ``` Working now.
205,458
<p>For years, I've been using named blocks to limit the scope of temporary variables. I've never seen this done anywhere else, which makes me wonder if this is a bad idea. Especially since the Eclipse IDE flags these as warnings by default.</p> <p>I've used this to good effect, I think, in my own code. But since it is un-idiomatic to the point where good programmers will distrust it when they see it, I really have two ways to go from here: </p> <ol> <li>avoid doing it, or </li> <li>promote it, with the hope that it will become an idiom.</li> </ol> <p>Example (within a larger method):</p> <pre><code>final Date nextTuesday; initNextTuesday: { GregorianCalendar cal = new GregorianCalendar(); ... // About 5-10 lines of setting the calendar fields nextTuesday = cal.getTime(); } </code></pre> <p>Here I'm using a GregorianCalendar just to initialize a date, and I want to make sure that I don't accidentally reuse it.</p> <p>Some people have commented that you don't actually need to name the block. While that's true, a raw block looks even more like a bug, as the intent is unclear. Furthermore, naming something encourages you to think about the intention of the block. The goal here is to identify distinct sections of code, not to give every temporary variable its own scope.</p> <p>Many people have commented that it's best to go straight to small methods. I agree that this should be your first instinct. However, there may be several mitigating factors:</p> <ul> <li>To even consider a named block, the code should be short, one-off code that will never be called elsewhere.</li> <li>A named block is a quick way to organize an oversized method without creating a one-off method with a dozen parameters. This is especially true when a class is in flux, and the inputs are likely to change from version to version.</li> <li>Creating a new method encourages its reuse, which may be ill-advised if the use cases aren't well-established. A named block is easier (psychologically, at least) to throw away.</li> <li>Especially for unit tests, you may need to define a dozen different objects for one-off assertions, and they are just different enough that you can't (yet) find a way to consolidate them into a small number of methods, nor can you think of a way to distinguish them with names that aren't a mile long.</li> </ul> <p>Advantages of using the named scope:</p> <ol> <li>Can't accidentally reuse temporary variables</li> <li>Limited scope gives garbage collector and JIT compiler more information about programmer intent</li> <li>Block name provides a comment on a block of code, which I find more readable than open-ended comments</li> <li>Makes it easier to refactor code out of a big method into little methods, or vice versa, since the named block is easier to separate than unstructured code.</li> </ol> <p>Disadvantages:</p> <p>Not idiomatic: programmers who haven't seen this use of named blocks (i.e. everyone but me) assume it's buggy, since they can't find references to the block name. (Just like Eclipse does.) And getting something to become idiomatic is an uphill battle.</p> <p>It can be used as an excuse for bad programming habits, such as:</p> <ul> <li>Making huge, monolithic methods where several small methods would be more legible.</li> <li>Layers of indentation too deep to read easily.</li> </ul> <p>Note: I've edited this question extensively, based on some thoughtful responses. Thanks!</p>
[ { "answer_id": 205470, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "<p>I'd just go straight for refactoring into smaller methods. If a method is big enough that it needs breaking up like this, it really needs breaking up into multiple methods if <em>at all</em> possible.</p>\n\n<p>While limiting scope is nice, this isn't really what named blocks are for. It's unidiomatic, which is very rarely a good thing.</p>\n" }, { "answer_id": 205481, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 2, "selected": false, "text": "<p>If you have 5-10 lines of code that can safely be put into a block like that, the same code could just as well be extracted into a method.</p>\n\n<p>This might seem like it's only a semantic difference, but at least with extracting into a method then you would gain the benefit of the ability of re-use.</p>\n" }, { "answer_id": 205486, "author": "Scott Langham", "author_id": 11898, "author_profile": "https://Stackoverflow.com/users/11898", "pm_score": 4, "selected": false, "text": "<p>If this was bad, then why is this a feature in the language! It's got a purpose, and you've found it.</p>\n\n<p>I often write code exactly as in your example. When you want to initialize a variable, and there's a little calculation that needs doing to work out what that should be, and that involves a couple of variables... then you don't want those variables hanging around for the entire scope of your function, then a little scope to contain the initialization works great.</p>\n\n<p>Mini scopes are an easy way to break code into 'paragraphs'. If you split into methods you can make the code harder to navigate when those methods don't get called from anywhere else and have a serial kind of order in which they need to be executed.</p>\n\n<p>It's always a balance, but if you think it's going to be easiest to maintain and it actually adds value to a future reader of your code if its all inline, then go for it.</p>\n\n<p>There are no hard and fast rules. I get a little fed up sometimes with co-workers who excessively put everything into its own method or class or file, and this becomes a nightmare to navigate. There's a nice balance somewhere!</p>\n" }, { "answer_id": 205496, "author": "Jeremy", "author_id": 9266, "author_profile": "https://Stackoverflow.com/users/9266", "pm_score": 0, "selected": false, "text": "<p>I have done this in some of my c#. I didn't know you could name the blocks though, I'll have to try that see if it works in c# too. </p>\n\n<p>I think the scope block can be a nice idea, because you can encapsulate code specific to something within a block of code, where you might not want to split it out into its own function.</p>\n\n<p>As for the disadvantage of nesting them, I see that as more of a fault of a programmer not of scope blocks themselves. </p>\n" }, { "answer_id": 205533, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Using blocks to limit scope is a good technique in my book.</p>\n\n<p>But since you're using the label to do the work of a comment, why not just use an actual comment instead? This would remove the confusion about the unreferenced label.</p>\n" }, { "answer_id": 205548, "author": "John Nilsson", "author_id": 24243, "author_profile": "https://Stackoverflow.com/users/24243", "pm_score": 3, "selected": false, "text": "<p>Sometimes I use unnamed blocks to isolate mutable things needed to prepare some immutable thing. Instead of having a label I put the Block under the immutable variable declaration.</p>\n\n<pre><code>final String example;\n{\n final StringBuilder sb = new StringBuilder();\n for(int i = 0; i &lt; 100; i++)\n sb.append(i);\n example = sb.toString();\n\n}\n</code></pre>\n\n<p>When I find some other use for the block, or just think that it's in the way, I turn it into a method.</p>\n" }, { "answer_id": 206150, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 3, "selected": false, "text": "<p>This is the 1st time I am seeing someone else using blocks. whew! I thought I was the only one. I know that I didn't invent it -- remembered reading it somewhere -- possibly from my previous C++ world.</p>\n\n<p>I don't use the labels, though and just comment what I'm doing.</p>\n\n<p>I don't agree with all the guys that are asking you extract it into a method. Most of the things we don in such blocks aren't really reusable blocks. It makes sense in a big initialization AND YES, I've used blocks to prevent COPY/PASTE errors.</p>\n\n<p>BR,<BR>\n~A</p>\n" }, { "answer_id": 206336, "author": "Haphazard", "author_id": 22231, "author_profile": "https://Stackoverflow.com/users/22231", "pm_score": 2, "selected": false, "text": "<p>Just because they exist doesn't mean they should be used. Most of the advantages gained from using named blocks are better gained by using a new private method.</p>\n\n<ol>\n<li>You won't be able to use the temporary variables declared in the new method</li>\n<li>The GC and JIT Compiler will glean the same info by using a new method</li>\n<li>Using a descriptive name for the new method (using \"private Date initNextTuesday()\" in your case) will allow for the self commenting code advantage</li>\n<li>No need to refactor code when you have already \"pre-factored\" it</li>\n</ol>\n\n<p>In addition to these benefits, you also get code reuse benefits and it will shorten your long methods.</p>\n" }, { "answer_id": 206367, "author": "johnstok", "author_id": 27929, "author_profile": "https://Stackoverflow.com/users/27929", "pm_score": 0, "selected": false, "text": "<p>Named scopes are technically ok here, it's just they aren't used in this way very often. Therefore, when someone else comes to maintain your code in the future it may not be immediately obvious why they are there. IMHO a private helper method would be a better choice...</p>\n" }, { "answer_id": 208478, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 1, "selected": false, "text": "<p>It's a good technique in my book. Managing large numbers of throwaway methods is evil and the reasons you're providing for naming the blocks are good.</p>\n\n<p>What does the generated bytecode look like? That'd be my only hesitation. I suspect it strips away the block name and might even benefit from greater optimizations. But you'd have to check.</p>\n" }, { "answer_id": 213967, "author": "Will Sargent", "author_id": 5266, "author_profile": "https://Stackoverflow.com/users/5266", "pm_score": 2, "selected": false, "text": "<p>I'd use a block with a comment rather adding a label there. </p>\n\n<p>When I see a label, I can't assume that nothing else is referencing the block.</p>\n\n<p>If I change the behavior of the block, then the label name may not be appropriate any more. But I can't just reach out and change it: I'll have to look through the rest of the method to determine what label is calling out to the block. At which point I'll figure out that it's an unreferenced label.</p>\n\n<p>Using a comment is clearer in this instance, because it describes the behavior of the block without imposing any extra work on the part of the maintainer.</p>\n" }, { "answer_id": 26636059, "author": "Floegipoky", "author_id": 2517719, "author_profile": "https://Stackoverflow.com/users/2517719", "pm_score": 1, "selected": false, "text": "<p>Sorry for resurrecting this, but I didn't see anyone mention what I consider to be a very important point. Let's look at your example:</p>\n\n<pre><code>final Date nextTuesday;\ninitNextTuesday: {\n GregorianCalendar cal = new GregorianCalendar();\n ... // About 5-10 lines of setting the calendar fields\n nextTuesday = cal.getTime();\n}\n</code></pre>\n\n<p>Including this initialization logic here makes it easier to understand if you're reading the file from top to bottom and care about every line. But think about how you read code. Do you start reading from the top of a file and continue to the bottom? Of course not! The only time you would ever do that is during a code review. Instead, you probably have a starting point based on previous knowledge, a stack trace, etc. Then you drill further down/up through the execution path until you find what you're looking for. <strong>Optimize for reading based on execution path, not code reviews.</strong><br>\nDoes the person reading the code that uses <code>nextTuesday</code> really want to read about how it's initialized? I would argue that the only information that they need is that there's a <code>Date</code> corresponding to next Tuesday. All of this information is contained in its declaration. This is a perfect example of code that should be broken into a private method, because <strong>it isn't necessary to understand the logic that the reader cares about</strong>.</p>\n\n<pre><code>final Date nextTuesday;\ninitNextTuesday: {\n GregorianCalendar cal = new GregorianCalendar();\n //1\n //2\n //3\n //4\n //5\n nextTuesday = cal.getTime();\n}\n</code></pre>\n\n<p><strong>vs:</strong></p>\n\n<pre><code>final Date nextTuesday = getNextTuesday();\n</code></pre>\n\n<p>Which would you rather read on your way through a module?</p>\n" }, { "answer_id": 29760231, "author": "jin", "author_id": 1371719, "author_profile": "https://Stackoverflow.com/users/1371719", "pm_score": 0, "selected": false, "text": "<p>I love the idea of using block to limit var scope. \nSo many times I was confused by short-lived vars given large scope which should go away immediately after use. Long method + many non-final vars make it difficult to reason about the coder's intention, especially when comments are rare. Considering much of the logic I see in a method were like below</p>\n\n<pre><code>Type foo(args..){\n declare ret\n ...\n make temp vars to add information on ret\n ...\n\n make some more temp vars to add info on ret. not much related to above code. but previously declared vars are still alive\n ...\n\n\n return ret\n}\n</code></pre>\n\n<p>if vars can have smaller scope than the entire method body, I can quickly forget most of them (good thing). </p>\n\n<p>Also I agree that too many or too few private things leads to spaghetti code. </p>\n\n<p>Actually what I was looking for was something like nested method in functional languages, and seems its cousin in Java is a {<strong>BLOCK</strong>} (inner class and labmda expression are not for this..). </p>\n\n<p>However, I would prefer to use a unnamed block since this may be misleading to people trying to find the reference to the label, plus I can explain better with commented block. </p>\n\n<p>For using a private method, I would consider it as the next step of using blocks. </p>\n" }, { "answer_id": 29770223, "author": "Premraj", "author_id": 1697099, "author_profile": "https://Stackoverflow.com/users/1697099", "pm_score": 1, "selected": false, "text": "<p>Name Blocks helps: Using break as a Form of Goto</p>\n\n<p><strong>Using break as a civilized form of goto.</strong> </p>\n\n<pre><code>class Break {\n public static void main(String args[]) {\n boolean t = true;\n first: {\n second: {\n third: {\n System.out.println(\"Before the break.\");\n if (t)\n break second; // break out of second block\n System.out.println(\"This won't execute\");\n }\n System.out.println(\"This won't execute\");\n }\n System.out.println(\"This is after second block.\");\n }\n }\n}\n</code></pre>\n\n<p><strong>Using break to exit from nested loops</strong> </p>\n\n<pre><code>class BreakLoop4 {\n public static void main(String args[]) {\n outer: for (int i = 0; i &lt; 3; i++) {\n System.out.print(\"Pass \" + i + \": \");\n for (int j = 0; j &lt; 100; j++) {\n if (j == 10)\n break outer; // exit both loops\n System.out.print(j + \" \");\n }\n System.out.println(\"This will not print\");\n }\n System.out.println(\"Loops complete.\");\n }\n}\n</code></pre>\n\n<p>Source <a href=\"http://www.java-samples.com/showtutorial.php?tutorialid=278\" rel=\"nofollow\">Link</a></p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18078/" ]
For years, I've been using named blocks to limit the scope of temporary variables. I've never seen this done anywhere else, which makes me wonder if this is a bad idea. Especially since the Eclipse IDE flags these as warnings by default. I've used this to good effect, I think, in my own code. But since it is un-idiomatic to the point where good programmers will distrust it when they see it, I really have two ways to go from here: 1. avoid doing it, or 2. promote it, with the hope that it will become an idiom. Example (within a larger method): ``` final Date nextTuesday; initNextTuesday: { GregorianCalendar cal = new GregorianCalendar(); ... // About 5-10 lines of setting the calendar fields nextTuesday = cal.getTime(); } ``` Here I'm using a GregorianCalendar just to initialize a date, and I want to make sure that I don't accidentally reuse it. Some people have commented that you don't actually need to name the block. While that's true, a raw block looks even more like a bug, as the intent is unclear. Furthermore, naming something encourages you to think about the intention of the block. The goal here is to identify distinct sections of code, not to give every temporary variable its own scope. Many people have commented that it's best to go straight to small methods. I agree that this should be your first instinct. However, there may be several mitigating factors: * To even consider a named block, the code should be short, one-off code that will never be called elsewhere. * A named block is a quick way to organize an oversized method without creating a one-off method with a dozen parameters. This is especially true when a class is in flux, and the inputs are likely to change from version to version. * Creating a new method encourages its reuse, which may be ill-advised if the use cases aren't well-established. A named block is easier (psychologically, at least) to throw away. * Especially for unit tests, you may need to define a dozen different objects for one-off assertions, and they are just different enough that you can't (yet) find a way to consolidate them into a small number of methods, nor can you think of a way to distinguish them with names that aren't a mile long. Advantages of using the named scope: 1. Can't accidentally reuse temporary variables 2. Limited scope gives garbage collector and JIT compiler more information about programmer intent 3. Block name provides a comment on a block of code, which I find more readable than open-ended comments 4. Makes it easier to refactor code out of a big method into little methods, or vice versa, since the named block is easier to separate than unstructured code. Disadvantages: Not idiomatic: programmers who haven't seen this use of named blocks (i.e. everyone but me) assume it's buggy, since they can't find references to the block name. (Just like Eclipse does.) And getting something to become idiomatic is an uphill battle. It can be used as an excuse for bad programming habits, such as: * Making huge, monolithic methods where several small methods would be more legible. * Layers of indentation too deep to read easily. Note: I've edited this question extensively, based on some thoughtful responses. Thanks!
I'd just go straight for refactoring into smaller methods. If a method is big enough that it needs breaking up like this, it really needs breaking up into multiple methods if *at all* possible. While limiting scope is nice, this isn't really what named blocks are for. It's unidiomatic, which is very rarely a good thing.
205,468
<p>Hey everyone, I am researching a project where we would need to keep a value encrypted from the client all the way to a black box system without decrypting it at any point in between. We are using SSL between the browser and web server, but the values are automatically decrypted at the web server, which is what we need to keep from happening. We need to be able to pass it through the web server (still encrypted) and through other back end systems until it hits its final destination where it would be decrypted. </p> <p>So my question is what options are available to us for maintaining an encrypted state for a value from the browser back, without decrypting it anywhere along the way?</p> <p>Thanks Mark</p>
[ { "answer_id": 205484, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "<p>you'll want to take a look at <a href=\"http://en.wikipedia.org/wiki/Public-key_cryptography\" rel=\"nofollow noreferrer\">public key encryption</a>. SSL protects your session (browser &lt;-> server) but not the full transport. i'd suggest encrypting your data once it's received from the client, then sending the encrypted data all the way in.</p>\n\n<p>here's a terrible diagram outlining the flow of data</p>\n\n<pre><code> client browser web server random server blackbox\nroute ---- SSL -------------&gt;&lt;------------- not encrypted -------&gt;\ndata *-------- PGP/GPG encrypted ---------&gt;\n</code></pre>\n\n<p>basically your data is encrypted via SSL to the web server, where it is PGP/GPG encrypted, then sent downstream. SSL doesn't matter at this point (or at least, isn't the primary form of encryption).</p>\n\n<p>unless you can guarantee javascript in your environment, it may be better to encrypt at the web server to make sure your data is secure if the user has javascript off for some reason.</p>\n" }, { "answer_id": 205490, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 2, "selected": false, "text": "<p>Have you thought about doing a simple RSA encryption on the values and sending that through the system? You will need to make sure the clients have the public key in which to encrypt the data with, but that would be easy and secure enough to pass around. </p>\n\n<p>To my knowlege, most libraries out there will support RSA. A nice demo of how to do it purely in Javascript can be found <a href=\"http://www.ohdave.com/rsa/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 205493, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 1, "selected": false, "text": "<p>If you use a binary type in your database, the web server should send it as-is. Your client can then encrypt the data before inserting it, and would then have to decrypt the data after fetching it. Neither the web server nor the database server itself would be able to view the data.</p>\n" }, { "answer_id": 205665, "author": "Seun Osewa", "author_id": 6475, "author_profile": "https://Stackoverflow.com/users/6475", "pm_score": 0, "selected": false, "text": "<p>The black box system, by definition, can't decrypt the data unless it was built to do that. I'll suggest discussing the problem with the developers of the black box system.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15815/" ]
Hey everyone, I am researching a project where we would need to keep a value encrypted from the client all the way to a black box system without decrypting it at any point in between. We are using SSL between the browser and web server, but the values are automatically decrypted at the web server, which is what we need to keep from happening. We need to be able to pass it through the web server (still encrypted) and through other back end systems until it hits its final destination where it would be decrypted. So my question is what options are available to us for maintaining an encrypted state for a value from the browser back, without decrypting it anywhere along the way? Thanks Mark
you'll want to take a look at [public key encryption](http://en.wikipedia.org/wiki/Public-key_cryptography). SSL protects your session (browser <-> server) but not the full transport. i'd suggest encrypting your data once it's received from the client, then sending the encrypted data all the way in. here's a terrible diagram outlining the flow of data ``` client browser web server random server blackbox route ---- SSL -------------><------------- not encrypted -------> data *-------- PGP/GPG encrypted ---------> ``` basically your data is encrypted via SSL to the web server, where it is PGP/GPG encrypted, then sent downstream. SSL doesn't matter at this point (or at least, isn't the primary form of encryption). unless you can guarantee javascript in your environment, it may be better to encrypt at the web server to make sure your data is secure if the user has javascript off for some reason.
205,521
<p>I'm trying to write a regex to replace all spaces that are not included in quotes so something like this:</p> <pre><code>a = 4, b = 2, c = "space here" </code></pre> <p>would return this:</p> <pre><code>a=4,b=2,c="space here" </code></pre> <p>I spent some time searching this site and I found a similar q/a ( <a href="https://stackoverflow.com/questions/79968/split-a-string-by-spaces-in-python#80449">Split a string by spaces -- preserving quoted substrings -- in Python</a> ) that would replace all the spaces inside quotes with a token that could be re-substituted in after wiping all the other spaces...but I was hoping there was a cleaner way of doing it.</p>
[ { "answer_id": 205581, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 2, "selected": false, "text": "<p>I consider this very clean:</p>\n\n<pre><code>mystring.scan(/((\".*?\")|([^ ]))/).map { |x| x[0] }.join\n</code></pre>\n\n<p>I doubt <em>gsub</em> could do any better (assuming you want a pure regex approach).</p>\n" }, { "answer_id": 205862, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 3, "selected": false, "text": "<p>This seems to work:</p>\n\n<pre><code>result = string.gsub(/( |(\".*?\"))/, \"\\\\2\")\n</code></pre>\n" }, { "answer_id": 211024, "author": "Senmiao Liu", "author_id": 28809, "author_profile": "https://Stackoverflow.com/users/28809", "pm_score": 0, "selected": false, "text": "<p>try this one, string in single/double quoter is also matched (so you need to filter them, if you only need space):</p>\n\n<pre><code>/( |(\"([^\"\\\\]|\\\\.)*\")|('([^'\\\\]|\\\\.)*'))/\n</code></pre>\n" }, { "answer_id": 211063, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 3, "selected": false, "text": "<p>It's worth noting that <em>any</em> regular expression solution will fail in cases like the following:</p>\n\n<pre><code>a = 4, b = 2, c = \"space\" here\"\n</code></pre>\n\n<p>While it is true that you could construct a regexp to handle the three-quote case specifically, you cannot solve the problem in the general sense. This is a mathematically provable limitation of simple <a href=\"http://en.wikipedia.org/wiki/Deterministic_finite-state_machine\" rel=\"noreferrer\">DFAs</a>, of which regexps are a direct representation. To perform any serious brace/quote matching, you will need the more powerful <a href=\"http://en.wikipedia.org/wiki/Pushdown_automaton\" rel=\"noreferrer\">pushdown automaton</a>, usually in the form of a text parser library (ANTLR, Bison, Parsec).</p>\n\n<p>With that said, it sounds like regular expressions should be sufficient for your needs. Just be aware of the limitations.</p>\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/205521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to write a regex to replace all spaces that are not included in quotes so something like this: ``` a = 4, b = 2, c = "space here" ``` would return this: ``` a=4,b=2,c="space here" ``` I spent some time searching this site and I found a similar q/a ( [Split a string by spaces -- preserving quoted substrings -- in Python](https://stackoverflow.com/questions/79968/split-a-string-by-spaces-in-python#80449) ) that would replace all the spaces inside quotes with a token that could be re-substituted in after wiping all the other spaces...but I was hoping there was a cleaner way of doing it.
This seems to work: ``` result = string.gsub(/( |(".*?"))/, "\\2") ```