qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
39,855 | <p>Is it possible to embed a PowerPoint presentation (.ppt) into a webpage (.xhtml)?</p>
<p>This will be used on a local intranet where there is a mix of Internet Explorer 6 and Internet Explorer 7 only, so no need to consider other browsers.</p>
<hr>
<p>I've given up... I guess Flash is the way forward.</p>
| [
{
"answer_id": 39857,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 0,
"selected": false,
"text": "<p>The first few results on Google all sound like good options:</p>\n\n<p><a href=\"http://www.pptfaq.com/FAQ00708.htm\" rel=\"nofollow noreferrer\">http://www.pptfaq.com/FAQ00708.htm</a></p>\n\n<p><a href=\"http://www.webdeveloper.com/forum/showthread.php?t=86212\" rel=\"nofollow noreferrer\">http://www.webdeveloper.com/forum/showthread.php?t=86212</a></p>\n"
},
{
"answer_id": 39888,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know of a way to embed PowerPoint slides directly into HTML. However, there are a number of solutions online for converting a PPT file into a <a href=\"http://en.wikipedia.org/wiki/SWF\" rel=\"nofollow noreferrer\">SWF</a>, which can be embedded into HTML just like any other Flash movie.</p>\n\n<p><a href=\"http://www.google.com/search?source=ig&hl=en&rlz=&=&q=ppt+to+swf&btnG=Google+Search\" rel=\"nofollow noreferrer\">Googling for 'ppt to swf'</a> seems to give a lot of hits. Some are free, others aren't. Some handle things like animations, others just do still images. There's got to be one out there that does what you need. :)</p>\n"
},
{
"answer_id": 40203,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>Try <em><a href=\"http://www.freedownloadscenter.com/Programming/Delphi_Tools_and_Components/PowerPoint_ActiveX.html\" rel=\"nofollow noreferrer\">PowerPoint ActiveX 2.4</a></em>. This is an ActiveX component that embeds PowerPoint into an OCX.</p>\n\n<p>Since you are using just Internet Explorer 6 and Internet Explorer 7 you can embed this component into the HTML.</p>\n"
},
{
"answer_id": 41395,
"author": "yoavf",
"author_id": 1011,
"author_profile": "https://Stackoverflow.com/users/1011",
"pm_score": 0,
"selected": false,
"text": "<p>As a side note: If your intranet users also have access to the Internet, you can use the <a href=\"http://en.wikipedia.org/wiki/SlideShare\" rel=\"nofollow noreferrer\">SlideShare</a> widget to embed your PowerPoint presentations in your website.</p>\n\n<p>(Remember to mark your presentation as private!)</p>\n"
},
{
"answer_id": 544615,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Some Flash tool that can convert the PowerPoint file to Flash could be helpful. Slide share is also helpful. For me, I will take something like PPT2Flash Pro or things like that.</p>\n"
},
{
"answer_id": 686546,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I think you get to convert the powerpoint to flash first. PowerPoint is not a sharable format on Internet. Some tool like <a href=\"http://www.sameshow.com/powerpoint-to-flash.html#107\" rel=\"nofollow noreferrer\">PowerPoint to Flash</a> could be helpful for you.</p>\n"
},
{
"answer_id": 1199883,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The 'actual answer' is that you cannot do it directly. You have to convert your PowerPoint presentation to something that the browser can process. You can save each page of the PowerPoint presentation as a JPEG image and then display as a series of images. You can save the PowerPoint presentation as HTML. Both of these solutions will render only static pages, without any of the animations of PowerPoint. You can use a tool to convert your PowerPoint presentation to Flash (.swf) and embed it that way. This will preserve any animations and presumably allow you to do an automatic slideshow without the need for writing special code to change the images.</p>\n"
},
{
"answer_id": 1694659,
"author": "Steg",
"author_id": 121872,
"author_profile": "https://Stackoverflow.com/users/121872",
"pm_score": 0,
"selected": false,
"text": "<p>I spent a while looking into this and pretty much all of the freeware and shareware on the web sucked. This included software to directly convert the .ppt file to Flash or some sort of video format and also software to record your desktop screen. Software was clunky, and the quality was poor.</p>\n\n<p>The solution we eventually came up with is a little bit manual, but it gave by far the best quality results:</p>\n\n<ol>\n<li>Export the .ppt file into some sort of image format (.bmp, .jpeg, .png, .tif) - it writes out one file per slide</li>\n<li>Import all the slide image files into <a href=\"http://en.wikipedia.org/wiki/Picasa\" rel=\"nofollow noreferrer\">Google Picasa</a> and use them to create a video. You can add in some nice simple transitions (it hasn't got some of the horrific .ppt one's, but who cares) and it dumps out a <a href=\"http://en.wikipedia.org/wiki/Windows_Media_Video\" rel=\"nofollow noreferrer\">WMV</a> file of your specified resolution.</li>\n</ol>\n\n<p>Saving out as .wmv isn't perfect, but I'm sure it's probably quite straightforward to convert that to some other format or Flash. We were looking to get them up on YouTube and this did the trick.</p>\n"
},
{
"answer_id": 1694704,
"author": "Steve Pasetti",
"author_id": 205818,
"author_profile": "https://Stackoverflow.com/users/205818",
"pm_score": 8,
"selected": true,
"text": "<p>Google Docs can serve up PowerPoint (and PDF) documents in it's document viewer. You don't have to sign up for Google Docs, just upload it to your website, and call it from your page:</p>\n\n<pre><code><iframe src=\"//docs.google.com/gview?url=https://www.yourwebsite.com/powerpoint.ppt&embedded=true\" style=\"width:600px; height:500px;\" frameborder=\"0\"></iframe>\n</code></pre>\n"
},
{
"answer_id": 3875506,
"author": "Ryan Nadeau",
"author_id": 468295,
"author_profile": "https://Stackoverflow.com/users/468295",
"pm_score": 2,
"selected": false,
"text": "<p>You can use Microsoft <a href=\"http://en.wikipedia.org/wiki/Office_Web_Apps\" rel=\"nofollow\">Office Web Apps</a> to embed PowerPoint and Excel Files. See <em><a href=\"http://blogs.office.com/b/office_blog/archive/2010/09/24/say-more-in-your-blog-with-embedded-powerpoint-and-excel-files.aspx\" rel=\"nofollow\">Say more in your blog with embedded PowerPoint and Excel files</a></em>.</p>\n"
},
{
"answer_id": 3875673,
"author": "Insomn3ak",
"author_id": 428957,
"author_profile": "https://Stackoverflow.com/users/428957",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.docstoc.com\" rel=\"noreferrer\">DocStoc.com</a> and <a href=\"http://www.scribd.com/\" rel=\"noreferrer\">Scribd.com</a> both work well with Internet Explorer 6 and Internet Explorer 7. They'll show a variety of document types, including PowerPoint files (.ppt). I use these services for my intranet here at work. Of course, just remember to mark your documents as 'private' after you upload them.</p>\n"
},
{
"answer_id": 4937004,
"author": "Richard Wilson",
"author_id": 608630,
"author_profile": "https://Stackoverflow.com/users/608630",
"pm_score": 2,
"selected": false,
"text": "<p>Google Docs allows you to upload a PowerPoint document, you can then 'Share' it with everyone then you can 'Publish' it and this will provide code to embed it in your site or you can use a direct link which runs at the full size of the browser window. The conversion is pretty good and scales well because the text is retained rather than converted to an image. The conversion is pretty good and the whole thing is free. Definitely worth a go.</p>\n"
},
{
"answer_id": 7549880,
"author": "Michael Crocker",
"author_id": 964241,
"author_profile": "https://Stackoverflow.com/users/964241",
"pm_score": 0,
"selected": false,
"text": "<p>An easy (and free) way is to download <a href=\"http://en.wikipedia.org/wiki/OpenOffice.org\" rel=\"nofollow\">OpenOffice</a> and use <a href=\"http://en.wikipedia.org/wiki/OpenOffice.org_Impress\" rel=\"nofollow\">Impress</a> to open the PowerPoint presentation. Then export into a separate folder as HTML. Your presentation will consist of separate HTML files and images for each PowerPoint slide. Link to the title page, and you're done.</p>\n"
},
{
"answer_id": 11308896,
"author": "Dean",
"author_id": 1498460,
"author_profile": "https://Stackoverflow.com/users/1498460",
"pm_score": 4,
"selected": false,
"text": "<p>I got so sick of trying all of the different options to web host a power point that were flaky or required flash so I rolled my own.</p>\n\n<p>My solution uses a very simple javascript function to simply scroll / replace a image tag with GIFs that I saved from the Power Point presentation itself. </p>\n\n<ol>\n<li><p>In the power point presentation click Save As and select GIF. Pick the quality you want to display the presentation at. Power Point will save one GIF image for each slide and name them Slide1.GIF, Slide2.GIF, etc.....</p></li>\n<li><p>Create a HTML page and add a image tag to display the Power point GIF images.</p>\n\n<pre><code><img src=\"Slide1.GIF\" id=\"mainImage\" name=\"mainImage\" width=\"100%\" height=\"100%\" alt=\"\">\n</code></pre></li>\n<li><p>Add some first, previous, next and last clickable objects with the onClick action as below:</p>\n\n<pre><code><a href=\"#\" onclick=\"swapImage(0);\"><img src=\"/images/first.png\" border=0 alt=\"First\"></a>\n<a href=\"#\" onclick=\"swapImage(currentIndex-1);\"><img src=\"/images/left.png\" border=0 alt=\"Back\"></a>\n<a href=\"#\" onclick=\"swapImage(currentIndex+1);\"><img src=\"/images/right.png\" border=0 alt=\"Next\"></a>\n<a href=\"#\" onclick=\"swapImage(maxIndex);\"><img src=\"/images/last.png\" border=0 alt=\"Last\"></a>\n</code></pre></li>\n<li><p>Finally, add the below javascript function that when called grabs the next Slide.GIF image and displays it to the img tag.</p>\n\n<pre><code><script type=\"text/javascript\">\n //Initilize start value to 1 'For Slide1.GIF'\n var currentIndex = 1;\n\n //NOTE: Set this value to the number of slides you have in the presentation.\n var maxIndex=12;\n\n function swapImage(imageIndex){\n //Check if we are at the last image already, return if we are.\n if(imageIndex>maxIndex){\n currentIndex=maxIndex;\n return;\n }\n\n //Check if we are at the first image already, return if we are.\n if(imageIndex<1){\n currentIndex=1;\n return;\n }\n\n currentIndex=imageIndex;\n //Otherwise update mainImage\n document.getElementById(\"mainImage\").src='Slide' + currentIndex + '.GIF';\n return;\n }\n</script>\n</code></pre></li>\n</ol>\n\n<p>Make sure the GIFs are reachable from the HTMl page. They are by default expected to be in the same directory but you should be able to see the logic and how to set to a image directory if required</p>\n\n<p>I have training material up for my company that uses this technique at <a href=\"http://www.vanguarddata.com.au\" rel=\"noreferrer\">http://www.vanguarddata.com.au</a> so before you spend any time trying it out you are welcome to look at in action. </p>\n\n<p>I hope this helps someone else out there who is having as much headaches with this as I did.....</p>\n"
},
{
"answer_id": 12349200,
"author": "Ally R Reeves",
"author_id": 1659767,
"author_profile": "https://Stackoverflow.com/users/1659767",
"pm_score": 2,
"selected": false,
"text": "<p>Tried all of the options in this stack and couldn't reach something that loaded swiftly, used PPT. file directly, and scaled easily. Saved out my ppt. as .gif and opted for \"Infinite Carousel\" (javascript) that I can drop images into easily. Has left right controls, play option, all the same stuff you find in ppt. presenter mode...</p>\n\n<p><a href=\"http://www.catchmyfame.com/2009/12/30/huge-updates-to-jquery-infinite-carousel-version-2-released/\" rel=\"nofollow\">http://www.catchmyfame.com/2009/12/30/huge-updates-to-jquery-infinite-carousel-version-2-released/</a></p>\n"
},
{
"answer_id": 13501173,
"author": "Deep",
"author_id": 1707126,
"author_profile": "https://Stackoverflow.com/users/1707126",
"pm_score": 2,
"selected": false,
"text": "<p>I ended up going for screenshooting each slide, and using two different tabs to navigate, this was put into an . this gives high-res, but you sacrifice animations and interactivity, the only thing the user can do is read and change slide. heres an example off my website: <a href=\"http://deepschool.jaberwokkee.kodingen.com/~/Miss%20Necchi%27s%20powerpoints/Volume%20of%20prisms%20powerpoint/slide1.htm\" rel=\"nofollow\">http://deepschool.jaberwokkee.kodingen.com/~/Miss%20Necchi%27s%20powerpoints/Volume%20of%20prisms%20powerpoint/slide1.htm</a></p>\n"
},
{
"answer_id": 15427615,
"author": "navins",
"author_id": 1315755,
"author_profile": "https://Stackoverflow.com/users/1315755",
"pm_score": 2,
"selected": false,
"text": "<p>besides, if you save ppt as <code>.pps</code> format using microsoft powerpoint, you can use the following code:</p>\n\n<pre><code><iframe src=\"file.pps\" width=\"800px\" heigt=\"600px\"></iframe>\n</code></pre>\n\n<hr>\n\n<p>Another common way to do it is to convert ppt/doc to pdf, </p>\n\n<p>then use swftool(<a href=\"http://www.swftools.org\" rel=\"nofollow\">http://www.swftools.org</a>) to convert it to swf</p>\n\n<p>finally, take FlexPaper(<a href=\"http://flexpaper.devaldi.com\" rel=\"nofollow\">http://flexpaper.devaldi.com</a>) as document viewer.</p>\n"
},
{
"answer_id": 17611564,
"author": "Mekey Salaria",
"author_id": 1794977,
"author_profile": "https://Stackoverflow.com/users/1794977",
"pm_score": 0,
"selected": false,
"text": "<p>I was looking for a solution for similar problem. </p>\n\n<p>I looked into <a href=\"http://phppowerpoint.codeplex.com/\" rel=\"nofollow\">http://phppowerpoint.codeplex.com/</a></p>\n\n<p>But they have no better documentation, and even no demo page I could see over there and it was seemingly difficult. </p>\n\n<p>What I came up with is: SkyDrive by Microsoft. <a href=\"https://skydrive.live.com\" rel=\"nofollow\">https://skydrive.live.com</a></p>\n\n<p>All you need is an account with them and upload your PPT and embed them straightaway. PPT player is quite clean to use and I like it. </p>\n"
},
{
"answer_id": 36278080,
"author": "Dave",
"author_id": 6111584,
"author_profile": "https://Stackoverflow.com/users/6111584",
"pm_score": 0,
"selected": false,
"text": "<p>I've noticed people recommending some PPT-to-Flash solutions, but Flash doesn't work on mobile devices. There's a hosting service called <a href=\"https://www.ispringsolutions.com/ispring-cloud\" rel=\"nofollow\">iSpring Cloud</a> that automatically converts your PPT to combined Flash+HTML5 format and lets you generate an embed code for your website or blog. Full instructions can be found on their <a href=\"http://www.ispringsolutions.com/articles/how-to-insert-your-html5-presentation-into-a-website-or-blog.html\" rel=\"nofollow\">website</a>.</p>\n"
},
{
"answer_id": 38346071,
"author": "nniicc",
"author_id": 3292976,
"author_profile": "https://Stackoverflow.com/users/3292976",
"pm_score": 4,
"selected": false,
"text": "<p>Id recommend the official View Office documents online</p>\n\n<p><a href=\"https://products.office.com/en-GB/office-online/view-office-documents-online?legRedir=true&CorrelationId=b28c7173-79a2-4fb7-a1eb-9e75651fd1a1\" rel=\"noreferrer\">link</a></p>\n\n<p>for embeding you can simply use </p>\n\n<pre><code><iframe src='https://view.officeapps.live.com/op/embed.aspx?src={urlencode(site-to-ppt)}' width='962px' height='565px' frameborder='0'></iframe>\n</code></pre>\n"
},
{
"answer_id": 48190992,
"author": "Aba",
"author_id": 1902468,
"author_profile": "https://Stackoverflow.com/users/1902468",
"pm_score": 1,
"selected": false,
"text": "<p>Power point supports converting to mp4 which can be posted using a html5 video tag. </p>\n\n<p>Save As > MPEG-4 Video (*.mp4)</p>\n\n<pre><code><video controls autoplay reload=\"none\" style=\"width:1000px;\">\n<source src=\"my_power_point.mp4\" type=\"video/mp4\" />\n</video>\n</code></pre>\n"
},
{
"answer_id": 48988944,
"author": "kjyv",
"author_id": 974478,
"author_profile": "https://Stackoverflow.com/users/974478",
"pm_score": 0,
"selected": false,
"text": "<p>Another option is to use Apple Keynote on a Mac (Libre Office couldn't event open a pptx I had) to save the presentation to HTML5. It does a pretty good job to produce exactly what it displays in keynote, e.g. it includes animations and video. Compatibility of keynote to powerpoint has it's limits though (independent of the export).</p>\n"
},
{
"answer_id": 70084375,
"author": "Vlad Bilyk",
"author_id": 2516831,
"author_profile": "https://Stackoverflow.com/users/2516831",
"pm_score": 1,
"selected": false,
"text": "<p>As an alternate solution, you can convert PPT/PPTX to JPG/SVG images and display them with <a href=\"https://revealjs.com/\" rel=\"nofollow noreferrer\">revealjs</a>. See example code <a href=\"https://github.com/aspose-slides/Aspose.Slides-for-.NET/blob/master/Demos/Aspose.Slides.Web/Views/Slides/Slideshow.cshtml\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>PS. I am working as SW developer at Aspose.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | Is it possible to embed a PowerPoint presentation (.ppt) into a webpage (.xhtml)?
This will be used on a local intranet where there is a mix of Internet Explorer 6 and Internet Explorer 7 only, so no need to consider other browsers.
---
I've given up... I guess Flash is the way forward. | Google Docs can serve up PowerPoint (and PDF) documents in it's document viewer. You don't have to sign up for Google Docs, just upload it to your website, and call it from your page:
```
<iframe src="//docs.google.com/gview?url=https://www.yourwebsite.com/powerpoint.ppt&embedded=true" style="width:600px; height:500px;" frameborder="0"></iframe>
``` |
39,856 | <p>I have an actionscript file that defines a class that I would like to use inside a Flex application. </p>
<p>I have defined some custom controls in a actionscript file and then import them via the application tag:</p>
<pre>
<code>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:scorecard="com.apterasoftware.scorecard.controls.*"
...
</mx:Application>
</code>
</pre>
<p>but this code is not a flex component, rather it is a library for performing math routines, how do I import this class?</p>
| [
{
"answer_id": 39864,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 4,
"selected": true,
"text": "<p>You'd need to import the class inside a script tag.</p>\n\n<pre><code><mx:Application\n xmlns:mx=\"http://www.adobe.com/2006/mxml\">\n <mx:Script>\n import com.apterasoftware.scorecard.controls.*;\n // Other imports go here\n\n // Functions and other code go here\n </mx:Script>\n\n <!-- Components and other MXML stuff go here -->\n <mx:VBox>\n <!-- Just a sample -->\n </mx:VBox>\n</mx:Application>\n</code></pre>\n\n<p>Then you'll be able to reference that class anywhere else in your script tag. Depending on how the class is written you may not be able to use binding within the MXML, but you could define your own code to handle that.</p>\n\n<p>Namespace declarations are only used to import other MXML components. AS classes are imported using the import statement either within a Script block or another AS file.</p>\n"
},
{
"answer_id": 400550,
"author": "Niko Nyman",
"author_id": 36817,
"author_profile": "https://Stackoverflow.com/users/36817",
"pm_score": 0,
"selected": false,
"text": "<p>@Herms: To clarify a little, namespace declarations can be used to \"import\" AS classes as well, when you're going to instantiate them using MXML.</p>\n\n<p>For example, consider having a custom visual component you've written entirely in AS, let's say <code>com.apterasoftware.scorecard.controls.MathVisualizer</code>. To use it within MXML:</p>\n\n<pre><code><mx:Application\n xmlns:mx=\"http://www.adobe.com/2006/mxml\"\n xmlns:aptera=\"com.apterasoftware.scorecard.controls.*\">\n\n <aptera:MathVisualizer width=\"400\" height=\"300\" />\n</mx:Application>\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | I have an actionscript file that defines a class that I would like to use inside a Flex application.
I have defined some custom controls in a actionscript file and then import them via the application tag:
```
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:scorecard="com.apterasoftware.scorecard.controls.*"
...
</mx:Application>
```
but this code is not a flex component, rather it is a library for performing math routines, how do I import this class? | You'd need to import the class inside a script tag.
```
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
import com.apterasoftware.scorecard.controls.*;
// Other imports go here
// Functions and other code go here
</mx:Script>
<!-- Components and other MXML stuff go here -->
<mx:VBox>
<!-- Just a sample -->
</mx:VBox>
</mx:Application>
```
Then you'll be able to reference that class anywhere else in your script tag. Depending on how the class is written you may not be able to use binding within the MXML, but you could define your own code to handle that.
Namespace declarations are only used to import other MXML components. AS classes are imported using the import statement either within a Script block or another AS file. |
39,867 | <p>I have a script that has a part that looks like that:</p>
<pre><code>for file in `ls *.tar.gz`; do
echo encrypting $file
gpg --passphrase-file /home/$USER/.gnupg/backup-passphrase \
--simple-sk-checksum -c $file
done
</code></pre>
<p>For some reason if I run this script manually, works perfectly fine and all files are encrypted. If I run this as cron job, <code>echo $file</code> works fine (I see "encrypting <file>" in the log), but the file doesn't get encrypted and gpg silent fails with no stdout/stderr output.</p>
<p>Any clues?</p>
| [
{
"answer_id": 39877,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>make sure the user that is running the cron job has the permissions needed to encrypt the file. </p>\n"
},
{
"answer_id": 39898,
"author": "skinp",
"author_id": 2907,
"author_profile": "https://Stackoverflow.com/users/2907",
"pm_score": 0,
"selected": false,
"text": "<p>I've came across this problem once.</p>\n\n<p>I can't really tell you why, but I dont think cron executes with the same environment variable as the user do.</p>\n\n<p>I actually had to export the good path for my programs to execute well.\nIs gpg at least trying to execute?</p>\n\n<p>Or are the files you are trying to encypt actually in the current directory when the cron executes?</p>\n\n<p>Maybe try to execute a <code>echo whereis gpg</code> and <code>echo $PATH</code> in your script to see if it's included... Worked for me.</p>\n"
},
{
"answer_id": 39917,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 1,
"selected": false,
"text": "<p>You should make sure that GPG is in your path when the cronjob is running. Your best guess would be do get the full path of GPG (by doing <code>which gpg</code>) and running it using the full path (for example <code>/usr/bin/gpp...</code>).</p>\n\n<p>Some other debugging tips:</p>\n\n<ul>\n<li>output the value of <code>$?</code> after running GPG (like this: echo \"$?\"). This gives you the exit code, which should be 0, if it succeded</li>\n<li>redirect the STDERR to STDOUT for GPG and then redirect STDOUT to a file, to inspect any error messages which might get printed (you can do this a command line: <code>/usr/bin/gpg ... 2>&1 >> gpg.log</code>)</li>\n</ul>\n"
},
{
"answer_id": 40141,
"author": "Marcin",
"author_id": 3105,
"author_profile": "https://Stackoverflow.com/users/3105",
"pm_score": 6,
"selected": true,
"text": "<p>It turns out that the answer was easier than I expected. There is a <code>--batch</code> parameter missing, gpg tries to read from /dev/tty that doesn't exist for cron jobs. To debug that I have used <code>--exit-on-status-write-error</code> param. But to use that I was inspired by exit status 2, reported by echoing <code>$?</code> as Cd-Man suggested. </p>\n"
},
{
"answer_id": 42790,
"author": "dr-jan",
"author_id": 2599,
"author_profile": "https://Stackoverflow.com/users/2599",
"pm_score": 0,
"selected": false,
"text": "<p>@skinp Cron jobs are executed by sh, whereas most modern Unixes use bash or ksh for interactive logins. The biggest problem (in my experience) is that sh doesn't understand things like:</p>\n\n<pre><code>export PS1='\\u@\\h:\\w> '\n</code></pre>\n\n<p>which needs to be changed to:</p>\n\n<pre><code>PS1='\\u@\\h:\\w> '\nexport PS1\n</code></pre>\n\n<p>So if cron runs a shell script which defines an environment variable using the first syntax, before running some other command, the other command will never be executed because sh bombs out trying to define the variable.</p>\n"
},
{
"answer_id": 7624924,
"author": "Enginer",
"author_id": 975169,
"author_profile": "https://Stackoverflow.com/users/975169",
"pm_score": 3,
"selected": false,
"text": "<p>In my case gpg cant find home dir for using keys:</p>\n<blockquote>\n<p>gpg: no default secret key: No secret key</p>\n<p>gpg: 0003608.cmd: sign+encrypt failed: No secret key</p>\n</blockquote>\n<p>So I added <code>--homedir /root/.gnupg</code>. The final command can looks like</p>\n<blockquote>\n<p>echo 'password' | gpg -vvv --homedir /root/.gnupg --batch --passphrase-fd 0\n--output /usr/share/file.gpg --encrypt --sign /usr/share/file.tar.bz2</p>\n</blockquote>\n"
},
{
"answer_id": 47820507,
"author": "Mike Lapinskas",
"author_id": 4267138,
"author_profile": "https://Stackoverflow.com/users/4267138",
"pm_score": 0,
"selected": false,
"text": "<p>In my case: \"gpg: decryption failed: Bad session key\".</p>\n\n<p>Tried adding /usr/bin/gpg, checking the version, setting --batch, setting --home (with /root/.gnupg and /home/user/.gnupg) and all did not work.</p>\n\n<pre><code>/usr/bin/gpg -d --batch --homedir /home/ec2-user/.gnupg --no-mdc-warning -quiet --passphrase \"$GPG_PP\" \"$file\"\n</code></pre>\n\n<p>Turned out that cron on AWS beanstalk instance needed the environment variable being used to set the --passphrase $GPG_PP. Cron now:</p>\n\n<pre><code>0 15 * * * $(source /opt/elasticbeanstalk/support/envvars && /home/ec2-user/bin/script.sh >> /home/ec2-user/logs/cron_out.log 2>&1)\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3105/"
] | I have a script that has a part that looks like that:
```
for file in `ls *.tar.gz`; do
echo encrypting $file
gpg --passphrase-file /home/$USER/.gnupg/backup-passphrase \
--simple-sk-checksum -c $file
done
```
For some reason if I run this script manually, works perfectly fine and all files are encrypted. If I run this as cron job, `echo $file` works fine (I see "encrypting <file>" in the log), but the file doesn't get encrypted and gpg silent fails with no stdout/stderr output.
Any clues? | It turns out that the answer was easier than I expected. There is a `--batch` parameter missing, gpg tries to read from /dev/tty that doesn't exist for cron jobs. To debug that I have used `--exit-on-status-write-error` param. But to use that I was inspired by exit status 2, reported by echoing `$?` as Cd-Man suggested. |
39,874 | <p>What data structures would you use to represent a chessboard for a computer chess program?</p>
| [
{
"answer_id": 39881,
"author": "slm",
"author_id": 4262,
"author_profile": "https://Stackoverflow.com/users/4262",
"pm_score": 3,
"selected": false,
"text": "<p>The simple approach is to use an 8x8 integer array. Use 0 for empty squares and assign values for the pieces:</p>\n\n<pre><code>1 white pawns\n2 white knights\n3 white bishops\n4 white rooks\n5 white queens\n6 white king\n\nBlack pieces use negative values\n-1 black pawn\n-2 black knight\netc\n\n8| -4 -2 -3 -5 -6 -3 -2 -4\n7| -1 -1 -1 -1 -1 -1 -1 -1\n6| 0 0 0 0 0 0 0 0\n5| 0 0 0 0 0 0 0 0\n4| 0 0 0 0 0 0 0 0\n3| 0 0 0 0 0 0 0 0\n2| 1 1 1 1 1 1 1 1 \n1| 4 2 3 5 6 3 2 4\n -------------------------\n 1 2 3 4 5 6 7 8\n</code></pre>\n\n<p>Piece moves can be calculated by using the array indexes. For example the white pawns move by increasing the row index by 1, or by 2 if it's the pawn's first move. So the white pawn on [2][1] could move to [3][1] or [4][1].</p>\n\n<p>However this simple 8x8 array representation of has chessboard has several problems. Most notably when you're moving 'sliding' pieces like rooks, bishops and queens you need to constantly be checking the indexes to see if the piece has moved off the board. </p>\n\n<p>Most chessprograms today, especially those that run on a 64 bit CPU, use a bitmapped approach to represent a chessboard and generate moves. x88 is an alternate board model for machines without 64 bit CPUs.</p>\n"
},
{
"answer_id": 39883,
"author": "Larsenal",
"author_id": 337,
"author_profile": "https://Stackoverflow.com/users/337",
"pm_score": -1,
"selected": false,
"text": "<p>An array would probably be fine. If you wanted more convenient means of \"traversing\" the board, you could easily build methods to abstract away the details of the data structure implementation.</p>\n"
},
{
"answer_id": 39885,
"author": "Marcel",
"author_id": 2554,
"author_profile": "https://Stackoverflow.com/users/2554",
"pm_score": 0,
"selected": false,
"text": "<pre><code>int[8][8]\n\n0=no piece\n1=king\n2=queen\n3=rook\n4=knight\n5=bishop\n6=pawn\n</code></pre>\n\n<p>use positive ints for white and negative ints for black</p>\n"
},
{
"answer_id": 39896,
"author": "Niyaz",
"author_id": 184,
"author_profile": "https://Stackoverflow.com/users/184",
"pm_score": 4,
"selected": false,
"text": "<p>Initially, use an <strong>8 * 8 integer array</strong> to represent the chess board.</p>\n\n<p>You can start programing using this notation. Give point values for the pieces. For example:</p>\n\n<pre><code>**White**\n9 = white queen\n5 = white rook\n3 = bishop\n3 = knight\n1 = pawn\n\n**black**\n-9 = white queen\n-5 = white rook\n-3 = bishop\n-3 = knight\n-1 = pawn\n\nWhite King: very large positive number\nBlack King: very large negative number\n</code></pre>\n\n<p>etc. (Note that the points given above are approximations of trading power of each chess piece)</p>\n\n<p>After you develop the basic backbones of your application and clearly understand the working of the algorithms used, try to improve the performance by using bit boards.</p>\n\n<p>In bit boards, you use eight 8 -bit words to represent the boards. This representation needs a board for each chess piece. In one bit board you will be storing the position of the rook while in another you will be storing the position of the knight... etc</p>\n\n<p>Bit boards can improve the performance of your application very much because manipulating the pieces with bit boards are very easy and fast.</p>\n\n<p>As you pointed out,</p>\n\n<blockquote>\n <p>Most chessprograms today, especially\n those that run on a 64 bit CPU, use a\n bitmapped approach to represent a\n chessboard and generate moves. x88 is\n an alternate board model for machines\n without 64 bit CPUs.</p>\n</blockquote>\n"
},
{
"answer_id": 39899,
"author": "Binarytales",
"author_id": 319,
"author_profile": "https://Stackoverflow.com/users/319",
"pm_score": 1,
"selected": false,
"text": "<p>I would use a multidimensional array so that each element in an array is a grid reference to a square on the board.</p>\n\n<p>Thus</p>\n\n<pre><code>board = arrary(A = array (1,2,3,4,5,5,6,7,8),\n B = array (12,3,.... etc...\n etc... \n )\n</code></pre>\n\n<p>Then <em>board[A][1]</em> is then the board square A1.</p>\n\n<p>In reality you would use numbers not letters to help keep your maths logic for where pieces are allowed to move to simple.</p>\n"
},
{
"answer_id": 39926,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 2,
"selected": false,
"text": "<p>There are of course a number of different ways to represent a chessboard, and the best way will depend on what is most important to you.</p>\n\n<p>Your two main choices are between speed and code clarity.</p>\n\n<p>If speed is your priority then you must use a 64 bit data type for each set of pieces on the board (e.g. white pawns, black queens, en passant pawns). You can then take advantage of native bitwise operations when generating moves and testing move legality.</p>\n\n<p>If clarity of code is priority then forget bit shuffling and go for nicely abstracted data types like others have already suggested. Just remember that if you go this way you will probably hit a performance ceiling sooner.</p>\n\n<p>To start you off, look at the code for <a href=\"http://en.wikipedia.org/wiki/Crafty\" rel=\"nofollow noreferrer\">Crafty</a> (C) and <a href=\"http://sharpchess.com/\" rel=\"nofollow noreferrer\">SharpChess</a> (C#).</p>\n"
},
{
"answer_id": 39964,
"author": "Esa",
"author_id": 4224,
"author_profile": "https://Stackoverflow.com/users/4224",
"pm_score": 2,
"selected": false,
"text": "<p>Well, not sure if this helps, but Deep Blue used a single 6-bit number to represent a specific position on the board. This helped it save footprint on-chip in comparison to it's competitor, which used a 64-bit bitboard. </p>\n\n<p>This might not be relevant, since chances are, you might have 64 bit registers on your target hardware, already. </p>\n"
},
{
"answer_id": 524497,
"author": "Nixuz",
"author_id": 61793,
"author_profile": "https://Stackoverflow.com/users/61793",
"pm_score": 2,
"selected": false,
"text": "<p>Using a bitboard would be an efficient way to represent the state of a chess board. The basic idea is that you use 64bit bitsets to represent each of the squares on the board, where first bit usually represents A1 (the lower left square), and the 64th bit represents H8 (the diagonally opposite square). Each type of piece (pawn, king, etc.) of each player (black, white) gets its own bit board and all 12 of these boards makes up the game state. For more information check out this Wikipedia <a href=\"http://en.wikipedia.org/wiki/Bitboard\" rel=\"nofollow noreferrer\">article</a>. </p>\n"
},
{
"answer_id": 524505,
"author": "Henry B",
"author_id": 6414,
"author_profile": "https://Stackoverflow.com/users/6414",
"pm_score": 0,
"selected": false,
"text": "<p>I actually wouldn't model the chess board, I'd just model the position of the pieces.\nYou can have bounds for the chess board then.</p>\n\n<pre><code>Piece.x= x position of piece\nPiece.y= y position of piece\n</code></pre>\n"
},
{
"answer_id": 749948,
"author": "Adam Berent",
"author_id": 90793,
"author_profile": "https://Stackoverflow.com/users/90793",
"pm_score": 2,
"selected": false,
"text": "<p>When creating my chess engine I originally went with the [8][8] approach, however recently I changed my code to represent the chess board using a 64 item array. I found that this implementation was about 1/3 more efficient, at least in my case. </p>\n\n<p>One of the things you want to consider when doing the [8][8] approach is describing positions. For example if you wish to describe a valid move for a chess piece, you will need 2 bytes to do so. While with the [64] item array you can do it with one byte. </p>\n\n<p>To convert from a position on the [64] item board to a [8][8] board you can simply use the following calculations:</p>\n\n<p>Row= (byte)(index / 8)</p>\n\n<p>Col = (byte)(index % 8)</p>\n\n<p>Although I found that you never have to do that during the recursive move searching which is performance sensitive.</p>\n\n<p>For more information on building a chess engine, feel free to visit my blog that describes the process from scratch: <a href=\"http://www.chessbin.com\" rel=\"nofollow noreferrer\">www.chessbin.com</a></p>\n\n<p>Adam Berent</p>\n"
},
{
"answer_id": 1185812,
"author": "David Plumpton",
"author_id": 16709,
"author_profile": "https://Stackoverflow.com/users/16709",
"pm_score": 3,
"selected": false,
"text": "<p>Array of 120 bytes.</p>\n\n<p>This is a chessboard of 8x8 surrounded by sentinel squares (e.g. a 255 to indicate that a piece can't move to this square). The sentinels have a depth of two so that a knight can't jump over.</p>\n\n<p>To move right add 1. To move left add -1. Up 10, down -10, up and right diagonal 11 etc. Square A1 is index 21. H1 is index 29. H8 is index 99.</p>\n\n<p>All designed for simplicity. But it's never going to be as fast as bitboards.</p>\n"
},
{
"answer_id": 18475233,
"author": "bytefire",
"author_id": 1719372,
"author_profile": "https://Stackoverflow.com/users/1719372",
"pm_score": 4,
"selected": false,
"text": "<p>For a serious chess engine, using bitboards is an efficient way to represent a chess board in memory. Bitboards are faster than any array based representation, specially in 64-bit architectures where a bitboard can fit inside a single CPU register.</p>\n\n<p><strong>Bitboards</strong></p>\n\n<p>Basic idea of bitboards is to represent every chess piece type in 64 bits. In C++/C# it will be <code>ulong/UInt64</code>. So you'll maintain 12 <code>UInt64</code> variables to represent your chess board: two (one black and one white) for each piece type, namely, pawn, rook, knight, bishop, queen and king. Every bit in a <code>UInt64</code> will correspond to a square on chessboard. Typically, the least significant bit will be a1 square, the next b1, then c1 and so on in a row-major fashion. The bit corresponding to a piece's location on chess board will be set to 1, all others will be set to 0. For example, if you have two white rooks on a2 and h1 then the white rooks bitboard will look like this: </p>\n\n<pre><code>0000000000000000000000000000000000000000000000000000000110000000\n</code></pre>\n\n<p>Now for example, if you wanted to move your rook from a2 to g2 in the above example, all you need to do is XOR you bitboard with:</p>\n\n<pre><code>0000000000000000000000000000000000000000000000000100000100000000\n</code></pre>\n\n<p>Bitboards have a performance advantage when it comes to move generation. There are other performance advantages too that spring naturally from bitboards representation. For example you could use <a href=\"http://www.cis.uab.edu/hyatt/hashing.html\" rel=\"noreferrer\">lockless hash tables</a> which are an immense advantage when parallelising your search algorithm.</p>\n\n<p><strong>Further Reading</strong></p>\n\n<p>The ultimate resource for chess engine development is the <a href=\"http://chessprogramming.wikispaces.com/Bitboards\" rel=\"noreferrer\">Chess Programming Wiki</a>. I've recently written <a href=\"https://github.com/bytefire/Shutranj/blob/master/Shutranj.Engine/Board.cs\" rel=\"noreferrer\">this chess engine</a> which implements bitboards in C#. An even better open source chess engine is <a href=\"https://github.com/mcostalba/Stockfish/tree/master/src\" rel=\"noreferrer\">StockFish</a> which also implements bitboards but in C++.</p>\n"
},
{
"answer_id": 20709640,
"author": "Wayne",
"author_id": 592746,
"author_profile": "https://Stackoverflow.com/users/592746",
"pm_score": 2,
"selected": false,
"text": "<p>An alternative to the standard <a href=\"http://chessprogramming.wikispaces.com/8x8+Board\" rel=\"nofollow\">8x8 board</a> is the <a href=\"http://chessprogramming.wikispaces.com/10x12+Board\" rel=\"nofollow\">10x12</a> mailbox (so-called because, uh, I guess it looks like a mailbox). This is a one-dimensional array that includes <a href=\"http://en.wikipedia.org/wiki/Sentinel_value\" rel=\"nofollow\">sentinels</a> around its \"borders\" to assist with move generation. It looks like this:</p>\n\n<pre><code>-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n-1, \"a8\", \"b8\", \"c8\", \"d8\", \"e8\", \"f8\", \"g8\", \"h8\", -1,\n-1, \"a7\", \"b7\", \"c7\", \"d7\", \"e7\", \"f7\", \"g7\", \"h7\", -1,\n-1, \"a6\", \"b6\", \"c6\", \"d6\", \"e6\", \"f6\", \"g6\", \"h6\", -1,\n-1, \"a5\", \"b5\", \"c5\", \"d5\", \"e5\", \"f5\", \"g5\", \"h5\", -1,\n-1, \"a4\", \"b4\", \"c4\", \"d4\", \"e4\", \"f4\", \"g4\", \"h4\", -1,\n-1, \"a3\", \"b3\", \"c3\", \"d3\", \"e3\", \"f3\", \"g3\", \"h3\", -1,\n-1, \"a2\", \"b2\", \"c2\", \"d2\", \"e2\", \"f2\", \"g2\", \"h2\", -1,\n-1, \"a1\", \"b1\", \"c1\", \"d1\", \"e1\", \"f1\", \"g1\", \"h1\", -1,\n-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n-1, -1, -1, -1, -1, -1, -1, -1, -1, -1\n</code></pre>\n\n<p>You can generate that array like this (in JavaScript):</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function generateEmptyBoard() {\n var row = [];\n for(var i = 0; i < 120; i++) {\n row.push((i < 20 || i > 100 || !(i % 10) || i % 10 == 9) \n ? -1 \n : i2an(i));\n }\n return row;\n}\n\n// converts an index in the mailbox into its corresponding value in algebraic notation\nfunction i2an(i) {\n return \"abcdefgh\"[(i % 10) - 1] + (10 - Math.floor(i / 10));\n}\n</code></pre>\n\n<p>Of course, in a real implementation you'd put actual piece objects where the board labels are. But you'd keep the negative ones (or something equivalent). Those locations make move generation a lot less painful because you can easily tell when you've run off the board by checking for that special value.</p>\n\n<p>Let's first look at generating the legal moves for the knight (a non-sliding piece):</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function knightMoves(square, board) {\n var i = an2i(square);\n var moves = [];\n [8, 12, 19, 21].forEach(function(offset) {\n [i + offset, i - offset].forEach(function(pos) {\n // make sure we're on the board\n if (board[pos] != -1) {\n // in a real implementation you'd also check whether \n // the squares you encounter are occupied\n moves.push(board[pos]);\n }\n });\n });\n return moves;\n}\n\n// converts a position in algebraic notation into its location in the mailbox\nfunction an2i(square) {\n return \"abcdefgh\".indexOf(square[0]) + 1 + (10 - square[1]) * 10;\n}\n</code></pre>\n\n<p>We know that the valid Knight moves are a fixed distance from the piece's starting point, so we only needed to check that those locations are valid (i.e. not sentinel squares).</p>\n\n<p>The sliding pieces aren't much harder. Let's look at the bishop:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function bishopMoves(square, board) {\n var oSlide = function(direction) {\n return slide(square, direction, board);\n }\n return [].concat(oSlide(11), oSlide(-11), oSlide(9), oSlide(-9)); \n}\n\nfunction slide(square, direction, board) {\n var moves = [];\n for(var pos = direction + an2i(square); board[pos] != -1; pos += direction) {\n // in a real implementation you'd also check whether \n // the squares you encounter are occupied\n moves.push(board[pos]);\n }\n return moves;\n}\n</code></pre>\n\n<p>Here are some examples:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>knightMoves(\"h1\", generateEmptyBoard()) => [\"f2\", \"g3\"]\nbishopMoves(\"a4\", generateEmptyBoard()) => [\"b3\", \"c2\", \"d1\", \"b5\", \"c6\", \"d7\", \"e8\"]\n</code></pre>\n\n<p>Note that the <code>slide</code> function is a general implementation. You should be able to model the legal moves of the other sliding pieces fairly easily.</p>\n"
},
{
"answer_id": 21966534,
"author": "rpd",
"author_id": 247135,
"author_profile": "https://Stackoverflow.com/users/247135",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is a very old post which I have stumbled across a few times when googling chess programming, yet I feel I must mention it is perfectly feasible to model a chessboard with a 1D array e.g. chessboard[64]; </p>\n\n<p>I would say this is the simplest approach to chessboard representation...but of course it is a basic approach. </p>\n\n<p>Is a 1D chessboard array structure more efficient than a 2D array (which needs a nested for loop to access and manipulate the indices)?</p>\n\n<p>It is also possible to use a 1D array with more than 64 squares to represent OffBoard squares also e.g. chessboard[120]; (with the array sentinel and board playing squares correctly initialised).</p>\n\n<p>Finally and again for completeness for this post I feel I must mention the 0x88 board array representation. This is quite a popular way to represent a chessboard which also accounts for offboard squares.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4262/"
] | What data structures would you use to represent a chessboard for a computer chess program? | Initially, use an **8 \* 8 integer array** to represent the chess board.
You can start programing using this notation. Give point values for the pieces. For example:
```
**White**
9 = white queen
5 = white rook
3 = bishop
3 = knight
1 = pawn
**black**
-9 = white queen
-5 = white rook
-3 = bishop
-3 = knight
-1 = pawn
White King: very large positive number
Black King: very large negative number
```
etc. (Note that the points given above are approximations of trading power of each chess piece)
After you develop the basic backbones of your application and clearly understand the working of the algorithms used, try to improve the performance by using bit boards.
In bit boards, you use eight 8 -bit words to represent the boards. This representation needs a board for each chess piece. In one bit board you will be storing the position of the rook while in another you will be storing the position of the knight... etc
Bit boards can improve the performance of your application very much because manipulating the pieces with bit boards are very easy and fast.
As you pointed out,
>
> Most chessprograms today, especially
> those that run on a 64 bit CPU, use a
> bitmapped approach to represent a
> chessboard and generate moves. x88 is
> an alternate board model for machines
> without 64 bit CPUs.
>
>
> |
39,910 | <p>I want to use the MultipleLookupField control in a web page that will run in the context of SharePoint. I was wondering if anyone would help me with an example, which shows step by step how to use the control two display two SPField Collections.</p>
| [
{
"answer_id": 40929,
"author": "Matt Bishop",
"author_id": 4301,
"author_profile": "https://Stackoverflow.com/users/4301",
"pm_score": 3,
"selected": true,
"text": "<p>I'm not entirely sure I understand your question, especially the bit about displaying two SPField collections. Sorry if this turns out to be the answer to a completely different question!</p>\n\n<p>Anyway here's a quick demo walkthrough of using the MultipleLookupField in a web part.</p>\n\n<p>Create a team site. Add a few tasks to the task list. Also put a document in the Shared Documents library. Create a new column in the Shared Documents library; call it \"Related\", have it be a Lookup into the Title field of the Tasks list, and allow multiple values.</p>\n\n<p>Now create a web part, do all the usual boilerplate and then add this:</p>\n\n<pre><code>Label l;\nMultipleLookupField mlf;\n\nprotected override void CreateChildControls()\n{\n base.CreateChildControls();\n SPList list = SPContext.Current.Web.Lists[\"Shared Documents\"];\n if (list != null && list.Items.Count > 0)\n {\n LiteralControl lit = new LiteralControl(\"Associate tasks to \" + \n list.Items[0].Name);\n this.Controls.Add(lit);\n\n mlf = new MultipleLookupField();\n mlf.ControlMode = SPControlMode.Edit;\n mlf.FieldName = \"Related\";\n mlf.ItemId = list.Items[0].ID;\n mlf.ListId = list.ID;\n mlf.ID = \"Related\";\n this.Controls.Add(mlf);\n\n Button b = new Button();\n b.Text = \"Change\";\n b.Click += new EventHandler(bClick);\n this.Controls.Add(b);\n\n l = new Label();\n this.Controls.Add(l);\n }\n\n}\n\nvoid bClick(object sender, EventArgs e)\n{\n l.Text = \"\";\n foreach (SPFieldLookupValue val in (SPFieldLookupValueCollection)mlf.Value)\n {\n l.Text += val.LookupValue.ToString() + \" \";\n }\n SPListItem listitem = mlf.List.Items[0];\n listitem[\"Related\"] = mlf.Value;\n listitem.Update();\n mlf.Value = listitem[\"Related\"];\n}\n\nprotected override void OnInit(EventArgs e)\n{\n base.OnInit(e);\n EnsureChildControls();\n}\n</code></pre>\n\n<p>Granted, this is borderline ridiculous -- everything is hard-coded, there is no error-handling at all, and it serves no useful purpose -- but it's only meant as a quick demo. Now build and deploy this web part and add an instance of it to your team site's homepage; it should allow you to get and set the tasks which are associated with the first document in the library.</p>\n\n<p>The strange bit towards the end of the button Click handler, where we read a value from mlf.Value and then write it back again, appears to be required if you want the UI to stay in sync with the actual list values. Try omitting the last line of bClick to see what I mean. This has been driving me nuts for the last hour or so, and I'm hoping another commenter can come up with a better approach...</p>\n"
},
{
"answer_id": 41439,
"author": "Matt Bishop",
"author_id": 4301,
"author_profile": "https://Stackoverflow.com/users/4301",
"pm_score": 0,
"selected": false,
"text": "<p>Hm. Works fine on mine, so let's see if we can work out how your setup is different...</p>\n\n<p>It looks as though it's having trouble populating the control; my first guess would be that this is because the code makes so many assumptions about the lists it's talking to. Can you check that you've got a plain vanilla Team site, with (assume these names are case-sensitive): </p>\n\n<ol>\n<li>A list called Tasks, with several items in it</li>\n<li>A library called Shared Documents with at least one document</li>\n<li>A column called Related in the Shared Documents library</li>\n<li>The Related column is a Lookup field into the Title column of Tasks, and allows multiple values.</li>\n<li>The first document in Shared Documents has a value for Related</li>\n</ol>\n\n<p>Then add the webpart. Fingers crossed...</p>\n"
},
{
"answer_id": 45022,
"author": "Matt Bishop",
"author_id": 4301,
"author_profile": "https://Stackoverflow.com/users/4301",
"pm_score": 0,
"selected": false,
"text": "<p>Hm. OK, I'm still trying to break mine... so I went to the layouts directory and created a file foo.aspx. Here it is:</p>\n\n<pre><code><%@ Page Language=\"C#\" Inherits=\"System.Web.UI.Page\" MasterPageFile=\"~/_layouts/simple.master\" %> \n<%@ Register Tagprefix=\"foo\" Namespace=\"Foople\" Assembly=\"Foople, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5\"%>\n<asp:Content ContentPlaceHolderId=\"PlaceHolderMain\" runat=\"server\">\n<foo:WebPart1 id=\"fred\" runat=\"server\" />\n<foo:WebPart1a id=\"barney\" runat=\"server\" />\n</asp:Content>\n</code></pre>\n\n<p>WebPart1 is the webpart from before. WebPart1a is the exact same code, but in a class that inherits directly from WebControl rather than from WebPart.</p>\n\n<p>It works fine, apart from a security validation problem on the postback that I can't be bothered to debug.</p>\n\n<p>Changing the masterpage to ~masterurl/default.master, I uploaded foo.aspx to the Shared Documents library, and it works fine from there too -- both the WebControl and the WebPart behave properly, and the security problem is gone too.</p>\n\n<p>So I'm at a loss. Although I did notice this page with an obscure might-be-bug which is also in SPFolder.get_ContentTypeOrder(): <a href=\"http://forums.msdn.microsoft.com/en-US/sharepointdevelopment/thread/63baf273-7f36-453e-8293-26417759e2e1/\" rel=\"nofollow noreferrer\">http://forums.msdn.microsoft.com/en-US/sharepointdevelopment/thread/63baf273-7f36-453e-8293-26417759e2e1/</a></p>\n\n<p>Any chance you could post your code?</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360/"
] | I want to use the MultipleLookupField control in a web page that will run in the context of SharePoint. I was wondering if anyone would help me with an example, which shows step by step how to use the control two display two SPField Collections. | I'm not entirely sure I understand your question, especially the bit about displaying two SPField collections. Sorry if this turns out to be the answer to a completely different question!
Anyway here's a quick demo walkthrough of using the MultipleLookupField in a web part.
Create a team site. Add a few tasks to the task list. Also put a document in the Shared Documents library. Create a new column in the Shared Documents library; call it "Related", have it be a Lookup into the Title field of the Tasks list, and allow multiple values.
Now create a web part, do all the usual boilerplate and then add this:
```
Label l;
MultipleLookupField mlf;
protected override void CreateChildControls()
{
base.CreateChildControls();
SPList list = SPContext.Current.Web.Lists["Shared Documents"];
if (list != null && list.Items.Count > 0)
{
LiteralControl lit = new LiteralControl("Associate tasks to " +
list.Items[0].Name);
this.Controls.Add(lit);
mlf = new MultipleLookupField();
mlf.ControlMode = SPControlMode.Edit;
mlf.FieldName = "Related";
mlf.ItemId = list.Items[0].ID;
mlf.ListId = list.ID;
mlf.ID = "Related";
this.Controls.Add(mlf);
Button b = new Button();
b.Text = "Change";
b.Click += new EventHandler(bClick);
this.Controls.Add(b);
l = new Label();
this.Controls.Add(l);
}
}
void bClick(object sender, EventArgs e)
{
l.Text = "";
foreach (SPFieldLookupValue val in (SPFieldLookupValueCollection)mlf.Value)
{
l.Text += val.LookupValue.ToString() + " ";
}
SPListItem listitem = mlf.List.Items[0];
listitem["Related"] = mlf.Value;
listitem.Update();
mlf.Value = listitem["Related"];
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
EnsureChildControls();
}
```
Granted, this is borderline ridiculous -- everything is hard-coded, there is no error-handling at all, and it serves no useful purpose -- but it's only meant as a quick demo. Now build and deploy this web part and add an instance of it to your team site's homepage; it should allow you to get and set the tasks which are associated with the first document in the library.
The strange bit towards the end of the button Click handler, where we read a value from mlf.Value and then write it back again, appears to be required if you want the UI to stay in sync with the actual list values. Try omitting the last line of bClick to see what I mean. This has been driving me nuts for the last hour or so, and I'm hoping another commenter can come up with a better approach... |
39,912 | <p>I was looking at the API documentation for stl vector, and noticed there was no method on the vector class that allowed the removal of an element with a certain value. This seems like a common operation, and it seems odd that there's no built in way to do this.</p>
| [
{
"answer_id": 39923,
"author": "bradtgmurray",
"author_id": 1546,
"author_profile": "https://Stackoverflow.com/users/1546",
"pm_score": 4,
"selected": false,
"text": "<p>Use the global method std::remove with the begin and end iterator, and then use std::vector.erase to actually remove the elements.</p>\n\n<p>Documentation links<br>\nstd::remove <a href=\"http://www.cppreference.com/cppalgorithm/remove.html\" rel=\"noreferrer\">http://www.cppreference.com/cppalgorithm/remove.html</a><br>\nstd::vector.erase <a href=\"http://www.cppreference.com/cppvector/erase.html\" rel=\"noreferrer\">http://www.cppreference.com/cppvector/erase.html</a></p>\n\n<pre><code>std::vector<int> v;\nv.push_back(1);\nv.push_back(2);\n\n//Vector should contain the elements 1, 2\n\n//Find new end iterator\nstd::vector<int>::iterator newEnd = std::remove(v.begin(), v.end(), 1);\n\n//Erase the \"removed\" elements.\nv.erase(newEnd, v.end());\n\n//Vector should now only contain 2\n</code></pre>\n\n<p>Thanks to Jim Buck for pointing out my error.</p>\n"
},
{
"answer_id": 39941,
"author": "Xavier Nodet",
"author_id": 4177,
"author_profile": "https://Stackoverflow.com/users/4177",
"pm_score": 2,
"selected": false,
"text": "<p>See also <a href=\"https://en.cppreference.com/w/cpp/algorithm/remove\" rel=\"nofollow noreferrer\">std::remove_if</a> to be able to use a predicate...</p>\n\n<p>Here's the example from the link above:</p>\n\n<pre><code>vector<int> V;\nV.push_back(1);\nV.push_back(4);\nV.push_back(2);\nV.push_back(8);\nV.push_back(5);\nV.push_back(7);\n\ncopy(V.begin(), V.end(), ostream_iterator<int>(cout, \" \"));\n // The output is \"1 4 2 8 5 7\"\n\nvector<int>::iterator new_end = \n remove_if(V.begin(), V.end(), \n compose1(bind2nd(equal_to<int>(), 0),\n bind2nd(modulus<int>(), 2)));\nV.erase(new_end, V.end()); [1]\n\ncopy(V.begin(), V.end(), ostream_iterator<int>(cout, \" \"));\n // The output is \"1 5 7\".\n</code></pre>\n"
},
{
"answer_id": 39944,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 9,
"selected": true,
"text": "<p><code>std::remove</code> does not actually erase elements from the container: it moves the elements to be removed to the end of the container, and returns the new end iterator which can be passed to <code>container_type::erase</code> to do the actual removal of the extra elements that are now at the end of the container:</p>\n<pre><code>std::vector<int> vec;\n// .. put in some values ..\nint int_to_remove = n;\nvec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());\n</code></pre>\n"
},
{
"answer_id": 39985,
"author": "nsanders",
"author_id": 1244,
"author_profile": "https://Stackoverflow.com/users/1244",
"pm_score": 3,
"selected": false,
"text": "<p>If you have an unsorted vector, then you can simply swap with the last vector element then <code>resize()</code>.</p>\n\n<p>With an ordered container, you'll be best off with <code>std::vector::erase()</code>. Note that there is a <code>std::remove()</code> defined in <code><algorithm></code>, but that doesn't actually do the erasing. (Read the documentation carefully).</p>\n"
},
{
"answer_id": 40008,
"author": "Luke Halliwell",
"author_id": 3974,
"author_profile": "https://Stackoverflow.com/users/3974",
"pm_score": 3,
"selected": false,
"text": "<p>The other answers cover how to do this well, but I thought I'd also point out that it's not really odd that this isn't in the vector API: it's inefficient, linear search through the vector for the value, followed by a bunch of copying to remove it.</p>\n\n<p>If you're doing this operation intensively, it can be worth considering std::set instead for this reason.</p>\n"
},
{
"answer_id": 15998752,
"author": "Etherealone",
"author_id": 1576556,
"author_profile": "https://Stackoverflow.com/users/1576556",
"pm_score": 6,
"selected": false,
"text": "<p>If you want to remove <strong><em>an</em></strong> item, the following will be a bit more efficient.</p>\n\n<pre><code>std::vector<int> v;\n\n\nauto it = std::find(v.begin(), v.end(), 5);\nif(it != v.end())\n v.erase(it);\n</code></pre>\n\n<p>or you may avoid overhead of moving the items if the order does not matter to you:</p>\n\n<pre><code>std::vector<int> v;\n\nauto it = std::find(v.begin(), v.end(), 5);\n\nif (it != v.end()) {\n using std::swap;\n\n // swap the one to be removed with the last element\n // and remove the item at the end of the container\n // to prevent moving all items after '5' by one\n swap(*it, v.back());\n v.pop_back();\n}\n</code></pre>\n"
},
{
"answer_id": 45186119,
"author": "jhasse",
"author_id": 647898,
"author_profile": "https://Stackoverflow.com/users/647898",
"pm_score": 2,
"selected": false,
"text": "<p>A shorter solution (which doesn't force you to repeat the vector name 4 times) would be to use Boost:</p>\n\n<pre><code>#include <boost/range/algorithm_ext/erase.hpp>\n\n// ...\n\nboost::remove_erase(vec, int_to_remove);\n</code></pre>\n\n<p>See <a href=\"http://www.boost.org/doc/libs/1_64_0/libs/range/doc/html/range/reference/algorithms/new/remove_erase.html\" rel=\"nofollow noreferrer\">http://www.boost.org/doc/libs/1_64_0/libs/range/doc/html/range/reference/algorithms/new/remove_erase.html</a></p>\n"
},
{
"answer_id": 47603631,
"author": "Katianie",
"author_id": 389832,
"author_profile": "https://Stackoverflow.com/users/389832",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to do it without any extra includes: </p>\n\n<pre><code>vector<IComponent*> myComponents; //assume it has items in it already.\nvoid RemoveComponent(IComponent* componentToRemove)\n{\n IComponent* juggler;\n\n if (componentToRemove != NULL)\n {\n for (int currComponentIndex = 0; currComponentIndex < myComponents.size(); currComponentIndex++)\n {\n if (componentToRemove == myComponents[currComponentIndex])\n {\n //Since we don't care about order, swap with the last element, then delete it.\n juggler = myComponents[currComponentIndex];\n myComponents[currComponentIndex] = myComponents[myComponents.size() - 1];\n myComponents[myComponents.size() - 1] = juggler;\n\n //Remove it from memory and let the vector know too.\n myComponents.pop_back();\n delete juggler;\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 52623923,
"author": "DecPK",
"author_id": 9153448,
"author_profile": "https://Stackoverflow.com/users/9153448",
"pm_score": 0,
"selected": false,
"text": "<p>Two ways are there by which you can use to erase an item particularly. \nlets take a vector</p>\n\n<pre><code>std :: vector < int > v;\nv.push_back(10);\nv.push_back(20);\nv.push_back(30);\nv.push_back(40);\nv.push_back(40);\nv.push_back(50);\n</code></pre>\n\n<p><strong>1) Non efficient way :</strong> Although it seems to be quite efficient but it's not because erase function delets the elements and shifts all the elements towards left by 1. \n<strong>so its complexity will be O(n^2)</strong></p>\n\n<pre><code>std :: vector < int > :: iterator itr = v.begin();\nint value = 40;\nwhile ( itr != v.end() )\n{\n if(*itr == value)\n { \n v.erase(itr);\n }\n else\n ++itr;\n}\n</code></pre>\n\n<p><strong>2) Efficient way ( RECOMMENDED )</strong> : It is also known as <strong><em>ERASE - REMOVE idioms</em></strong> . </p>\n\n<ul>\n<li>std::remove transforms the given range into a range with all the elements that compare not equal to given element shifted to the start of the container.</li>\n<li>So, actually don't remove the matched elements.\nIt just shifted the non matched to starting and gives an iterator to new valid end.\nIt just requires O(n) complexity.</li>\n</ul>\n\n<p>output of the remove algorithm is : </p>\n\n<pre><code>10 20 30 50 40 50 \n</code></pre>\n\n<p>as return type of remove is iterator to the new end of that range.</p>\n\n<pre><code>template <class ForwardIterator, class T>\n ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);\n</code></pre>\n\n<p>Now use vector’s erase function to delete elements from the new end to old end of the vector. It requires O(1) time.</p>\n\n<pre><code>v.erase ( std :: remove (v.begin() , v.end() , element ) , v.end () );\n</code></pre>\n\n<p><strong>so this method work in O(n)</strong></p>\n"
},
{
"answer_id": 56157255,
"author": "Pavan Chandaka",
"author_id": 6866309,
"author_profile": "https://Stackoverflow.com/users/6866309",
"pm_score": 3,
"selected": false,
"text": "<p>From <strong>c++20</strong>:</p>\n\n<p>A non-member function introduced <code>std::erase</code>, which takes the vector and value to be removed as inputs.</p>\n\n<p>ex:</p>\n\n<pre><code>std::vector<int> v = {90,80,70,60,50};\nstd::erase(v,50);\n</code></pre>\n"
},
{
"answer_id": 61587400,
"author": "Harshad Sharma",
"author_id": 9060084,
"author_profile": "https://Stackoverflow.com/users/9060084",
"pm_score": 2,
"selected": false,
"text": "<p>*</p>\n\n<blockquote>\n <p>C++ community has heard your request :)</p>\n</blockquote>\n\n<p>*</p>\n\n<p><strong>C++ 20</strong> provides an easy way of doing it now. \nIt gets as simple as :</p>\n\n<pre><code>#include <vector>\n...\nvector<int> cnt{5, 0, 2, 8, 0, 7};\nstd::erase(cnt, 0);\n</code></pre>\n\n<p>You should check out <a href=\"https://en.cppreference.com/w/cpp/container/vector/erase2\" rel=\"nofollow noreferrer\">std::erase</a> and <a href=\"https://en.cppreference.com/w/cpp/container/vector/erase2\" rel=\"nofollow noreferrer\">std::erase_if</a>.</p>\n\n<p>Not only will it remove all elements of the value (here '0'), it will do it in <strong><em>O(n)</em></strong> time complexity. Which is the very best you can get.</p>\n\n<p>If your compiler does not support C++ 20, you should use <a href=\"https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom\" rel=\"nofollow noreferrer\">erase-remove idiom</a>:</p>\n\n<pre><code>#include <algorithm>\n...\nvec.erase(std::remove(vec.begin(), vec.end(), 0), vec.end());\n</code></pre>\n"
},
{
"answer_id": 72653247,
"author": "Antonio",
"author_id": 2436175,
"author_profile": "https://Stackoverflow.com/users/2436175",
"pm_score": 0,
"selected": false,
"text": "<p>Similar to the <a href=\"https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom\" rel=\"nofollow noreferrer\">erase remove idiom</a>, for <code>vector</code> one could use <code>resize</code> and <code>remove</code> and use iterator distance computation:</p>\n<pre><code>std::vector<int> vec;\n// .. put in some values ..\nint int_to_remove = n;\nvec.resize(std::remove(vec.begin(), vec.end(), int_to_remove) - vec.begin());\n</code></pre>\n<p>Tested <a href=\"https://coliru.stacked-crooked.com/a/a54995654e909f79\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1546/"
] | I was looking at the API documentation for stl vector, and noticed there was no method on the vector class that allowed the removal of an element with a certain value. This seems like a common operation, and it seems odd that there's no built in way to do this. | `std::remove` does not actually erase elements from the container: it moves the elements to be removed to the end of the container, and returns the new end iterator which can be passed to `container_type::erase` to do the actual removal of the extra elements that are now at the end of the container:
```
std::vector<int> vec;
// .. put in some values ..
int int_to_remove = n;
vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());
``` |
39,916 | <p>Is there a programmatic way to build <em>htpasswd</em> files, without depending on OS specific functions (i.e. <code>exec()</code>, <code>passthru()</code>)?</p>
| [
{
"answer_id": 39935,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"http://trac.edgewall.org\" rel=\"nofollow noreferrer\">Trac</a> ships with a Python replacement for htpasswd, which I'm sure you could port to your language of choice: <a href=\"http://trac.edgewall.org/browser/trunk/contrib/htpasswd.py\" rel=\"nofollow noreferrer\">htpasswd.py</a>.</p>\n"
},
{
"answer_id": 39963,
"author": "Greg Roberts",
"author_id": 4269,
"author_profile": "https://Stackoverflow.com/users/4269",
"pm_score": 6,
"selected": true,
"text": "<p>.httpasswd files are just text files with a specific format depending on the hash function specified. If you are using MD5 they look like this:</p>\n\n<pre><code>foo:$apr1$y1cXxW5l$3vapv2yyCXaYz8zGoXj241\n</code></pre>\n\n<p>That's the login, a colon, ,$apr1$, the salt and 1000 times md5 encoded as base64. If you select SHA1 they look like this:</p>\n\n<pre><code>foo:{SHA}BW6v589SIg3i3zaEW47RcMZ+I+M=\n</code></pre>\n\n<p>That's the login, a colon, the string {SHA} and the SHA1 hash encoded with base64.</p>\n\n<p>If your language has an implementation of either MD5 or SHA1 and base64 you can just create the file like this:</p>\n\n<pre><code><?php\n\n$login = 'foo';\n$pass = 'pass';\n$hash = base64_encode(sha1($pass, true));\n\n$contents = $login . ':{SHA}' . $hash;\n\nfile_put_contents('.htpasswd', $contents);\n\n?>\n</code></pre>\n\n<p>Here's more information on the format:</p>\n\n<p><a href=\"http://httpd.apache.org/docs/2.2/misc/password_encryptions.html\" rel=\"noreferrer\">http://httpd.apache.org/docs/2.2/misc/password_encryptions.html</a></p>\n"
},
{
"answer_id": 53006,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": -1,
"selected": false,
"text": "<p>From what it says on the PHP website, you can use crypt() in the following method:</p>\n\n<pre><code><?php\n\n// Set the password & username\n$username = 'user';\n$password = 'mypassword';\n\n// Get the hash, letting the salt be automatically generated\n$hash = crypt($password);\n\n// write to a file\nfile_set_contents('.htpasswd', $username ':' . $contents);\n\n?>\n</code></pre>\n\n<p>Part of this example can be found: <a href=\"http://ca3.php.net/crypt\" rel=\"nofollow noreferrer\">http://ca3.php.net/crypt</a></p>\n\n<p>This will of course overwrite the entire existing file, so you'll want to do some kind of concatination.</p>\n\n<p>I'm not 100% sure this will work, but I'm pretty sure.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] | Is there a programmatic way to build *htpasswd* files, without depending on OS specific functions (i.e. `exec()`, `passthru()`)? | .httpasswd files are just text files with a specific format depending on the hash function specified. If you are using MD5 they look like this:
```
foo:$apr1$y1cXxW5l$3vapv2yyCXaYz8zGoXj241
```
That's the login, a colon, ,$apr1$, the salt and 1000 times md5 encoded as base64. If you select SHA1 they look like this:
```
foo:{SHA}BW6v589SIg3i3zaEW47RcMZ+I+M=
```
That's the login, a colon, the string {SHA} and the SHA1 hash encoded with base64.
If your language has an implementation of either MD5 or SHA1 and base64 you can just create the file like this:
```
<?php
$login = 'foo';
$pass = 'pass';
$hash = base64_encode(sha1($pass, true));
$contents = $login . ':{SHA}' . $hash;
file_put_contents('.htpasswd', $contents);
?>
```
Here's more information on the format:
<http://httpd.apache.org/docs/2.2/misc/password_encryptions.html> |
39,928 | <p>I'm getting a <strong><code>Connection Busy With Results From Another Command</code></strong> error from a SQLServer Native Client driver when a SSIS package is running. Only when talking to SQLServer 2000. A different part that talks to SQLServer 2005 seems to always run fine. Any thoughts?</p>
| [
{
"answer_id": 40105,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"http://support.microsoft.com/kb/822668\" rel=\"nofollow noreferrer\">Microsoft KB article 822668</a> is relevant here:</p>\n\n<blockquote>\n <h2>FIX: \"Connection is busy with results for another command\" error message occurs when you run a linked server query</h2>\n \n <h3>Symptoms</h3>\n \n <p>Under stress conditions, you may receive the following error message when you perform linked server activity:</p>\n\n<pre><code>Server: Msg 7399, Level 16, State 1, Procedure <storedProcedureName>, Line 18 OLE DB provider 'SQLOLEDB' reported an error. \nOLE/DB Provider 'SQLOLEDB' ::GetSchemaLock returned 0x80004005:\n\nOLE DB provider SQLOLEDB supported the Schema Lock interface, but returned 0x80004005 for GetSchemaLock .]. \nOLE/DB provider returned message: Connection is busy with results for another command \nOLE DB error trace [OLE/DB Provider 'SQLOLEDB' ::CreateSession returned 0x80004005.\n</code></pre>\n \n <p><strong>Note</strong> The OLE DB source of the error may vary. However, all variations of the error message include the text \"Connection is busy with results for another command\".</p>\n \n <h3>Resolution</h3>\n \n <p>To resolve this problem, obtain the latest service pack for Microsoft SQL Server 2000.</p>\n</blockquote>\n\n<p>As noted there, the problem was first corrected in SQL Server 2000 Service Pack 4.</p>\n\n<p><a href=\"https://web.archive.org/web/20071124140051/http://bisqlserver.blogspot.com/2007/02/issues-transferring-data-back-and-forth.html\" rel=\"nofollow noreferrer\">This blog post</a> by Mark Meyerovich, a Senior Software Engineer at RDA Corp, also provides some insight (now archived, because the original link went dead):</p>\n\n<blockquote>\n <p><strong>SQL Server service pack upgrade</strong></p>\n \n <p>A quick search on Google turns up the following article (<a href=\"http://support.microsoft.com/kb/822668\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/822668</a>):\n FIX: \"Connection is busy with results for another command\" error message occurs when you run a linked server query.</p>\n \n <p>It basically implies the issue is a bug and recommends an upgrade to Service Pack 4. We have started out with SQL Server 2000 SP3 and we do have some linked servers in the equation, so we give it a try. After the upgrade to SP4 – same result.</p>\n</blockquote>\n"
},
{
"answer_id": 2173947,
"author": "Dave Markle",
"author_id": 24995,
"author_profile": "https://Stackoverflow.com/users/24995",
"pm_score": 4,
"selected": false,
"text": "<p>As I just found out, this can also happen on SQL 2005 if you do not have MARS enabled. I never even knew that it was disabled by default, but it is. And make sure you are using the \n\"NATIVE OLEDB\\SQL Native Client\" connection type. If you're using the \"OLEDB.1\" type connection (or whatever...) MARS is not even an option, and you get the SQL 2000 behavior, which is nasty. </p>\n\n<p>You can enable MARS by opening the connection properties, and clicking \"All\", and scolling down in Management Studio.</p>\n\n<p>I know your question has long since been answered, but I'm just throwing this in for the next sucker like me who gets burned by this.</p>\n"
},
{
"answer_id": 17923000,
"author": "OZ_",
"author_id": 680786,
"author_profile": "https://Stackoverflow.com/users/680786",
"pm_score": 2,
"selected": false,
"text": "<p>If somebody met this annoying bug while using PHP PDO with ODBC, then use <code>closeCursor()</code> method after query execution.</p>\n"
},
{
"answer_id": 28130401,
"author": "smozgur",
"author_id": 3115000,
"author_profile": "https://Stackoverflow.com/users/3115000",
"pm_score": 3,
"selected": false,
"text": "<p>Had this error today with MS ODBC Driver 11 for SQL Server for Linux to SQL Server connection. Wanted to help next searcher considering this was the first Google search result when I made the search.</p>\n\n<p>You need to set MARS_Connection in /etc/odbc.ini as following:</p>\n\n<pre><code>[ConnName]\nDriver=ODBC Driver 11 for SQL Server\nServer=192.168.2.218,1433\nDatabase=DBNameHere\nMARS_Connection=yes\n</code></pre>\n\n<p>Speaking of MS ODBC Linux Driver: It is a complete PITA to deal with it but I insisted using native solution. I experienced too many walls especially working with ZF2, however, every trouble has a solution with the driver I can say. Just to encourage people using it instead quickly give up. </p>\n"
},
{
"answer_id": 43854950,
"author": "marcob",
"author_id": 7982355,
"author_profile": "https://Stackoverflow.com/users/7982355",
"pm_score": 0,
"selected": false,
"text": "<p>Just for information if somebody else have the problem. I tried connecting via NetCobol of Fujitsu on an SQLEXPRESS via ODBC with embedded sql and to solve the problem I had to change a value in the registry namely </p>\n\n<pre><code>\\HKLM\\Software\\ODBC\\ODBC.INI\\MyDSN\n</code></pre>\n\n<p>with MyDSN as a string value:</p>\n\n<pre><code>Name - MARS_Connection\nValue - Yes\n</code></pre>\n\n<p>I just put the information here if it can help.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2978/"
] | I'm getting a **`Connection Busy With Results From Another Command`** error from a SQLServer Native Client driver when a SSIS package is running. Only when talking to SQLServer 2000. A different part that talks to SQLServer 2005 seems to always run fine. Any thoughts? | [Microsoft KB article 822668](http://support.microsoft.com/kb/822668) is relevant here:
>
> FIX: "Connection is busy with results for another command" error message occurs when you run a linked server query
> ------------------------------------------------------------------------------------------------------------------
>
>
> ### Symptoms
>
>
> Under stress conditions, you may receive the following error message when you perform linked server activity:
>
>
>
> ```
> Server: Msg 7399, Level 16, State 1, Procedure <storedProcedureName>, Line 18 OLE DB provider 'SQLOLEDB' reported an error.
> OLE/DB Provider 'SQLOLEDB' ::GetSchemaLock returned 0x80004005:
>
> OLE DB provider SQLOLEDB supported the Schema Lock interface, but returned 0x80004005 for GetSchemaLock .].
> OLE/DB provider returned message: Connection is busy with results for another command
> OLE DB error trace [OLE/DB Provider 'SQLOLEDB' ::CreateSession returned 0x80004005.
>
> ```
>
> **Note** The OLE DB source of the error may vary. However, all variations of the error message include the text "Connection is busy with results for another command".
>
>
> ### Resolution
>
>
> To resolve this problem, obtain the latest service pack for Microsoft SQL Server 2000.
>
>
>
As noted there, the problem was first corrected in SQL Server 2000 Service Pack 4.
[This blog post](https://web.archive.org/web/20071124140051/http://bisqlserver.blogspot.com/2007/02/issues-transferring-data-back-and-forth.html) by Mark Meyerovich, a Senior Software Engineer at RDA Corp, also provides some insight (now archived, because the original link went dead):
>
> **SQL Server service pack upgrade**
>
>
> A quick search on Google turns up the following article (<http://support.microsoft.com/kb/822668>):
> FIX: "Connection is busy with results for another command" error message occurs when you run a linked server query.
>
>
> It basically implies the issue is a bug and recommends an upgrade to Service Pack 4. We have started out with SQL Server 2000 SP3 and we do have some linked servers in the equation, so we give it a try. After the upgrade to SP4 – same result.
>
>
> |
39,960 | <p>In Python one can get a dictionary of all local and global variables in the current scope with the built-in functions <code>locals()</code> and <code>globals()</code>. Is there some equivalent way of doing this in Javascript? For instance, I would like to do something like the following:</p>
<pre><code>var foo = function(){ alert('foo'); };
var bar = function(){ alert('bar'); };
var s = 'foo';
locals()[s](); // alerts 'foo'
</code></pre>
<p>Is this at all possible, or should I just be using a local object for the lookup?</p>
| [
{
"answer_id": 39982,
"author": "Bartosz Bierkowski",
"author_id": 3666,
"author_profile": "https://Stackoverflow.com/users/3666",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I don't think that there is something like that in js. You can always use eval instead of locals(). Like this: </p>\n\n<pre><code>eval(s+\"()\");\n</code></pre>\n\n<p>You just have to know that actually function <em>foo</em> exists.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Don't use eval:) Use:</p>\n\n<pre><code>var functionName=\"myFunctionName\";\nwindow[functionName]();\n</code></pre>\n"
},
{
"answer_id": 39992,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": -1,
"selected": false,
"text": "<p>AFAIK, no. If you just want to check the existence of a given variable, you can do it by testing for it, something like this:</p>\n\n<pre><code>if (foo) foo();\n</code></pre>\n"
},
{
"answer_id": 40012,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 2,
"selected": false,
"text": "<p>I seem to remember Brendan Eich commented on this in a recent podcast; if i recall correctly, it's not being considered, as it adds unreasonable restrictions to optimization. He compared it to the <code>arguments</code> local in that, while useful for varargs, its very existence removes the ability to guess at what a function will touch just by looking at its definition. </p>\n\n<p>BTW: i believe JS <em>did</em> have support for accessing locals through the arguments local at one time - <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Functions/arguments\" rel=\"nofollow noreferrer\">a quick search</a> shows this has been deprecated though.</p>\n"
},
{
"answer_id": 40035,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 0,
"selected": false,
"text": "<p>@e-bartek, I think that window[functionName] won't work if you in some closure, and the function name is local to that closure. For example:</p>\n\n<pre><code>function foo() {\n var bar = function () {\n alert('hello world');\n };\n var s = 'bar';\n window[s](); // this won't work\n}\n</code></pre>\n\n<p>In this case, s is 'bar', but the function 'bar' only exists inside the scope of the function 'foo'. It is not defined in the window scope.</p>\n\n<p>Of course, this doesn't really answer the original question, I just wanted to chime in on this response. I don't believe there is a way to do what the original question asked.</p>\n"
},
{
"answer_id": 40067,
"author": "Bartosz Bierkowski",
"author_id": 3666,
"author_profile": "https://Stackoverflow.com/users/3666",
"pm_score": 0,
"selected": false,
"text": "<p>@pkaeding</p>\n\n<p>Yes, you're right. <em>window[functionName]()</em> doesn't work in this case, but <em>eval</em> does. If I needed something like this, I'd create my own object to keep those functions together.</p>\n\n<pre><code>var func = {};\nfunc.bar = ...;\nvar s = \"bar\";\nfunc[s]();\n</code></pre>\n"
},
{
"answer_id": 40173,
"author": "sverrejoh",
"author_id": 473,
"author_profile": "https://Stackoverflow.com/users/473",
"pm_score": 5,
"selected": true,
"text": "<ul>\n<li><p>locals() - No. </p></li>\n<li><p>globals() - Yes.</p></li>\n</ul>\n\n<p><code>window</code> is a reference to the global scope, like <code>globals()</code> in python.</p>\n\n<pre><code>globals()[\"foo\"]\n</code></pre>\n\n<p>is the same as:</p>\n\n<pre><code>window[\"foo\"]\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/208/"
] | In Python one can get a dictionary of all local and global variables in the current scope with the built-in functions `locals()` and `globals()`. Is there some equivalent way of doing this in Javascript? For instance, I would like to do something like the following:
```
var foo = function(){ alert('foo'); };
var bar = function(){ alert('bar'); };
var s = 'foo';
locals()[s](); // alerts 'foo'
```
Is this at all possible, or should I just be using a local object for the lookup? | * locals() - No.
* globals() - Yes.
`window` is a reference to the global scope, like `globals()` in python.
```
globals()["foo"]
```
is the same as:
```
window["foo"]
``` |
40,022 | <p>I'm using LINQ to SQL classes in a project where the database design is still in a bit of flux.</p>
<p>Is there an easy way of synchronising the classes with the schema, or do I need to manually update the classes if a table design changes?</p>
| [
{
"answer_id": 40027,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 2,
"selected": false,
"text": "<p>I think Jeff complained about this recently. One common technique is to drag all the objects into the designer again...</p>\n\n<p>I hope someone else chimes in with a better approach!</p>\n"
},
{
"answer_id": 40029,
"author": "vzczc",
"author_id": 224,
"author_profile": "https://Stackoverflow.com/users/224",
"pm_score": 7,
"selected": true,
"text": "<p>You can use SQLMetal.exe to generate your dbml and or cs/vb file. Use a pre-build script to start it and target the directory where your datacontext project belongs. </p>\n\n<pre><code>C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\Bin\\x64\\sqlmetal.exe \n /server:<SERVER> \n /database:<database> \n /code:\"path\\Solution\\DataContextProject\\dbContext.cs\" \n /language:csharp \n /namespace:<your namespace>\n</code></pre>\n"
},
{
"answer_id": 40034,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 4,
"selected": false,
"text": "<p>I haven't tried it myself, but <a href=\"http://www.huagati.com/dbmltools/\" rel=\"nofollow noreferrer\">Huagati DBML/EDMX Tools</a> is recommended by other people.</p>\n\n<blockquote>\n <p>Huagati DBML/EDMX Tools is an add-in\n for Visual Studio that adds\n functionality to the Linq2SQL/DBML\n diagram designer in Visual Studio\n 2008, and to the ADO.NET Entity\n Framework designer in Visual Studio\n 2008 SP1. The add-in adds new menu\n options for updating Linq2SQL designer\n diagrams with database changes, for\n renaming Linq-to-SQL (DBML) and EF\n (EDMX) classes and properties to use\n .net naming conventions, and for\n adding documentation/descriptions to\n Linq-to-SQL generated classes from the\n database properties.</p>\n</blockquote>\n\n<p><img src=\"https://i.stack.imgur.com/ZUC8r.png\" alt=\"Screenshot of DBML Tools\"></p>\n"
},
{
"answer_id": 221749,
"author": "Rory Becker",
"author_id": 11356,
"author_profile": "https://Stackoverflow.com/users/11356",
"pm_score": 3,
"selected": false,
"text": "<p>DamienG has written some <a href=\"http://damieng.com/blog/2008/07/23/linq-to-sql-t4-template-reloaded\" rel=\"noreferrer\">t4 templates</a> which can replace some of what VS generates for you. These can be rerun whenever you like via a command line tool. </p>\n\n<p>T4 templates have the added benefit of being editable. This allows you to tweak what is generated to you hearts content.</p>\n"
},
{
"answer_id": 326368,
"author": "mcintyre321",
"author_id": 2086,
"author_profile": "https://Stackoverflow.com/users/2086",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote a tool to do script changes to Dbml scripts see <a href=\"http://code.google.com/p/linqtodbmlrunner/\" rel=\"nofollow noreferrer\">http://code.google.com/p/linqtodbmlrunner/</a> and my blog <a href=\"http://www.adverseconditionals.com\" rel=\"nofollow noreferrer\">http://www.adverseconditionals.com</a></p>\n"
},
{
"answer_id": 21531735,
"author": "Levite",
"author_id": 1680919,
"author_profile": "https://Stackoverflow.com/users/1680919",
"pm_score": 3,
"selected": false,
"text": "<p>Here is an easy fix without any additional software, that just works for simple changes (like added fields, few tables, etc).</p>\n\n<h3>Instructions:</h3>\n\n<ul>\n<li>You pull a copy of the changed table into the designer (will be removed later)</li>\n<li>Now select all the new (or changed) fields and (<code>right-click -></code>) <code>copy</code></li>\n<li>In your original table right click and <code>insert</code> them (delete changed fields first)</li>\n<li>Now delete the table you copied them from</li>\n</ul>\n\n<p>I know it is kinda obvious, but somehow non-intuitive, and it helped me a lot, since all the right attributes and types will be copied, and all links stay intact. Hope it helps.</p>\n\n<h3>When to use:</h3>\n\n<p>Of course it is - as said - for small changes, but surely better than manually replacing tables with many links, or when you don't want your whole database structure generated by SQLMetal. For example when you have a big amount of tables (e.g. SAP), or when using cross-linked tables from different databases.</p>\n"
},
{
"answer_id": 44769612,
"author": "Dean",
"author_id": 3274152,
"author_profile": "https://Stackoverflow.com/users/3274152",
"pm_score": 0,
"selected": false,
"text": "<p>How about modifying the Properties of the entity/table within the DataContext design surface within Visual Studio?</p>\n\n<p>For instance if I added a column to an SQL Server table:</p>\n\n<ol>\n<li>Open the *.dbml file.</li>\n<li>Right click the entity and select Add > Property.</li>\n<li>Fill out the values in the Properties window for the new column.</li>\n<li>Build your solution.</li>\n</ol>\n\n<p>The auto generated model classes should reflect the new column that was added.</p>\n\n<p><a href=\"https://i.stack.imgur.com/S2Ixq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/S2Ixq.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/PMtq9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PMtq9.png\" alt=\"enter image description here\"></a></p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4048/"
] | I'm using LINQ to SQL classes in a project where the database design is still in a bit of flux.
Is there an easy way of synchronising the classes with the schema, or do I need to manually update the classes if a table design changes? | You can use SQLMetal.exe to generate your dbml and or cs/vb file. Use a pre-build script to start it and target the directory where your datacontext project belongs.
```
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\x64\sqlmetal.exe
/server:<SERVER>
/database:<database>
/code:"path\Solution\DataContextProject\dbContext.cs"
/language:csharp
/namespace:<your namespace>
``` |
40,028 | <p>I think it can be done by applying the transformation matrix of the scenegraph to z-normal (0, 0, 1), but it doesn't work. My code goes like this:</p>
<pre><code>Vector3f toScreenVector = new Vector3f(0, 0, 1);
Transform3D t3d = new Transform3D();
tg.getTransform(t3d); //tg is Transform Group of all objects in a scene
t3d.transform(toScreenVector);
</code></pre>
<p>Then I tried something like this too:</p>
<pre><code>Point3d eyePos = new Point3d();
Point3d mousePos = new Point3d();
canvas.getCenterEyeInImagePlate(eyePos);
canvas.getPixelLocationInImagePlate(new Point2d(Main.WIDTH/2, Main.HEIGHT/2), mousePos); //Main is the class for main window.
Transform3D motion = new Transform3D();
canvas.getImagePlateToVworld(motion);
motion.transform(eyePos);
motion.transform(mousePos);
Vector3d toScreenVector = new Vector3f(eyePos);
toScreenVector.sub(mousePos);
toScreenVector.normalize();
</code></pre>
<p>But still this doesn't work correctly. I think there must be an easy way to create such vector. Do you know what's wrong with my code or better way to do so?</p>
| [
{
"answer_id": 40666,
"author": "caramelcarrot",
"author_id": 3877,
"author_profile": "https://Stackoverflow.com/users/3877",
"pm_score": 2,
"selected": false,
"text": "<p>If I get this right, you want a vector that is normal to the screen plane, but in world coordinates?</p>\n\n<p>In that case you want to <code>INVERT</code> the transformation from <code>World -> Screen and do Screen -> World</code> of <code>(0,0,-1)</code> or <code>(0,0,1)</code> depending on which axis the screen points down.</p>\n\n<p>Since the ModelView matrix is just a rotation matrix (ignoring the homogeneous transformation part), you can simply pull this out by taking the transpose of the rotational part, or simple reading in the bottom row - as this transposes onto the <code>Z</code> coordinate column under transposition.</p>\n"
},
{
"answer_id": 41231,
"author": "puri",
"author_id": 3388,
"author_profile": "https://Stackoverflow.com/users/3388",
"pm_score": 1,
"selected": true,
"text": "<p>Yes, you got my question right. Sorry that I was a little bit confused yesterday. Now I have corrected the code by following your suggestion and mixing two pieces of code in the question together:</p>\n\n<pre><code>Vector3f toScreenVector = new Vector3f(0, 0, 1);\n\nTransform3D t3d = new Transform3D();\ncanvas.getImagePlateToVworld(t3d);\nt3d.transform(toScreenVector);\n\ntg.getTransform(t3d); //tg is Transform Group of all objects in a scene\nt3d.transform(toScreenVector);\n</code></pre>\n\n<p>Thank you.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3388/"
] | I think it can be done by applying the transformation matrix of the scenegraph to z-normal (0, 0, 1), but it doesn't work. My code goes like this:
```
Vector3f toScreenVector = new Vector3f(0, 0, 1);
Transform3D t3d = new Transform3D();
tg.getTransform(t3d); //tg is Transform Group of all objects in a scene
t3d.transform(toScreenVector);
```
Then I tried something like this too:
```
Point3d eyePos = new Point3d();
Point3d mousePos = new Point3d();
canvas.getCenterEyeInImagePlate(eyePos);
canvas.getPixelLocationInImagePlate(new Point2d(Main.WIDTH/2, Main.HEIGHT/2), mousePos); //Main is the class for main window.
Transform3D motion = new Transform3D();
canvas.getImagePlateToVworld(motion);
motion.transform(eyePos);
motion.transform(mousePos);
Vector3d toScreenVector = new Vector3f(eyePos);
toScreenVector.sub(mousePos);
toScreenVector.normalize();
```
But still this doesn't work correctly. I think there must be an easy way to create such vector. Do you know what's wrong with my code or better way to do so? | Yes, you got my question right. Sorry that I was a little bit confused yesterday. Now I have corrected the code by following your suggestion and mixing two pieces of code in the question together:
```
Vector3f toScreenVector = new Vector3f(0, 0, 1);
Transform3D t3d = new Transform3D();
canvas.getImagePlateToVworld(t3d);
t3d.transform(toScreenVector);
tg.getTransform(t3d); //tg is Transform Group of all objects in a scene
t3d.transform(toScreenVector);
```
Thank you. |
40,043 | <p>How can I create a new database from my C# application?</p>
<p>I'm assuming once I create it, I can simply generate a connection string on the fly and connect to it, and the issue all the CREATE TABLE statements.</p>
| [
{
"answer_id": 40061,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://support.microsoft.com/kb/307283\" rel=\"noreferrer\">KB307283</a> explains how to create a database using ADO.NET.</p>\n\n<p>From the article:</p>\n\n<pre><code>String str;\nSqlConnection myConn = new SqlConnection (\"Server=localhost;Integrated security=SSPI;database=master\");\n\nstr = \"CREATE DATABASE MyDatabase ON PRIMARY \" +\n \"(NAME = MyDatabase_Data, \" +\n \"FILENAME = 'C:\\\\MyDatabaseData.mdf', \" +\n \"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) \" +\n \"LOG ON (NAME = MyDatabase_Log, \" +\n \"FILENAME = 'C:\\\\MyDatabaseLog.ldf', \" +\n \"SIZE = 1MB, \" +\n \"MAXSIZE = 5MB, \" +\n \"FILEGROWTH = 10%)\";\n\nSqlCommand myCommand = new SqlCommand(str, myConn);\ntry \n{\n myConn.Open();\n myCommand.ExecuteNonQuery();\n MessageBox.Show(\"DataBase is Created Successfully\", \"MyProgram\", MessageBoxButtons.OK, MessageBoxIcon.Information);\n}\ncatch (System.Exception ex)\n{\n MessageBox.Show(ex.ToString(), \"MyProgram\", MessageBoxButtons.OK, MessageBoxIcon.Information);\n}\nfinally\n{\n if (myConn.State == ConnectionState.Open)\n {\n myConn.Close();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 40085,
"author": "Lulu",
"author_id": 4290,
"author_profile": "https://Stackoverflow.com/users/4290",
"pm_score": 1,
"selected": false,
"text": "<p>CREATE DATABASE works</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] | How can I create a new database from my C# application?
I'm assuming once I create it, I can simply generate a connection string on the fly and connect to it, and the issue all the CREATE TABLE statements. | [KB307283](http://support.microsoft.com/kb/307283) explains how to create a database using ADO.NET.
From the article:
```
String str;
SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");
str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\MyDatabaseData.mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\MyDatabaseLog.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
``` |
40,054 | <p>Code below does not run correctly and throws <code>InvalidOperationExcepiton</code>.</p>
<pre><code>public void Foo()
{
DataContext context = new DataContext();
LinqEntity item = new LinqEntity(){ Id = 1, Name = "John", Surname = "Doe"} ;
context.LinqEntities.Attach(item, true);
}
</code></pre>
| [
{
"answer_id": 40079,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure what you mean by disconnected from the database.</p>\n\n<p>It appears that you are trying to insert a new row into the LinqEntities table -- is that correct?</p>\n\n<p>If that is the case you'll want to do</p>\n\n<pre><code>context.LinqEntities.InsertOnSubmit(item);\ncontext.Submit();\n</code></pre>\n"
},
{
"answer_id": 40108,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 1,
"selected": false,
"text": "<p>OK, if you're trying to update a row with ID = 1, you'll do it like this:</p>\n\n<pre><code>DataContext context = new DataContext();\nLinqEntity item = (from le in context.LinqEntities\n where le.ID == 1\n select le).Single();\nitem.Name = \"John\";\nitem.Surname = \"Doe\";\n\ncontext.Submit();\n</code></pre>\n\n<p>You could also replace the Linq expression with a more concise lambda:</p>\n\n<pre><code>LinqEntity item = context.LinqEntities.Single(le => le.ID == 1);\n</code></pre>\n\n<p>The most important thing the DataContext does is track any changes you make, so that when you call the Submit method it will autogenerate the Insert statements for the things you've changed.</p>\n"
},
{
"answer_id": 40208,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 3,
"selected": true,
"text": "<p>By default, the entities will use all fields for checking concurrency when making edits. That's what's throwing the InvalidOperationException.</p>\n\n<p>This can be setting the Update Check property for all fields to Never. This must be done on all fields to attach the entity as modified. If this is done, an additional call to context.SubmitChanges() will save the data.</p>\n\n<p>Alternatively, if you know the original values, you can attach and then make the updates, but all values that are being checked must match the original values.</p>\n\n<pre><code>LinqEntity item = new LinqEntity(){ Id = 1, Name = \"OldName\", Surname = \"OldSurname\"}; \ncontext.LinqEntities.Attach(item);\nitem.Name = \"John\";\nitem.Surname = \"Doe\";\ncontext.SubmitChanges();\n</code></pre>\n"
},
{
"answer_id": 40948,
"author": "liammclennan",
"author_id": 2785,
"author_profile": "https://Stackoverflow.com/users/2785",
"pm_score": 0,
"selected": false,
"text": "<p>When using an ORM you typically select an object before updating it. </p>\n\n<p>You can use <code>DataContext.ExecuteCommand(...)</code> to bypass the ORM if you do not want to do a select. </p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4215/"
] | Code below does not run correctly and throws `InvalidOperationExcepiton`.
```
public void Foo()
{
DataContext context = new DataContext();
LinqEntity item = new LinqEntity(){ Id = 1, Name = "John", Surname = "Doe"} ;
context.LinqEntities.Attach(item, true);
}
``` | By default, the entities will use all fields for checking concurrency when making edits. That's what's throwing the InvalidOperationException.
This can be setting the Update Check property for all fields to Never. This must be done on all fields to attach the entity as modified. If this is done, an additional call to context.SubmitChanges() will save the data.
Alternatively, if you know the original values, you can attach and then make the updates, but all values that are being checked must match the original values.
```
LinqEntity item = new LinqEntity(){ Id = 1, Name = "OldName", Surname = "OldSurname"};
context.LinqEntities.Attach(item);
item.Name = "John";
item.Surname = "Doe";
context.SubmitChanges();
``` |
40,075 | <p>I am writing a few extensions to mimic the map and reduce functions in Lisp.</p>
<pre><code>public delegate R ReduceFunction<T,R>(T t, R previous);
public delegate void TransformFunction<T>(T t, params object[] args);
public static R Reduce<T,R>(this List<T> list, ReduceFunction<T,R> r, R initial)
{
var aggregate = initial;
foreach(var t in list)
aggregate = r(t,aggregate);
return aggregate;
}
public static void Transform<T>(this List<T> list, TransformFunction<T> f, params object [] args)
{
foreach(var t in list)
f(t,args);
}
</code></pre>
<p>The transform function will cut down on cruft like:</p>
<pre><code>foreach(var t in list)
if(conditions && moreconditions)
//do work etc
</code></pre>
<p>Does this make sense? Could it be better?</p>
| [
{
"answer_id": 40084,
"author": "Jake Pearson",
"author_id": 632,
"author_profile": "https://Stackoverflow.com/users/632",
"pm_score": 2,
"selected": false,
"text": "<p>I would use the built in Func delegates instead. This same code would work on any IEnumerable. Your code would turn into:</p>\n\n<pre><code>public static R Reduce<T,R>(this IEnumerable<T> list, Func<T,R> r, R initial)\n{\n var aggregate = initial;\n foreach(var t in list)\n aggregate = r(t,aggregate);\n\n return aggregate;\n}\npublic static void Transform<T>(this IEnumerable<T> list, Func<T> f)\n{\n foreach(var t in list)\n f(t);\n}\n</code></pre>\n"
},
{
"answer_id": 40089,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 1,
"selected": false,
"text": "<p>You might want to add a way to do a map but return a new list, instead of working on the list passed in (and returning the list can prove useful to chain other operations)... perhaps an overloaded version with a boolean that indicates if you want to return a new list or not, as such:</p>\n\n<pre><code>public static List<T> Transform<T>(this List<T> list, TransformFunction<T> f,\n params object [] args)\n{\n return Transform(list, f, false, args);\n}\n\npublic static List<T> Transform<T>(this List<T> list, TransformFunction<T> f,\n bool create, params object [] args)\n{\n // Add code to create if create is true (sorry,\n // too lazy to actually code this up)\n foreach(var t in list)\n f(t,args);\n return list;\n}\n</code></pre>\n"
},
{
"answer_id": 40148,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 6,
"selected": true,
"text": "<p>These look very similar to extensions in Linq already:</p>\n\n<pre><code>//takes a function that matches the Func<T,R> delegate\nlistInstance.Aggregate( \n startingValue, \n (x, y) => /* aggregate two subsequent values */ );\n\n//takes a function that matches the Action<T> delegate\nlistInstance.ForEach( \n x => /* do something with x */);\n</code></pre>\n\n<p>Why is the 2nd example called Transform? Do you intend to change the values in the list somehow? If that's the case you may be better off using <code>ConvertAll<T></code> or <code>Select<T></code>.</p>\n"
},
{
"answer_id": 278287,
"author": "Ray",
"author_id": 4872,
"author_profile": "https://Stackoverflow.com/users/4872",
"pm_score": 6,
"selected": false,
"text": "<p>According to this link <a href=\"http://www.25hoursaday.com/weblog/2008/06/16/FunctionalProgrammingInC30HowMapReduceFilterCanRockYourWorld.aspx\" rel=\"noreferrer\">Functional Programming in C# 3.0: How Map/Reduce/Filter can Rock your World</a> the following are the equivalent in C# under the System.Linq namespace:</p>\n\n<ul>\n<li>map --> <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.select.aspx\" rel=\"noreferrer\">Enumerable.Select</a></li>\n<li>reduce --> <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aggregate.aspx\" rel=\"noreferrer\">Enumerable.Aggregate</a></li>\n<li>filter --> <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.where.aspx\" rel=\"noreferrer\">Enumerable.Where</a></li>\n</ul>\n"
},
{
"answer_id": 54801689,
"author": "CsUtil.com",
"author_id": 10808596,
"author_profile": "https://Stackoverflow.com/users/10808596",
"pm_score": 1,
"selected": false,
"text": "<p>I would recommend to create extension methods that internally use LinQ <a href=\"https://github.com/cs-util-com/cscore/blob/master/CsCore/PlainNetClassLib/src/Plugins/CsCore/com/csutil/collections/IEnumerableExtensions.cs\" rel=\"nofollow noreferrer\">like this</a>:</p>\n\n<pre><code>public static IEnumerable<R> Map<T, R>(this IEnumerable<T> self, Func<T, R> selector) {\n return self.Select(selector);\n}\n\npublic static T Reduce<T>(this IEnumerable<T> self, Func<T, T, T> func) {\n return self.Aggregate(func);\n}\n\npublic static IEnumerable<T> Filter<T>(this IEnumerable<T> self, Func<T, bool> predicate) {\n return self.Where(predicate);\n}\n</code></pre>\n\n<p>Here some example usages:</p>\n\n<pre><code>IEnumerable<string> myStrings = new List<string>() { \"1\", \"2\", \"3\", \"4\", \"5\" };\nIEnumerable<int> convertedToInts = myStrings.Map(s => int.Parse(s));\nIEnumerable<int> filteredInts = convertedToInts.Filter(i => i <= 3); // Keep 1,2,3\nint sumOfAllInts = filteredInts.Reduce((sum, i) => sum + i); // Sum up all ints\nAssert.Equal(6, sumOfAllInts); // 1+2+3 is 6\n</code></pre>\n\n<p>(See <a href=\"https://github.com/cs-util-com/cscore#ienumerable-extensions\" rel=\"nofollow noreferrer\">https://github.com/cs-util-com/cscore#ienumerable-extensions</a> for more examples)</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1455/"
] | I am writing a few extensions to mimic the map and reduce functions in Lisp.
```
public delegate R ReduceFunction<T,R>(T t, R previous);
public delegate void TransformFunction<T>(T t, params object[] args);
public static R Reduce<T,R>(this List<T> list, ReduceFunction<T,R> r, R initial)
{
var aggregate = initial;
foreach(var t in list)
aggregate = r(t,aggregate);
return aggregate;
}
public static void Transform<T>(this List<T> list, TransformFunction<T> f, params object [] args)
{
foreach(var t in list)
f(t,args);
}
```
The transform function will cut down on cruft like:
```
foreach(var t in list)
if(conditions && moreconditions)
//do work etc
```
Does this make sense? Could it be better? | These look very similar to extensions in Linq already:
```
//takes a function that matches the Func<T,R> delegate
listInstance.Aggregate(
startingValue,
(x, y) => /* aggregate two subsequent values */ );
//takes a function that matches the Action<T> delegate
listInstance.ForEach(
x => /* do something with x */);
```
Why is the 2nd example called Transform? Do you intend to change the values in the list somehow? If that's the case you may be better off using `ConvertAll<T>` or `Select<T>`. |
40,090 | <p>Is it true that the only way to handle default function arguments is through function overloading?</p>
<p>For example, in PHP I can do this:</p>
<pre><code>function foo($x, $y=0)
{
}
</code></pre>
<p>Would the best way to handle it in C# be this?</p>
<pre><code>void foo(int x)
{
foo(x, 0);
}
void foo(int x, int y)
{
}
</code></pre>
<p><strong><em><a href="http://bytes.com/forum/thread224970.html" rel="noreferrer">Example lifted from here</a></em></strong></p>
<p>Edit</p>
<p><strong><em>Made the C# example into actual C# (Thanks Blair Conrad)</em></strong></p>
| [
{
"answer_id": 40093,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, that'd be best<s>, except you'd omit the <code>$</code>s on the parameter names</s>, as others have pointed out. For those interested in the rationale behind the lack of default parameter values, see @Giovanni Galbo's explanation.</p>\n"
},
{
"answer_id": 40095,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>Default arguments are part of C++, but as of C# 3.5 default arguments are still not supported-- you'll have to overload. They've been available in VB.Net since 1.0.</p>\n"
},
{
"answer_id": 40096,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 0,
"selected": false,
"text": "<p>Yes. </p>\n\n<p>Or currying. </p>\n\n<p>Or abstracting into a class and using default values there. </p>\n"
},
{
"answer_id": 40098,
"author": "Brian Stewart",
"author_id": 3114,
"author_profile": "https://Stackoverflow.com/users/3114",
"pm_score": 0,
"selected": false,
"text": "<p>No, AFAIK C# does not support overriding, and yes, that is the recommended way of accomplishing the same effect.</p>\n"
},
{
"answer_id": 40121,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 4,
"selected": false,
"text": "<p>Just to satisfy some curiosity:</p>\n<p>From <a href=\"http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85556.aspx\" rel=\"noreferrer\">Why doesn't C# support default parameters?</a>:</p>\n<blockquote>\n<p>In languages such as C++, a default value can be included as part of the method declaration:</p>\n<p>void Process(Employee employee, bool bonus = false)</p>\n<p>This method can be called either with:</p>\n<p>a.Process(employee, true);</p>\n<p>or</p>\n<p>a.Process(employee);</p>\n<p>in the second case, the parameter bonus is set to false.</p>\n<p>C# doesn't have this feature.</p>\n<p>One reason we don't have this feature is related to a specific implementation of the feature. In the C++ world, when the user writes:</p>\n<p>a.Process(employee);</p>\n<p>the compiler generates</p>\n<p>a.process(employee, false);</p>\n<p>In other words, the compiler takes the default value that is specified in the method prototype and puts it into the method call - it's just as if the user wrote 'false' as the second parameter. There's no way to change that default value without forcing the user of the class to recompile, which is unfortunate.</p>\n<p>The overloading model works better in this respect. The framework author just defines two separate methods, and the single-parameter one calls the two-parameter method. This keeps the default value in the framework, where it can be modified if necessary.</p>\n<p>It would be possible for a compiler to take something like the C++ definition and produce the overloads, but there are a few issues with that approach.</p>\n<p>The first one is that the correlation between the code that the user writes and the code the compiler generates is less obvious. We generally try to limit magic when possible, as it makes it harder for programmers. The second issue has to do with things like XML doc comments and intellisense. The compiler would have to have special rules for how it generates doc comments for the overloaded methods, and intellisense would need to have smarts to collapse the overloaded methods into a single method.</p>\n<p>Writing overloads yourself is a bit less convenient, but we think it's an acceptable solution.</p>\n</blockquote>\n"
},
{
"answer_id": 40235,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>Regarding the <a href=\"http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85556.aspx\" rel=\"nofollow noreferrer\">excerpt from the c# faq</a>: </p>\n\n<p>Most of the problems listed there were solved for VB.Net (specifically the intellisense and xml comments issues), meaning they're really red herrings-- <em>there is code available to the C# team that will solve the problem.</em> </p>\n\n<p>Another reason has to do with forcing a user of a class to re-compile, but that's a bit of a red herring, too. If you <em>change</em> a default value in your framework class and the user does <em>not</em> have to recompile, you risk the user <em>not knowing that the default value changed.</em> Now you have a potential bug in the code that doesn't show up until runtime. In other words, the alternative of overloading the function is at least as bad. Of course, this also presumes a specific implementation of the feature, but it's the implementation suggested in the faq.</p>\n\n<p>Therefore you have to weigh the remaining reason (\"try to limit the magic\") vs the fact (which they acknowledge) that writing the overloads is \"a bit less convenient\". Personally, I say put the feature in, and let the programmer decide whether or not to use it.</p>\n"
},
{
"answer_id": 696656,
"author": "gazhay",
"author_id": 84545,
"author_profile": "https://Stackoverflow.com/users/84545",
"pm_score": 0,
"selected": false,
"text": "<p>doe this not do the job?</p>\n\n<pre><code>void foo(int x):this(x, 0){}\n\nvoid foo(int x, int y){\n // code here\n}\n</code></pre>\n"
},
{
"answer_id": 696676,
"author": "Ian",
"author_id": 21061,
"author_profile": "https://Stackoverflow.com/users/21061",
"pm_score": 0,
"selected": false,
"text": "<p>As pointed out, this isn't currently available in C# however they will be present within C# 4.0 as Sam Ng discusses on his blog:</p>\n\n<p><a href=\"http://blogs.msdn.com/samng/archive/2009/02/03/named-arguments-optional-arguments-and-default-values.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/samng/archive/2009/02/03/named-arguments-optional-arguments-and-default-values.aspx</a></p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | Is it true that the only way to handle default function arguments is through function overloading?
For example, in PHP I can do this:
```
function foo($x, $y=0)
{
}
```
Would the best way to handle it in C# be this?
```
void foo(int x)
{
foo(x, 0);
}
void foo(int x, int y)
{
}
```
***[Example lifted from here](http://bytes.com/forum/thread224970.html)***
Edit
***Made the C# example into actual C# (Thanks Blair Conrad)*** | Yes, that'd be best~~, except you'd omit the `$`s on the parameter names~~, as others have pointed out. For those interested in the rationale behind the lack of default parameter values, see @Giovanni Galbo's explanation. |
40,107 | <p>I imagine everyone has seen code like:</p>
<pre><code>public void Server2ClientEnumConvert( ServerEnum server)
{
switch(server)
{
case ServerEnum.One:
return ClientEnum.ABC
//And so on.
</code></pre>
<p>Instead of this badness we could do somthing like:</p>
<pre><code>public enum ServerEnum
{
[Enum2Enum(ClientEnum.ABC)]
One,
}
</code></pre>
<p>Now we can use reflection to rip through ServerEnum and get the conversion mappings from the enum declaration itself.</p>
<p>The problem I am having here is in the declaration of the Enum2Enum attribute.</p>
<p>This works but replacing object o with Enum e does not. I do not want to be able to pass in objects to the constructor, only other enums.</p>
<pre><code>public class EnumToEnumAttribute : Attribute
{
public EnumToEnumAttribute(object o){}
}
</code></pre>
<p>This fails to compile.</p>
<pre><code>public class EnumToEnumAttribute : Attribute
{
public EnumToEnumAttribute(Enum e){}
}
</code></pre>
<p>Is there a reason for the compile error? How else could I pass in the information needed to map besides: </p>
<pre><code>EnumtoEnumAttribute(Type dest, string enumString)
</code></pre>
<p>This seems too verbose but if it is the only way then I guess I will use it.</p>
| [
{
"answer_id": 40128,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 0,
"selected": false,
"text": "<p>I would probably use struct as the type, and then throw an exception if it isn't an Enum type. I don't see how your (Type, string) option is any safer than using object or struct.</p>\n"
},
{
"answer_id": 40131,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/aa664615%28VS.71%29.aspx\" rel=\"nofollow noreferrer\">Here are the rules</a> for the types that can be included as Attribute parameters:</p>\n"
},
{
"answer_id": 40160,
"author": "Ben McNiel",
"author_id": 1455,
"author_profile": "https://Stackoverflow.com/users/1455",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>@Danial Jennings I read through the rules there and found: \"An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility (Section 17.2).\". </p>\n</blockquote>\n\n<p>How does trying for Enum e in the constructor fail based on the quoted rule? Is it because being of type enum does not guarantee that the enums passed in are publicly visibly? This seems right. Is there a way for force this rule at compile time?</p>\n\n<blockquote>\n <p>@ bdukes You are exactly correct. I should have thought about that more.</p>\n</blockquote>\n\n<p>It looks like run time type checking is my only option to make sure I am only mapping enums to other enums. </p>\n"
},
{
"answer_id": 40190,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 0,
"selected": false,
"text": "<p>Why not use a Dictionary? This could be a static property of your class, initialized with those fancy schmancy object initializers we got in 3.0? You would not be typing more code (the mapping has to be done even with the Attribute sollution).</p>\n"
},
{
"answer_id": 398461,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 2,
"selected": false,
"text": "<p>Using almost the same example, you can achieve this directly in the enum:</p>\n\n<pre><code>public enum ServerEnum\n{\n One = ClientEnum.ABC,\n}\n</code></pre>\n\n<p>This has the benefit of not requiring Reflection, is easier to read (in my opinion), and overall requires less overhead.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1455/"
] | I imagine everyone has seen code like:
```
public void Server2ClientEnumConvert( ServerEnum server)
{
switch(server)
{
case ServerEnum.One:
return ClientEnum.ABC
//And so on.
```
Instead of this badness we could do somthing like:
```
public enum ServerEnum
{
[Enum2Enum(ClientEnum.ABC)]
One,
}
```
Now we can use reflection to rip through ServerEnum and get the conversion mappings from the enum declaration itself.
The problem I am having here is in the declaration of the Enum2Enum attribute.
This works but replacing object o with Enum e does not. I do not want to be able to pass in objects to the constructor, only other enums.
```
public class EnumToEnumAttribute : Attribute
{
public EnumToEnumAttribute(object o){}
}
```
This fails to compile.
```
public class EnumToEnumAttribute : Attribute
{
public EnumToEnumAttribute(Enum e){}
}
```
Is there a reason for the compile error? How else could I pass in the information needed to map besides:
```
EnumtoEnumAttribute(Type dest, string enumString)
```
This seems too verbose but if it is the only way then I guess I will use it. | Using almost the same example, you can achieve this directly in the enum:
```
public enum ServerEnum
{
One = ClientEnum.ABC,
}
```
This has the benefit of not requiring Reflection, is easier to read (in my opinion), and overall requires less overhead. |
40,112 | <p>I've got an MS-Access app (1/10th MS-Acccess, 9/10ths MS-SQL) that needs to display photographs of some assets along with their specifications. Currently the images are stored in an MS-Access table as an OLE Object (and copy-n-pasted into the field by the users).</p>
<p>For various reasons, I would like to do is store the original .jpgs in a folder on the network drive, and reference them from the application portion. I have considered moving into MS-SQL's image data type (and its replacement varbinary), but I think my user population will more easily grasp the concept of the network folder.</p>
<p>How can I get MS Access to display the contents of a .jpg?</p>
| [
{
"answer_id": 40182,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way is probably to plop an Internet Explorer onto one of your forms. Check out this site: <a href=\"http://www.acky.net/tutorials/vb/wbrowser/\" rel=\"nofollow noreferrer\">http://www.acky.net/tutorials/vb/wbrowser/</a></p>\n\n<p>Since you can reference that object in Access, you will only need to point the webbrowser control to the path of the .jpg (NavigateTo() if I remember correctly).</p>\n\n<p><strong>EDIT:</strong> The above link was just googled and picked from the results (first one that opened quickly). I do not think it is a very good tutorial, it just has all the pointers you need... Check out msdn etc. if you need more information!</p>\n"
},
{
"answer_id": 41036,
"author": "WaterBoy",
"author_id": 3270,
"author_profile": "https://Stackoverflow.com/users/3270",
"pm_score": 4,
"selected": true,
"text": "<p>Another option is to put an image control on your form. There is a property of that control (Picture) that is simply the path to the image. Here is a short example in VBA of how you might use it.</p>\n\n<p>txtPhoto would be a text box bound to the database field with the path to the image\nimgPicture is the image control\nThe example is a click event for a button that would advance to the next record.</p>\n\n<pre><code>Private Sub cmdNextClick()\n DoCmd.GoToRecord , , acNext\n txtPhoto.SetFocus\n imgPicture.Picture = txtPhoto.Text\n Exit Sub\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 41321,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": false,
"text": "<p>I found that this article by Microsoft with full VBA worked very well for me.</p>\n\n<p><a href=\"http://support.microsoft.com/kb/285820/\" rel=\"nofollow noreferrer\">How to display images from a folder in a form, a report, or a data access page</a></p>\n"
},
{
"answer_id": 67132,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 2,
"selected": false,
"text": "<p>Have you looked at Stephen Lebans' solutions? Here's one:</p>\n\n<p><a href=\"http://www.lebans.com/imageclass.htm\" rel=\"nofollow noreferrer\">Image Class Module for Access</a></p>\n\n<p>Check out the list of other great code along the left-hand side of that web page. You may find something that fully matches what you need.</p>\n"
},
{
"answer_id": 1081292,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can try an ActiveX control called <a href=\"http://access.bukrek.net\" rel=\"nofollow noreferrer\">AccessImagine</a>, makes adding images to database more convenient - you can load from file, scan, paste from buffer or drag-n-drop. You can crop image right inside the database and resample it automatically. It handles external image storage automatically if you need it.</p>\n"
},
{
"answer_id": 25858063,
"author": "Gord Thompson",
"author_id": 2144390,
"author_profile": "https://Stackoverflow.com/users/2144390",
"pm_score": 0,
"selected": false,
"text": "<p>Note that in Access 2010 (and later) this is dead simple to do because the Image control can be bound to a field in the table that contains the <em>path</em> to the image file (.jpg, .png, ...). No VBA required.</p>\n\n<p>For more details see my other answer <a href=\"https://stackoverflow.com/a/25857967/2144390\">here</a>.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/685/"
] | I've got an MS-Access app (1/10th MS-Acccess, 9/10ths MS-SQL) that needs to display photographs of some assets along with their specifications. Currently the images are stored in an MS-Access table as an OLE Object (and copy-n-pasted into the field by the users).
For various reasons, I would like to do is store the original .jpgs in a folder on the network drive, and reference them from the application portion. I have considered moving into MS-SQL's image data type (and its replacement varbinary), but I think my user population will more easily grasp the concept of the network folder.
How can I get MS Access to display the contents of a .jpg? | Another option is to put an image control on your form. There is a property of that control (Picture) that is simply the path to the image. Here is a short example in VBA of how you might use it.
txtPhoto would be a text box bound to the database field with the path to the image
imgPicture is the image control
The example is a click event for a button that would advance to the next record.
```
Private Sub cmdNextClick()
DoCmd.GoToRecord , , acNext
txtPhoto.SetFocus
imgPicture.Picture = txtPhoto.Text
Exit Sub
End Sub
``` |
40,116 | <p>How do I get it to work with my project?</p>
<p><a href="http://ajax.asp.net/" rel="noreferrer">http://ajax.asp.net/</a></p>
<p><a href="http://www.codeplex.com/AjaxControlToolkit/" rel="noreferrer">http://www.codeplex.com/AjaxControlToolkit/</a></p>
| [
{
"answer_id": 40118,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Install the ASP.NET AJAX Control Toolkit</strong></p>\n\n<ol>\n<li><p>Download the ZIP file\nAjaxControlToolkit-Framework3.5SP1-DllOnly.zip\nfrom the <a href=\"http://www.codeplex.com/AjaxControlToolkit/Release/ProjectReleases.aspx?ReleaseId=16488\" rel=\"noreferrer\">ASP.NET AJAX Control\nToolkit Releases</a> page of the\nCodePlex web site.</p></li>\n<li><p>Copy the contents of this zip file\ndirectly into the bin directory of\nyour web site.</p></li>\n</ol>\n\n<p><strong>Update web.config</strong></p>\n\n<ol start=\"3\">\n<li><p>Put this in your web.config under the <controls> section:</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<configuration>\n ...\n <system.web>\n ...\n <pages>\n ...\n <controls>\n ...\n <add tagPrefix=\"ajaxtoolkit\"\n namespace=\"AjaxControlToolkit\"\n assembly=\"AjaxControlToolKit\"/>\n </controls>\n </pages>\n ...\n </system.web>\n ...\n</configuration>\n</code></pre></li>\n</ol>\n\n<p><strong>Setup Visual Studio</strong></p>\n\n<ol start=\"4\">\n<li><p>Right-click on the Toolbox and select \"Add Tab\", and add a tab called \"AJAX Control Toolkit\"</p></li>\n<li><p>Inside that tab, right-click on the Toolbox and select \"Choose Items...\"</p></li>\n<li><p>When the \"Choose Toolbox Items\" dialog appears, click the \"Browse...\" button. Navigate to your project's \"bin\" folder. Inside that folder, select \"AjaxControlToolkit.dll\" and click OK. Click OK again to close the Choose Items Dialog.</p></li>\n</ol>\n\n<p>You can now use the controls in your web sites!</p>\n"
},
{
"answer_id": 43934,
"author": "Mike",
"author_id": 4523,
"author_profile": "https://Stackoverflow.com/users/4523",
"pm_score": 1,
"selected": false,
"text": "<p>you will also need to have a asp:ScriptManager control on every page that you want to use ajax controls on. you should be able to just drag the scriptmanager over from your toolbox one the toolkit is installed following Zack's instructions.</p>\n"
},
{
"answer_id": 721899,
"author": "Jim Evans",
"author_id": 87627,
"author_profile": "https://Stackoverflow.com/users/87627",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using MasterPages and Content pages in your app - you also have the option of putting the ScriptManager on the Masterpage and then every ContentPage that uses that MasterPage will <em>NOT</em> need a script manager added. If you need some of the special configurations of the ScriptManager - like javascript file references - you can use a ScriptManagerProxy control on the content page that needs it.</p>\n"
},
{
"answer_id": 7851499,
"author": "Xenon",
"author_id": 331798,
"author_profile": "https://Stackoverflow.com/users/331798",
"pm_score": 4,
"selected": false,
"text": "<p>You can easily install it by writing </p>\n\n<p><code>Install-Package AjaxControlToolkit</code> in package manager console.</p>\n\n<p>for more information you can check this <a href=\"http://ajaxcontroltoolkit.codeplex.com/\" rel=\"noreferrer\">link</a></p>\n"
},
{
"answer_id": 11398469,
"author": "Mohammad Sepahvand",
"author_id": 189756,
"author_profile": "https://Stackoverflow.com/users/189756",
"pm_score": 1,
"selected": false,
"text": "<p>It's really <a href=\"http://weblogs.asp.net/yousefjadallah/archive/2010/04/16/installing-ajax-control-toolkit-4-in-visual-studio-2010.aspx\" rel=\"nofollow\">simple</a>, just download the latest toolkit from <a href=\"http://ajaxcontroltoolkit.codeplex.com/releases/view/90063\" rel=\"nofollow\">Codeplex</a> and add the extracted <code>AjaxControlToolkit.dll</code> to your toolbox in Visual Studio by right clicking the toolbox and selecting 'choose items'. You will then have the controls in your Visual STudio toolbox and using them is just a matter of dragging and dropping them onto your form, of course don't forget to add a <code>asp:ScriptManager</code> to every page that uses controls from the toolkit, or optionally include it in your master page only and your content pages will inherit the script manager.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | How do I get it to work with my project?
<http://ajax.asp.net/>
<http://www.codeplex.com/AjaxControlToolkit/> | **Install the ASP.NET AJAX Control Toolkit**
1. Download the ZIP file
AjaxControlToolkit-Framework3.5SP1-DllOnly.zip
from the [ASP.NET AJAX Control
Toolkit Releases](http://www.codeplex.com/AjaxControlToolkit/Release/ProjectReleases.aspx?ReleaseId=16488) page of the
CodePlex web site.
2. Copy the contents of this zip file
directly into the bin directory of
your web site.
**Update web.config**
3. Put this in your web.config under the <controls> section:
```
<?xml version="1.0"?>
<configuration>
...
<system.web>
...
<pages>
...
<controls>
...
<add tagPrefix="ajaxtoolkit"
namespace="AjaxControlToolkit"
assembly="AjaxControlToolKit"/>
</controls>
</pages>
...
</system.web>
...
</configuration>
```
**Setup Visual Studio**
4. Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit"
5. Inside that tab, right-click on the Toolbox and select "Choose Items..."
6. When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog.
You can now use the controls in your web sites! |
40,122 | <p>My group is developing a service-based (.NET WCF) application and we're trying to decide how to handle exceptions in our internal services. Should we throw exceptions? Return exceptions serialized as XML? Just return an error code?</p>
<p>Keep in mind that the user will never see these exceptions, it's only for other parts of the application.</p>
| [
{
"answer_id": 40140,
"author": "Phil Bennett",
"author_id": 2995,
"author_profile": "https://Stackoverflow.com/users/2995",
"pm_score": 1,
"selected": false,
"text": "<p>I'm a bit confused, I'm not being flippant -- you say you want to return exceptions serialised as XML on the one hand and that the user will never see the exceptions on the other hand. Who will be seeing these exceptions?</p>\n\n<p>Normally I'd say to use WCF fault contracts. </p>\n"
},
{
"answer_id": 40153,
"author": "hova",
"author_id": 2170,
"author_profile": "https://Stackoverflow.com/users/2170",
"pm_score": 2,
"selected": false,
"text": "<p>Well, why not just throw the standard SOAPExceptions? The problem with error codes and serialized XML is that they both require additional logic to recognize that an error did in fact happen. Such an approach is only useful if you have specialized logging or logic that needs to happen on the other side of the web service. Such an example would be returning a flag that says \"it's ok to continue\" with an error exception report. </p>\n\n<p>Regardless of how you throw it, it won't make the job any easier, as the calling side still needs to recognize there was an exception and deal with it. </p>\n"
},
{
"answer_id": 40164,
"author": "brien",
"author_id": 4219,
"author_profile": "https://Stackoverflow.com/users/4219",
"pm_score": 0,
"selected": false,
"text": "<p>Phil, different parts of the application call each other using WCF. By \"return exceptions serialized as XML,\" I meant that the return value of the function wold be an exception object. Success would be indicated by null. </p>\n\n<p>I don't think that's the right option.</p>\n\n<p>WCF fault contracts sound good, but I don't know anything about them. Checking google right now.</p>\n"
},
{
"answer_id": 40170,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": true,
"text": "<p>WCF uses <code>SoapFaults</code> as its native way of transmitting exceptions from either the service to the client, or the client to the service.</p>\n\n<p>You can declare a custom SOAP fault using the <code>FaultContract</code> attribute in your contract interface:</p>\n\n<p>For example:</p>\n\n<pre><code>[ServiceContract(Namespace=\"foobar\")]\ninterface IContract\n{\n [OperationContract]\n [FaultContract(typeof(CustomFault))]\n void DoSomething();\n}\n\n\n[DataContract(Namespace=\"Foobar\")]\nclass CustomFault\n{\n [DataMember]\n public string error;\n\n public CustomFault(string err)\n {\n error = err;\n }\n}\n\nclass myService : IContract\n{\n public void DoSomething()\n {\n throw new FaultException<CustomFault>( new CustomFault(\"Custom Exception!\"));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 65072,
"author": "wojo",
"author_id": 9022,
"author_profile": "https://Stackoverflow.com/users/9022",
"pm_score": 0,
"selected": false,
"text": "<p>I would avoid sending exceptions directly back to the client unless you are okay with that much detail being sent back.</p>\n\n<p>I would recommend using WCF faults to transmit your error message and code (something that can be used to make a decision on the receiver to retry, error out, etc) depending if it is the sender or receiver at fault.</p>\n\n<p>This can be done using FaultCode.CreateReceiverFaultCode and FaultCode.CreateSenderFaultCode.</p>\n\n<p>I'm in the process of going through this right now, but ran into a nasty snag it seems in the WCF fault generated SOAP 1.1 response. If you are interested, you can check out my question about it here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/65008/net-wcf-faults-generating-incorrect-soap-11-faultcode-values\">.NET WCF faults generating incorrect SOAP 1.1 faultcode values</a></p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4219/"
] | My group is developing a service-based (.NET WCF) application and we're trying to decide how to handle exceptions in our internal services. Should we throw exceptions? Return exceptions serialized as XML? Just return an error code?
Keep in mind that the user will never see these exceptions, it's only for other parts of the application. | WCF uses `SoapFaults` as its native way of transmitting exceptions from either the service to the client, or the client to the service.
You can declare a custom SOAP fault using the `FaultContract` attribute in your contract interface:
For example:
```
[ServiceContract(Namespace="foobar")]
interface IContract
{
[OperationContract]
[FaultContract(typeof(CustomFault))]
void DoSomething();
}
[DataContract(Namespace="Foobar")]
class CustomFault
{
[DataMember]
public string error;
public CustomFault(string err)
{
error = err;
}
}
class myService : IContract
{
public void DoSomething()
{
throw new FaultException<CustomFault>( new CustomFault("Custom Exception!"));
}
}
``` |
40,125 | <p>I'm trying to get a Firefox plugin to read data from a HTTP get, parse the results and present them as links in a bookmark-like drop-down menu.</p>
<p>My quesion then is: Does anyone have any sample code that will do this?</p>
| [
{
"answer_id": 40167,
"author": "Robert J. Walker",
"author_id": 4287,
"author_profile": "https://Stackoverflow.com/users/4287",
"pm_score": 2,
"selected": false,
"text": "<p>Having never developed one myself, I'm not certain how this is typically done in Firefox plugins, but since plugin scripting is JavaScript, I can probably help out with the loading part. Assuming a variable named url containing the URL you want to request:</p>\n\n<pre><code>var xmlhttp = new XMLHttpRequest();\nxmlhttp.open(\"GET\", url, true);\n\nxmlhttp.onreadystatechange = function() {\n if(this.readyState == 4) { // Done loading?\n if(this.status == 200) { // Everything okay?\n // read content from this.responseXML or this.responseText\n } else { // Error occurred; handle it\n alert(\"Error \" + this.status + \":\\n\" + this.statusText);\n }\n }\n};\n\nxmlhttp.send(null);\n</code></pre>\n\n<p>A couple of notes on this code:</p>\n\n<ul>\n<li>You may want more sophisticated status code handling. For example, 200 is not the only non-error status code. Details on status codes can be found <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html\" rel=\"nofollow noreferrer\">here</a>.</li>\n<li>You probably want to have a timeout to handle the case where, for some reason, you don't get to readyState 4 in a reasonable amount of time.</li>\n<li>You may want to do things when earlier readyStates are received. <a href=\"http://www.w3.org/TR/XMLHttpRequest/#xmlhttprequest-object\" rel=\"nofollow noreferrer\">This page</a> documents the readyState codes, along with other properties and methods on the XMLHttpRequest object which you may find useful.</li>\n</ul>\n"
},
{
"answer_id": 58273,
"author": "pc1oad1etter",
"author_id": 525,
"author_profile": "https://Stackoverflow.com/users/525",
"pm_score": 0,
"selected": false,
"text": "<p>Robert Walker did a great job of describing <a href=\"https://stackoverflow.com/questions/40125/reading-from-a-http-get-presenting-in-firefox-bookmarks#40167\">how to send the request</a>. You can read more about <a href=\"http://developer.mozilla.org/En/XMLHttpRequest\" rel=\"nofollow noreferrer\">Mozilla's xmlhttprequest here</a>.</p>\n\n<p><strike>I would just add that the response would be found (using Robert's code) using</p>\n\n<pre><code> xmlhttp.responseText\n</code></pre>\n\n<p></strike>\n(<em>Edit - i didn't read closely enough, thanks Robert</em>)</p>\n\n<p>You didn't indicate exactly what the data was, although you mentioned wanting to parse links from the data. You could the xmlhttp.responseText as an xml document, parse out the links, and place it into a menulist or whatever you like.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4165/"
] | I'm trying to get a Firefox plugin to read data from a HTTP get, parse the results and present them as links in a bookmark-like drop-down menu.
My quesion then is: Does anyone have any sample code that will do this? | Having never developed one myself, I'm not certain how this is typically done in Firefox plugins, but since plugin scripting is JavaScript, I can probably help out with the loading part. Assuming a variable named url containing the URL you want to request:
```
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4) { // Done loading?
if(this.status == 200) { // Everything okay?
// read content from this.responseXML or this.responseText
} else { // Error occurred; handle it
alert("Error " + this.status + ":\n" + this.statusText);
}
}
};
xmlhttp.send(null);
```
A couple of notes on this code:
* You may want more sophisticated status code handling. For example, 200 is not the only non-error status code. Details on status codes can be found [here](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html).
* You probably want to have a timeout to handle the case where, for some reason, you don't get to readyState 4 in a reasonable amount of time.
* You may want to do things when earlier readyStates are received. [This page](http://www.w3.org/TR/XMLHttpRequest/#xmlhttprequest-object) documents the readyState codes, along with other properties and methods on the XMLHttpRequest object which you may find useful. |
40,133 | <p>I have been experimenting with <a href="http://www.woopra.com/" rel="nofollow noreferrer">woopra.com</a> A web analytics tool. Which requires a piece of javascript code to be added to each page to function. This is easy enough with more dynamic sites with universal headers or footers but not for totally static html pages.</p>
<p>I attempted to work round it by using a combination of Apache rewrites and SSI's to "Wrap" the static html with the required code. For example...</p>
<p>I made the following changes to my apache config</p>
<pre><code> RewriteEngine On
RewriteCond %{REQUEST_URI} !=test.shtml
RewriteCond %{IS_SUBREQ} false
RewriteRule (.*)\.html test.shtml?$1.html
</code></pre>
<p>The test.shtml file contains...</p>
<pre><code> <script type="text/javascript">
var XXXXid = 'xxxxxxx';
</script>
<script src="http://xxxx.woopra.com/xx/xxx.js"></script>
<!--#set var="page" value="$QUERY_STRING" -->
<!--#include virtual= $page -->
</code></pre>
<p>The idea was that a request coming in for</p>
<pre><code> /abc.html
</code></pre>
<p>would be redirected to</p>
<pre><code> /test.shtml?abc.html
</code></pre>
<p>the shtml would then include the original file into the response page.</p>
<p>Unfortunately it doesn't quite work as planed :) can anyone see what I am doing wrong or perhaps suggest an alternative approach. Is there any apache modules that could do the same thing. Preferably that can be configured on a per site basis.</p>
<p>Thanks</p>
<p>Peter</p>
| [
{
"answer_id": 40156,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 3,
"selected": true,
"text": "<p>I think that <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_ext_filter.html\" rel=\"nofollow noreferrer\">mod_filter_ext</a> is the module you are looking for. You can write a short Perl script for example to insert the JS code in the pages and register it to process HTML pages:</p>\n\n<pre><code>while (<>) {\n s/<html>/\\Q<script>....\\E/;\n print $_;\n}\n</code></pre>\n\n<p>You could even use something like <code>sed</code> to perform the substitution.</p>\n"
},
{
"answer_id": 40256,
"author": "Pablo Alsina",
"author_id": 2295,
"author_profile": "https://Stackoverflow.com/users/2295",
"pm_score": 1,
"selected": false,
"text": "<p>If the pages are static, why would you change them on the fly instead of preprocessing all pages on a site, adding the piece of requiered javascript to each one of them? This is simple and probably more efficent (you probably have more pageviews than pages to change)</p>\n\n<p>This could be done a lots of way. I would suggest a small perl to to inline replacement.</p>\n"
},
{
"answer_id": 490116,
"author": "Alan Doherty",
"author_id": 59995,
"author_profile": "https://Stackoverflow.com/users/59995",
"pm_score": 0,
"selected": false,
"text": "<p>ok the method above's biggest problem is it would break your html validity by placing a script tag outside the <code><html></code> tags</p>\n\n<p>i'd agree with the others on a pre-process run over your html files such as a sed/awk script</p>\n\n<p>heres a quick example {assuming the script part can be added before the <code></head></code>\nand that the <code></head></code> is at the start of a newline</p>\n\n<pre><code>#!/bin/bash\n\ncd /var/webserver/whatever/\n\ngrep -r '<\\/head>' */*|grep \"^.*\\.html*:\" >/var/tmp/tempfile.txt\n((lines = $(wc -l /var/tmp/dom-tempfile.txt | awk '{print $1}')))\nif [ $lines -gt 0 ]\nthen\n while read line; do\n sed 's/<script type=\"text\\/javascript\"> var XXXXid = \"xxxxxxx\"; <\\/script><script src=\"http:\\/\\/xxxx\\.woopra\\.com\\/xx\\/xxx\\.js\"><\\/script><\\/head>/^<\\/head>/g' $line>/var/tmp/tempfile.htm\n mv /var/tmp/tempfile.htm $line\n done < <(sed 's/\\(^.*\\.html*\\):.*$/\\1/' /var/tmp/tempfile.txt)\nfi\nexit 0\n</code></pre>\n"
},
{
"answer_id": 1196832,
"author": "Alex Lehmann",
"author_id": 27069,
"author_profile": "https://Stackoverflow.com/users/27069",
"pm_score": 0,
"selected": false,
"text": "<p>You may have a syntax error since <code>$page</code> is not included in quotes, however the two main reasons that this doesn't are the following:</p>\n\n<ul>\n<li>include virtual should a path starting with /, in your example the query string should be /abc.html , not abc.html</li>\n<li><p>the rewrite rule should start with the path as well, so the rewrite rule has to be</p>\n\n<pre><code>RewriteRule ^(.*)\\.html /test.shtml?$1.html\n</code></pre></li>\n</ul>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3720/"
] | I have been experimenting with [woopra.com](http://www.woopra.com/) A web analytics tool. Which requires a piece of javascript code to be added to each page to function. This is easy enough with more dynamic sites with universal headers or footers but not for totally static html pages.
I attempted to work round it by using a combination of Apache rewrites and SSI's to "Wrap" the static html with the required code. For example...
I made the following changes to my apache config
```
RewriteEngine On
RewriteCond %{REQUEST_URI} !=test.shtml
RewriteCond %{IS_SUBREQ} false
RewriteRule (.*)\.html test.shtml?$1.html
```
The test.shtml file contains...
```
<script type="text/javascript">
var XXXXid = 'xxxxxxx';
</script>
<script src="http://xxxx.woopra.com/xx/xxx.js"></script>
<!--#set var="page" value="$QUERY_STRING" -->
<!--#include virtual= $page -->
```
The idea was that a request coming in for
```
/abc.html
```
would be redirected to
```
/test.shtml?abc.html
```
the shtml would then include the original file into the response page.
Unfortunately it doesn't quite work as planed :) can anyone see what I am doing wrong or perhaps suggest an alternative approach. Is there any apache modules that could do the same thing. Preferably that can be configured on a per site basis.
Thanks
Peter | I think that [mod\_filter\_ext](http://httpd.apache.org/docs/2.2/mod/mod_ext_filter.html) is the module you are looking for. You can write a short Perl script for example to insert the JS code in the pages and register it to process HTML pages:
```
while (<>) {
s/<html>/\Q<script>....\E/;
print $_;
}
```
You could even use something like `sed` to perform the substitution. |
40,161 | <p>Does C# have built-in support for parsing strings of page numbers? By page numbers, I mean the format you might enter into a print dialog that's a mixture of comma and dash-delimited.</p>
<p>Something like this:</p>
<pre><code>1,3,5-10,12
</code></pre>
<p>What would be really nice is a solution that gave me back some kind of list of all page numbers represented by the string. In the above example, getting a list back like this would be nice:</p>
<pre><code>1,3,5,6,7,8,9,10,12
</code></pre>
<p>I just want to avoid rolling my own if there's an easy way to do it.</p>
| [
{
"answer_id": 40165,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 3,
"selected": false,
"text": "<p>It doesn't have a built-in way to do this, but it would be trivial to do using String.Split.</p>\n\n<p>Simply split on ',' then you have a series of strings that represent either page numbers or ranges. Iterate over that series and do a String.Split of '-'. If there isn't a result, it's a plain page number, so stick it in your list of pages. If there is a result, take the left and right of the '-' as the bounds and use a simple for loop to add each page number to your final list over that range.</p>\n\n<p>Can't take but 5 minutes to do, then maybe another 10 to add in some sanity checks to throw errors when the user tries to input invalid data (like \"1-2-3\" or something.)</p>\n"
},
{
"answer_id": 40180,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 6,
"selected": true,
"text": "<p>Should be simple:</p>\n\n<pre><code>foreach( string s in \"1,3,5-10,12\".Split(',') ) \n{\n // try and get the number\n int num;\n if( int.TryParse( s, out num ) )\n {\n yield return num;\n continue; // skip the rest\n }\n\n // otherwise we might have a range\n // split on the range delimiter\n string[] subs = s.Split('-');\n int start, end;\n\n // now see if we can parse a start and end\n if( subs.Length > 1 &&\n int.TryParse(subs[0], out start) &&\n int.TryParse(subs[1], out end) &&\n end >= start )\n {\n // create a range between the two values\n int rangeLength = end - start + 1;\n foreach(int i in Enumerable.Range(start, rangeLength))\n {\n yield return i;\n }\n }\n}\n</code></pre>\n\n<p><strong>Edit:</strong> thanks for the fix ;-) </p>\n"
},
{
"answer_id": 40207,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 3,
"selected": false,
"text": "<p>Keith's approach seems nice. I put together a more naive approach using lists. This has error checking so hopefully should pick up most problems:-</p>\n\n<pre><code>public List<int> parsePageNumbers(string input) {\n if (string.IsNullOrEmpty(input))\n throw new InvalidOperationException(\"Input string is empty.\");\n\n var pageNos = input.Split(',');\n\n var ret = new List<int>();\n foreach(string pageString in pageNos) {\n if (pageString.Contains(\"-\")) {\n parsePageRange(ret, pageString);\n } else {\n ret.Add(parsePageNumber(pageString));\n }\n }\n\n ret.Sort();\n return ret.Distinct().ToList();\n}\n\nprivate int parsePageNumber(string pageString) {\n int ret;\n\n if (!int.TryParse(pageString, out ret)) {\n throw new InvalidOperationException(\n string.Format(\"Page number '{0}' is not valid.\", pageString));\n }\n\n return ret;\n}\n\nprivate void parsePageRange(List<int> pageNumbers, string pageNo) {\n var pageRange = pageNo.Split('-');\n\n if (pageRange.Length != 2)\n throw new InvalidOperationException(\n string.Format(\"Page range '{0}' is not valid.\", pageNo));\n\n int startPage = parsePageNumber(pageRange[0]),\n endPage = parsePageNumber(pageRange[1]);\n\n if (startPage > endPage) {\n throw new InvalidOperationException(\n string.Format(\"Page number {0} is greater than page number {1}\" +\n \" in page range '{2}'\", startPage, endPage, pageNo));\n }\n\n pageNumbers.AddRange(Enumerable.Range(startPage, endPage - startPage + 1));\n}\n</code></pre>\n"
},
{
"answer_id": 40384,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>Here's something I cooked up for something similar.</p>\n\n<p>It handles the following types of ranges:</p>\n\n<pre><code>1 single number\n1-5 range\n-5 range from (firstpage) up to 5\n5- range from 5 up to (lastpage)\n.. can use .. instead of -\n;, can use both semicolon, comma, and space, as separators\n</code></pre>\n\n<p>It does not check for duplicate values, so the set <em>1,5,-10</em> will produce the sequence <em>1, 5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10</em>.</p>\n\n<pre><code>public class RangeParser\n{\n public static IEnumerable<Int32> Parse(String s, Int32 firstPage, Int32 lastPage)\n {\n String[] parts = s.Split(' ', ';', ',');\n Regex reRange = new Regex(@\"^\\s*((?<from>\\d+)|(?<from>\\d+)(?<sep>(-|\\.\\.))(?<to>\\d+)|(?<sep>(-|\\.\\.))(?<to>\\d+)|(?<from>\\d+)(?<sep>(-|\\.\\.)))\\s*$\");\n foreach (String part in parts)\n {\n Match maRange = reRange.Match(part);\n if (maRange.Success)\n {\n Group gFrom = maRange.Groups[\"from\"];\n Group gTo = maRange.Groups[\"to\"];\n Group gSep = maRange.Groups[\"sep\"];\n\n if (gSep.Success)\n {\n Int32 from = firstPage;\n Int32 to = lastPage;\n if (gFrom.Success)\n from = Int32.Parse(gFrom.Value);\n if (gTo.Success)\n to = Int32.Parse(gTo.Value);\n for (Int32 page = from; page <= to; page++)\n yield return page;\n }\n else\n yield return Int32.Parse(gFrom.Value);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 205166,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a slightly modified version of lassevk's code that handles the string.Split operation inside of the Regex match. It's written as an extension method and you can easily handle the duplicates problem using the Disinct() extension from LINQ.</p>\n\n<pre><code> /// <summary>\n /// Parses a string representing a range of values into a sequence of integers.\n /// </summary>\n /// <param name=\"s\">String to parse</param>\n /// <param name=\"minValue\">Minimum value for open range specifier</param>\n /// <param name=\"maxValue\">Maximum value for open range specifier</param>\n /// <returns>An enumerable sequence of integers</returns>\n /// <remarks>\n /// The range is specified as a string in the following forms or combination thereof:\n /// 5 single value\n /// 1,2,3,4,5 sequence of values\n /// 1-5 closed range\n /// -5 open range (converted to a sequence from minValue to 5)\n /// 1- open range (converted to a sequence from 1 to maxValue)\n /// \n /// The value delimiter can be either ',' or ';' and the range separator can be\n /// either '-' or ':'. Whitespace is permitted at any point in the input.\n /// \n /// Any elements of the sequence that contain non-digit, non-whitespace, or non-separator\n /// characters or that are empty are ignored and not returned in the output sequence.\n /// </remarks>\n public static IEnumerable<int> ParseRange2(this string s, int minValue, int maxValue) {\n const string pattern = @\"(?:^|(?<=[,;])) # match must begin with start of string or delim, where delim is , or ;\n \\s*( # leading whitespace\n (?<from>\\d*)\\s*(?:-|:)\\s*(?<to>\\d+) # capture 'from <sep> to' or '<sep> to', where <sep> is - or :\n | # or\n (?<from>\\d+)\\s*(?:-|:)\\s*(?<to>\\d*) # capture 'from <sep> to' or 'from <sep>', where <sep> is - or :\n | # or\n (?<num>\\d+) # capture lone number\n )\\s* # trailing whitespace\n (?:(?=[,;\\b])|$) # match must end with end of string or delim, where delim is , or ;\";\n\n Regex regx = new Regex(pattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);\n\n foreach (Match m in regx.Matches(s)) {\n Group gpNum = m.Groups[\"num\"];\n if (gpNum.Success) {\n yield return int.Parse(gpNum.Value);\n\n } else {\n Group gpFrom = m.Groups[\"from\"];\n Group gpTo = m.Groups[\"to\"];\n if (gpFrom.Success || gpTo.Success) {\n int from = (gpFrom.Success && gpFrom.Value.Length > 0 ? int.Parse(gpFrom.Value) : minValue);\n int to = (gpTo.Success && gpTo.Value.Length > 0 ? int.Parse(gpTo.Value) : maxValue);\n\n for (int i = from; i <= to; i++) {\n yield return i;\n }\n }\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 25334542,
"author": "Chris Fazzio",
"author_id": 1274209,
"author_profile": "https://Stackoverflow.com/users/1274209",
"pm_score": 3,
"selected": false,
"text": "<p>Below is the code I just put together to do this.. You can enter in the format like.. 1-2,5abcd,6,7,20-15,,,,,,</p>\n\n<p>easy to add-on for other formats</p>\n\n<pre><code> private int[] ParseRange(string ranges)\n { \n string[] groups = ranges.Split(',');\n return groups.SelectMany(t => GetRangeNumbers(t)).ToArray();\n }\n\n private int[] GetRangeNumbers(string range)\n {\n //string justNumbers = new String(text.Where(Char.IsDigit).ToArray());\n\n int[] RangeNums = range\n .Split('-')\n .Select(t => new String(t.Where(Char.IsDigit).ToArray())) // Digits Only\n .Where(t => !string.IsNullOrWhiteSpace(t)) // Only if has a value\n .Select(t => int.Parse(t)) // digit to int\n .ToArray();\n return RangeNums.Length.Equals(2) ? Enumerable.Range(RangeNums.Min(), (RangeNums.Max() + 1) - RangeNums.Min()).ToArray() : RangeNums;\n }\n</code></pre>\n"
},
{
"answer_id": 33666576,
"author": "w.b",
"author_id": 2720372,
"author_profile": "https://Stackoverflow.com/users/2720372",
"pm_score": 0,
"selected": false,
"text": "<p>The answer I came up with:</p>\n\n<pre><code>static IEnumerable<string> ParseRange(string str)\n{\n var numbers = str.Split(',');\n\n foreach (var n in numbers)\n {\n if (!n.Contains(\"-\")) \n yield return n;\n else\n {\n string startStr = String.Join(\"\", n.TakeWhile(c => c != '-'));\n int startInt = Int32.Parse(startStr);\n\n string endStr = String.Join(\"\", n.Reverse().TakeWhile(c => c != '-').Reverse());\n int endInt = Int32.Parse(endStr);\n\n var range = Enumerable.Range(startInt, endInt - startInt + 1)\n .Select(num => num.ToString());\n\n foreach (var s in range)\n yield return s;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 33667542,
"author": "bradgonesurfing",
"author_id": 158285,
"author_profile": "https://Stackoverflow.com/users/158285",
"pm_score": 2,
"selected": false,
"text": "<p>You can't be sure till you have test cases. In my case i would prefer to be white space delimited instead of comma delimited. It make the parsing a little more complex.</p>\n\n<pre><code> [Fact]\n public void ShouldBeAbleToParseRanges()\n {\n RangeParser.Parse( \"1\" ).Should().BeEquivalentTo( 1 );\n RangeParser.Parse( \"-1..2\" ).Should().BeEquivalentTo( -1,0,1,2 );\n\n RangeParser.Parse( \"-1..2 \" ).Should().BeEquivalentTo( -1,0,1,2 );\n RangeParser.Parse( \"-1..2 5\" ).Should().BeEquivalentTo( -1,0,1,2,5 );\n RangeParser.Parse( \" -1 .. 2 5\" ).Should().BeEquivalentTo( -1,0,1,2,5 );\n }\n</code></pre>\n\n<p>Note that Keith's answer ( or a small variation) will fail the last test where there is whitespace between the range token. This requires a tokenizer and a proper parser with lookahead.</p>\n\n<pre><code>namespace Utils\n{\n public class RangeParser\n {\n\n public class RangeToken\n {\n public string Name;\n public string Value;\n }\n\n public static IEnumerable<RangeToken> Tokenize(string v)\n {\n var pattern =\n @\"(?<number>-?[1-9]+[0-9]*)|\" +\n @\"(?<range>\\.\\.)\";\n\n var regex = new Regex( pattern );\n var matches = regex.Matches( v );\n foreach (Match match in matches)\n {\n var numberGroup = match.Groups[\"number\"];\n if (numberGroup.Success)\n {\n yield return new RangeToken {Name = \"number\", Value = numberGroup.Value};\n continue;\n }\n var rangeGroup = match.Groups[\"range\"];\n if (rangeGroup.Success)\n {\n yield return new RangeToken {Name = \"range\", Value = rangeGroup.Value};\n }\n\n }\n }\n\n public enum State { Start, Unknown, InRange}\n\n public static IEnumerable<int> Parse(string v)\n {\n\n var tokens = Tokenize( v );\n var state = State.Start;\n var number = 0;\n\n foreach (var token in tokens)\n {\n switch (token.Name)\n {\n case \"number\":\n var nextNumber = int.Parse( token.Value );\n switch (state)\n {\n case State.Start:\n number = nextNumber;\n state = State.Unknown;\n break;\n case State.Unknown:\n yield return number;\n number = nextNumber;\n break;\n case State.InRange:\n int rangeLength = nextNumber - number+ 1;\n foreach (int i in Enumerable.Range( number, rangeLength ))\n {\n yield return i;\n }\n state = State.Start;\n break;\n default:\n throw new ArgumentOutOfRangeException();\n }\n break;\n case \"range\":\n switch (state)\n {\n case State.Start:\n throw new ArgumentOutOfRangeException();\n break;\n case State.Unknown:\n state = State.InRange;\n break;\n case State.InRange:\n throw new ArgumentOutOfRangeException();\n break;\n default:\n throw new ArgumentOutOfRangeException();\n }\n break;\n default:\n throw new ArgumentOutOfRangeException( nameof( token ) );\n }\n }\n switch (state)\n {\n case State.Start:\n break;\n case State.Unknown:\n yield return number;\n break;\n case State.InRange:\n break;\n default:\n throw new ArgumentOutOfRangeException();\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 43974476,
"author": "jdweng",
"author_id": 5015238,
"author_profile": "https://Stackoverflow.com/users/5015238",
"pm_score": 0,
"selected": false,
"text": "<p>Regex is not efficient as following code. String methods are more efficient than Regex and should be used when possible.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n string[] inputs = {\n \"001-005/015\",\n \"009/015\"\n };\n\n foreach (string input in inputs)\n {\n List<int> numbers = new List<int>();\n string[] strNums = input.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);\n foreach (string strNum in strNums)\n {\n if (strNum.Contains(\"-\"))\n {\n int startNum = int.Parse(strNum.Substring(0, strNum.IndexOf(\"-\")));\n int endNum = int.Parse(strNum.Substring(strNum.IndexOf(\"-\") + 1));\n for (int i = startNum; i <= endNum; i++)\n {\n numbers.Add(i);\n }\n }\n else\n numbers.Add(int.Parse(strNum));\n }\n Console.WriteLine(string.Join(\",\", numbers.Select(x => x.ToString())));\n }\n Console.ReadLine();\n\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 43974770,
"author": "fubo",
"author_id": 1315444,
"author_profile": "https://Stackoverflow.com/users/1315444",
"pm_score": 1,
"selected": false,
"text": "<p>One line approach with <code>Split</code> and <code>Linq</code></p>\n\n<pre><code>string input = \"1,3,5-10,12\";\nIEnumerable<int> result = input.Split(',').SelectMany(x => x.Contains('-') ? Enumerable.Range(int.Parse(x.Split('-')[0]), int.Parse(x.Split('-')[1]) - int.Parse(x.Split('-')[0]) + 1) : new int[] { int.Parse(x) });\n</code></pre>\n"
},
{
"answer_id": 51023394,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>My solution:</p>\n\n<ul>\n<li>return list of integers</li>\n<li>reversed/typo/duplicate possible: 1,-3,5-,7-10,12-9 => 1,3,5,7,8,9,10,12,11,10,9 (used when you want to extract, repeat pages)</li>\n<li>option to set total of pages: 1,-3,5-,7-10,12-9 (Nmax=9) => 1,3,5,7,8,9,9</li>\n<li><p>autocomplete: 1,-3,5-,8 (Nmax=9) => 1,3,5,6,7,8,9,8</p>\n\n<pre><code> public static List<int> pageRangeToList(string pageRg, int Nmax = 0)\n{\n List<int> ls = new List<int>();\n int lb,ub,i;\n foreach (string ss in pageRg.Split(','))\n {\n if(int.TryParse(ss,out lb)){\n ls.Add(Math.Abs(lb));\n } else {\n var subls = ss.Split('-').ToList();\n lb = (int.TryParse(subls[0],out i)) ? i : 0;\n ub = (int.TryParse(subls[1],out i)) ? i : Nmax;\n ub = ub > 0 ? ub : lb; // if ub=0, take 1 value of lb\n for(i=0;i<=Math.Abs(ub-lb);i++) \n ls.Add(lb<ub? i+lb : lb-i);\n }\n }\n Nmax = Nmax > 0 ? Nmax : ls.Max(); // real Nmax\n return ls.Where(s => s>0 && s<=Nmax).ToList();\n}\n</code></pre></li>\n</ul>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | Does C# have built-in support for parsing strings of page numbers? By page numbers, I mean the format you might enter into a print dialog that's a mixture of comma and dash-delimited.
Something like this:
```
1,3,5-10,12
```
What would be really nice is a solution that gave me back some kind of list of all page numbers represented by the string. In the above example, getting a list back like this would be nice:
```
1,3,5,6,7,8,9,10,12
```
I just want to avoid rolling my own if there's an easy way to do it. | Should be simple:
```
foreach( string s in "1,3,5-10,12".Split(',') )
{
// try and get the number
int num;
if( int.TryParse( s, out num ) )
{
yield return num;
continue; // skip the rest
}
// otherwise we might have a range
// split on the range delimiter
string[] subs = s.Split('-');
int start, end;
// now see if we can parse a start and end
if( subs.Length > 1 &&
int.TryParse(subs[0], out start) &&
int.TryParse(subs[1], out end) &&
end >= start )
{
// create a range between the two values
int rangeLength = end - start + 1;
foreach(int i in Enumerable.Range(start, rangeLength))
{
yield return i;
}
}
}
```
**Edit:** thanks for the fix ;-) |
40,193 | <p>I've got to get a directory listing that contains about 2 million files, but when I do an <code>ls</code> command on it nothing comes back. I've waited 3 hours. I've tried <code>ls | tee directory.txt</code>, but that seems to hang forever. </p>
<p>I assume the server is doing a lot of inode sorting. Is there any way to speed up the <code>ls</code> command to just get a directory listing of filenames? I don't care about size, dates, permission or the like at this time.</p>
| [
{
"answer_id": 40195,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 1,
"selected": false,
"text": "<p>How about <code>find ./ -type f</code> (which will find all files in the currently directory)? Take off the <code>-type f</code> to find everything.</p>\n"
},
{
"answer_id": 40200,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 4,
"selected": false,
"text": "<p>Try using:</p>\n\n<pre><code>find . -type f -maxdepth 1\n</code></pre>\n\n<p>This will only list the files in the directory, leave out the <code>-type f</code> argument if you want to list files and directories.</p>\n"
},
{
"answer_id": 40201,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 1,
"selected": false,
"text": "<p>Things to try:</p>\n\n<p>Check ls isn't aliased?</p>\n\n<pre><code>alias ls\n</code></pre>\n\n<p>Perhaps try find instead?</p>\n\n<pre><code>find . \\( -type d -name . -prune \\) -o \\( -type f -print \\)\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 40202,
"author": "Eric",
"author_id": 4277,
"author_profile": "https://Stackoverflow.com/users/4277",
"pm_score": 3,
"selected": false,
"text": "<p>You can redirect output and run the ls process in the background.</p>\n\n<pre><code>ls > myls.txt &\n</code></pre>\n\n<p>This would allow you to go on about your business while its running. It wouldn't lock up your shell.</p>\n\n<p>Not sure about what options are for running ls and getting less data back. You could always run <code>man ls</code> to check.</p>\n"
},
{
"answer_id": 40204,
"author": "wbkang",
"author_id": 2710,
"author_profile": "https://Stackoverflow.com/users/2710",
"pm_score": 2,
"selected": false,
"text": "<p>I'm assuming you are using GNU ls? \ntry</p>\n\n<pre><code>\\ls\n</code></pre>\n\n<p>It will unalias the usual ls (ls --color=auto).</p>\n"
},
{
"answer_id": 40206,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 6,
"selected": false,
"text": "<pre><code>ls -U\n</code></pre>\n<p>will do the ls without sorting.</p>\n<p>Another source of slowness is <code>--color</code>. On some linux machines, there is a convenience alias which adds <code>--color=auto'</code> to the ls call, making it look up file attributes for each file found (slow), to color the display. This can be avoided by <code>ls -U --color=never</code> or <code>\\ls -U</code>.</p>\n"
},
{
"answer_id": 40301,
"author": "Tanj",
"author_id": 4275,
"author_profile": "https://Stackoverflow.com/users/4275",
"pm_score": 1,
"selected": false,
"text": "<p>What partition type are you using? </p>\n\n<p>Having millions of small files in one directory it might be a good idea to use JFS or ReiserFS which have better performance with many small sized files.</p>\n"
},
{
"answer_id": 40433,
"author": "tonylo",
"author_id": 4071,
"author_profile": "https://Stackoverflow.com/users/4071",
"pm_score": 0,
"selected": false,
"text": "<p>You should provide information about what operating system and the type of filesystem you are using. On certain flavours of UNIX and certain filesystems you might be able to use the commands <a href=\"http://www.unix.com/man-page/all/0/ff\" rel=\"nofollow noreferrer\"><code>ff</code></a> and <a href=\"http://www.unix.com/man-page/all/0/ncheck\" rel=\"nofollow noreferrer\"><code>ncheck</code></a> as alternatives.</p>\n"
},
{
"answer_id": 40496,
"author": "Benedikt Waldvogel",
"author_id": 4308,
"author_profile": "https://Stackoverflow.com/users/4308",
"pm_score": 2,
"selected": false,
"text": "<p>If a process \"doesn't come back\", I recommend <a href=\"http://linux.die.net/man/1/strace\" rel=\"nofollow noreferrer\">strace</a> to analyze how a process is interacting with the operating system.</p>\n\n<p>In case of ls:</p>\n\n<pre><code>$strace ls\n</code></pre>\n\n<p>you would have seen that it reads all directory entries (<a href=\"http://linux.die.net/man/2/getdents\" rel=\"nofollow noreferrer\">getdents(2)</a>) before it actually outputs anything. (sorting… as it was already mentioned here)</p>\n"
},
{
"answer_id": 41088,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": -1,
"selected": false,
"text": "<p>Lots of other good solutions here, but in the interest of completeness:</p>\n\n<pre><code>echo *\n</code></pre>\n"
},
{
"answer_id": 75731,
"author": "Jim",
"author_id": 12419,
"author_profile": "https://Stackoverflow.com/users/12419",
"pm_score": -1,
"selected": false,
"text": "<p>You can also make use of <em>xargs</em>. Just pipe the output of <em>ls</em> through <em>xargs</em>.</p>\n\n<pre><code>ls | xargs\n</code></pre>\n\n<p>If that doesn't work and the <em>find</em> examples above aren't working, try piping them to <em>xargs</em> as it can help the memory usage that might be causing your problems.</p>\n"
},
{
"answer_id": 1650700,
"author": "Rich Homolka",
"author_id": 128439,
"author_profile": "https://Stackoverflow.com/users/128439",
"pm_score": 1,
"selected": false,
"text": "<p>Some followup:\nYou don't mention what OS you're running on, which would help indicate which version of ls you're using. This probably isn't a 'bash' question as much as an ls question. My guess is that you're using GNU ls, which has some features that are useful in some contexts, but kill you on big directories.</p>\n\n<p>GNU ls Trying to have prettier arranging of columns. GNU ls tries to do a smart arrange of all the filenames. In a huge directory, this will take some time, and memory.</p>\n\n<p>To 'fix' this, you can try:</p>\n\n<p><code>ls -1</code> # no columns at all</p>\n\n<p>find BSD ls someplace, <a href=\"http://www.freebsd.org/cgi/cvsweb.cgi/src/bin/ls/\" rel=\"nofollow noreferrer\" title=\"FreeBSD ls source\">http://www.freebsd.org/cgi/cvsweb.cgi/src/bin/ls/</a> and use that on your big directories.</p>\n\n<p>Use other tools, such as find</p>\n"
},
{
"answer_id": 3619973,
"author": "telent",
"author_id": 419653,
"author_profile": "https://Stackoverflow.com/users/419653",
"pm_score": 2,
"selected": false,
"text": "<p>This is probably not a helpful answer, but if you don't have <code>find</code> you may be able to make do with <code>tar</code></p>\n\n<pre><code>$ tar cvf /dev/null .\n</code></pre>\n\n<p>I am told by people older than me that, \"back in the day\", single-user and recovery environments were a lot more limited than they are nowadays. That's where this trick comes from.</p>\n"
},
{
"answer_id": 18464192,
"author": "plasmafire",
"author_id": 2721409,
"author_profile": "https://Stackoverflow.com/users/2721409",
"pm_score": 3,
"selected": false,
"text": "<p>This would be the fastest option AFAIK: <code>ls -1 -f</code>.</p>\n\n<ul>\n<li><code>-1</code> (No columns)</li>\n<li><code>-f</code> (No sorting)</li>\n</ul>\n"
},
{
"answer_id": 26295448,
"author": "Pouya",
"author_id": 4083267,
"author_profile": "https://Stackoverflow.com/users/4083267",
"pm_score": 1,
"selected": false,
"text": "<p>There are several ways to get a list of files:</p>\n\n<p>Use this command to get a list without sorting:</p>\n\n<pre><code>ls -U\n</code></pre>\n\n<p>or send the list of files to a file by using:</p>\n\n<pre><code>ls /Folder/path > ~/Desktop/List.txt\n</code></pre>\n"
},
{
"answer_id": 26691147,
"author": "Limalski",
"author_id": 4205706,
"author_profile": "https://Stackoverflow.com/users/4205706",
"pm_score": 3,
"selected": false,
"text": "<p>Using </p>\n\n<pre><code>ls -1 -f \n</code></pre>\n\n<p>is about 10 times faster and it is easy to do (I tested with 1 million files, but my original problem had 6 800 000 000 files)</p>\n\n<p>But in my case I needed to check if some specific directory contains more than 10 000 files. If there were more than 10 000 files, I am not anymore interested that how many files there is. I just quit the program so that it will run faster and wont try to read the rest one-by-one. If there are less than 10 000, I will print the exact amount. Speed of my program is quite similar to ls -1 -f if you specify bigger value for parameter than amount of files.</p>\n\n<p>You can use my program find_if_more.pl in current directory by typing:</p>\n\n<pre><code>find_if_more.pl 999999999\n</code></pre>\n\n<p>If you are just interested if there are more than n files, script will finish faster than ls -1 -f with very large amount of files.</p>\n\n<pre><code>#!/usr/bin/perl\n use warnings;\n my ($maxcount) = @ARGV;\n my $dir = '.';\n $filecount = 0;\n if (not defined $maxcount) {\n die \"Need maxcount\\n\";\n }\n opendir(DIR, $dir) or die $!;\n while (my $file = readdir(DIR)) {\n $filecount = $filecount + 1;\n last if $filecount> $maxcount\n }\n print $filecount;\n closedir(DIR);\n exit 0;\n</code></pre>\n"
},
{
"answer_id": 26699902,
"author": "Kannan Mohan",
"author_id": 1198887,
"author_profile": "https://Stackoverflow.com/users/1198887",
"pm_score": 3,
"selected": false,
"text": "<p>This question seems to be interesting and I was going through multiple answers that were posted. To understand the efficiency of the answers posted, I have executed them on 2 million files and found the results as below.</p>\n\n<pre><code>$ time tar cvf /dev/null . &> /tmp/file-count\n\nreal 37m16.553s\nuser 0m11.525s\nsys 0m41.291s\n\n------------------------------------------------------\n\n$ time echo ./* &> /tmp/file-count\n\nreal 0m50.808s\nuser 0m49.291s\nsys 0m1.404s\n\n------------------------------------------------------\n\n$ time ls &> /tmp/file-count\n\nreal 0m42.167s\nuser 0m40.323s\nsys 0m1.648s\n\n------------------------------------------------------\n\n$ time find . &> /tmp/file-count\n\nreal 0m2.738s\nuser 0m1.044s\nsys 0m1.684s\n\n------------------------------------------------------\n\n$ time ls -U &> /tmp/file-count\n\nreal 0m2.494s\nuser 0m0.848s\nsys 0m1.452s\n\n\n------------------------------------------------------\n\n$ time ls -f &> /tmp/file-count\n\nreal 0m2.313s\nuser 0m0.856s\nsys 0m1.448s\n\n------------------------------------------------------\n</code></pre>\n\n<p>To summarize the results</p>\n\n<ol>\n<li><code>ls -f</code> command ran a bit faster than <code>ls -U</code>. Disabling color might have caused this improvement.</li>\n<li><code>find</code> command ran third with an average speed of 2.738 seconds. </li>\n<li>Running just <code>ls</code> took 42.16 seconds. Here in my system <code>ls</code> is an alias for <code>ls --color=auto</code></li>\n<li>Using shell expansion feature with <code>echo ./*</code> ran for 50.80 seconds.</li>\n<li>And the <code>tar</code> based solution took about 37 miuntes.</li>\n</ol>\n\n<p>All tests were done seperately when system was in idle condition.</p>\n\n<p>One important thing to note here is that the file lists are not printed in the terminal rather\nthey were redirected to a file and the file count was calculated later with <code>wc</code> command.\nCommands ran too slow if the outputs where printed on the screen.</p>\n\n<p>Any ideas why this happens ?</p>\n"
},
{
"answer_id": 33785526,
"author": "stu",
"author_id": 12386,
"author_profile": "https://Stackoverflow.com/users/12386",
"pm_score": 4,
"selected": false,
"text": "<p>I have a directory with 4 million files in it and the only way I got ls to spit out files immediately without a lot of churning first was</p>\n\n<pre><code>ls -1U\n</code></pre>\n"
},
{
"answer_id": 61469784,
"author": "blacksite",
"author_id": 5015569,
"author_profile": "https://Stackoverflow.com/users/5015569",
"pm_score": 0,
"selected": false,
"text": "<p>I had a directory with timestamps in the file names. I wanted to check the date of the latest file and found <code>find . -type f -maxdepth 1 | sort | tail -n 1</code> to be about twice as fast as <code>ls -alh</code>.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1536194/"
] | I've got to get a directory listing that contains about 2 million files, but when I do an `ls` command on it nothing comes back. I've waited 3 hours. I've tried `ls | tee directory.txt`, but that seems to hang forever.
I assume the server is doing a lot of inode sorting. Is there any way to speed up the `ls` command to just get a directory listing of filenames? I don't care about size, dates, permission or the like at this time. | ```
ls -U
```
will do the ls without sorting.
Another source of slowness is `--color`. On some linux machines, there is a convenience alias which adds `--color=auto'` to the ls call, making it look up file attributes for each file found (slow), to color the display. This can be avoided by `ls -U --color=never` or `\ls -U`. |
40,211 | <p>I have a flag enum below.</p>
<pre><code>[Flags]
public enum FlagTest
{
None = 0x0,
Flag1 = 0x1,
Flag2 = 0x2,
Flag3 = 0x4
}
</code></pre>
<p>I cannot make the if statement evaluate to true.</p>
<pre><code>FlagTest testItem = FlagTest.Flag1 | FlagTest.Flag2;
if (testItem == FlagTest.Flag1)
{
// Do something,
// however This is never true.
}
</code></pre>
<p>How can I make this true?</p>
| [
{
"answer_id": 40213,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 3,
"selected": false,
"text": "<p>For bit operations, you need to use bitwise operators.</p>\n\n<p>This should do the trick:</p>\n\n<pre><code>if ((testItem & FlagTest.Flag1) == FlagTest.Flag1)\n{\n // Do something,\n // however This is never true.\n}\n</code></pre>\n\n<p><strong>Edit:</strong> Fixed my if check - I slipped back into my C/C++ ways (thanks to Ryan Farley for pointing it out)</p>\n"
},
{
"answer_id": 40217,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 8,
"selected": false,
"text": "<pre><code>if ((testItem & FlagTest.Flag1) == FlagTest.Flag1)\n{\n // Do something\n}\n</code></pre>\n\n<p><code>(testItem & FlagTest.Flag1)</code> is a bitwise AND operation.</p>\n\n<p><code>FlagTest.Flag1</code> is equivalent to <code>001</code> with OP's enum. Now let's say <code>testItem</code> has Flag1 and Flag2 (so it's bitwise <code>101</code>):</p>\n\n<pre><code> 001\n &101\n ----\n 001 == FlagTest.Flag1\n</code></pre>\n"
},
{
"answer_id": 40218,
"author": "Damian",
"author_id": 3390,
"author_profile": "https://Stackoverflow.com/users/3390",
"pm_score": 3,
"selected": false,
"text": "<pre><code>if((testItem & FlagTest.Flag1) == FlagTest.Flag1) \n{\n...\n}\n</code></pre>\n"
},
{
"answer_id": 40221,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:\n<pre><code>\nif ((testItem & FlagTest.Flag1) == FlagTest.Flag1)\n{\n // do something\n}\n</code></pre>Basically, your code is asking if having both flags set is the same as having one flag set, which is obviously false. The code above will leave only the Flag1 bit set if it is set at all, then compares this result to Flag1.</p>\n"
},
{
"answer_id": 40239,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": false,
"text": "<p>I set up an extension method to do it: <a href=\"https://stackoverflow.com/questions/7244/anyone-know-a-good-workaround-for-the-lack-of-an-enum-generic-constraint\">related question</a>.</p>\n\n<p>Basically:</p>\n\n<pre><code>public static bool IsSet( this Enum input, Enum matchTo )\n{\n return ( Convert.ToUInt32( input ) & Convert.ToUInt32( matchTo ) ) != 0;\n}\n</code></pre>\n\n<p>Then you can do:</p>\n\n<pre><code>FlagTests testItem = FlagTests.Flag1 | FlagTests.Flag2;\n\nif( testItem.IsSet ( FlagTests.Flag1 ) )\n //Flag1 is set\n</code></pre>\n\n<hr>\n\n<p>Incidentally the convention I use for enums is singular for standard, plural for flags. That way you know from the enum name whether it can hold multiple values.</p>\n"
},
{
"answer_id": 40268,
"author": "Martin Clarke",
"author_id": 2422,
"author_profile": "https://Stackoverflow.com/users/2422",
"pm_score": 3,
"selected": false,
"text": "<p>Regarding the edit. You can't make it true. I suggest you wrap what you want into another class (or extension method) to get closer to the syntax you need. </p>\n\n<p>i.e. </p>\n\n<pre><code>public class FlagTestCompare\n{\n public static bool Compare(this FlagTest myFlag, FlagTest condition)\n {\n return ((myFlag & condition) == condition);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1769763,
"author": "Phil Devaney",
"author_id": 88468,
"author_profile": "https://Stackoverflow.com/users/88468",
"pm_score": 9,
"selected": true,
"text": "<p>In .NET 4 there is a new method <a href=\"http://msdn.microsoft.com/en-us/library/system.enum.hasflag%28VS.100%29.aspx\" rel=\"noreferrer\">Enum.HasFlag</a>. This allows you to write:</p>\n\n<pre><code>if ( testItem.HasFlag( FlagTest.Flag1 ) )\n{\n // Do Stuff\n}\n</code></pre>\n\n<p>which is much more readable, IMO.</p>\n\n<p>The .NET source indicates that this performs the same logic as the accepted answer:</p>\n\n<pre><code>public Boolean HasFlag(Enum flag) {\n if (!this.GetType().IsEquivalentTo(flag.GetType())) {\n throw new ArgumentException(\n Environment.GetResourceString(\n \"Argument_EnumTypeDoesNotMatch\", \n flag.GetType(), \n this.GetType()));\n }\n\n ulong uFlag = ToUInt64(flag.GetValue()); \n ulong uThis = ToUInt64(GetValue());\n // test predicate\n return ((uThis & uFlag) == uFlag); \n}\n</code></pre>\n"
},
{
"answer_id": 1769814,
"author": "Sekhat",
"author_id": 1610,
"author_profile": "https://Stackoverflow.com/users/1610",
"pm_score": 6,
"selected": false,
"text": "<p>For those who have trouble visualizing what is happening with the accepted solution\n(which is this),</p>\n\n<pre><code>if ((testItem & FlagTest.Flag1) == FlagTest.Flag1)\n{\n // Do stuff.\n}\n</code></pre>\n\n<p><code>testItem</code> (as per the question) is defined as,</p>\n\n<pre><code>testItem \n = flag1 | flag2 \n = 001 | 010 \n = 011\n</code></pre>\n\n<p>Then, in the if statement, the left hand side of the comparison is,</p>\n\n<pre><code>(testItem & flag1) \n = (011 & 001) \n = 001\n</code></pre>\n\n<p>And the full if statement (that evaluates to true if <code>flag1</code> is set in <code>testItem</code>),</p>\n\n<pre><code>(testItem & flag1) == flag1\n = (001) == 001\n = true\n</code></pre>\n"
},
{
"answer_id": 3412480,
"author": "Leonid",
"author_id": 372909,
"author_profile": "https://Stackoverflow.com/users/372909",
"pm_score": 4,
"selected": false,
"text": "<p>One more piece of advice... Never do the standard binary check with the flag whose value is \"0\". Your check on this flag will always be true.</p>\n\n<pre><code>[Flags]\npublic enum LevelOfDetail\n{\n [EnumMember(Value = \"FullInfo\")]\n FullInfo=0,\n [EnumMember(Value = \"BusinessData\")]\n BusinessData=1\n}\n</code></pre>\n\n<hr>\n\n<p>If you binary check input parameter against FullInfo - you get:</p>\n\n<pre><code>detailLevel = LevelOfDetail.BusinessData;\nbool bPRez = (detailLevel & LevelOfDetail.FullInfo) == LevelOfDetail.FullInfo;\n</code></pre>\n\n<p>bPRez will always be true as ANYTHING & 0 always == 0.</p>\n\n<hr>\n\n<p>Instead you should simply check that the value of the input is 0:</p>\n\n<pre><code>bool bPRez = (detailLevel == LevelOfDetail.FullInfo);\n</code></pre>\n"
},
{
"answer_id": 7164314,
"author": "Chuck Dee",
"author_id": 275594,
"author_profile": "https://Stackoverflow.com/users/275594",
"pm_score": 5,
"selected": false,
"text": "<p>@phil-devaney</p>\n\n<p>Note that except in the simplest of cases, the <a href=\"http://msdn.microsoft.com/en-us/library/system.enum.hasflag%28VS.100%29.aspx\" rel=\"noreferrer\">Enum.HasFlag</a> carries a heavy performance penalty in comparison to writing out the code manually. Consider the following code:</p>\n\n<pre><code>[Flags]\npublic enum TestFlags\n{\n One = 1,\n Two = 2,\n Three = 4,\n Four = 8,\n Five = 16,\n Six = 32,\n Seven = 64,\n Eight = 128,\n Nine = 256,\n Ten = 512\n}\n\n\nclass Program\n{\n static void Main(string[] args)\n {\n TestFlags f = TestFlags.Five; /* or any other enum */\n bool result = false;\n\n Stopwatch s = Stopwatch.StartNew();\n for (int i = 0; i < 10000000; i++)\n {\n result |= f.HasFlag(TestFlags.Three);\n }\n s.Stop();\n Console.WriteLine(s.ElapsedMilliseconds); // *4793 ms*\n\n s.Restart();\n for (int i = 0; i < 10000000; i++)\n {\n result |= (f & TestFlags.Three) != 0;\n }\n s.Stop();\n Console.WriteLine(s.ElapsedMilliseconds); // *27 ms* \n\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p>Over 10 million iterations, the HasFlags extension method takes a whopping 4793 ms, compared to the 27 ms for the standard bitwise implementation. </p>\n"
},
{
"answer_id": 33811816,
"author": "Waleed A.K.",
"author_id": 347374,
"author_profile": "https://Stackoverflow.com/users/347374",
"pm_score": 1,
"selected": false,
"text": "<p>even without [Flags], you could use something like this</p>\n\n<pre><code>if((testItem & (FlagTest.Flag1 | FlagTest.Flag2 ))!=0){\n//..\n}\n</code></pre>\n\n<p>or if you have a Zero value enum</p>\n\n<pre><code>if((testItem & (FlagTest.Flag1 | FlagTest.Flag2 ))!=FlagTest.None){\n//..\n}\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
] | I have a flag enum below.
```
[Flags]
public enum FlagTest
{
None = 0x0,
Flag1 = 0x1,
Flag2 = 0x2,
Flag3 = 0x4
}
```
I cannot make the if statement evaluate to true.
```
FlagTest testItem = FlagTest.Flag1 | FlagTest.Flag2;
if (testItem == FlagTest.Flag1)
{
// Do something,
// however This is never true.
}
```
How can I make this true? | In .NET 4 there is a new method [Enum.HasFlag](http://msdn.microsoft.com/en-us/library/system.enum.hasflag%28VS.100%29.aspx). This allows you to write:
```
if ( testItem.HasFlag( FlagTest.Flag1 ) )
{
// Do Stuff
}
```
which is much more readable, IMO.
The .NET source indicates that this performs the same logic as the accepted answer:
```
public Boolean HasFlag(Enum flag) {
if (!this.GetType().IsEquivalentTo(flag.GetType())) {
throw new ArgumentException(
Environment.GetResourceString(
"Argument_EnumTypeDoesNotMatch",
flag.GetType(),
this.GetType()));
}
ulong uFlag = ToUInt64(flag.GetValue());
ulong uThis = ToUInt64(GetValue());
// test predicate
return ((uThis & uFlag) == uFlag);
}
``` |
40,244 | <p>Assume that I have programs <code>P0</code>, <code>P1</code>, ...<code>P(n-1)</code> for some <code>n > 0</code>. How can I easily redirect the output of program <code>Pi</code> to program <code>P(i+1 mod n)</code> for all <code>i</code> (<code>0 <= i < n</code>)?</p>
<p>For example, let's say I have a program <code>square</code>, which repeatedly reads a number and than prints the square of that number, and a program <code>calc</code>, which sometimes prints a number after which it expects to be able to read the square of it. How do I connect these programs such that whenever <code>calc</code> prints a number, <code>square</code> squares it returns it to <code>calc</code>?</p>
<p>Edit: I should probably clarify what I mean with "easily". The named pipe/fifo solution is one that indeed works (and I have used in the past), but it actually requires quite a bit of work to do properly if you compare it with using a bash pipe. (You need to get a not yet existing filename, make a pipe with that name, run the "pipe loop", clean up the named pipe.) Imagine you could no longer write <code>prog1 | prog2</code> and would always have to use named pipes to connect programs.</p>
<p>I'm looking for something that is almost as easy as writing a "normal" pipe. For instance something like <code>{ prog1 | prog2 } >&0</code> would be great.</p>
| [
{
"answer_id": 40339,
"author": "Mark Witczak",
"author_id": 1536194,
"author_profile": "https://Stackoverflow.com/users/1536194",
"pm_score": 3,
"selected": false,
"text": "<p>This is a very interesting question. I (vaguely) remember an assignment very similar in college 17 years ago. We had to create an array of pipes, where our code would get filehandles for the input/output of each pipe. Then the code would fork and close the unused filehandles. </p>\n\n<p>I'm thinking you could do something similar with named pipes in bash. Use mknod or mkfifo to create a set of pipes with unique names you can reference then fork your program. </p>\n"
},
{
"answer_id": 40555,
"author": "Penz",
"author_id": 4118,
"author_profile": "https://Stackoverflow.com/users/4118",
"pm_score": -1,
"selected": false,
"text": "<p>I doubt sh/bash can do it.\nZSH would be a better bet, with its MULTIOS and coproc features.</p>\n"
},
{
"answer_id": 40642,
"author": "1729",
"author_id": 4319,
"author_profile": "https://Stackoverflow.com/users/4319",
"pm_score": 1,
"selected": false,
"text": "<p>Named pipes.</p>\n\n<p>Create a series of fifos, using mkfifo</p>\n\n<p>i.e fifo0, fifo1</p>\n\n<p>Then attach each process in term to the pipes you want:</p>\n\n<p>processn < fifo(n-1) > fifon</p>\n"
},
{
"answer_id": 40644,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 4,
"selected": false,
"text": "<p>A named pipe might do it:</p>\n\n<pre><code>$ mkfifo outside\n$ <outside calc | square >outside &\n$ echo \"1\" >outside ## Trigger the loop to start\n</code></pre>\n"
},
{
"answer_id": 43332,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 5,
"selected": false,
"text": "<p>After spending quite some time yesterday trying to redirect <code>stdout</code> to <code>stdin</code>, I ended up with the following method. It isn't really nice, but I think I prefer it over the named pipe/fifo solution.</p>\n\n<pre><code>read | { P0 | ... | P(n-1); } >/dev/fd/0\n</code></pre>\n\n<p>The <code>{ ... } >/dev/fd/0</code> is to redirect stdout to stdin for the pipe sequence as a whole (i.e. it redirects the output of P(n-1) to the input of P0). Using <code>>&0</code> or something similar does not work; this is probably because bash assumes <code>0</code> is read-only while it doesn't mind writing to <code>/dev/fd/0</code>.</p>\n\n<p>The initial <code>read</code>-pipe is necessary because without it both the input and output file descriptor are the same pts device (at least on my system) and the redirect has no effect. (The pts device doesn't work as a pipe; writing to it puts things on your screen.) By making the input of the <code>{ ... }</code> a normal pipe, the redirect has the desired effect.</p>\n\n<p>To illustrate with my <code>calc</code>/<code>square</code> example:</p>\n\n<pre><code>function calc() {\n # calculate sum of squares of numbers 0,..,10\n\n sum=0\n for ((i=0; i<10; i++)); do\n echo $i # \"request\" the square of i\n\n read ii # read the square of i\n echo \"got $ii\" >&2 # debug message\n\n let sum=$sum+$ii\n done\n\n echo \"sum $sum\" >&2 # output result to stderr\n}\n\nfunction square() {\n # square numbers\n\n read j # receive first \"request\"\n while [ \"$j\" != \"\" ]; do\n let jj=$j*$j\n echo \"square($j) = $jj\" >&2 # debug message\n\n echo $jj # send square\n\n read j # receive next \"request\"\n done\n}\n\nread | { calc | square; } >/dev/fd/0\n</code></pre>\n\n<p>Running the above code gives the following output:</p>\n\n<pre><code>square(0) = 0\ngot 0\nsquare(1) = 1\ngot 1\nsquare(2) = 4\ngot 4\nsquare(3) = 9\ngot 9\nsquare(4) = 16\ngot 16\nsquare(5) = 25\ngot 25\nsquare(6) = 36\ngot 36\nsquare(7) = 49\ngot 49\nsquare(8) = 64\ngot 64\nsquare(9) = 81\ngot 81\nsum 285\n</code></pre>\n\n<p>Of course, this method is quite a bit of a hack. Especially the <code>read</code> part has an undesired side-effect: termination of the \"real\" pipe loop does not lead to termination of the whole. I couldn't think of anything better than <code>read</code> as it seems that you can only determine that the pipe loop has terminated by try to writing write something to it.</p>\n"
},
{
"answer_id": 464638,
"author": "Fritz G. Mehner",
"author_id": 57457,
"author_profile": "https://Stackoverflow.com/users/57457",
"pm_score": -1,
"selected": false,
"text": "<p>A command stack can be composed as string from an array of arbitrary commands\nand evaluated with eval. The following example gives the result 65536.</p>\n\n<pre><code>function square ()\n{\n read n\n echo $((n*n))\n} # ---------- end of function square ----------\n\ndeclare -a commands=( 'echo 4' 'square' 'square' 'square' )\n\n#-------------------------------------------------------------------------------\n# build the command stack using pipes\n#-------------------------------------------------------------------------------\ndeclare stack=${commands[0]}\n\nfor (( COUNTER=1; COUNTER<${#commands[@]}; COUNTER++ )); do\n stack=\"${stack} | ${commands[${COUNTER}]}\"\ndone\n\n#-------------------------------------------------------------------------------\n# run the command stack\n#-------------------------------------------------------------------------------\neval \"$stack\" \n</code></pre>\n"
},
{
"answer_id": 29053837,
"author": "Andreas Florath",
"author_id": 1247301,
"author_profile": "https://Stackoverflow.com/users/1247301",
"pm_score": 2,
"selected": false,
"text": "<p>My solutions uses <a href=\"https://github.com/flonatel/pipexec\" rel=\"nofollow\">pipexec</a> (Most of the function implementation comes from your answer):</p>\n\n<p>square.sh</p>\n\n<pre><code>function square() {\n # square numbers\n\n read j # receive first \"request\"\n while [ \"$j\" != \"\" ]; do\n let jj=$j*$j\n echo \"square($j) = $jj\" >&2 # debug message\n\n echo $jj # send square\n\n read j # receive next \"request\"\n done\n}\n\nsquare $@\n</code></pre>\n\n<p>calc.sh</p>\n\n<pre><code>function calc() {\n # calculate sum of squares of numbers 0,..,10\n\n sum=0\n for ((i=0; i<10; i++)); do\n echo $i # \"request\" the square of i\n\n read ii # read the square of i\n echo \"got $ii\" >&2 # debug message\n\n let sum=$sum+$ii\n done\n\n echo \"sum $sum\" >&2 # output result to stderr\n}\n\ncalc $@\n</code></pre>\n\n<p>The command</p>\n\n<pre><code>pipexec [ CALC /bin/bash calc.sh ] [ SQUARE /bin/bash square.sh ] \\\n \"{CALC:1>SQUARE:0}\" \"{SQUARE:1>CALC:0}\"\n</code></pre>\n\n<p>The output (same as in your answer)</p>\n\n<pre><code>square(0) = 0\ngot 0\nsquare(1) = 1\ngot 1\nsquare(2) = 4\ngot 4\nsquare(3) = 9\ngot 9\nsquare(4) = 16\ngot 16\nsquare(5) = 25\ngot 25\nsquare(6) = 36\ngot 36\nsquare(7) = 49\ngot 49\nsquare(8) = 64\ngot 64\nsquare(9) = 81\ngot 81\nsum 285\n</code></pre>\n\n<p>Comment: pipexec was designed to start processes and build arbitrary pipes in between. Because bash functions cannot be handled as processes, there is the need to have the functions in separate files and use a separate bash.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4285/"
] | Assume that I have programs `P0`, `P1`, ...`P(n-1)` for some `n > 0`. How can I easily redirect the output of program `Pi` to program `P(i+1 mod n)` for all `i` (`0 <= i < n`)?
For example, let's say I have a program `square`, which repeatedly reads a number and than prints the square of that number, and a program `calc`, which sometimes prints a number after which it expects to be able to read the square of it. How do I connect these programs such that whenever `calc` prints a number, `square` squares it returns it to `calc`?
Edit: I should probably clarify what I mean with "easily". The named pipe/fifo solution is one that indeed works (and I have used in the past), but it actually requires quite a bit of work to do properly if you compare it with using a bash pipe. (You need to get a not yet existing filename, make a pipe with that name, run the "pipe loop", clean up the named pipe.) Imagine you could no longer write `prog1 | prog2` and would always have to use named pipes to connect programs.
I'm looking for something that is almost as easy as writing a "normal" pipe. For instance something like `{ prog1 | prog2 } >&0` would be great. | After spending quite some time yesterday trying to redirect `stdout` to `stdin`, I ended up with the following method. It isn't really nice, but I think I prefer it over the named pipe/fifo solution.
```
read | { P0 | ... | P(n-1); } >/dev/fd/0
```
The `{ ... } >/dev/fd/0` is to redirect stdout to stdin for the pipe sequence as a whole (i.e. it redirects the output of P(n-1) to the input of P0). Using `>&0` or something similar does not work; this is probably because bash assumes `0` is read-only while it doesn't mind writing to `/dev/fd/0`.
The initial `read`-pipe is necessary because without it both the input and output file descriptor are the same pts device (at least on my system) and the redirect has no effect. (The pts device doesn't work as a pipe; writing to it puts things on your screen.) By making the input of the `{ ... }` a normal pipe, the redirect has the desired effect.
To illustrate with my `calc`/`square` example:
```
function calc() {
# calculate sum of squares of numbers 0,..,10
sum=0
for ((i=0; i<10; i++)); do
echo $i # "request" the square of i
read ii # read the square of i
echo "got $ii" >&2 # debug message
let sum=$sum+$ii
done
echo "sum $sum" >&2 # output result to stderr
}
function square() {
# square numbers
read j # receive first "request"
while [ "$j" != "" ]; do
let jj=$j*$j
echo "square($j) = $jj" >&2 # debug message
echo $jj # send square
read j # receive next "request"
done
}
read | { calc | square; } >/dev/fd/0
```
Running the above code gives the following output:
```
square(0) = 0
got 0
square(1) = 1
got 1
square(2) = 4
got 4
square(3) = 9
got 9
square(4) = 16
got 16
square(5) = 25
got 25
square(6) = 36
got 36
square(7) = 49
got 49
square(8) = 64
got 64
square(9) = 81
got 81
sum 285
```
Of course, this method is quite a bit of a hack. Especially the `read` part has an undesired side-effect: termination of the "real" pipe loop does not lead to termination of the whole. I couldn't think of anything better than `read` as it seems that you can only determine that the pipe loop has terminated by try to writing write something to it. |
40,264 | <p>Let's say you have a class called Customer, which contains the following fields:</p>
<ul>
<li>UserName</li>
<li>Email</li>
<li>First Name</li>
<li>Last Name</li>
</ul>
<p>Let's also say that according to your business logic, all Customer objects must have these four properties defined.</p>
<p>Now, we can do this pretty easily by forcing the constructor to specify each of these properties. But it's pretty easy to see how this can spiral out of control when you are forced to add more required fields to the Customer object. </p>
<p>I've seen classes that take in 20+ arguments into their constructor and it's just a pain to use them. But, alternatively, if you don't require these fields you run into the risk of having undefined information, or worse, object referencing errors if you rely on the calling code to specify these properties.</p>
<p>Are there any alternatives to this or do you you just have to decide whether X amount of constructor arguments is too many for you to live with?</p>
| [
{
"answer_id": 40276,
"author": "Aldie",
"author_id": 4133,
"author_profile": "https://Stackoverflow.com/users/4133",
"pm_score": -1,
"selected": false,
"text": "<p>Unless it's more than 1 argument, I always use arrays or objects as constructor parameters and rely on error checking to make sure the required parameters are there.</p>\n"
},
{
"answer_id": 40278,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 3,
"selected": false,
"text": "<p>If you have unpalatably many arguments, then just package them together into structs / POD classes, preferably declared as inner classes of the class you are constructing. That way you can still require the fields while making the code that calls the constructor reasonably readable.</p>\n"
},
{
"answer_id": 40284,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 1,
"selected": false,
"text": "<p>Just use default arguments. In a language that supports default method arguments (PHP, for example), you could do this in the method signature:</p>\n\n<p><code>public function doSomethingWith($this = val1, $this = val2, $this = val3)</code></p>\n\n<p>There are other ways to create default values, such as in languages that support method overloading.</p>\n\n<p>Of course, you could also set default values when you declare the fields, if you deem it appropriate to do so.</p>\n\n<p>It really just comes down to whether or not it is appropriate for you to set these default values, or if your objects should be specced out at construction all the time. That's really a decision that only you can make.</p>\n"
},
{
"answer_id": 40287,
"author": "Adam Hollidge",
"author_id": 4069,
"author_profile": "https://Stackoverflow.com/users/4069",
"pm_score": 2,
"selected": false,
"text": "<p>Style counts for a lot, and it seems to me that if there is a constructor with 20+ arguments, then the design should be altered. Provide reasonable defaults.</p>\n"
},
{
"answer_id": 40288,
"author": "Ethan Gunderson",
"author_id": 2066,
"author_profile": "https://Stackoverflow.com/users/2066",
"pm_score": 3,
"selected": false,
"text": "<p>I think it all depends on the situation. For something like your example, a customer class, I wouldn't risk the chance of having that data being undefined when needed. On the flip side, passing a struct would clear up the argument list, but you would still have a lot of things to define in the struct. </p>\n"
},
{
"answer_id": 40289,
"author": "helloandre",
"author_id": 50,
"author_profile": "https://Stackoverflow.com/users/50",
"pm_score": 2,
"selected": false,
"text": "<p>I would think the easiest way would be to find an acceptable default for each value. In this case, each field looks like it would be required to construct, so possibly overload the function call so that if something is not defined in the call, to set it to a default.</p>\n\n<p>Then, make getter and setter functions for each property so that the default values could be changed.</p>\n\n<p>Java implementation:</p>\n\n<pre><code>public static void setEmail(String newEmail){\n this.email = newEmail;\n}\n\npublic static String getEmail(){\n return this.email;\n}\n</code></pre>\n\n<p>This is also good practice to keep your global variables secure.</p>\n"
},
{
"answer_id": 40292,
"author": "Booji Boy",
"author_id": 1433,
"author_profile": "https://Stackoverflow.com/users/1433",
"pm_score": 2,
"selected": false,
"text": "<p>Steve Mcconnell writes in Code Complete that people have trouble keeping more 7 things in their head at a time, so that'd be the number I try to stay under. </p>\n"
},
{
"answer_id": 40298,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 1,
"selected": false,
"text": "<p>I agree on the 7 item limit Boojiboy mentions. Beyond that, it may be worth looking at anonymous (or specialized) types, IDictionary, or indirection via primary key to another data source.</p>\n"
},
{
"answer_id": 40299,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 3,
"selected": false,
"text": "<p>I think the \"pure OOP\" answer is that if operations on the class are invalid when certain members aren't initialized, then these members must be set by the constructor. There's always the case where default values can be used, but I'll assume we're not considering that case. This is a good approach when the API is fixed, because changing the single allowable constructor after the API goes public will be a nightmare for you and all users of your code.</p>\n\n<p>In C#, what I understand about the design guidelines is that this isn't necessarily the only way to handle the situation. Particularly with WPF objects, you'll find that .NET classes tend to favor parameterless constructors and will throw exceptions if the data has not been initialized to a desirable state before calling the method. This is probably mainly specific to component-based design though; I can't come up with a concrete example of a .NET class that behaves in this manner. In your case, it'd definitely cause an increased burden on testing to ensure that the class is never saved to the data store unless the properties have been validated. Honestly because of this I'd prefer the \"constructor sets the required properties\" approach if your API is either set in stone or not public.</p>\n\n<p>The one thing I <em>am</em> certain of is that there are probably countless methodologies that can solve this problem, and each of them introduces its own set of problems. The best thing to do is learn as many patterns as possible and pick the best one for the job. (Isn't that such a cop-out of an answer?)</p>\n"
},
{
"answer_id": 40300,
"author": "vitule",
"author_id": 1287,
"author_profile": "https://Stackoverflow.com/users/1287",
"pm_score": 3,
"selected": false,
"text": "<p>I think your question is more about the design of your classes than about the number of arguments in the constructor. If I needed 20 pieces of data (arguments) to successfully initialize an object, I would probably consider breaking up the class.</p>\n"
},
{
"answer_id": 40324,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 8,
"selected": true,
"text": "<p>Two design approaches to consider</p>\n\n<p>The <a href=\"http://www.hillside.net/plop/plop98/final_submissions/P10.pdf\" rel=\"noreferrer\">essence</a> pattern</p>\n\n<p>The <a href=\"https://martinfowler.com/bliki/FluentInterface.html\" rel=\"noreferrer\">fluent interface</a> pattern</p>\n\n<p>These are both similar in intent, in that we slowly build up an intermediate object, and then create our target object in a single step.</p>\n\n<p>An example of the fluent interface in action would be:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class CustomerBuilder {\n String surname;\n String firstName;\n String ssn;\n public static CustomerBuilder customer() {\n return new CustomerBuilder();\n }\n public CustomerBuilder withSurname(String surname) {\n this.surname = surname; \n return this; \n }\n public CustomerBuilder withFirstName(String firstName) {\n this.firstName = firstName;\n return this; \n }\n public CustomerBuilder withSsn(String ssn) {\n this.ssn = ssn; \n return this; \n }\n // client doesn't get to instantiate Customer directly\n public Customer build() {\n return new Customer(this); \n }\n}\n\npublic class Customer {\n private final String firstName;\n private final String surname;\n private final String ssn;\n\n Customer(CustomerBuilder builder) {\n if (builder.firstName == null) throw new NullPointerException(\"firstName\");\n if (builder.surname == null) throw new NullPointerException(\"surname\");\n if (builder.ssn == null) throw new NullPointerException(\"ssn\");\n this.firstName = builder.firstName;\n this.surname = builder.surname;\n this.ssn = builder.ssn;\n }\n\n public String getFirstName() { return firstName; }\n public String getSurname() { return surname; }\n public String getSsn() { return ssn; } \n}\n</code></pre>\n\n<pre class=\"lang-java prettyprint-override\"><code>import static com.acme.CustomerBuilder.customer;\n\npublic class Client {\n public void doSomething() {\n Customer customer = customer()\n .withSurname(\"Smith\")\n .withFirstName(\"Fred\")\n .withSsn(\"123XS1\")\n .build();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 40364,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 4,
"selected": false,
"text": "<p>In your case, stick with the constructor. The information belongs in Customer and 4 fields are fine. </p>\n\n<p>In the case you have many required and optional fields the constructor is not the best solution. As @boojiboy said, it's hard to read and it's also hard to write client code.</p>\n\n<p>@contagious suggested using the default pattern and setters for optional attributs. That mandates that the fields are mutable, but that's a minor problem.</p>\n\n<p>Joshua Block on Effective Java 2 say that in this case you should consider a builder. An example taken from the book:</p>\n\n<pre><code> public class NutritionFacts { \n private final int servingSize; \n private final int servings; \n private final int calories; \n private final int fat; \n private final int sodium; \n private final int carbohydrate; \n\n public static class Builder { \n // required parameters \n private final int servingSize; \n private final int servings; \n\n // optional parameters \n private int calories = 0; \n private int fat = 0; \n private int carbohydrate = 0; \n private int sodium = 0; \n\n public Builder(int servingSize, int servings) { \n this.servingSize = servingSize; \n this.servings = servings; \n } \n\n public Builder calories(int val) \n { calories = val; return this; } \n public Builder fat(int val) \n { fat = val; return this; } \n public Builder carbohydrate(int val) \n { carbohydrate = val; return this; } \n public Builder sodium(int val) \n { sodium = val; return this; } \n\n public NutritionFacts build() { \n return new NutritionFacts(this); \n } \n } \n\n private NutritionFacts(Builder builder) { \n servingSize = builder.servingSize; \n servings = builder.servings; \n calories = builder.calories; \n fat = builder.fat; \n soduim = builder.sodium; \n carbohydrate = builder.carbohydrate; \n } \n} \n</code></pre>\n\n<p>And then use it like this:</p>\n\n<pre><code>NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).\n calories(100).sodium(35).carbohydrate(27).build();\n</code></pre>\n\n<p>The example above was taken from <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201310058\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Effective Java 2</a></p>\n\n<p>And that doesn't only applies to constructor. Citing Kent Beck in <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321413091\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Implementation Patterns</a>:</p>\n\n<pre><code>setOuterBounds(x, y, width, height);\nsetInnerBounds(x + 2, y + 2, width - 4, height - 4);\n</code></pre>\n\n<p>Making the rectangle explicit as an object explains the code better:</p>\n\n<pre><code>setOuterBounds(bounds);\nsetInnerBounds(bounds.expand(-2));\n</code></pre>\n"
},
{
"answer_id": 40371,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 2,
"selected": false,
"text": "<p>I'd encapsulate similar fields into an object of its own with its own construction/validation logic.</p>\n\n<p>Say for example, if you've got</p>\n\n<ul>\n<li>BusinessPhone</li>\n<li>BusinessAddress</li>\n<li>HomePhone</li>\n<li>HomeAddress</li>\n</ul>\n\n<p>I'd make a class that stores phone and address together with a tag specifying wether its a \"home\" or a \"business\" phone/address. And then reduce the 4 fields to merely an array.</p>\n\n<pre><code>ContactInfo cinfos = new ContactInfo[] {\n new ContactInfo(\"home\", \"+123456789\", \"123 ABC Avenue\"),\n new ContactInfo(\"biz\", \"+987654321\", \"789 ZYX Avenue\")\n};\n\nCustomer c = new Customer(\"john\", \"doe\", cinfos);\n</code></pre>\n\n<p>That should make it look less like spaghetti.</p>\n\n<p>Surely if you have a lot of fields, there must be some pattern you can extract out that would make a nice unit of function of its own. And make for more readable code too.</p>\n\n<p>And the following is also possible solutions:</p>\n\n<ul>\n<li>Spread out the validation logic instead of storing it in a single class. Validate when user input them and then validate again at the database layer etc...</li>\n<li>Make a <code>CustomerFactory</code> class that would help me construct <code>Customer</code>s</li>\n<li>@marcio's solution is also interesting...</li>\n</ul>\n"
},
{
"answer_id": 15531632,
"author": "Keith Pinson",
"author_id": 834176,
"author_profile": "https://Stackoverflow.com/users/834176",
"pm_score": 5,
"selected": false,
"text": "<p>I see that some people are recommending seven as an upper limit. Apparently it is not true that people can hold seven things in their head at once; they can only remember four (Susan Weinschenk, <em>100 Things Every Designer Needs to Know about People</em>, 48). Even so, I consider four to be something of a high earth orbit. But that's because my thinking has been altered by Bob Martin.</p>\n\n<p>In <em>Clean Code</em>, Uncle Bob argues for three as an general upper limit for number of parameters. He makes the radical claim (40):</p>\n\n<blockquote>\n <p>The ideal number of arguments for a function is zero (niladic). Next comes one (monadic) followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification—and then shouldn't be used anyway.</p>\n</blockquote>\n\n<p>He says this because of readability; but also because of testability:</p>\n\n<blockquote>\n <p>Imagine the difficulty of writing all the test cases to ensure that all various combinations of arguments work properly.</p>\n</blockquote>\n\n<p>I encourage you to find a copy of his book and read his full discussion of function arguments (40-43).</p>\n\n<p>I agree with those who have mentioned the Single Responsibility Principle. It is hard for me to believe that a class that needs more than two or three values/objects without reasonable defaults really has only one responsibility, and would not be better off with another class extracted.</p>\n\n<p>Now, if you are injecting your dependencies through the constructor, Bob Martin's arguments about how easy it is to invoke the constructor do not so much apply (because usually then there is only one point in your application where you wire that up, or you even have a framework that does it for you). However, the Single Responsibility Principle is still relevant: once a class has four dependencies, I consider that a smell that it is doing a large amount of work.</p>\n\n<p>However, as with all things in computer science, there are doubtless valid cases for having a large number of constructor parameters. Don't contort your code to avoid using a large number of parameters; but if you do use a large number of parameters, stop and give it some thought, because it may mean your code is already contorted.</p>\n"
},
{
"answer_id": 58661084,
"author": "rrswa",
"author_id": 3076593,
"author_profile": "https://Stackoverflow.com/users/3076593",
"pm_score": 1,
"selected": false,
"text": "<p>In a more Object-Oriented situation of the problem, you can use properties in C#. It doesn't help much if you create an instance of an object, but suppose we have a parent class that needs too many parameters in its constructor.<br>\nSince you can have abstract properties, you can use this to your advantage. The parent class needs to define an abstract property that the child class must override.<br>\nNormally a class might look like:</p>\n\n<pre><code>class Customer {\n private string name;\n private int age;\n private string email;\n\n Customer(string name, int age, string email) {\n this.name = name;\n this.age = age;\n this.email = email;\n }\n}\n\nclass John : Customer {\n John() : base(\"John\", 20, \"[email protected]\") { \n\n }\n}\n</code></pre>\n\n<p>It can become messy and unreadable with too many parameters.<br>\nWhereas this method:</p>\n\n<pre><code>class Customer {\n protected abstract string name { get; }\n protected abstract int age { get; }\n protected abstract string email { get; }\n}\n\nclass John : Customer {\n protected override string name => \"John\";\n protected override int age => 20;\n protected override string email=> \"[email protected]\";\n}\n</code></pre>\n\n<p>Which is much cleaner code in my opinion and no contractors are needed in this case, which saves room for other necessary parameters.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] | Let's say you have a class called Customer, which contains the following fields:
* UserName
* Email
* First Name
* Last Name
Let's also say that according to your business logic, all Customer objects must have these four properties defined.
Now, we can do this pretty easily by forcing the constructor to specify each of these properties. But it's pretty easy to see how this can spiral out of control when you are forced to add more required fields to the Customer object.
I've seen classes that take in 20+ arguments into their constructor and it's just a pain to use them. But, alternatively, if you don't require these fields you run into the risk of having undefined information, or worse, object referencing errors if you rely on the calling code to specify these properties.
Are there any alternatives to this or do you you just have to decide whether X amount of constructor arguments is too many for you to live with? | Two design approaches to consider
The [essence](http://www.hillside.net/plop/plop98/final_submissions/P10.pdf) pattern
The [fluent interface](https://martinfowler.com/bliki/FluentInterface.html) pattern
These are both similar in intent, in that we slowly build up an intermediate object, and then create our target object in a single step.
An example of the fluent interface in action would be:
```java
public class CustomerBuilder {
String surname;
String firstName;
String ssn;
public static CustomerBuilder customer() {
return new CustomerBuilder();
}
public CustomerBuilder withSurname(String surname) {
this.surname = surname;
return this;
}
public CustomerBuilder withFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public CustomerBuilder withSsn(String ssn) {
this.ssn = ssn;
return this;
}
// client doesn't get to instantiate Customer directly
public Customer build() {
return new Customer(this);
}
}
public class Customer {
private final String firstName;
private final String surname;
private final String ssn;
Customer(CustomerBuilder builder) {
if (builder.firstName == null) throw new NullPointerException("firstName");
if (builder.surname == null) throw new NullPointerException("surname");
if (builder.ssn == null) throw new NullPointerException("ssn");
this.firstName = builder.firstName;
this.surname = builder.surname;
this.ssn = builder.ssn;
}
public String getFirstName() { return firstName; }
public String getSurname() { return surname; }
public String getSsn() { return ssn; }
}
```
```java
import static com.acme.CustomerBuilder.customer;
public class Client {
public void doSomething() {
Customer customer = customer()
.withSurname("Smith")
.withFirstName("Fred")
.withSsn("123XS1")
.build();
}
}
``` |
40,269 | <p>Is there an easy way to find the storage card's path on a Windows Mobile device
when there is a storage card and a bluetooth ftp connection?</p>
| [
{
"answer_id": 41316,
"author": "Dominik Grabiec",
"author_id": 3719,
"author_profile": "https://Stackoverflow.com/users/3719",
"pm_score": 1,
"selected": false,
"text": "<p>On Windows CE 5 (which is the base for Windows Mobile 6) the storage cards get mounted at the root file system as \"Storage Card\\\", \"Storage Card2\\\", etc.</p>\n\n<p>To find out if it's mounted call GetFileAttributes (or the remote version CeGetFileAttributes I believe) passing in the full path (\"\\Storage Card\\\"). If it returns INVALID_FILE_ATTRIBUTES then it's not mounted, otherwise check to make sure it's a directory before returning true.</p>\n"
},
{
"answer_id": 48430,
"author": "Tim Norman",
"author_id": 2716,
"author_profile": "https://Stackoverflow.com/users/2716",
"pm_score": 3,
"selected": false,
"text": "<p>The mount point is usually \"\\Storage Card\" but can be localized into other languages or modified by OEMs (some devices use \"\\SD Card\" or other mount points, and some devices support mounting multiple storage media). The best way to enumerate the available cards is to use FindFirstFlashCard and FindNextFlashCard.</p>\n\n<p>Both functions fill in a WIN32_FIND_DATA structure. The most important field is cFileName, which will contain the path to the card's mount point (e.g. \"\\Storage Card\").</p>\n\n<p>Note that the device's internal memory will also be enumerated by these functions. If you only care about external volumes, ignore the case where cFileName is an empty string (\"\").</p>\n\n<p>Using these functions require you to #include <projects.h> and link with note_prj.lib. Both are included in the Windows Mobile SDKs for WM 2000 and later.</p>\n"
},
{
"answer_id": 661129,
"author": "Joel ",
"author_id": 79853,
"author_profile": "https://Stackoverflow.com/users/79853",
"pm_score": 4,
"selected": true,
"text": "<p>Keep in mind that \"\\Storage Card\" is english oriented. A device made for a different region may have a different name. The name of the storage card path on my device varies with how I am using the device. </p>\n\n<p>Some time ago in the MSDN forms I responded to a few questions on how to detect the storage cards in the file system and how does one get the storage card's capacity. I wrote the following could are a response to those questions and thought it would be helpful to share. Storage cards show up in the file system as temporary directories. This program examines the objects in the root of the device and any folders that have temp attribute are considered to be a positive match </p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Runtime.InteropServices;\n\nnamespace StorageCardInfo\n{\n class Program\n {\n const ulong Megabyte = 1048576;\n const ulong Gigabyte = 1073741824;\n\n [DllImport(\"CoreDLL\")]\n static extern int GetDiskFreeSpaceEx(\n string DirectoryName,\n out ulong lpFreeBytesAvailableToCaller,\n out ulong lpTotalNumberOfBytes,\n out ulong lpTotalNumberOfFreeBytes \n );\n\n static void Main(string[] args)\n {\n DirectoryInfo root = new DirectoryInfo(\"\\\\\");\n DirectoryInfo[] directoryList = root.GetDirectories();\n ulong FreeBytesAvailable;\n ulong TotalCapacity;\n ulong TotalFreeBytes;\n\n for (int i = 0; i < directoryList.Length; ++i)\n {\n if ((directoryList.Attributes & FileAttributes.Temporary) != 0)\n {\n GetDiskFreeSpaceEx(directoryList.FullName, out FreeBytesAvailable, out TotalCapacity, out TotalFreeBytes);\n Console.Out.WriteLine(\"Storage card name: {0}\", directoryList.FullName);\n Console.Out.WriteLine(\"Available Bytes : {0}\", FreeBytesAvailable);\n Console.Out.WriteLine(\"Total Capacity : {0}\", TotalCapacity);\n Console.Out.WriteLine(\"Total Free Bytes : {0}\", TotalFreeBytes);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 698076,
"author": "John Sibly",
"author_id": 1078,
"author_profile": "https://Stackoverflow.com/users/1078",
"pm_score": 3,
"selected": false,
"text": "<p>I've found using the FindFirstFlashCard/FindNextFlashCard APIs to be more reliable than enumerating directories and checking the temporary flag (which will return bluetooth shared folders for example). </p>\n\n<p>The following sample application demonstrates how to use them and the required P/Invoke statements.</p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\n\nnamespace RemovableStorageTest\n{\n class Program\n {\n static void Main(string[] args)\n {\n string removableDirectory = GetRemovableStorageDirectory();\n if (removableDirectory != null)\n {\n Console.WriteLine(removableDirectory);\n }\n else\n {\n Console.WriteLine(\"No removable drive found\");\n }\n }\n\n public static string GetRemovableStorageDirectory()\n {\n string removableStorageDirectory = null;\n\n WIN32_FIND_DATA findData = new WIN32_FIND_DATA();\n IntPtr handle = IntPtr.Zero;\n\n handle = FindFirstFlashCard(ref findData);\n\n if (handle != INVALID_HANDLE_VALUE)\n {\n do\n {\n if (!string.IsNullOrEmpty(findData.cFileName))\n {\n removableStorageDirectory = findData.cFileName;\n break;\n }\n }\n while (FindNextFlashCard(handle, ref findData));\n FindClose(handle);\n }\n\n return removableStorageDirectory;\n }\n\n public static readonly IntPtr INVALID_HANDLE_VALUE = (IntPtr)(-1);\n\n // The CharSet must match the CharSet of the corresponding PInvoke signature\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]\n public struct WIN32_FIND_DATA\n {\n public int dwFileAttributes;\n public FILETIME ftCreationTime;\n public FILETIME ftLastAccessTime;\n public FILETIME ftLastWriteTime;\n public int nFileSizeHigh;\n public int nFileSizeLow;\n public int dwOID;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]\n public string cFileName;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]\n public string cAlternateFileName;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n public struct FILETIME\n {\n public int dwLowDateTime;\n public int dwHighDateTime;\n };\n\n [DllImport(\"note_prj\", EntryPoint = \"FindFirstFlashCard\")]\n public extern static IntPtr FindFirstFlashCard(ref WIN32_FIND_DATA findData);\n\n [DllImport(\"note_prj\", EntryPoint = \"FindNextFlashCard\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n public extern static bool FindNextFlashCard(IntPtr hFlashCard, ref WIN32_FIND_DATA findData);\n\n [DllImport(\"coredll\")]\n public static extern bool FindClose(IntPtr hFindFile);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 840425,
"author": "Tristan Warner-Smith",
"author_id": 29553,
"author_profile": "https://Stackoverflow.com/users/29553",
"pm_score": 2,
"selected": false,
"text": "<p>There's a pure C# way to do this without native calls.</p>\n\n<p>Taken from <a href=\"http://www.treehouseconsulting.co.uk/Blog/post/2009/05/08/Accessing-the-memory-card-in-Windows-Mobile.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<pre><code>//codesnippet:06EE3DE0-D469-44DD-A15F-D8AF629E4E03\npublic string GetStorageCardFolder()\n{\n string storageCardFolder = string.Empty;\n foreach (string directory in Directory.GetDirectories(\"\\\\\"))\n {\n DirectoryInfo dirInfo = new DirectoryInfo(directory);\n\n //Storage cards have temporary attributes do a bitwise check.\n //http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=612136&SiteID=1\n if ((dirInfo.Attributes & FileAttributes.Temporary) == FileAttributes.Temporary)\n storageCardFolder = directory;\n }\n\n return storageCardFolder;\n}\n</code></pre>\n"
},
{
"answer_id": 2027247,
"author": "lmb_nl",
"author_id": 246350,
"author_profile": "https://Stackoverflow.com/users/246350",
"pm_score": 2,
"selected": false,
"text": "<p>Can't add a comment on the TreeUK and ctacke discusion below : </p>\n\n<blockquote>\n <p>This isn't guaranteed to find a\n Storage Card - many devices mount\n built-in flash in teh same way, and it\n would show up in this list as well. –\n ctacke May 8 at 18:23<br>\n This has\n worked well for me on HTC and Psion\n devices. What devices are you aware\n this doesn't work on? Would be worth\n seeing if there's another attribute\n you can discount the build in flash\n memory with. – TreeUK May 9 at 22:29</p>\n</blockquote>\n\n<p>To give a idea on a Motorola MC75 (used to be SymboL), i used this piece (of native) code : </p>\n\n<pre><code> WIN32_FIND_DATA cardinfo;\nHANDLE card = FindFirstFlashCard(&cardinfo);\nif (card != INVALID_HANDLE_VALUE)\n{\n TCHAR existFile[MAX_PATH];\n\n wprintf(_T(\"found : %s\\n\"), cardinfo.cFileName);\n\n while(FindNextFlashCard(card, &cardinfo))\n {\n wprintf(_T(\"found : %s\\n\"), cardinfo.cFileName);\n }\n}\nFindClose(card);\n</code></pre>\n\n<p>Debug output : </p>\n\n<pre><code>cardinfo.dwFileAttributes 0x00000110 unsigned long int\ncardinfo.cFileName \"Application\" wchar_t[260]\n\ncardinfo.dwFileAttributes 0x00000110 unsigned long int\ncardinfo.cFileName \"Cache Disk\" wchar_t[260]\n\ncardinfo.dwFileAttributes 0x00000110 unsigned long int\ncardinfo.cFileName \"Storage Card\" wchar_t[260]\n</code></pre>\n\n<p>The \"Application\" and \"Cache disk\" are internal Flash drives. The \"Storage Card\" a removable SD Card. All are marked as a FlashDrive (which they are), but only \"Storage Card\" is removable. </p>\n"
},
{
"answer_id": 7272591,
"author": "qwlice",
"author_id": 507127,
"author_profile": "https://Stackoverflow.com/users/507127",
"pm_score": 2,
"selected": false,
"text": "<p>I post here the code that I use to get the mount dirs of the storage cards.\nThe part where I get the flash cards paths is copied from Sibly's post with a few changes.</p>\n\n<p>The main difference is in that I search through the mount dirs of all the flash cards and I keep the one(s) that match the default storage card name that I read from windows' registry.</p>\n\n<p>It solves the problem that one has on motorola's smart devices where there are multiple flash cards and only one sd card reader whose mount dir's name can change from the default by the numeric suffix (ie. in english WM systems: 'Storage Card' , 'Storage Card2' and so on). \nI tested it on some motorola models (MC75, MC75A, MC90, MC65) with WM 6.5 english. </p>\n\n<p>This solution should work well with different windows mobile's languages but I don't know if it can deal with those that change the\ndefault name of the storage cards.\nIt all depends whether the device's manufacturer updates the windows registry with the <strong>new</strong> default name.</p>\n\n<p>It would be great if you can test it on different WMs or devices.\nFeedback is welcome.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> //\n // the storage card is a flash drive mounted as a directory in the root folder \n // of the smart device\n //\n // on english windows mobile systems the storage card is mounted in the directory \"/Storage Card\", \n // if that directory already exists then it's mounted in \"/Storage Card2\" and so on\n //\n // the regional name of the mount base dir of the storage card can be found in\n // the registry at [HKEY_LOCAL_MACHINE\\System\\StorageManager\\Profiles\\SDMemory\\Folder]\n // \n // in order to find the path of the storage card we look for the flash drive that starts \n // with the base name\n //\n\n public class StorageCard\n {\n private StorageCard()\n {\n }\n\n public static List<string> GetMountDirs()\n {\n string key = @\"HKEY_LOCAL_MACHINE\\System\\StorageManager\\Profiles\\SDMemory\";\n string storageCardBaseName = Registry.GetValue(key, \"Folder\", \"Storage Card\") as String;\n List<string> storageCards = new List<string>();\n foreach (string flashCard in GetFlashCardMountDirs())\n {\n string path = flashCard.Trim();\n if (path.StartsWith(storageCardBaseName))\n {\n storageCards.Add(path);\n }\n }\n return storageCards;\n }\n\n private static List<string> GetFlashCardMountDirs()\n {\n List<string> storages = new List<string>();\n\n WIN32_FIND_DATA findData = new WIN32_FIND_DATA();\n IntPtr handle = IntPtr.Zero;\n\n handle = FindFirstFlashCard(ref findData);\n\n if (handle != INVALID_HANDLE_VALUE)\n {\n do\n {\n if (!string.IsNullOrEmpty(findData.cFileName))\n {\n storages.Add(findData.cFileName);\n storages.Add(findData.cAlternateFileName);\n }\n }\n while (FindNextFlashCard(handle, ref findData));\n FindClose(handle);\n }\n\n return storages;\n }\n\n private static readonly IntPtr INVALID_HANDLE_VALUE = (IntPtr)(-1); \n\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]\n private struct WIN32_FIND_DATA\n {\n public int dwFileAttributes;\n public FILETIME ftCreationTime;\n public FILETIME ftLastAccessTime;\n public FILETIME ftLastWriteTime;\n public int nFileSizeHigh;\n public int nFileSizeLow;\n public int dwOID;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]\n public string cFileName;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]\n public string cAlternateFileName;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct FILETIME\n {\n public int dwLowDateTime;\n public int dwHighDateTime;\n };\n\n [DllImport(\"note_prj\", EntryPoint = \"FindFirstFlashCard\")]\n private extern static IntPtr FindFirstFlashCard(ref WIN32_FIND_DATA findData);\n\n [DllImport(\"note_prj\", EntryPoint = \"FindNextFlashCard\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n private extern static bool FindNextFlashCard(IntPtr hFlashCard, ref WIN32_FIND_DATA findData);\n\n [DllImport(\"coredll\")]\n private static extern bool FindClose(IntPtr hFindFile);\n }\n</code></pre>\n"
},
{
"answer_id": 12400572,
"author": "Lief",
"author_id": 778579,
"author_profile": "https://Stackoverflow.com/users/778579",
"pm_score": 2,
"selected": false,
"text": "<p>I have combined a number of the solutions above, particularly qwlice's code, to find SD cards on a range of devices. This solution finds SD cards only (so excludes all of the internal \"storage cards\" that some devices have) without using native dll calls.</p>\n\n<p>The code searches the HKEY_LOCAL_MACHINE\\System\\StorageManager\\Profiles\\ key for keys containing \"SD\" as the name varies slightly on some devices, finds the default mount dir and then looks for temp directories that start with this. This means that it will find \\StorageCard2, \\StorageCard3, etc. </p>\n\n<p>I have been using this on a range of Intermec and Motorola/Symbol devices and haven't had any problems. Here is the code below:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class StorageCardFinder\n{\n public static List<string> GetMountDirs()\n {\n //get default sd card folder name\n string key = @\"HKEY_LOCAL_MACHINE\\System\\StorageManager\\Profiles\";\n RegistryKey profiles = Registry.LocalMachine.OpenSubKey(@\"System\\StorageManager\\Profiles\");\n string sdprofilename = profiles.GetSubKeyNames().FirstOrDefault(k => k.Contains(\"SD\"));\n if (sdprofilename == null)\n return new List<string>();\n\n key += \"\\\\\" + sdprofilename;\n string storageCardBaseName = Registry.GetValue(key, \"Folder\", \"Storage Card\") as String;\n if (storageCardBaseName == null)\n return new List<string>();\n\n //find storage card\n List<string> cardDirectories = GetFlashCardMountDirs();\n\n List<string> storageCards = new List<string>();\n foreach (string flashCard in GetFlashCardMountDirs())\n {\n string path = flashCard.Trim();\n if (path.StartsWith(storageCardBaseName))\n {\n storageCards.Add(\"\\\\\" + path);\n }\n }\n return storageCards;\n }\n\n private static List<string> GetFlashCardMountDirs()\n {\n DirectoryInfo root = new DirectoryInfo(\"\\\\\");\n return root.GetDirectories().Where(d => (d.Attributes & FileAttributes.Temporary) != 0)\n .Select(d => d.Name).ToList();\n }\n}\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4298/"
] | Is there an easy way to find the storage card's path on a Windows Mobile device
when there is a storage card and a bluetooth ftp connection? | Keep in mind that "\Storage Card" is english oriented. A device made for a different region may have a different name. The name of the storage card path on my device varies with how I am using the device.
Some time ago in the MSDN forms I responded to a few questions on how to detect the storage cards in the file system and how does one get the storage card's capacity. I wrote the following could are a response to those questions and thought it would be helpful to share. Storage cards show up in the file system as temporary directories. This program examines the objects in the root of the device and any folders that have temp attribute are considered to be a positive match
```
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace StorageCardInfo
{
class Program
{
const ulong Megabyte = 1048576;
const ulong Gigabyte = 1073741824;
[DllImport("CoreDLL")]
static extern int GetDiskFreeSpaceEx(
string DirectoryName,
out ulong lpFreeBytesAvailableToCaller,
out ulong lpTotalNumberOfBytes,
out ulong lpTotalNumberOfFreeBytes
);
static void Main(string[] args)
{
DirectoryInfo root = new DirectoryInfo("\\");
DirectoryInfo[] directoryList = root.GetDirectories();
ulong FreeBytesAvailable;
ulong TotalCapacity;
ulong TotalFreeBytes;
for (int i = 0; i < directoryList.Length; ++i)
{
if ((directoryList.Attributes & FileAttributes.Temporary) != 0)
{
GetDiskFreeSpaceEx(directoryList.FullName, out FreeBytesAvailable, out TotalCapacity, out TotalFreeBytes);
Console.Out.WriteLine("Storage card name: {0}", directoryList.FullName);
Console.Out.WriteLine("Available Bytes : {0}", FreeBytesAvailable);
Console.Out.WriteLine("Total Capacity : {0}", TotalCapacity);
Console.Out.WriteLine("Total Free Bytes : {0}", TotalFreeBytes);
}
}
}
}
``` |
40,273 | <p>A client of mine has asked me to integrate a 3rd party API into their Rails app. The only problem is that the API uses SOAP. Ruby has basically dropped SOAP in favor of REST. They provide a Java adapter that apparently works with the Java-Ruby bridge, but we'd like to keep it all in Ruby, if possible. I looked into soap4r, but it seems to have a slightly bad reputation.</p>
<p>So what's the best way to integrate SOAP calls into a Rails app?</p>
| [
{
"answer_id": 40318,
"author": "Jason Navarrete",
"author_id": 3920,
"author_profile": "https://Stackoverflow.com/users/3920",
"pm_score": 2,
"selected": false,
"text": "<p>Try <strong>SOAP4R</strong></p>\n\n<ul>\n<li><a href=\"http://dev.ctor.org/soap4r\" rel=\"nofollow noreferrer\">SOAP4R</a></li>\n<li><a href=\"http://markthomas.org/2007/09/12/getting-started-with-soap4r/\" rel=\"nofollow noreferrer\">Getting Started with SOAP4R</a></li>\n</ul>\n\n<p>And I just heard about this on the Rails Envy Podcast (ep 31):</p>\n\n<ul>\n<li><a href=\"http://hideoustriumph.wordpress.com/2008/05/05/ws-deathstar-for-the-rest-of-us/\" rel=\"nofollow noreferrer\">WS-Deathstar SOAP walkthrough </a></li>\n</ul>\n"
},
{
"answer_id": 40961,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 6,
"selected": true,
"text": "<p>We used the built in <code>soap/wsdlDriver</code> class, which is actually SOAP4R.\nIt's dog slow, but really simple. The SOAP4R that you get from gems/etc is just an updated version of the same thing.</p>\n\n<p>Example code:</p>\n\n<pre><code>require 'soap/wsdlDriver'\n\nclient = SOAP::WSDLDriverFactory.new( 'http://example.com/service.wsdl' ).create_rpc_driver\nresult = client.doStuff();\n</code></pre>\n\n<p>That's about it</p>\n"
},
{
"answer_id": 1208200,
"author": "Philippe Monnet",
"author_id": 23308,
"author_profile": "https://Stackoverflow.com/users/23308",
"pm_score": 2,
"selected": false,
"text": "<p>Kent Sibilev from <a href=\"http://www.datanoise.com/\" rel=\"nofollow noreferrer\">Datanoise</a> had also ported the Rails ActionWebService library to Rails 2.1 (and above).\nThis allows you to expose your own Ruby-based SOAP services.\nHe even has a scaffold/test mode which allows you to test your services using a browser.</p>\n"
},
{
"answer_id": 2088376,
"author": "phoet",
"author_id": 100731,
"author_profile": "https://Stackoverflow.com/users/100731",
"pm_score": 4,
"selected": false,
"text": "<p>We switched from Handsoap to Savon.</p>\n\n<p>Here is a <a href=\"http://www.dzone.com/links/savon_handsoap_shootout_two_popular_ruby_soap_cli.html\" rel=\"noreferrer\">series of blog posts</a> comparing the two client libraries.</p>\n"
},
{
"answer_id": 2088452,
"author": "rubiii",
"author_id": 141590,
"author_profile": "https://Stackoverflow.com/users/141590",
"pm_score": 7,
"selected": false,
"text": "<p>I built <a href=\"http://savonrb.com\" rel=\"noreferrer\">Savon</a> to make interacting with SOAP webservices via Ruby as easy as possible.<br>\nI'd recommend you check it out.</p>\n"
},
{
"answer_id": 2432222,
"author": "Bruno Duyé",
"author_id": 276894,
"author_profile": "https://Stackoverflow.com/users/276894",
"pm_score": 3,
"selected": false,
"text": "<p>I also recommend <a href=\"http://wiki.github.com/rubiii/savon\" rel=\"nofollow noreferrer\">Savon</a>. I spent too many hours trying to deal with Soap4R, without results. Big lack of functionality, no doc.</p>\n\n<p>Savon is the answer for me.</p>\n"
},
{
"answer_id": 6140364,
"author": "ChrisW",
"author_id": 709569,
"author_profile": "https://Stackoverflow.com/users/709569",
"pm_score": 2,
"selected": false,
"text": "<p>Just got my stuff working within 3 hours using Savon.</p>\n\n<p>The Getting Started documentation on Savon's homepage was really easy to follow - and actually matched what I was seeing (not always the case)</p>\n"
},
{
"answer_id": 26263023,
"author": "Ecommerce-Technician",
"author_id": 4044067,
"author_profile": "https://Stackoverflow.com/users/4044067",
"pm_score": 1,
"selected": false,
"text": "<p>I was having the same issue, switched to Savon and then just tested it on an open WSDL (I used <a href=\"http://www.webservicex.net/geoipservice.asmx?WSDL\" rel=\"nofollow\">http://www.webservicex.net/geoipservice.asmx?WSDL</a>) and so far so good!</p>\n\n<p><a href=\"https://github.com/savonrb/savon\" rel=\"nofollow\">https://github.com/savonrb/savon</a></p>\n"
},
{
"answer_id": 35152994,
"author": "Raja",
"author_id": 3999718,
"author_profile": "https://Stackoverflow.com/users/3999718",
"pm_score": 2,
"selected": false,
"text": "<p>I have used HTTP call like below to call a SOAP method,</p>\n\n<pre><code>require 'net/http'\n\nclass MyHelper\n def initialize(server, port, username, password)\n @server = server\n @port = port\n @username = username\n @password = password\n\n puts \"Initialised My Helper using #{@server}:#{@port} username=#{@username}\"\n end\n\n\n\n def post_job(job_name)\n\n puts \"Posting job #{job_name} to update order service\"\n\n job_xml =\"<soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" xmlns:ns=\\\"http://test.com/Test/CreateUpdateOrders/1.0\\\">\n <soapenv:Header/>\n <soapenv:Body>\n <ns:CreateTestUpdateOrdersReq>\n <ContractGroup>ITE2</ContractGroup>\n <ProductID>topo</ProductID>\n <PublicationReference>#{job_name}</PublicationReference>\n </ns:CreateTestUpdateOrdersReq>\n </soapenv:Body>\n </soapenv:Envelope>\"\n\n @http = Net::HTTP.new(@server, @port)\n puts \"server: \" + @server + \"port : \" + @port\n request = Net::HTTP::Post.new(('/XISOAPAdapter/MessageServlet?/Test/CreateUpdateOrders/1.0'), initheader = {'Content-Type' => 'text/xml'})\n request.basic_auth(@username, @password)\n request.body = job_xml\n response = @http.request(request)\n\n puts \"request was made to server \" + @server\n\n validate_response(response, \"post_job_to_pega_updateorder job\", '200')\n\n end\n\n\n\n private \n\n def validate_response(response, operation, required_code)\n if response.code != required_code\n raise \"#{operation} operation failed. Response was [#{response.inspect} #{response.to_hash.inspect} #{response.body}]\"\n end\n end\nend\n\n/*\ntest = MyHelper.new(\"mysvr.test.test.com\",\"8102\",\"myusername\",\"mypassword\")\ntest.post_job(\"test_201601281419\")\n*/\n</code></pre>\n\n<p>Hope it helps. Cheers.</p>\n"
},
{
"answer_id": 37676319,
"author": "Radu Rosu",
"author_id": 6082342,
"author_profile": "https://Stackoverflow.com/users/6082342",
"pm_score": 2,
"selected": false,
"text": "<p>I have used SOAP in Ruby when i've had to make a fake SOAP server for my acceptance tests. I don't know if this was the best way to approach the problem, but it worked for me. </p>\n\n<p>I have used Sinatra gem (I wrote about creating mocking endpoints with Sinatra <a href=\"http://intelligentbee.com/blog/2016/01/06/how-to-mock-endpoints-in-automated-acceptance-tests/\" rel=\"nofollow\">here</a>) for server and also <a href=\"https://rubygems.org/gems/nokogiri/versions/1.6.7.2\" rel=\"nofollow\">Nokogiri</a> for XML stuff (SOAP is working with XML).</p>\n\n<p>So, for the beginning I have create two files (e.g. config.rb and responses.rb) in which I have put the predefined answers that SOAP server will return. \nIn <em>config.rb</em> I have put the WSDL file, but as a string. </p>\n\n<pre><code>@@wsdl = '<wsdl:definitions name=\"StockQuote\"\n targetNamespace=\"http://example.com/stockquote.wsdl\"\n xmlns:tns=\"http://example.com/stockquote.wsdl\"\n xmlns:xsd1=\"http://example.com/stockquote.xsd\"\n xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\"\n xmlns=\"http://schemas.xmlsoap.org/wsdl/\">\n .......\n </wsdl:definitions>'\n</code></pre>\n\n<p>In <em>responses.rb</em> I have put samples for responses that SOAP server will return for different scenarios.</p>\n\n<pre><code>@@login_failure = \"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <s:Body>\n <LoginResponse xmlns=\"http://tempuri.org/\">\n <LoginResult xmlns:a=\"http://schemas.datacontract.org/2004/07/WEBMethodsObjects\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">\n <a:Error>Invalid username and password</a:Error>\n <a:ObjectInformation i:nil=\"true\"/>\n <a:Response>false</a:Response>\n </LoginResult>\n </LoginResponse>\n </s:Body>\n</s:Envelope>\"\n</code></pre>\n\n<p>So now let me show you how I have actually created the server.</p>\n\n<pre><code>require 'sinatra'\nrequire 'json'\nrequire 'nokogiri'\nrequire_relative 'config/config.rb'\nrequire_relative 'config/responses.rb'\n\nafter do\n# cors\nheaders({\n \"Access-Control-Allow-Origin\" => \"*\",\n \"Access-Control-Allow-Methods\" => \"POST\",\n \"Access-Control-Allow-Headers\" => \"content-type\",\n})\n\n# json\ncontent_type :json\nend\n\n#when accessing the /HaWebMethods route the server will return either the WSDL file, either and XSD (I don't know exactly how to explain this but it is a WSDL dependency)\nget \"/HAWebMethods/\" do\n case request.query_string\n when 'xsd=xsd0'\n status 200\n body = @@xsd0\n when 'wsdl'\n status 200\n body = @@wsdl\n end\nend\n\npost '/HAWebMethods/soap' do\nrequest_payload = request.body.read\nrequest_payload = Nokogiri::XML request_payload\nrequest_payload.remove_namespaces!\n\nif request_payload.css('Body').text != ''\n if request_payload.css('Login').text != ''\n if request_payload.css('email').text == some username && request_payload.css('password').text == some password\n status 200\n body = @@login_success\n else\n status 200\n body = @@login_failure\n end\n end\nend\nend\n</code></pre>\n\n<p>I hope you'll find this helpful!</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2884/"
] | A client of mine has asked me to integrate a 3rd party API into their Rails app. The only problem is that the API uses SOAP. Ruby has basically dropped SOAP in favor of REST. They provide a Java adapter that apparently works with the Java-Ruby bridge, but we'd like to keep it all in Ruby, if possible. I looked into soap4r, but it seems to have a slightly bad reputation.
So what's the best way to integrate SOAP calls into a Rails app? | We used the built in `soap/wsdlDriver` class, which is actually SOAP4R.
It's dog slow, but really simple. The SOAP4R that you get from gems/etc is just an updated version of the same thing.
Example code:
```
require 'soap/wsdlDriver'
client = SOAP::WSDLDriverFactory.new( 'http://example.com/service.wsdl' ).create_rpc_driver
result = client.doStuff();
```
That's about it |
40,317 | <p>I have an NFS-mounted directory on a Linux machine that has hung. I've tried to force an unmount, but it doesn't seem to work:</p>
<pre><code>$ umount -f /mnt/data
$ umount2: Device or resource busy
$ umount: /mnt/data: device is busy
</code></pre>
<p>If I type "<code>mount</code>", it appears that the directory is no longer mounted, but it hangs if I do "<code>ls /mnt/data</code>", and if I try to remove the mountpoint, I get:</p>
<pre><code>$ rmdir /mnt/data
rmdir: /mnt/data: Device or resource busy
</code></pre>
<p>Is there anything I can do other than reboot the machine?</p>
| [
{
"answer_id": 40320,
"author": "tessein",
"author_id": 3075,
"author_profile": "https://Stackoverflow.com/users/3075",
"pm_score": 9,
"selected": true,
"text": "<p>You might try a lazy unmount:</p>\n\n<pre><code>umount -l\n</code></pre>\n"
},
{
"answer_id": 40331,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 4,
"selected": false,
"text": "<p>Try running</p>\n\n<pre><code>lsof | grep /mnt/data\n</code></pre>\n\n<p>That should list any process that is accessing /mnt/data that would prevent it from being unmounted.</p>\n"
},
{
"answer_id": 64180,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 6,
"selected": false,
"text": "<p>If the NFS server disappeared and you can't get it back online, one trick that I use is to add an alias to the interface with the IP of the NFS server (in this example, 192.0.2.55). </p>\n\n<h2>Linux</h2>\n\n<p>The command for that is something roughly like:</p>\n\n<pre><code>ifconfig eth0:fakenfs 192.0.2.55 netmask 255.255.255.255\n</code></pre>\n\n<p>Where 192.0.2.55 is the IP of the NFS server that went away. You should then be able to ping the address, and you should also be able to unmount the filesystem (use unmount -f). You should then destroy the aliased interface so you no longer route traffic to the old NFS server to yourself with:</p>\n\n<pre><code>ifconfig eth0:fakenfs down\n</code></pre>\n\n<h2>FreeBSD and similar operating systems</h2>\n\n<p>The command would be something like:</p>\n\n<pre><code>ifconfig em0 alias 192.0.2.55 netmask 255.255.255.255\n</code></pre>\n\n<p>And then to remove it:</p>\n\n<pre><code>ifconfig em0 delete 192.0.2.55\n</code></pre>\n\n<p>man ifconfig(8) for more!</p>\n"
},
{
"answer_id": 64264,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Your NFS server disappeared.</p>\n\n<p>Ideally your best bet is if the NFS server comes back.</p>\n\n<p>If not, the \"umount -f\" should have done the trick.\nIt doesn't ALWAYS work, but it often will.</p>\n\n<p>If you happen to know what processes are USING the NFS filesystem,\nyou could try killing those processes and then maybe an unmount would work.</p>\n\n<p>Finally, I'd guess you need to reboot.</p>\n\n<p>Also, DON'T soft-mount your NFS drives. You use hard-mounts to guarantee\nthat they worked. That's necessary if you're doing writes.</p>\n"
},
{
"answer_id": 12211102,
"author": "Dave",
"author_id": 1057407,
"author_profile": "https://Stackoverflow.com/users/1057407",
"pm_score": 2,
"selected": false,
"text": "<p>Couldn't find a working answer here; but on linux you can run \"umount.nfs4 /volume -f\" and it definitely unmounts it.</p>\n"
},
{
"answer_id": 14048770,
"author": "Daniel N.",
"author_id": 1931086,
"author_profile": "https://Stackoverflow.com/users/1931086",
"pm_score": 4,
"selected": false,
"text": "<p>I had the same problem, and \nneither <code>umount /path -f</code>,\nneither <code>umount.nfs /path -f</code>,\nneither <code>fuser -km /path</code>,\nworks</p>\n\n<p>finally I found a simple solution >.<</p>\n\n<p><code>sudo /etc/init.d/nfs-common restart</code>, then lets do the simple <code>umount</code> ;-)</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] | I have an NFS-mounted directory on a Linux machine that has hung. I've tried to force an unmount, but it doesn't seem to work:
```
$ umount -f /mnt/data
$ umount2: Device or resource busy
$ umount: /mnt/data: device is busy
```
If I type "`mount`", it appears that the directory is no longer mounted, but it hangs if I do "`ls /mnt/data`", and if I try to remove the mountpoint, I get:
```
$ rmdir /mnt/data
rmdir: /mnt/data: Device or resource busy
```
Is there anything I can do other than reboot the machine? | You might try a lazy unmount:
```
umount -l
``` |
40,335 | <p>I'm need to find a method to programmatically determine which disk drive Windows is using to boot. In other words, I need a way from Windows to determine which drive the BIOS is using to boot the whole system. </p>
<p>Does Windows expose an interface to discover this? With how big the Windows API is, I'm hoping there is something buried in there that might do the trick.</p>
<p>Terry</p>
<p>p.s. Just reading the first sectors of the hard disk isn't reveling anything. On my dev box I have two hard disks, and when I look at the contents of the first couple of sectors on either of the hard disks I have a standard boiler plate MBR.</p>
<p>Edit to clarify a few things.
The way I want to identify the device is with a string which will identify a physical disk drive (as opposed to a logical disk drive). Physical disk drives are of the form "\\.\PHYSICALDRIVEx" where x is a number. On the other hand, a logical drive is identified by a string of the form, "\\.\x" where x is a drive letter.</p>
<p>Edit to discuss a few of the ideas that were thrown out.
Knowing which logical volume Windows used to boot doesn't help me here. Here is the reason. Assume that C: is using a mirrored RAID setup. Now, that means we have at least two physical drives. Now, I get the mapping from Logical Drive to Physical Drive and I discover that there are two physical drives used by that volume. Which one did Windows use to boot? Of course, this is assuming that the physical drive Windows used to boot is the same physical drive that contains the MBR. </p>
| [
{
"answer_id": 40347,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 3,
"selected": false,
"text": "<p>Unless C: is not the drive that windows booted from.<br />Parse the %SystemRoot% variable, it contains the location of the windows folder (i.e. c:\\windows).</p>\n"
},
{
"answer_id": 40355,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>There is no boot.ini on a machine with just Vista installed.</p>\n\n<p>How do you want to identify the drive/partition: by the windows drive letter it is mapped to (eg. c:\\, d:) or by how its hardware signature (which bus, etc).</p>\n\n<p>For the simple case check out <a href=\"http://msdn.microsoft.com/en-us/library/ms724373(VS.85).aspx\" rel=\"nofollow noreferrer\">GetSystemDirectory</a></p>\n"
},
{
"answer_id": 40362,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 1,
"selected": false,
"text": "<p>Try HKEY_LOCAL_MACHINE\\SYSTEM\\Setup\\SystemPartition</p>\n"
},
{
"answer_id": 40682,
"author": "Chris Gillum",
"author_id": 2069,
"author_profile": "https://Stackoverflow.com/users/2069",
"pm_score": 2,
"selected": false,
"text": "<p>You can use WMI to figure this out. The <a href=\"http://msdn.microsoft.com/en-us/library/aa394078.aspx\" rel=\"nofollow noreferrer\">Win32_BootConfiguration</a> class will tell you both the logical drive and the physical device from which Windows boots. Specifically, the Caption property will tell you which <em>device</em> you're booting from.</p>\n\n<p>For example, in powershell, just type <strong>gwmi Win32_BootConfiguration</strong> to get your answer.</p>\n"
},
{
"answer_id": 40753,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "<p>That depends on your definition of which disk drive Windows used to boot. I can think of 3 different answers on a standard BIOS system (who knows what an EFI system does):</p>\n\n<ol>\n<li>The drive that contains the active MBR</li>\n<li>The active partition, with NTLDR (the system partition)</li>\n<li>The partition with Windows on it (the boot partition)</li>\n</ol>\n\n<p>2 and 3 should be easy to find - I'm not so sure about 1. Though you can raw disk read to find an MBR, that doesn't mean it's the BIOS boot device this time or even next time (you could have multiple disks with MBRs).</p>\n\n<p>You really can't even be sure that the PC was started from a hard drive - it's perfectly possible to boot Windows from a floppy. In that case, both 1 and 2 would technically be a floppy disk, though 3 would remain C:\\Windows.</p>\n\n<p>You might need to be a bit more specific in your requirements or goals.</p>\n"
},
{
"answer_id": 18424806,
"author": "JD.",
"author_id": 300041,
"author_profile": "https://Stackoverflow.com/users/300041",
"pm_score": 4,
"selected": false,
"text": "<ol>\n<li>Go into <code>Control Panel</code></li>\n<li><code>System and Security</code></li>\n<li><code>Administrative Tools</code></li>\n<li>Launch the <code>System Configuration</code> tool</li>\n</ol>\n\n<p>If you have multiple copies of Windows installed, the one you are booted with will be named such as:</p>\n\n<pre><code>Windows 7 (F:\\Windows)\nWindows 7 (C:\\Windows) : Current OS, Default OS\n</code></pre>\n"
},
{
"answer_id": 34293003,
"author": "ST3",
"author_id": 1237747,
"author_profile": "https://Stackoverflow.com/users/1237747",
"pm_score": 0,
"selected": false,
"text": "<p>You can try use simple command line. <a href=\"https://technet.microsoft.com/en-us/library/cc709667%28v=ws.10%29.aspx\" rel=\"nofollow\">bcdedit</a> is what you need, just run cmd as administrator and type <code>bcdedit</code> or <code>bcdedit \\v</code>, this doesn't work on XP, but hope it is not an issue.</p>\n\n<p>Anyway for XP you can take a look into <code>boot.ini</code> file.</p>\n"
},
{
"answer_id": 64396478,
"author": "Mark",
"author_id": 14465066,
"author_profile": "https://Stackoverflow.com/users/14465066",
"pm_score": 2,
"selected": false,
"text": "<p>You type diskpart, list disk and check disks for boot.<br />\nEx:</p>\n<pre><code>dispart \nlist disk \nselect disk 0 \ndetail disk\n</code></pre>\n<p>The disk with Boot volume is disk with windows installed:</p>\n<p><a href=\"https://i.stack.imgur.com/gtfAP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gtfAP.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 65987496,
"author": "sandstorm",
"author_id": 9854447,
"author_profile": "https://Stackoverflow.com/users/9854447",
"pm_score": 0,
"selected": false,
"text": "<p><strong>a simpler way</strong>\nsearch downloads in the start menu and click on downloads in the search results to see where it will take you the drive will be highlighted in the explorer.</p>\n"
},
{
"answer_id": 67981692,
"author": "Peter Futterleib",
"author_id": 16230464,
"author_profile": "https://Stackoverflow.com/users/16230464",
"pm_score": 0,
"selected": false,
"text": "<p>On Windows 10.\nOpen "Computer Management"\nLook for "Storage" in list "left top side of page"\nselect "Disk Management"\nOn section of page showing the list of disks and the partitions find the disk that has the partition assigned as drive C:\nOn that disk containing C: partition\nUse the right mouse button to select the Square section containing The Disk Number, Type of drive and size in GB . When menu opens select the Properties.\nA window will open showing what drive hardware was used.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2171/"
] | I'm need to find a method to programmatically determine which disk drive Windows is using to boot. In other words, I need a way from Windows to determine which drive the BIOS is using to boot the whole system.
Does Windows expose an interface to discover this? With how big the Windows API is, I'm hoping there is something buried in there that might do the trick.
Terry
p.s. Just reading the first sectors of the hard disk isn't reveling anything. On my dev box I have two hard disks, and when I look at the contents of the first couple of sectors on either of the hard disks I have a standard boiler plate MBR.
Edit to clarify a few things.
The way I want to identify the device is with a string which will identify a physical disk drive (as opposed to a logical disk drive). Physical disk drives are of the form "\\.\PHYSICALDRIVEx" where x is a number. On the other hand, a logical drive is identified by a string of the form, "\\.\x" where x is a drive letter.
Edit to discuss a few of the ideas that were thrown out.
Knowing which logical volume Windows used to boot doesn't help me here. Here is the reason. Assume that C: is using a mirrored RAID setup. Now, that means we have at least two physical drives. Now, I get the mapping from Logical Drive to Physical Drive and I discover that there are two physical drives used by that volume. Which one did Windows use to boot? Of course, this is assuming that the physical drive Windows used to boot is the same physical drive that contains the MBR. | 1. Go into `Control Panel`
2. `System and Security`
3. `Administrative Tools`
4. Launch the `System Configuration` tool
If you have multiple copies of Windows installed, the one you are booted with will be named such as:
```
Windows 7 (F:\Windows)
Windows 7 (C:\Windows) : Current OS, Default OS
``` |
40,361 | <p>I have an application which extracts data from an XML file using XPath. If a node in that XML source file is missing I want to return the value "N/A" (much like the Oracle NVL function). The trick is that the application doesn't support XSLT; I'd like to do this using XPath and XPath alone.</p>
<p>Is that possible?</p>
| [
{
"answer_id": 40443,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 2,
"selected": false,
"text": "<p>Short answer: no. Such a function was considered and explicitly rejected for version 2 of the XPath spec (see the non-normative <a href=\"http://www.w3.org/TR/xpath-functions/#examples\" rel=\"nofollow noreferrer\">Illustrative User-written Functions section</a>).</p>\n"
},
{
"answer_id": 41142,
"author": "jelovirt",
"author_id": 2679,
"author_profile": "https://Stackoverflow.com/users/2679",
"pm_score": 1,
"selected": false,
"text": "<p>It can be done with XPath 1.0. Say you have</p>\n\n<pre><code><foo>\n <bar/>\n</foo>\n</code></pre>\n\n<p>If you want to test if <code>foo</code> has a <code>baz</code> child,</p>\n\n<pre><code>substring(\"N/A\", 4 * number(boolean(/foo/baz)))\n</code></pre>\n\n<p>will return \"N/A\" if the expression <code>/foo/baz</code> returns an empty node-set, otherwise it returns an empty string.</p>\n"
},
{
"answer_id": 41152,
"author": "jelovirt",
"author_id": 2679,
"author_profile": "https://Stackoverflow.com/users/2679",
"pm_score": 4,
"selected": true,
"text": "<p>It can be done but only if the return value when the node does exist is <em>the string value of the node, not the node itself</em>. The XPath</p>\n\n<pre><code>substring(concat(\"N/A\", /foo/baz), 4 * number(boolean(/foo/baz)))\n</code></pre>\n\n<p>will return the string value of the <code>baz</code> element if it exists, otherwise the string \"N/A\".</p>\n\n<p>To generalize the approach:</p>\n\n<pre><code>substring(concat($null-value, $node),\n (string-length($null-value) + 1) * number(boolean($node)))\n</code></pre>\n\n<p>where <code>$null-value</code> is the null value string and <code>$node</code> the expression to select the node. Note that if <code>$node</code> evaluates to a node-set that contains more than one node, the string value of the <em>first</em> node is used.</p>\n"
},
{
"answer_id": 41713,
"author": "JPLemme",
"author_id": 1019,
"author_profile": "https://Stackoverflow.com/users/1019",
"pm_score": 1,
"selected": false,
"text": "<p>@jelovirt</p>\n\n<p>So if I understand this correctly, we concatenate the default answer and the value of the node, and then take the correct subset of the resulting string by testing for the existence of the node to set the offset to either zero or the position right after my default string. That is the most perverse twisting of a language I've ever seen. (I love it!)</p>\n\n<p>To clarify what you said, this approach works when the the node is missing, not when the node is empty. But by replacing \"number(boolean($node))\" with \"string-length($node)\" it will work on empty nodes instead.</p>\n"
},
{
"answer_id": 43142,
"author": "jelovirt",
"author_id": 2679,
"author_profile": "https://Stackoverflow.com/users/2679",
"pm_score": 2,
"selected": false,
"text": "<p>For empty nodes, you need</p>\n\n<pre><code>boolean(string-length($node))\n</code></pre>\n\n<p>(You can omit the call to <code>number()</code> as the cast from boolean to number is implicit here.)</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1019/"
] | I have an application which extracts data from an XML file using XPath. If a node in that XML source file is missing I want to return the value "N/A" (much like the Oracle NVL function). The trick is that the application doesn't support XSLT; I'd like to do this using XPath and XPath alone.
Is that possible? | It can be done but only if the return value when the node does exist is *the string value of the node, not the node itself*. The XPath
```
substring(concat("N/A", /foo/baz), 4 * number(boolean(/foo/baz)))
```
will return the string value of the `baz` element if it exists, otherwise the string "N/A".
To generalize the approach:
```
substring(concat($null-value, $node),
(string-length($null-value) + 1) * number(boolean($node)))
```
where `$null-value` is the null value string and `$node` the expression to select the node. Note that if `$node` evaluates to a node-set that contains more than one node, the string value of the *first* node is used. |
40,402 | <p>I need to empty an LDF file before sending to a colleague. How do I force SQL Server to truncate the log?</p>
| [
{
"answer_id": 40420,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 8,
"selected": false,
"text": "<p>In management studio:</p>\n\n<ul>\n<li>Don't do this on a live environment, but to ensure you shrink your dev db as much as you can:\n\n<ul>\n<li>Right-click the database, choose <code>Properties</code>, then <code>Options</code>.</li>\n<li>Make sure \"Recovery model\" is set to \"Simple\", not \"Full\"</li>\n<li>Click OK</li>\n</ul></li>\n<li>Right-click the database again, choose <code>Tasks</code> -> <code>Shrink</code> -> <code>Files</code></li>\n<li>Change file type to \"Log\"</li>\n<li>Click OK.</li>\n</ul>\n\n<p>Alternatively, the SQL to do it:</p>\n\n<pre><code> ALTER DATABASE mydatabase SET RECOVERY SIMPLE\n DBCC SHRINKFILE (mydatabase_Log, 1)\n</code></pre>\n\n<p>Ref: <a href=\"http://msdn.microsoft.com/en-us/library/ms189493.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms189493.aspx</a></p>\n"
},
{
"answer_id": 40421,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": false,
"text": "<p>backup log logname with truncate_only followed by a dbcc shrinkfile command</p>\n"
},
{
"answer_id": 40427,
"author": "ila",
"author_id": 1178,
"author_profile": "https://Stackoverflow.com/users/1178",
"pm_score": 8,
"selected": true,
"text": "<p>if I remember well... in query analyzer or equivalent:</p>\n\n<pre><code>BACKUP LOG databasename WITH TRUNCATE_ONLY\n\nDBCC SHRINKFILE ( databasename_Log, 1)\n</code></pre>\n"
},
{
"answer_id": 6978809,
"author": "Nathan R",
"author_id": 584878,
"author_profile": "https://Stackoverflow.com/users/584878",
"pm_score": 6,
"selected": false,
"text": "<p>For SQL Server 2008, the command is:</p>\n\n<pre><code>ALTER DATABASE ExampleDB SET RECOVERY SIMPLE\nDBCC SHRINKFILE('ExampleDB_log', 0, TRUNCATEONLY)\nALTER DATABASE ExampleDB SET RECOVERY FULL\n</code></pre>\n\n<p>This reduced my 14GB log file down to 1MB.</p>\n"
},
{
"answer_id": 7361576,
"author": "Matej",
"author_id": 117965,
"author_profile": "https://Stackoverflow.com/users/117965",
"pm_score": 5,
"selected": false,
"text": "<p>For SQL 2008 you can backup log to <code>nul</code> device:</p>\n\n<pre><code>BACKUP LOG [databaseName]\nTO DISK = 'nul:' WITH STATS = 10\n</code></pre>\n\n<p>And then use <code>DBCC SHRINKFILE</code> to truncate the log file.</p>\n"
},
{
"answer_id": 21087363,
"author": "Rask",
"author_id": 325049,
"author_profile": "https://Stackoverflow.com/users/325049",
"pm_score": -1,
"selected": false,
"text": "<p>Another option altogether is to detach the database via Management Studio. Then simply delete the log file, or rename it and delete later. </p>\n\n<p>Back in Management Studio attach the database again. In the attach window remove the log file from list of files.</p>\n\n<p>The DB attaches and creates a new empty log file. After you check everything is all right, you can delete the renamed log file.</p>\n\n<p>You probably ought not use this for production databases.</p>\n"
},
{
"answer_id": 61259458,
"author": "rip747",
"author_id": 31278,
"author_profile": "https://Stackoverflow.com/users/31278",
"pm_score": 0,
"selected": false,
"text": "<p>Since the answer for me was buried in the comments. For SQL Server 2012 and beyond, you can use the following:</p>\n\n<pre><code>BACKUP LOG Database TO DISK='NUL:'\nDBCC SHRINKFILE (Database_Log, 1)\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1042/"
] | I need to empty an LDF file before sending to a colleague. How do I force SQL Server to truncate the log? | if I remember well... in query analyzer or equivalent:
```
BACKUP LOG databasename WITH TRUNCATE_ONLY
DBCC SHRINKFILE ( databasename_Log, 1)
``` |
40,422 | <p>Ok, so I want an autocomplete dropdown with linkbuttons as selections. So, the user puts the cursor in the "text box" and is greated with a list of options. They can either start typing to narrow down the list, or select one of the options on the list. As soon as they click (or press enter) the dataset this is linked to will be filtered by the selection. </p>
<p>Ok, is this as easy as wrapping an AJAX autocomplete around a dropdown? No? (Please?) </p>
| [
{
"answer_id": 40504,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 0,
"selected": false,
"text": "<p>You'll have to handle the OnSelectedIndexChanged event of your drop down list to rebind your dataset based on the users selection. If you want the filtering to happen in an asynch postback, wrap the dataset (or datagrid I'm assuming) and your drop down in an UpdatePanel. That is one way to do it anyhow.</p>\n"
},
{
"answer_id": 339033,
"author": "thoughtcrimes",
"author_id": 37814,
"author_profile": "https://Stackoverflow.com/users/37814",
"pm_score": 1,
"selected": true,
"text": "<p>This widget can be made with three items: a text input, button input, and an unordered list to hold the results.</p>\n\n<pre><code> __________ _\n|__________||v|__ <-- text and button\n | | <-- ul (styled to appear relative to text input)\n | |\n | |\n |______________|\n</code></pre>\n\n<p>ul shown on:</p>\n\n<ul>\n<li>'keyUp' event of the text input (if value is non-empty) </li>\n<li>'click' event of the button input (if currently not visible)</li>\n</ul>\n\n<p>ul hidden on:</p>\n\n<ul>\n<li>'click' event of the button input (if currently visible)</li>\n<li>'click' event of list items</li>\n</ul>\n\n<p>When the ul is shown or the 'keyUp' event of the text input is triggered an AJAX call to the server needs to be made to update the list. </p>\n\n<p>On success the results should be placed in the ul. When creating the list items they should have a 'click' event attached to them that sets the text input value and hides the ul (may have to add a link inside the li to attach the event to).</p>\n\n<p>The hardest part is really the CSS. The JavaScript is simple especially with a solid library like prototype that supports multiple browsers. </p>\n\n<p>You will probably want to support some IDs for the items, so you can add some hidden inputs to each list item with the id and next to the text input to store the selected items ID.</p>\n"
},
{
"answer_id": 339826,
"author": "Alterlife",
"author_id": 36848,
"author_profile": "https://Stackoverflow.com/users/36848",
"pm_score": -1,
"selected": false,
"text": "<p>In my opinion, you shouldn't use AJAX for this at all. </p>\n\n<p>here's why:</p>\n\n<p>(1) On focus: ALL the options that he can select are shown in the dropdown. This means that all possible options are already sent to the client.</p>\n\n<p>(2) If the user types something in, the number of entries in the drop down are filtered down to match. This can easily be done on the client side. Being ajax'y and going back to the server at this point will just slow things down.</p>\n\n<p>phpguru.org has a control which is 'almost exactly' what you need:</p>\n\n<p><a href=\"http://www.phpguru.org/static/AutoComplete.html#demo\" rel=\"nofollow noreferrer\">http://www.phpguru.org/static/AutoComplete.html#demo</a></p>\n\n<p>It differs slightly from what you need in that it shows the dropdown on double-click instead of on focus. That should be fairly easy to modify.</p>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 339855,
"author": "Thomas Hansen",
"author_id": 29746,
"author_profile": "https://Stackoverflow.com/users/29746",
"pm_score": 0,
"selected": false,
"text": "<p>I am not entirely sure what you want, but the Ra-Ajax <a href=\"http://ra-ajax.org/samples/Ajax-AutoCompleter.aspx\" rel=\"nofollow noreferrer\">AutoCompleter</a> definitely have support for having \"controls\" within itself. You can see that in the search box at <a href=\"http://stacked.ra-ajax.org/\" rel=\"nofollow noreferrer\">Stacked</a> in fact (upper right corner) where we're using links. But this could also be LinkButtons if you wish...</p>\n\n<p>Disclaimer; I work with Ra-Ajax...</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
] | Ok, so I want an autocomplete dropdown with linkbuttons as selections. So, the user puts the cursor in the "text box" and is greated with a list of options. They can either start typing to narrow down the list, or select one of the options on the list. As soon as they click (or press enter) the dataset this is linked to will be filtered by the selection.
Ok, is this as easy as wrapping an AJAX autocomplete around a dropdown? No? (Please?) | This widget can be made with three items: a text input, button input, and an unordered list to hold the results.
```
__________ _
|__________||v|__ <-- text and button
| | <-- ul (styled to appear relative to text input)
| |
| |
|______________|
```
ul shown on:
* 'keyUp' event of the text input (if value is non-empty)
* 'click' event of the button input (if currently not visible)
ul hidden on:
* 'click' event of the button input (if currently visible)
* 'click' event of list items
When the ul is shown or the 'keyUp' event of the text input is triggered an AJAX call to the server needs to be made to update the list.
On success the results should be placed in the ul. When creating the list items they should have a 'click' event attached to them that sets the text input value and hides the ul (may have to add a link inside the li to attach the event to).
The hardest part is really the CSS. The JavaScript is simple especially with a solid library like prototype that supports multiple browsers.
You will probably want to support some IDs for the items, so you can add some hidden inputs to each list item with the id and next to the text input to store the selected items ID. |
40,423 | <p>Actually, this question seems to have two parts:</p>
<ul>
<li>How to implement pattern matching?</li>
<li>How to implement <a href="http://erlang.org/doc/reference_manual/expressions.html#6.9" rel="noreferrer">send and receive</a> (i.e. the Actor model)?</li>
</ul>
<p>For the pattern matching part, I've been looking into various projects like <a href="http://members.cox.net/nelan/app.html" rel="noreferrer">App</a> and <a href="http://www.cs.nyu.edu/leunga/papers/research/prop/prop.html" rel="noreferrer">Prop</a>. These look pretty nice, but couldn't get them to work on a recent version (4.x) of g++. The <a href="http://felix-lang.org/" rel="noreferrer">Felix</a> language also seems to support pattern matching pretty well, but isn't really C++.</p>
<p>As for the <a href="http://en.wikipedia.org/wiki/Actor_model" rel="noreferrer">Actor model</a>, there are existing implementations like ACT++ and <a href="http://theron.ashtonmason.net/" rel="noreferrer">Theron</a>, but I couldn't find anything but papers on the former<strike>, and the latter is single-threaded only</strike> [see answers].</p>
<p>Personally, I've implemented actors using threading and a thread-safe message queue. Messages are hash-like structures, and used these together with a number of preprocessor macros to implemented simple pattern matching.</p>
<p>Right now, I can use the following code to send a message:</p>
<pre><code>(new Message(this))
->set("foo", "bar")
->set("baz", 123)
->send(recipient);
</code></pre>
<p>And the following to do simple pattern matching (<code>qDebug</code> and <code>qPrintable</code> are Qt-specific):</p>
<pre><code>receive_and_match(m)
match_key("foo") { qDebug("foo: %s", qPrintable(m->value("foo").toString())); }
or_match_key("baz") { qDebug("baz: %d", m->value("baz").toInt()); }
or_match_ignore
end_receive
</code></pre>
<p>However, this looks a bit hackish to me, and isn't very robust.</p>
<p>How would you do it? Did I miss any existing work?</p>
| [
{
"answer_id": 40616,
"author": "1729",
"author_id": 4319,
"author_profile": "https://Stackoverflow.com/users/4319",
"pm_score": 3,
"selected": true,
"text": "<p>One of the important things about erlang is how the features are used to make robust systems.</p>\n\n<p>The send/recieve model is no-sharing, and explicitly copying.\nThe processes themselves are lightweight threads.</p>\n\n<p>If you did desire the robust properties of the erlang model, you would be best to use real processes and IPC rather than threads.</p>\n\n<p>If you want robust message passing though you may end up wanting to serialize and deserialise the contents. Especially with type safety.</p>\n\n<p>Pattern matching in C++ isn't always pretty but there will be a good pattern for this - you will end up creating a dispatcher object that uses some form of polymorphism to get what you want.</p>\n\n<p>Although if you are not careful you end up with xml over pipes :)</p>\n\n<p>Really, if you want the erlang model you really want to use erlang. If there are slow bits, I'm sure you can augment your program using a foreign function internet.</p>\n\n<p>The problem about re-implementing parts, is you won't get a good cohesive library and solution. The solutions you have already don't look much like C++ anymore.</p>\n"
},
{
"answer_id": 185138,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>As for the Actor model, there are\n existing implementations like ACT++\n and Theron, but I couldn't find\n anything but papers on the former, and\n the latter is single-threaded only.</p>\n</blockquote>\n\n<p>As the author of Theron, I was curious why you believe it's single-threaded?</p>\n\n<blockquote>\n <p>Personally, I've implemented actors\n using threading and a thread-safe\n message queue</p>\n</blockquote>\n\n<p>That's how Theron is implemented.. :-)</p>\n\n<p>Ash</p>\n"
},
{
"answer_id": 912489,
"author": "neverlord",
"author_id": 112736,
"author_profile": "https://Stackoverflow.com/users/112736",
"pm_score": 2,
"selected": false,
"text": "<p>I'm currently implementing an actor library for C++ called \"acedia\" (there's nothing yet about it on google) that uses \"type matching\". The library is a project for my master thesis and you can send any kind of data to an actor with it.</p>\n\n<p>A small snippet:</p>\n\n<pre><code>recipient.send(23, 12.23f);\n</code></pre>\n\n<p>And on the recipient side you can either analyze the received message like this:</p>\n\n<pre><code>Message msg = receive();\nif (msg.match<int, float>() { ... }\n</code></pre>\n\n<p>... or you can define a rule set that invokes a function or method for you:</p>\n\n<pre><code>void doSomething(int, float);\n\nInvokeRuleSet irs;\nirs.add(on<int, float>() >> doSomething);\nreceiveAndInvoke(irs);\n</code></pre>\n\n<p>It's also possible to match both on type and on value:</p>\n\n<pre><code>Message msg = receive();\nif (msg.match<int, float>(42, WILDCARD) { ... }\nelse if (msg.match<int, float>() { ... }\n</code></pre>\n\n<p>The constant \"WILDCARD\" means, that any value will be acceptet. Pass no arguments is equal set all arguments to \"WILDCARD\"; meaning that you only want to match the types.</p>\n\n<p>This is certainly a small snippet. Also you can use \"case classes\" like in Scala. They are comparable to \"atomics\" in erlang. Here is a more detailed example:</p>\n\n<pre><code>ACEDIA_DECLARE_CASE_CLASS(ShutdownMessage)\nACEDIA_DECLARE_CASE_CLASS(Event1)\nACEDIA_DECLARE_CASE_CLASS(Event2)\n</code></pre>\n\n<p>To react to the defined case classes you can write an actor like this:</p>\n\n<pre><code>class SomeActor : public Actor\n{\n\n void shutdown() { done = true; }\n void handleEvent1();\n void handleEvent1();\n\n public:\n\n SomeActor() : done(false) { }\n\n virtual void act()\n {\n InvokeRuleSet irs;\n irs\n .add(on<ShutdownMessage>() >> method(&SomeActor::shutdown))\n .add(on<Event1>() >> method(&SomeActor::handleEvent1))\n .add(on<Event2>() >> method(&SomeActor::handleEvent2))\n ;\n while (!done) receiveAndInvoke(irs);\n }\n\n};\n</code></pre>\n\n<p>To create a new actor and start it, all you have to write is:</p>\n\n<pre><code>Acedia::spawn<SomeActor>();\n</code></pre>\n\n<p>Although the library not even reached beta stadium the shown snippets work and i have a first application running on it. One major goal of the library is to support distributed programming (also across a network).</p>\n\n<p>Your question is a while ago, but if you're interested in it: let me know! :)</p>\n"
},
{
"answer_id": 929028,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I would definitely be interested in looking at your \"acedia\" library and would love to help in any way that I could. Erlang has some wonderful constructs and C++ could definitely benefit from such a library.</p>\n"
},
{
"answer_id": 966716,
"author": "neverlord",
"author_id": 112736,
"author_profile": "https://Stackoverflow.com/users/112736",
"pm_score": 0,
"selected": false,
"text": "<p>Today I hostet the library at sourceforge: <a href=\"https://sourceforge.net/projects/acedia/\" rel=\"nofollow noreferrer\">https://sourceforge.net/projects/acedia/</a></p>\n\n<p>As I said before it's an early release. But feel free to critique it!</p>\n"
},
{
"answer_id": 4140159,
"author": "sivabudh",
"author_id": 65313,
"author_profile": "https://Stackoverflow.com/users/65313",
"pm_score": 2,
"selected": false,
"text": "<p>You can mimic the behavior using Qt's signal/slot mechanism, especially since Qt's signal/slot supports multithread.</p>\n"
},
{
"answer_id": 23127725,
"author": "centaurian_slug",
"author_id": 1044688,
"author_profile": "https://Stackoverflow.com/users/1044688",
"pm_score": 0,
"selected": false,
"text": "<p>Today, if you want erlang style robust actors in C++, and pattern matching,\nmaybe Rust is the answer. </p>\n\n<p>Of course this wasn't around publically when the OP asked ~5years ago, and as of april 2014 it still isn't v1.0 yet - but its been progressing very well and is definitely stabilizing, enough of the language core is stable I think.</p>\n\n<p>And ok its not C++, but it has the same approach to memory management as C++, except that it supports lightweight tasks with no shared memory by default (then provides controlled library features for sharing - \"Arc\"); \nIt can directly call (and directly expose) 'extern C' functions. You can't share templated library headers with C++ - but you can write generics that mimick C++ collection classes (and vica versa) to pass references to data-structures across.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Actually, this question seems to have two parts:
* How to implement pattern matching?
* How to implement [send and receive](http://erlang.org/doc/reference_manual/expressions.html#6.9) (i.e. the Actor model)?
For the pattern matching part, I've been looking into various projects like [App](http://members.cox.net/nelan/app.html) and [Prop](http://www.cs.nyu.edu/leunga/papers/research/prop/prop.html). These look pretty nice, but couldn't get them to work on a recent version (4.x) of g++. The [Felix](http://felix-lang.org/) language also seems to support pattern matching pretty well, but isn't really C++.
As for the [Actor model](http://en.wikipedia.org/wiki/Actor_model), there are existing implementations like ACT++ and [Theron](http://theron.ashtonmason.net/), but I couldn't find anything but papers on the former, and the latter is single-threaded only [see answers].
Personally, I've implemented actors using threading and a thread-safe message queue. Messages are hash-like structures, and used these together with a number of preprocessor macros to implemented simple pattern matching.
Right now, I can use the following code to send a message:
```
(new Message(this))
->set("foo", "bar")
->set("baz", 123)
->send(recipient);
```
And the following to do simple pattern matching (`qDebug` and `qPrintable` are Qt-specific):
```
receive_and_match(m)
match_key("foo") { qDebug("foo: %s", qPrintable(m->value("foo").toString())); }
or_match_key("baz") { qDebug("baz: %d", m->value("baz").toInt()); }
or_match_ignore
end_receive
```
However, this looks a bit hackish to me, and isn't very robust.
How would you do it? Did I miss any existing work? | One of the important things about erlang is how the features are used to make robust systems.
The send/recieve model is no-sharing, and explicitly copying.
The processes themselves are lightweight threads.
If you did desire the robust properties of the erlang model, you would be best to use real processes and IPC rather than threads.
If you want robust message passing though you may end up wanting to serialize and deserialise the contents. Especially with type safety.
Pattern matching in C++ isn't always pretty but there will be a good pattern for this - you will end up creating a dispatcher object that uses some form of polymorphism to get what you want.
Although if you are not careful you end up with xml over pipes :)
Really, if you want the erlang model you really want to use erlang. If there are slow bits, I'm sure you can augment your program using a foreign function internet.
The problem about re-implementing parts, is you won't get a good cohesive library and solution. The solutions you have already don't look much like C++ anymore. |
40,452 | <p>I have to POST some parameters to a URL outside my network, and the developers on the other side asked me to not use HTTP Parameters: instead I have to post my key-values in <strong>HTTP Headers</strong>.</p>
<p>The fact is that I don't really understand what they mean: I tried to use a ajax-like post, with XmlHttp objects, and also I tried to write in the header with something like</p>
<pre><code>Request.Headers.Add(key,value);
</code></pre>
<p>but I cannot (exception from the framework); I tried the other way around, using the Response object like</p>
<pre><code>Response.AppendHeader("key", "value");
</code></pre>
<p>and then redirect to the page... but this doesn't work, as well.</p>
<p>It's evident, I think, that I'm stuck there, any help?</p>
<hr>
<p><strong>EDIT</strong> I forgot to tell you that my environment is .Net 2.0, c#, on Win server 2003.
The exception I got is</p>
<pre><code>System.PlatformNotSupportedException was unhandled by user code
Message="Operation is not supported on this platform."
Source="System.Web"
</code></pre>
<p>This looks like it's caused by my tentative to Request.Add, MS an year ago published some security fixes that don't permit this. </p>
| [
{
"answer_id": 40455,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>You should post more information.</p>\n\n<p>For instance, is this C#? It looks like it, but I might be wrong.</p>\n\n<p>Also, you say you get an exception, what is the exception type and message?</p>\n\n<p>In any case, you can't redirect to a page for POST, you need to submit it from the browser, not from the server redirect, so if you want to automate this, I would guess you would need to generate a html page with a form tag, with some hidden input fields, and then submit it with javascript.</p>\n"
},
{
"answer_id": 40467,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>I think they mean they don't want you to use URL parameters (GET). If you use http headers, it's not really querying through POST any more.</p>\n"
},
{
"answer_id": 40468,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 0,
"selected": false,
"text": "<p>What language/framework?</p>\n\n<p>Using Python and httplib2, you should be able to do something like:</p>\n\n<pre><code>http = httplib2.Http()\nhttp.request(url, 'POST', headers={'key': 'value'}, body=urllib.urlencode(''))\n</code></pre>\n"
},
{
"answer_id": 40475,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that the Request object would only accept a certain set of predefined headers.</p>\n\n<p>There's an enumeration that lists all the supported HTTP Headers too.</p>\n\n<p>But I can't remember it at the moment... I'll look it up in a sec...</p>\n"
},
{
"answer_id": 40478,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 1,
"selected": false,
"text": "<p>Take a look at HttpWebRequest. You should be able to construct a request to the URL in question using HttpWebRequest.Method = \"POST\".</p>\n"
},
{
"answer_id": 40479,
"author": "John Rutherford",
"author_id": 3880,
"author_profile": "https://Stackoverflow.com/users/3880",
"pm_score": 2,
"selected": true,
"text": "<p>Like @lassevk said, a redirect won't work.</p>\n\n<p>You should use the WebRequest class to do an HTTP POST from your page or application. There's an example <a href=\"http://msdn.microsoft.com/en-us/library/debx8sh9.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 40486,
"author": "Ryan Duffield",
"author_id": 2696,
"author_profile": "https://Stackoverflow.com/users/2696",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried the WebClient class? An example might look like:</p>\n\n<pre><code> WebClient client = new WebClient();\n NameValueCollection data = new NameValueCollection();\n data[\"var1\"] = \"var1\";\n client.UploadValues(\"http://somewhere.com/api\", \"POST\", data);\n</code></pre>\n"
},
{
"answer_id": 40742,
"author": "kudlur",
"author_id": 1647,
"author_profile": "https://Stackoverflow.com/users/1647",
"pm_score": 0,
"selected": false,
"text": "<p>I tested your scenario using 2 sample pages using XmlHttpRequest option.\nCustom headers are available in the aspx page posted to, using XmlHttpRequest.</p>\n\n<p>Create the following 2 pages. Make sure the aspx page is in a solution , so that you can run the in the debugger, set break point and inspect the Request.Header collection.</p>\n\n<p><html></p>\n\n<p><head></p>\n\n<pre><code>&lt; script language=\"javascript\"&gt;\n\nfunction SendRequest()\n{\n var r = new XMLHttpRequest();\n r.open('get', 'http://localhost/TestSite/CheckHeader.aspx');\n r.setRequestHeader('X-Test', 'one');\n r.setRequestHeader('X-Test', 'two');\n r.send(null);\n\n}\n&lt; script / &gt;\n</code></pre>\n\n<p></head>\n<body>\n<form>\n<input type=\"button\" value=\"Click Me\" OnClick=\"SendRequest();\" />\n</form>\n</body>\n</html></p>\n\n<hr>\n\n<p>CheckHeader.aspx</p>\n\n<p>using System;</p>\n\n<p>using System.Web;</p>\n\n<p>using System.Web.UI;</p>\n\n<p>public partial class CheckHeader : System.Web.UI.Page</p>\n\n<p>{</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n string value = string.Empty;\n foreach (string key in Request.Headers)\n value = Request.Headers[key].ToString();\n}\n</code></pre>\n\n<p>}</p>\n\n<p>Man.. This html editor sucks.. or i do not know how to use it...</p>\n"
},
{
"answer_id": 41831,
"author": "ila",
"author_id": 1178,
"author_profile": "https://Stackoverflow.com/users/1178",
"pm_score": 0,
"selected": false,
"text": "<p>The exception I was facing yesterday was caused by my stupid try to write on the headers of the already built page.</p>\n\n<p>When I started creating my Request following one of the mothods indicated here, I could write my headers. </p>\n\n<p>Now I'm using the WebRequest object, as in the sample indicated by @sectrean, <a href=\"http://msdn.microsoft.com/en-us/library/debx8sh9.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Thanks a lot to everybody. StackOverflow rocks :-)</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1178/"
] | I have to POST some parameters to a URL outside my network, and the developers on the other side asked me to not use HTTP Parameters: instead I have to post my key-values in **HTTP Headers**.
The fact is that I don't really understand what they mean: I tried to use a ajax-like post, with XmlHttp objects, and also I tried to write in the header with something like
```
Request.Headers.Add(key,value);
```
but I cannot (exception from the framework); I tried the other way around, using the Response object like
```
Response.AppendHeader("key", "value");
```
and then redirect to the page... but this doesn't work, as well.
It's evident, I think, that I'm stuck there, any help?
---
**EDIT** I forgot to tell you that my environment is .Net 2.0, c#, on Win server 2003.
The exception I got is
```
System.PlatformNotSupportedException was unhandled by user code
Message="Operation is not supported on this platform."
Source="System.Web"
```
This looks like it's caused by my tentative to Request.Add, MS an year ago published some security fixes that don't permit this. | Like @lassevk said, a redirect won't work.
You should use the WebRequest class to do an HTTP POST from your page or application. There's an example [here](http://msdn.microsoft.com/en-us/library/debx8sh9.aspx). |
40,456 | <p>If I select from a table group by the month, day, year,
it only returns rows with records and leaves out combinations without any records, making it appear at a glance that every day or month has activity, you have to look at the date column actively for gaps. How can I get a row for every day/month/year, even when no data is present, in T-SQL?</p>
| [
{
"answer_id": 40462,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 3,
"selected": false,
"text": "<p>Create a calendar table and outer join on that table</p>\n"
},
{
"answer_id": 40481,
"author": "Tom Mayfield",
"author_id": 2314,
"author_profile": "https://Stackoverflow.com/users/2314",
"pm_score": 0,
"selected": false,
"text": "<p>Look into using a <a href=\"http://andre-silva-cardoso.blogspot.com/2007/11/sql-trickspatterns-1-numbers-table.html\" rel=\"nofollow noreferrer\">numbers table</a>. While it can be hackish, it's the best method I've come by to quickly query missing data, or show all dates, or anything where you want to examine values within a range, regardless of whether all values in that range are used.</p>\n"
},
{
"answer_id": 40502,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Building on what SQLMenace said, you can use a CROSS JOIN to quickly populate the table or efficiently create it in memory.<br>\n<a href=\"http://www.sitepoint.com/forums/showthread.php?t=562806\" rel=\"nofollow noreferrer\">http://www.sitepoint.com/forums/showthread.php?t=562806</a></p>\n"
},
{
"answer_id": 40619,
"author": "ryw",
"author_id": 2477,
"author_profile": "https://Stackoverflow.com/users/2477",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"https://stackoverflow.com/users/51836/clark\">My developer</a> got back to me with this code, underscores converted to dashes because StackOverflow was mangling underscores -- no numbers table required. Our example is complicated a bit by a join to another table, but maybe the code example will help someone someday.</p>\n\n<pre><code>declare @career-fair-id int \nselect @career-fair-id = 125\n\ncreate table #data ([date] datetime null, [cumulative] int null) \n\ndeclare @event-date datetime, @current-process-date datetime, @day-count int \nselect @event-date = (select careerfairdate from tbl-career-fair where careerfairid = @career-fair-id) \nselect @current-process-date = dateadd(day, -90, @event-date) \n\n while @event-date <> @current-process-date \n begin \n select @current-process-date = dateadd(day, 1, @current-process-date) \n select @day-count = (select count(*) from tbl-career-fair-junction where attendanceregister <= @current-process-date and careerfairid = @career-fair-id) \n if @current-process-date <= getdate() \n insert into #data ([date], [cumulative]) values(@current-process-date, @day-count) \n end \n\n select * from #data \n drop table #data \n</code></pre>\n"
},
{
"answer_id": 274057,
"author": "6eorge Jetson",
"author_id": 23422,
"author_profile": "https://Stackoverflow.com/users/23422",
"pm_score": 0,
"selected": false,
"text": "<p>The task calls for a complete set of dates to be left-joined onto your data, such as</p>\n\n<p><code>\n<br/>DECLARE @StartInt int\n<br/>DECLARE @Increment int\n<br/>DECLARE @Iterations int\n<br/>\n<br/>SET @StartInt = 0\n<br/>SET @Increment = 1\n<br/>SET @Iterations = 365\n<br/>\n<br/>\n<br/>SELECT\n<br/> tCompleteDateSet.[Date]\n<br/> ,AggregatedMeasure = SUM(ISNULL(t.Data, 0))\n<br/>FROM\n<br/> (<br>\n<br/> SELECT \n<br/> [Date] = dateadd(dd,GeneratedInt, @StartDate)\n<br/> FROM \n<br/> [dbo].[tvfUtilGenerateIntegerList] (\n<br/> @StartInt, \n<br/> ,@Increment, \n<br/> ,@Iterations\n<br/> )\n<br/> ) tCompleteDateSet\n<br/> LEFT JOIN tblData t\n<br/> ON (t.[Date] = tCompleteDateSet.[Date])\n<br/>GROUP BY\n<br/> tCompleteDateSet.[Date]\n</code></p>\n\n<p>where the table-valued function tvfUtilGenerateIntegerList is defined as</p>\n\n<p><code>\n<br/>-- Example Inputs\n<br/>\n<br/>-- DECLARE @StartInt int \n<br/>-- DECLARE @Increment int\n<br/>-- DECLARE @Iterations int\n<br/>-- SET @StartInt = 56200\n<br/>-- SET @Increment = 1\n<br/>-- SET @Iterations = 400\n<br/>-- DECLARE @tblResults TABLE \n<br/>-- (\n<br/>-- IterationId int identity(1,1),\n<br/>-- GeneratedInt int\n<br/>-- )\n<br/>\n<br/>\n<br/>-- =============================================\n<br/>-- Author: 6eorge Jetson\n<br/>-- Create date: 11/22/3333\n<br/>-- Description: Generates and returns the desired list of integers as a table\n<br/>-- =============================================\n<br/>CREATE FUNCTION [dbo].[tvfUtilGenerateIntegerList]\n<br/>(\n<br/> @StartInt int, \n<br/> @Increment int,\n<br/> @Iterations int\n<br/>) \n<br/>RETURNS \n<br/>@tblResults TABLE \n<br/>(\n<br/> IterationId int identity(1,1),\n<br/> GeneratedInt int\n<br/>)\n<br/>AS\n<br/>BEGIN\n<br/>\n<br/> DECLARE @counter int \n<br/> SET @counter= 0\n<br/> WHILE (@counter < @Iterations)\n<br/> BEGIN\n<br/> INSERT @tblResults(GeneratedInt) VALUES(@StartInt + @counter*@Increment)\n<br/> SET @counter = @counter + 1\n<br/> END\n<br/><br>\n<br/> RETURN \n<br/>END\n<br/>--Debug\n<br/>--SELECT * FROM @tblResults</p>\n\n<p></code></p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2477/"
] | If I select from a table group by the month, day, year,
it only returns rows with records and leaves out combinations without any records, making it appear at a glance that every day or month has activity, you have to look at the date column actively for gaps. How can I get a row for every day/month/year, even when no data is present, in T-SQL? | [My developer](https://stackoverflow.com/users/51836/clark) got back to me with this code, underscores converted to dashes because StackOverflow was mangling underscores -- no numbers table required. Our example is complicated a bit by a join to another table, but maybe the code example will help someone someday.
```
declare @career-fair-id int
select @career-fair-id = 125
create table #data ([date] datetime null, [cumulative] int null)
declare @event-date datetime, @current-process-date datetime, @day-count int
select @event-date = (select careerfairdate from tbl-career-fair where careerfairid = @career-fair-id)
select @current-process-date = dateadd(day, -90, @event-date)
while @event-date <> @current-process-date
begin
select @current-process-date = dateadd(day, 1, @current-process-date)
select @day-count = (select count(*) from tbl-career-fair-junction where attendanceregister <= @current-process-date and careerfairid = @career-fair-id)
if @current-process-date <= getdate()
insert into #data ([date], [cumulative]) values(@current-process-date, @day-count)
end
select * from #data
drop table #data
``` |
40,465 | <p>I have a List of Foo.</p>
<p>Foo has a string property named Bar.</p>
<p>I'd like to use <strong>LINQ</strong> to get a string[] of <strong>distinct</strong> values for Foo.Bar in List of Foo.</p>
<p>How can I do this?</p>
| [
{
"answer_id": 40477,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>var distinctFooBars = (from foo in foos\n select foo.Bar).Distinct().ToArray();\n</code></pre>\n"
},
{
"answer_id": 40488,
"author": "Guy",
"author_id": 1463,
"author_profile": "https://Stackoverflow.com/users/1463",
"pm_score": 2,
"selected": false,
"text": "<p>This should work if you want to use the fluent pattern:</p>\n\n<pre><code>string[] arrayStrings = fooList.Select(a => a.Bar).Distinct().ToArray();\n</code></pre>\n"
},
{
"answer_id": 40497,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 4,
"selected": true,
"text": "<p>I'd go lambdas... wayyy nicer</p>\n\n<pre><code>var bars = Foos.Select(f => f.Bar).Distinct().ToArray();\n</code></pre>\n\n<p>works the same as what @lassevk posted.</p>\n\n<p>I'd also add that you might want to keep from converting to an array until the last minute. </p>\n\n<p>LINQ does some optimizations behind the scenes, queries stay in its query form until explicitly needed. So you might want to build everything you need into the query first so any possible optimization is applied altogether.</p>\n\n<p>By evaluation I means asking for something that explicitly requires evalution like \"Count()\" or \"ToArray()\" etc.</p>\n"
},
{
"answer_id": 40498,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Shouldn't you be able to do something like:</p>\n\n<pre><code>var strings = (from a in fooList select a.Bar).Distinct();\nstring[] array = strings.ToArray();\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] | I have a List of Foo.
Foo has a string property named Bar.
I'd like to use **LINQ** to get a string[] of **distinct** values for Foo.Bar in List of Foo.
How can I do this? | I'd go lambdas... wayyy nicer
```
var bars = Foos.Select(f => f.Bar).Distinct().ToArray();
```
works the same as what @lassevk posted.
I'd also add that you might want to keep from converting to an array until the last minute.
LINQ does some optimizations behind the scenes, queries stay in its query form until explicitly needed. So you might want to build everything you need into the query first so any possible optimization is applied altogether.
By evaluation I means asking for something that explicitly requires evalution like "Count()" or "ToArray()" etc. |
40,480 | <p>I always thought Java uses <strong>pass-by-reference</strong>.</p>
<p>However, I've seen <a href="http://javadude.com/articles/passbyvalue.htm" rel="noreferrer">a blog post</a> that claims that Java uses <strong>pass-by-value</strong>.</p>
<p>I don't think I understand the distinction they're making.</p>
<p>What is the explanation?</p>
| [
{
"answer_id": 40499,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 10,
"selected": false,
"text": "<p>Java is always pass by value, with no exceptions, <strong>ever</strong>.</p>\n\n<p>So how is it that anyone can be at all confused by this, and believe that Java is pass by reference, or think they have an example of Java acting as pass by reference? The key point is that Java <strong>never</strong> provides direct access to the values of <em>objects themselves</em>, in <em>any</em> circumstances. The only access to objects is through a <em>reference</em> to that object. Because Java objects are <em>always</em> accessed through a reference, rather than directly, it is common to talk about fields and variables <em>and method arguments</em> as being <em>objects</em>, when pedantically they are only <em>references to objects</em>. <strong>The confusion stems from this (strictly speaking, incorrect) change in nomenclature.</strong></p>\n\n<p>So, when calling a method</p>\n\n<ul>\n<li>For primitive arguments (<code>int</code>, <code>long</code>, etc.), the pass by value is <em>the actual value</em> of the primitive (for example, 3).</li>\n<li>For objects, the pass by value is the value of <em>the reference to the object</em>.</li>\n</ul>\n\n<p>So if you have <code>doSomething(foo)</code> and <code>public void doSomething(Foo foo) { .. }</code> the two Foos have copied <em>references</em> that point to the same objects.</p>\n\n<p>Naturally, passing by value a reference to an object looks very much like (and is indistinguishable in practice from) passing an object by reference.</p>\n"
},
{
"answer_id": 40501,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 9,
"selected": false,
"text": "<p>Java passes references by value.</p>\n\n<p>So you can't change the reference that gets passed in.</p>\n"
},
{
"answer_id": 40507,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 8,
"selected": false,
"text": "<p>Basically, reassigning Object parameters doesn't affect the argument, e.g.,</p>\n<pre><code>private static void foo(Object bar) {\n bar = null;\n}\n\npublic static void main(String[] args) {\n String baz = "Hah!";\n foo(baz);\n System.out.println(baz);\n}\n</code></pre>\n<p>will print out <code>"Hah!"</code> instead of <code>null</code>. The reason this works is because <code>bar</code> is a copy of the value of <code>baz</code>, which is just a reference to <code>"Hah!"</code>. If it were the actual reference itself, then <code>foo</code> would have redefined <code>baz</code> to <code>null</code>.</p>\n"
},
{
"answer_id": 40514,
"author": "John Channing",
"author_id": 3305,
"author_profile": "https://Stackoverflow.com/users/3305",
"pm_score": 8,
"selected": false,
"text": "<p>Java passes references to objects by value.</p>\n"
},
{
"answer_id": 40523,
"author": "erlando",
"author_id": 4192,
"author_profile": "https://Stackoverflow.com/users/4192",
"pm_score": 13,
"selected": false,
"text": "<p>The terms "pass-by-value" and "pass-by-reference" have special, <a href=\"https://en.wikipedia.org/w/index.php?title=Pass-by-value\" rel=\"noreferrer\">precisely defined</a> meanings in computer science. These meanings differ from the intuition many people have when first hearing the terms. Much of the confusion in this discussion seems to come from this fact.</p>\n<p>The terms "pass-by-value" and "pass-by-reference" are talking about <em>variables.</em> Pass-by-value means that the <em>value</em> of a variable is passed to a function/method. Pass-by-reference means that a <em>reference</em> to that variable is passed to the function. The latter gives the function a way to change the contents of the variable.</p>\n<p>By those definitions, Java is always <strong>pass-by-value</strong>. Unfortunately, when we deal with variables holding objects we are really dealing with object-handles called <em>references</em> which are passed-by-value as well. This terminology and semantics easily confuse many beginners.</p>\n<p>It goes like this:</p>\n<pre><code>public static void main(String[] args) {\n Dog aDog = new Dog("Max");\n Dog oldDog = aDog;\n\n // we pass the object to foo\n foo(aDog);\n // aDog variable is still pointing to the "Max" dog when foo(...) returns\n aDog.getName().equals("Max"); // true\n aDog.getName().equals("Fifi"); // false\n aDog == oldDog; // true\n}\n\npublic static void foo(Dog d) {\n d.getName().equals("Max"); // true\n // change d inside of foo() to point to a new Dog instance "Fifi"\n d = new Dog("Fifi");\n d.getName().equals("Fifi"); // true\n}\n</code></pre>\n<p>In the example above <code>aDog.getName()</code> will still return <code>"Max"</code>. The value <code>aDog</code> within <code>main</code> is not changed in the function <code>foo</code> with the <code>Dog</code> <code>"Fifi"</code> as the object reference is passed by value. If it were passed by reference, then the <code>aDog.getName()</code> in <code>main</code> would return <code>"Fifi"</code> after the call to <code>foo</code>.</p>\n<p>Likewise:</p>\n<pre><code>public static void main(String[] args) {\n Dog aDog = new Dog("Max");\n Dog oldDog = aDog;\n\n foo(aDog);\n // when foo(...) returns, the name of the dog has been changed to "Fifi"\n aDog.getName().equals("Fifi"); // true\n // but it is still the same dog:\n aDog == oldDog; // true\n}\n\npublic static void foo(Dog d) {\n d.getName().equals("Max"); // true\n // this changes the name of d to be "Fifi"\n d.setName("Fifi");\n}\n</code></pre>\n<p>In the above example, <code>Fifi</code> is the dog's name after call to <code>foo(aDog)</code> because the object's name was set inside of <code>foo(...)</code>. Any operations that <code>foo</code> performs on <code>d</code> are such that, for all practical purposes, they are performed on <code>aDog</code>, but it is <strong>not</strong> possible to change the value of the variable <code>aDog</code> itself.</p>\n<p>For more information on pass by reference and pass by value, consult the following answer: <a href=\"https://stackoverflow.com/a/430958/6005228\">https://stackoverflow.com/a/430958/6005228</a>. This explains more thoroughly the semantics and history behind the two and also explains why Java and many other modern languages appear to do both in certain cases.</p>\n"
},
{
"answer_id": 40630,
"author": "Paul de Vrieze",
"author_id": 4100,
"author_profile": "https://Stackoverflow.com/users/4100",
"pm_score": 5,
"selected": false,
"text": "<p>To make a long story short, <a href=\"http://en.wikipedia.org/wiki/Java_%28programming_language%29\" rel=\"noreferrer\">Java</a> objects have some very peculiar properties.</p>\n\n<p>In general, Java has primitive types (<code>int</code>, <code>bool</code>, <code>char</code>, <code>double</code>, etc) that are passed directly by value. Then Java has objects (everything that derives from <code>java.lang.Object</code>). Objects are actually always handled through a reference (a reference being a pointer that you can't touch). That means that in effect, objects are passed by reference, as the references are normally not interesting. It does however mean that you cannot change which object is pointed to as the reference itself is passed by value.</p>\n\n<p>Does this sound strange and confusing? Let's consider how C implements pass by reference and pass by value. In C, the default convention is pass by value. <code>void foo(int x)</code> passes an int by value. <code>void foo(int *x)</code> is a function that does not want an <code>int a</code>, but a pointer to an int: <code>foo(&a)</code>. One would use this with the <code>&</code> operator to pass a variable address.</p>\n\n<p>Take this to C++, and we have references. References are basically (in this context) syntactic sugar that hide the pointer part of the equation: <code>void foo(int &x)</code> is called by <code>foo(a)</code>, where the compiler itself knows that it is a reference and the address of the non-reference <code>a</code> should be passed. In Java, all variables referring to objects are actually of reference type, in effect forcing call by reference for most intends and purposes without the fine grained control (and complexity) afforded by, for example, C++.</p>\n"
},
{
"answer_id": 42392,
"author": "shsteimer",
"author_id": 292,
"author_profile": "https://Stackoverflow.com/users/292",
"pm_score": 6,
"selected": false,
"text": "<p>The distinction, or perhaps just the way I remember as I used to be under the same impression as the original poster is this: Java is always pass by value. All objects( in Java, anything except for primitives) in Java are references. These references are passed by value.</p>\n"
},
{
"answer_id": 42455,
"author": "pek",
"author_id": 2644,
"author_profile": "https://Stackoverflow.com/users/2644",
"pm_score": 5,
"selected": false,
"text": "<p>As many people mentioned it before, <a href=\"http://academic.regis.edu/dbahr/GeneralPages/IntroToProgramming/JavaPassByValue.htm\" rel=\"noreferrer\">Java is always pass-by-value</a></p>\n\n<p>Here is another example that will help you understand the difference (<a href=\"http://www.javaranch.com/campfire/StoryPassBy.jsp\" rel=\"noreferrer\">the classic swap example</a>):</p>\n\n<pre><code>public class Test {\n public static void main(String[] args) {\n Integer a = new Integer(2);\n Integer b = new Integer(3);\n System.out.println(\"Before: a = \" + a + \", b = \" + b);\n swap(a,b);\n System.out.println(\"After: a = \" + a + \", b = \" + b);\n }\n\n public static swap(Integer iA, Integer iB) {\n Integer tmp = iA;\n iA = iB;\n iB = tmp;\n }\n}\n</code></pre>\n\n<p>Prints: </p>\n\n<blockquote>\n <p>Before: a = 2, b = 3<br>\n After: a = 2, b = 3</p>\n</blockquote>\n\n<p>This happens because iA and iB are new local reference variables that have the same value of the passed references (they point to a and b respectively). So, trying to change the references of iA or iB will only change in the local scope and not outside of this method.</p>\n"
},
{
"answer_id": 49857,
"author": "SWD",
"author_id": 3034,
"author_profile": "https://Stackoverflow.com/users/3034",
"pm_score": 5,
"selected": false,
"text": "<p>I always think of it as \"pass by copy\". It is a copy of the value be it primitive or reference. If it is a primitive it is a copy of the bits that are the value and if it is an Object it is a copy of the reference.</p>\n\n<pre><code>public class PassByCopy{\n public static void changeName(Dog d){\n d.name = \"Fido\";\n }\n public static void main(String[] args){\n Dog d = new Dog(\"Maxx\");\n System.out.println(\"name= \"+ d.name);\n changeName(d);\n System.out.println(\"name= \"+ d.name);\n }\n}\nclass Dog{\n public String name;\n public Dog(String s){\n this.name = s;\n }\n}\n</code></pre>\n\n<p>output of java PassByCopy:</p>\n\n<blockquote>\n <p>name= Maxx<br>\n name= Fido</p>\n</blockquote>\n\n<p>Primitive wrapper classes and Strings are immutable so any example using those types will not work the same as other types/objects.</p>\n"
},
{
"answer_id": 49863,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 5,
"selected": false,
"text": "<p>I have created a thread devoted to these kind of questions for <em>any</em> programming languages <a href=\"https://stackoverflow.com/questions/2027/pass-by-reference-or-pass-by-value\">here</a>.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/2027/pass-by-reference-or-pass-by-value#2028\">Java is also mentioned</a>. Here is the short summary:</p>\n\n<ul>\n<li>Java passes it parameters by value</li>\n<li>\"by value\" is the only way in java to pass a parameter to a method</li>\n<li>using methods from the object given as parameter will alter the\nobject as the references point to\nthe original objects. (if that\nmethod itself alters some values)</li>\n</ul>\n"
},
{
"answer_id": 73021,
"author": "Scott Stanchfield",
"author_id": 12541,
"author_profile": "https://Stackoverflow.com/users/12541",
"pm_score": 12,
"selected": false,
"text": "<p>I just noticed you referenced <a href=\"http://javadude.com/articles/passbyvalue.htm\" rel=\"noreferrer\">my article</a>.</p>\n<p>The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java.</p>\n<p>The key to understanding this is that something like</p>\n<pre><code>Dog myDog;\n</code></pre>\n<p>is <em>not</em> a Dog; it's actually a <em>pointer</em> to a Dog. The use of the term "reference" in Java is very misleading and is what causes most of the confusion here. What they call "references" act/feel more like what we'd call "pointers" in most other languages.</p>\n<p>What that means, is when you have</p>\n<pre><code>Dog myDog = new Dog("Rover");\nfoo(myDog);\n</code></pre>\n<p>you're essentially passing the <em>address</em> of the created <code>Dog</code> object to the <code>foo</code> method.</p>\n<p>(I say essentially because Java pointers/references aren't direct addresses, but it's easiest to think of them that way.)</p>\n<p>Suppose the <code>Dog</code> object resides at memory address 42. This means we pass 42 to the method.</p>\n<p>if the Method were defined as</p>\n<pre><code>public void foo(Dog someDog) {\n someDog.setName("Max"); // AAA\n someDog = new Dog("Fifi"); // BBB\n someDog.setName("Rowlf"); // CCC\n}\n</code></pre>\n<p>let's look at what's happening.</p>\n<ul>\n<li>the parameter <code>someDog</code> is set to the value 42</li>\n<li>at line "AAA"\n<ul>\n<li><code>someDog</code> is followed to the <code>Dog</code> it points to (the <code>Dog</code> object at address 42)</li>\n<li>that <code>Dog</code> (the one at address 42) is asked to change his name to Max</li>\n</ul>\n</li>\n<li>at line "BBB"\n<ul>\n<li>a new <code>Dog</code> is created. Let's say he's at address 74</li>\n<li>we assign the parameter <code>someDog</code> to 74</li>\n</ul>\n</li>\n<li>at line "CCC"\n<ul>\n<li>someDog is followed to the <code>Dog</code> it points to (the <code>Dog</code> object at address 74)</li>\n<li>that <code>Dog</code> (the one at address 74) is asked to change his name to Rowlf</li>\n</ul>\n</li>\n<li>then, we return</li>\n</ul>\n<p>Now let's think about what happens outside the method:</p>\n<p><em>Did <code>myDog</code> change?</em></p>\n<p>There's the key.</p>\n<p>Keeping in mind that <code>myDog</code> is a <em>pointer</em>, and not an actual <code>Dog</code>, the answer is NO. <code>myDog</code> still has the value 42; it's still pointing to the original <code>Dog</code> (but note that because of line "AAA", its name is now "Max" - still the same Dog; <code>myDog</code>'s value has not changed.)</p>\n<p>It's perfectly valid to <em>follow</em> an address and change what's at the end of it; that does not change the variable, however.</p>\n<p>Java works exactly like C. You can assign a pointer, pass the pointer to a method, follow the pointer in the method and change the data that was pointed to. However, the caller will not see any changes you make to where that pointer points. (In a language with pass-by-reference semantics, the method function <em>can</em> change the pointer and the caller will see that change.)</p>\n<p>In C++, Ada, Pascal and other languages that support pass-by-reference, you can actually change the variable that was passed.</p>\n<p>If Java had pass-by-reference semantics, the <code>foo</code> method we defined above would have changed where <code>myDog</code> was pointing when it assigned <code>someDog</code> on line BBB.</p>\n<p>Think of reference parameters as being aliases for the variable passed in. When that alias is assigned, so is the variable that was passed in.</p>\n<h2>Update</h2>\n<p>A discussion in the comments warrants some clarification...</p>\n<p>In C, you can write</p>\n<pre class=\"lang-c prettyprint-override\"><code>void swap(int *x, int *y) {\n int t = *x;\n *x = *y;\n *y = t;\n}\n\nint x = 1;\nint y = 2;\nswap(&x, &y);\n</code></pre>\n<p>This is not a special case in C. Both languages use pass-by-value semantics. Here the call site is creating additional data structure to assist the function to access and manipulate data.</p>\n<p>The function is being passed pointers to data, and follows those pointers to access and modify that data.</p>\n<p>A similar approach in Java, where the caller sets up assisting structure, might be:</p>\n<pre class=\"lang-java prettyprint-override\"><code>void swap(int[] x, int[] y) {\n int temp = x[0];\n x[0] = y[0];\n y[0] = temp;\n}\n\nint[] x = {1};\nint[] y = {2};\nswap(x, y);\n</code></pre>\n<p>(or if you wanted both examples to demonstrate features the other language doesn't have, create a mutable IntWrapper class to use in place of the arrays)</p>\n<p>In these cases, both C and Java are <em>simulating</em> pass-by-reference. They're still both passing values (pointers to ints or arrays), and following those pointers inside the called function to manipulate the data.</p>\n<p>Pass-by-reference is all about the function <em>declaration/definition</em>, and how it handles its parameters. Reference semantics apply to <em>every</em> call to that function, and the call site only needs to pass variables, no additional data structure.</p>\n<p>These simulations require the call site and the function to cooperate. No doubt it's useful, but it's still pass-by-value.</p>\n"
},
{
"answer_id": 85711,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 8,
"selected": false,
"text": "<p>Just to show the contrast, compare the following <a href=\"https://en.wikipedia.org/wiki/C++\" rel=\"noreferrer\">C++</a> and <a href=\"http://en.wikipedia.org/wiki/Java_%28programming_language%29\" rel=\"noreferrer\">Java</a> snippets:</p>\n\n<p>In C++: <strong>Note: Bad code - memory leaks!</strong> But it demonstrates the point.</p>\n\n<pre><code>void cppMethod(int val, int &ref, Dog obj, Dog &objRef, Dog *objPtr, Dog *&objPtrRef)\n{\n val = 7; // Modifies the copy\n ref = 7; // Modifies the original variable\n obj.SetName(\"obj\"); // Modifies the copy of Dog passed\n objRef.SetName(\"objRef\"); // Modifies the original Dog passed\n objPtr->SetName(\"objPtr\"); // Modifies the original Dog pointed to \n // by the copy of the pointer passed.\n objPtr = new Dog(\"newObjPtr\"); // Modifies the copy of the pointer, \n // leaving the original object alone.\n objPtrRef->SetName(\"objRefPtr\"); // Modifies the original Dog pointed to \n // by the original pointer passed. \n objPtrRef = new Dog(\"newObjPtrRef\"); // Modifies the original pointer passed\n}\n\nint main()\n{\n int a = 0;\n int b = 0;\n Dog d0 = Dog(\"d0\");\n Dog d1 = Dog(\"d1\");\n Dog *d2 = new Dog(\"d2\");\n Dog *d3 = new Dog(\"d3\");\n cppMethod(a, b, d0, d1, d2, d3);\n // a is still set to 0\n // b is now set to 7\n // d0 still have name \"d0\"\n // d1 now has name \"objRef\"\n // d2 now has name \"objPtr\"\n // d3 now has name \"newObjPtrRef\"\n}\n</code></pre>\n\n<p>In Java, </p>\n\n<pre><code>public static void javaMethod(int val, Dog objPtr)\n{\n val = 7; // Modifies the copy\n objPtr.SetName(\"objPtr\") // Modifies the original Dog pointed to \n // by the copy of the pointer passed.\n objPtr = new Dog(\"newObjPtr\"); // Modifies the copy of the pointer, \n // leaving the original object alone.\n}\n\npublic static void main()\n{\n int a = 0;\n Dog d0 = new Dog(\"d0\");\n javaMethod(a, d0);\n // a is still set to 0\n // d0 now has name \"objPtr\"\n}\n</code></pre>\n\n<p>Java only has the two types of passing: by value for built-in types, and by value of the pointer for object types.</p>\n"
},
{
"answer_id": 436924,
"author": "Harald Schilly",
"author_id": 54236,
"author_profile": "https://Stackoverflow.com/users/54236",
"pm_score": 4,
"selected": false,
"text": "<p>It's a bit hard to understand, but Java always copies the value - the point is, normally the value is a reference. Therefore you end up with the same object without thinking about it...</p>\n"
},
{
"answer_id": 436969,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 7,
"selected": false,
"text": "<p>The crux of the matter is that the word <em>reference</em> in the expression \"pass by reference\" means something completely different from the usual meaning of the word <em>reference</em> in Java. </p>\n\n<p>Usually in Java <em>reference</em> means a a <em>reference to an object</em>. But the technical terms <em>pass by reference/value</em> from programming language theory is talking about a <em>reference to the memory cell holding the variable</em>, which is something completely different.</p>\n"
},
{
"answer_id": 623155,
"author": "Jared Oberhaus",
"author_id": 73019,
"author_profile": "https://Stackoverflow.com/users/73019",
"pm_score": 6,
"selected": false,
"text": "<p>You can never pass by reference in Java, and one of the ways that is obvious is when you want to return more than one value from a method call. Consider the following bit of code in C++:</p>\n\n<pre><code>void getValues(int& arg1, int& arg2) {\n arg1 = 1;\n arg2 = 2;\n}\nvoid caller() {\n int x;\n int y;\n getValues(x, y);\n cout << \"Result: \" << x << \" \" << y << endl;\n}\n</code></pre>\n\n<p>Sometimes you want to use the same pattern in Java, but you can't; at least not directly. Instead you could do something like this:</p>\n\n<pre><code>void getValues(int[] arg1, int[] arg2) {\n arg1[0] = 1;\n arg2[0] = 2;\n}\nvoid caller() {\n int[] x = new int[1];\n int[] y = new int[1];\n getValues(x, y);\n System.out.println(\"Result: \" + x[0] + \" \" + y[0]);\n}\n</code></pre>\n\n<p>As was explained in previous answers, in Java you're passing a pointer to the array as a value into <code>getValues</code>. That is enough, because the method then modifies the array element, and by convention you're expecting element 0 to contain the return value. Obviously you can do this in other ways, such as structuring your code so this isn't necessary, or constructing a class that can contain the return value or allow it to be set. But the simple pattern available to you in C++ above is not available in Java.</p>\n"
},
{
"answer_id": 707416,
"author": "kukudas",
"author_id": 48402,
"author_profile": "https://Stackoverflow.com/users/48402",
"pm_score": 6,
"selected": false,
"text": "<p>As far as I know, Java only knows call by value. This means for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects. However I think there are some pitfalls; for example, this will not work:</p>\n\n<pre><code>public static void swap(StringBuffer s1, StringBuffer s2) {\n StringBuffer temp = s1;\n s1 = s2;\n s2 = temp;\n}\n\n\npublic static void main(String[] args) {\n StringBuffer s1 = new StringBuffer(\"Hello\");\n StringBuffer s2 = new StringBuffer(\"World\");\n swap(s1, s2);\n System.out.println(s1);\n System.out.println(s2);\n}\n</code></pre>\n\n<p>This will populate Hello World and not World Hello because in the swap function you use copys which have no impact on the references in the main. But if your objects are not immutable you can change it for example:</p>\n\n<pre><code>public static void appendWorld(StringBuffer s1) {\n s1.append(\" World\");\n}\n\npublic static void main(String[] args) {\n StringBuffer s = new StringBuffer(\"Hello\");\n appendWorld(s);\n System.out.println(s);\n}\n</code></pre>\n\n<p>This will populate Hello World on the command line. If you change StringBuffer into String it will produce just Hello because String is immutable. For example:</p>\n\n<pre><code>public static void appendWorld(String s){\n s = s+\" World\";\n}\n\npublic static void main(String[] args) {\n String s = new String(\"Hello\");\n appendWorld(s);\n System.out.println(s);\n}\n</code></pre>\n\n<p>However you could make a wrapper for String like this which would make it able to use it with Strings:</p>\n\n<pre><code>class StringWrapper {\n public String value;\n\n public StringWrapper(String value) {\n this.value = value;\n }\n}\n\npublic static void appendWorld(StringWrapper s){\n s.value = s.value +\" World\";\n}\n\npublic static void main(String[] args) {\n StringWrapper s = new StringWrapper(\"Hello\");\n appendWorld(s);\n System.out.println(s.value);\n}\n</code></pre>\n\n<p>edit: i believe this is also the reason to use StringBuffer when it comes to \"adding\" two Strings because you can modifie the original object which u can't with immutable objects like String is.</p>\n"
},
{
"answer_id": 1964260,
"author": "Rusty Shackleford",
"author_id": 238938,
"author_profile": "https://Stackoverflow.com/users/238938",
"pm_score": 5,
"selected": false,
"text": "<p>A few corrections to some posts.</p>\n\n<p>C does NOT support pass by reference. It is ALWAYS pass by value. C++ does support pass by reference, but is not the default and is quite dangerous.</p>\n\n<p>It doesn't matter what the value is in Java: primitive or address(roughly) of object, it is ALWAYS passed by value.</p>\n\n<p>If a Java object \"behaves\" like it is being passed by reference, that is a property of mutability and has absolutely nothing to do with passing mechanisms.</p>\n\n<p>I am not sure why this is so confusing, perhaps because so many Java \"programmers\" are not formally trained, and thus do not understand what is really going on in memory?</p>\n"
},
{
"answer_id": 1964361,
"author": "fastcodejava",
"author_id": 184730,
"author_profile": "https://Stackoverflow.com/users/184730",
"pm_score": 5,
"selected": false,
"text": "<p>Java copies the reference by value. So if you change it to something else (e.g, using <code>new</code>) the reference does not change outside the method. For native types, it is always pass by value.</p>\n"
},
{
"answer_id": 3439923,
"author": "Vinay Lodha",
"author_id": 212665,
"author_profile": "https://Stackoverflow.com/users/212665",
"pm_score": 4,
"selected": false,
"text": "<p>Have a look at this code. This code will not throw <code>NullPointerException</code>... It will print \"Vinay\"</p>\n\n<pre><code>public class Main {\n public static void main(String[] args) {\n String temp = \"Vinay\";\n print(temp);\n System.err.println(temp);\n }\n\n private static void print(String temp) {\n temp = null;\n }\n}\n</code></pre>\n\n<p>If Java is pass by reference then it should have thrown <code>NullPointerException</code> as reference is set to Null.</p>\n"
},
{
"answer_id": 3663123,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 7,
"selected": false,
"text": "<p>I can't believe that nobody mentioned Barbara Liskov yet. When she designed CLU in 1974, she ran into this same terminology problem, and she invented the term <em>call by sharing</em> (also known as <em>call by object-sharing</em> and <em>call by object</em>) for this specific case of \"call by value where the value is a reference\".</p>\n"
},
{
"answer_id": 7034719,
"author": "Marsellus Wallace",
"author_id": 807231,
"author_profile": "https://Stackoverflow.com/users/807231",
"pm_score": 10,
"selected": false,
"text": "<p><strong>This will give you some insights of how Java really works to the point that in your next discussion about Java passing by reference or passing by value you'll just smile :-)</strong></p>\n\n<p>Step one please erase from your mind that word that starts with 'p' \"_ _ _ _ _ _ _\", especially if you come from other programming languages. Java and 'p' cannot be written in the same book, forum, or even txt.</p>\n\n<p>Step two remember that when you pass an Object into a method you're passing the Object reference and not the Object itself.</p>\n\n<ul>\n<li><em>Student</em>: Master, does this mean that Java is pass-by-reference?</li>\n<li><em>Master</em>: Grasshopper, No.</li>\n</ul>\n\n<p>Now think of what an Object's reference/variable does/is:</p>\n\n<ol>\n<li><strong>A variable holds the bits that tell the JVM how to get to the referenced Object in memory (Heap).</strong></li>\n<li>When passing arguments to a method <strong>you ARE NOT passing the reference variable, but a copy of the bits in the reference variable</strong>. Something like this: 3bad086a. 3bad086a represents a way to get to the passed object.</li>\n<li>So you're just passing 3bad086a that it's the value of the reference.</li>\n<li>You're passing the value of the reference and not the reference itself (and not the object).</li>\n<li><strong><em>This value is actually COPIED and given to the method</em></strong>. </li>\n</ol>\n\n<p>In the following (please don't try to compile/execute this...):</p>\n\n<pre><code>1. Person person;\n2. person = new Person(\"Tom\");\n3. changeName(person);\n4.\n5. //I didn't use Person person below as an argument to be nice\n6. static void changeName(Person anotherReferenceToTheSamePersonObject) {\n7. anotherReferenceToTheSamePersonObject.setName(\"Jerry\");\n8. }\n</code></pre>\n\n<p>What happens?</p>\n\n<ul>\n<li>The variable <em>person</em> is created in line #1 and it's null at the beginning.</li>\n<li>A new Person Object is created in line #2, stored in memory, and the variable <em>person</em> is given the reference to the Person object. That is, its address. Let's say 3bad086a.</li>\n<li>The variable <em>person</em> holding the address of the Object is passed to the function in line #3.</li>\n<li>In line #4 you can listen to the sound of silence </li>\n<li>Check the comment on line #5</li>\n<li>A method local variable -<em>anotherReferenceToTheSamePersonObject</em>- is created and then comes the magic in line #6:\n\n<ul>\n<li>The variable/reference <em>person</em> is copied bit-by-bit and passed to <em>anotherReferenceToTheSamePersonObject</em> inside the function.</li>\n<li>No new instances of Person are created.</li>\n<li>Both \"<em>person</em>\" and \"<em>anotherReferenceToTheSamePersonObject</em>\" hold the same value of 3bad086a.</li>\n<li>Don't try this but person==anotherReferenceToTheSamePersonObject would be true.</li>\n<li>Both variables have IDENTICAL COPIES of the reference and they both refer to the same Person Object, the SAME Object on the Heap and NOT A COPY.</li>\n</ul></li>\n</ul>\n\n<p>A picture is worth a thousand words:</p>\n\n<p><img src=\"https://i.stack.imgur.com/Ba3hJ.jpg\" alt=\"Pass by Value\"></p>\n\n<p><strong>Note that the anotherReferenceToTheSamePersonObject arrows is directed towards the Object and not towards the variable person!</strong></p>\n\n<p>If you didn't get it then just trust me and remember that it's better to say that <strong>Java is pass by value</strong>. Well, <strong>pass by reference value</strong>. Oh well, even better is <strong><em>pass-by-copy-of-the-variable-value! ;)</em></strong></p>\n\n<p>Now feel free to hate me but note that given this <strong>there is no difference between passing primitive data types and Objects</strong> when talking about method arguments.</p>\n\n<p>You always pass a copy of the bits of the value of the reference!</p>\n\n<ul>\n<li>If it's a primitive data type these bits will contain the value of the primitive data type itself.</li>\n<li>If it's an Object the bits will contain the value of the address that tells the JVM how to get to the Object.</li>\n</ul>\n\n<blockquote>\n <p>Java is pass-by-value because inside a method you can modify the referenced Object as much as you want but no matter how hard you try you'll never be able to modify the passed variable that will keep referencing (not p _ _ _ _ _ _ _) the same Object no matter what!</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p>The changeName function above will never be able to modify the actual content (the bit values) of the passed reference. In other word changeName cannot make Person person refer to another Object.</p>\n</blockquote>\n\n<hr>\n\n<p>Of course you can cut it short and just say that <strong>Java is pass-by-value!</strong></p>\n"
},
{
"answer_id": 10236169,
"author": "Luigi R. Viggiano",
"author_id": 258289,
"author_profile": "https://Stackoverflow.com/users/258289",
"pm_score": 3,
"selected": false,
"text": "<p>Everything is passed by value. Primitives and Object references. But objects can be changed, if their interface allows it.</p>\n\n<p>When you pass an object to a method, you are passing a reference, and the object can be modified by the method implementation. </p>\n\n<pre><code>void bithday(Person p) {\n p.age++;\n}\n</code></pre>\n\n<p>The reference of the object itself, is passed by value: you can reassign the parameter, but the change is not reflected back:</p>\n\n<pre><code>void renameToJon(Person p) { \n p = new Person(\"Jon\"); // this will not work\n}\n\njack = new Person(\"Jack\");\nrenameToJon(jack);\nsysout(jack); // jack is unchanged\n</code></pre>\n\n<p>As matter of effect, \"p\" is reference (pointer to the object) and can't be changed. </p>\n\n<p>Primitive types are passed by value. Object's reference can be considered a primitive type too. </p>\n\n<p>To recap, everything is passed by value.</p>\n"
},
{
"answer_id": 11764499,
"author": "Fernando Espinosa",
"author_id": 1426433,
"author_profile": "https://Stackoverflow.com/users/1426433",
"pm_score": 4,
"selected": false,
"text": "<p>It's really quite, quite simple:</p>\n\n<p>For a variable of primitive type (eg. <code>int</code>, <code>boolean</code>, <code>char</code>, etc...), when you use its name for a method argument, you are passing the value contained in it (<code>5</code>, <code>true</code>, or <code>'c'</code>). This value gets \"copied\", and the variable retains its value even after the method invocation.</p>\n\n<p>For a variable of reference type (eg. <code>String</code>, <code>Object</code>, etc...), when you use its name for a method argument, you are passing the value contained in it (<em>the <strong>reference value</strong> that \"points\" to the object</em>). This <strong><em>reference value</em></strong> gets \"copied\", and the variable retains its value even after the method invocation. <strong><em>The reference variable keeps \"pointing\" to the same object.</em></strong></p>\n\n<p>Either way, you're always passing stuff by value.</p>\n\n<hr>\n\n<p>Compare this to say C++ where you can have a method to take an <code>int&</code>, or in C# where you could have take a <code>ref int</code> (although, in this case, you also have to use the <code>ref</code> modifier when passing the variable's name to the method.)</p>\n"
},
{
"answer_id": 12429953,
"author": "Eng.Fouad",
"author_id": 597657,
"author_profile": "https://Stackoverflow.com/users/597657",
"pm_score": 11,
"selected": false,
"text": "<p>Java always passes arguments <em>by value</em>, NOT by reference.</p>\n<hr />\n<p>Let me explain this through an <a href=\"https://stackoverflow.com/a/9404727/597657\">example</a>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class Main {\n\n public static void main(String[] args) {\n Foo f = new Foo("f");\n changeReference(f); // It won't change the reference!\n modifyReference(f); // It will modify the object that the reference variable "f" refers to!\n }\n\n public static void changeReference(Foo a) {\n Foo b = new Foo("b");\n a = b;\n }\n\n public static void modifyReference(Foo c) {\n c.setAttribute("c");\n }\n\n}\n</code></pre>\n<p>I will explain this in steps:</p>\n<ol>\n<li><p>Declaring a reference named <code>f</code> of type <code>Foo</code> and assign it a new object of type <code>Foo</code> with an attribute <code>"f"</code>.</p>\n<pre><code>Foo f = new Foo("f");\n</code></pre>\n<p><img src=\"https://i.stack.imgur.com/arXpP.png\" alt=\"enter image description here\" /></p>\n</li>\n<li><p>From the method side, a reference of type <code>Foo</code> with a name <code>a</code> is declared and it's initially assigned <code>null</code>.</p>\n<pre><code>public static void changeReference(Foo a)\n</code></pre>\n<p><img src=\"https://i.stack.imgur.com/k2LBD.png\" alt=\"enter image description here\" /></p>\n</li>\n<li><p>As you call the method <code>changeReference</code>, the reference <code>a</code> will be assigned the object which is passed as an argument.</p>\n<pre><code>changeReference(f);\n</code></pre>\n<p><img src=\"https://i.stack.imgur.com/1Ez74.png\" alt=\"enter image description here\" /></p>\n</li>\n<li><p>Declaring a reference named <code>b</code> of type <code>Foo</code> and assign it a new object of type <code>Foo</code> with an attribute <code>"b"</code>.</p>\n<pre><code>Foo b = new Foo("b");\n</code></pre>\n<p><img src=\"https://i.stack.imgur.com/Krx4N.png\" alt=\"enter image description here\" /></p>\n</li>\n<li><p><code>a = b</code> makes a new assignment to the reference <code>a</code>, <strong>not</strong> <code>f</code>, of the object whose attribute is <code>"b"</code>.</p>\n<p><img src=\"https://i.stack.imgur.com/rCluu.png\" alt=\"enter image description here\" /></p>\n</li>\n<li><p>As you call <code>modifyReference(Foo c)</code> method, a reference <code>c</code> is created and assigned the object with attribute <code>"f"</code>.</p>\n<p><img src=\"https://i.stack.imgur.com/PRZPg.png\" alt=\"enter image description here\" /></p>\n</li>\n<li><p><code>c.setAttribute("c");</code> will change the attribute of the object that reference <code>c</code> points to it, and it's the same object that reference <code>f</code> points to it.</p>\n<p><img src=\"https://i.stack.imgur.com/H9Qsf.png\" alt=\"enter image description here\" /></p>\n</li>\n</ol>\n<p>I hope you understand now how passing objects as arguments works in Java :)</p>\n"
},
{
"answer_id": 12851599,
"author": "Herupkhart",
"author_id": 1733754,
"author_profile": "https://Stackoverflow.com/users/1733754",
"pm_score": 6,
"selected": false,
"text": "<p>No, it's not pass by reference.</p>\n\n<p>Java is pass by value according to the Java Language Specification:</p>\n\n<blockquote>\n <p>When the method or constructor is invoked (§15.12), <strong>the values of the actual argument expressions initialize newly created parameter variables</strong>, each of the declared type, before execution of the body of the method or constructor. The Identifier that appears in the DeclaratorId may be used as a simple name in the body of the method or constructor to refer to the <a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.1\" rel=\"noreferrer\">formal parameter</a>. </p>\n</blockquote>\n"
},
{
"answer_id": 14105447,
"author": "fatma.ekici",
"author_id": 1678760,
"author_profile": "https://Stackoverflow.com/users/1678760",
"pm_score": 4,
"selected": false,
"text": "<p>Java is pass by constant reference where a copy of the reference is passed which means that it is basically a pass by value. You might change the contents of the reference if the class is mutable but you cannot change the reference itself. In other words the address can not be changed since it is passed by value but the content that is pointed by the address can be changed. In case of immutable classes, the content of the reference cannot be changed either.</p>\n"
},
{
"answer_id": 16880062,
"author": "Khaled.K",
"author_id": 2128327,
"author_profile": "https://Stackoverflow.com/users/2128327",
"pm_score": 3,
"selected": false,
"text": "<p>Java is always pass-by-value, the parameters are copies of what the variables passed, all Objects are defined using a reference, and reference is a variable that stores a memory address of where the object is in memory.</p>\n\n<p>Check the comments to understand what happens in execution; follow numbers as they show the flow of execution ..</p>\n\n<pre><code>class Example\n{\n public static void test (Cat ref)\n {\n // 3 - <ref> is a copy of the reference <a>\n // both currently reference Grumpy\n System.out.println(ref.getName());\n\n // 4 - now <ref> references a new <Cat> object named \"Nyan\"\n ref = new Cat(\"Nyan\");\n\n // 5 - this should print \"Nyan\"\n System.out.println( ref.getName() );\n }\n\n public static void main (String [] args)\n {\n // 1 - a is a <Cat> reference that references a Cat object in memory with name \"Grumpy\"\n Cat a = new Cat(\"Grumpy\");\n\n // 2 - call to function test which takes a <Cat> reference\n test (a);\n\n // 6 - function call ends, and <ref> life-time ends\n // \"Nyan\" object has no references and the Garbage\n // Collector will remove it from memory when invoked\n\n // 7 - this should print \"Grumpy\"\n System.out.println(a.getName());\n }\n}\n</code></pre>\n"
},
{
"answer_id": 17303467,
"author": "JasonG",
"author_id": 1255825,
"author_profile": "https://Stackoverflow.com/users/1255825",
"pm_score": 4,
"selected": false,
"text": "<p>In an attempt to add even more to this, I thought I'd include the SCJP Study Guide section on the topic. This is from the guide that is made to pass the Sun/Oracle test on the behaviour of Java so it's a good source to use for this discussion.</p>\n\n<blockquote>\n <p>Passing Variables into Methods (Objective 7.3)</p>\n \n <p>7.3 Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.</p>\n \n <p>Methods can be declared to take primitives and/or object references. You need to know how (or if) the caller's variable can be affected by the called method. The difference between object reference and primitive variables, when passed into methods, is huge and important. To understand this section, you'll need to be comfortable with the assignments section covered in the first part of this chapter.</p>\n \n <p>Passing Object Reference Variables</p>\n \n <p>When you pass an object variable into a method, you must keep in mind that you're passing the object reference, and not the actual object itself. Remember that a reference variable holds bits that represent (to the underlying VM) a way to get to a specific object in memory (on the heap). More importantly, you must remember that you aren't even passing the actual reference variable, but rather a copy of the reference variable. A copy of a variable means you get a copy of the bits in that variable, so when you pass a reference variable, you're passing a copy of the bits representing how to get to a specific object. In other words, both the caller and the called method will now have identical copies of the reference, and thus both will refer to the same exact (not a copy) object on the heap.</p>\n \n <p>For this example, we'll use the Dimension class from the java.awt package:</p>\n</blockquote>\n\n<pre><code>1. import java.awt.Dimension;\n2. class ReferenceTest {\n3. public static void main (String [] args) {\n4. Dimension d = new Dimension(5,10);\n5. ReferenceTest rt = new ReferenceTest();\n6. System.out.println(\"Before modify() d.height = \" + d.height);\n7. rt.modify(d);\n8. System.out.println(\"After modify() d.height = \"\n9. }\n10.\n11.\n12.\n13. }\n14. }\n</code></pre>\n\n<blockquote>\n <p>When we run this class, we can see that the modify() method was indeed able to modify the original (and only) Dimension object created on line 4.</p>\n</blockquote>\n\n<pre>\nC:\\Java Projects\\Reference>java ReferenceTest\nBefore modify() d.height = 10\ndim = 11\nAfter modify() d.height = 11\n</pre>\n\n<blockquote>\n <p>Notice when the Dimension object on line 4 is passed to the modify() method, any changes to the object that occur inside the method are being made to the object whose reference was passed. In the preceding example, reference variables d and dim both point to the same object.</p>\n \n <p>Does Java Use Pass-By-Value Semantics?</p>\n \n <p>If Java passes objects by passing the reference variable instead, does that mean Java uses pass-by-reference for objects? Not exactly, although you'll often hear and read that it does. Java is actually pass-by-value for all variables running within a single VM. Pass-by-value means pass-by-variable-value. And that means, pass-by-copy-of- the-variable! (There's that word copy again!)</p>\n \n <p>It makes no difference if you're passing primitive or reference variables, you are always passing a copy of the bits in the variable. So for a primitive variable, you're passing a copy of the bits representing the value. For example, if you pass an int variable with the value of 3, you're passing a copy of the bits representing 3. The called method then gets its own copy of the value, to do with it what it likes.</p>\n \n <p>And if you're passing an object reference variable, you're passing a copy of the bits representing the reference to an object. The called method then gets its own copy of the reference variable, to do with it what it likes. But because two identical reference variables refer to the exact same object, if the called method modifies the object (by invoking setter methods, for example), the caller will see that the object the caller's original variable refers to has also been changed. In the next section, we'll look at how the picture changes when we're talking about primitives.</p>\n \n <p>The bottom line on pass-by-value: the called method can't change the caller's variable, although for object reference variables, the called method can change the object the variable referred to. What's the difference between changing the variable and changing the object? For object references, it means the called method can't reassign the caller's original reference variable and make it refer to a different object, or null. For example, in the following code fragment,</p>\n</blockquote>\n\n<pre><code> void bar() {\n Foo f = new Foo();\n doStuff(f);\n }\n void doStuff(Foo g) {\n g.setName(\"Boo\");\n g = new Foo();\n }\n</code></pre>\n\n<blockquote>\n <p>reassigning g does not reassign f! At the end of the bar() method, two Foo objects have been created, one referenced by the local variable f and one referenced by\n the local (argument) variable g. Because the doStuff() method has a copy of the reference variable, it has a way to get to the original Foo object, for instance to call the setName() method. But, the doStuff() method does not have a way to get to the f reference variable. So doStuff() can change values within the object f refers to, but doStuff() can't change the actual contents (bit pattern) of f. In other words, doStuff() can change the state of the object that f refers to, but it can't make f refer to a different object!</p>\n \n <p>Passing Primitive Variables</p>\n \n <p>Let's look at what happens when a primitive variable is passed to a method:</p>\n</blockquote>\n\n<pre><code>class ReferenceTest {\n public static void main (String [] args) {\n int a = 1;\n ReferenceTest rt = new ReferenceTest();\n System.out.println(\"Before modify() a = \" + a);\n rt.modify(a);\n System.out.println(\"After modify() a = \" + a);\n }\n void modify(int number) {\n number = number + 1;\n System.out.println(\"number = \" + number);\n }\n}\n</code></pre>\n\n<blockquote>\n <p>In this simple program, the variable a is passed to a method called modify(),\n which increments the variable by 1. The resulting output looks like this:</p>\n</blockquote>\n\n<pre><code> Before modify() a = 1\n number = 2\n After modify() a = 1\n</code></pre>\n\n<blockquote>\n <p>Notice that a did not change after it was passed to the method. Remember, it was a copy of a that was passed to the method. When a primitive variable is passed to a method, it is passed by value, which means pass-by-copy-of-the-bits-in-the-variable.</p>\n</blockquote>\n"
},
{
"answer_id": 17563873,
"author": "Gaurav",
"author_id": 1912964,
"author_profile": "https://Stackoverflow.com/users/1912964",
"pm_score": 5,
"selected": false,
"text": "<p>Java has only pass by value. A very simple example to validate this.</p>\n\n<pre><code>public void test() {\n MyClass obj = null;\n init(obj);\n //After calling init method, obj still points to null\n //this is because obj is passed as value and not as reference.\n}\nprivate void init(MyClass objVar) {\n objVar = new MyClass();\n}\n</code></pre>\n"
},
{
"answer_id": 18287583,
"author": "bvdb",
"author_id": 1833961,
"author_profile": "https://Stackoverflow.com/users/1833961",
"pm_score": 3,
"selected": false,
"text": "<p>Shortest answer :)</p>\n\n<ul>\n<li>Java has pass-by-value (and pass-reference-by-value.) </li>\n<li><strong>C# also has pass-by-reference</strong></li>\n</ul>\n\n<p>In C# this is accomplished with the \"out\" and \"ref\" keywords. </p>\n\n<p>Pass By Reference: The variable is passed in such a way that <strong>a reassignment inside the method is reflected even outside the method.</strong></p>\n\n<p>Here follows <strong>an example of passing-by-reference (C#)</strong>.\nThis feature does not exist in java.</p>\n\n<pre><code>class Example\n{\n static void InitArray(out int[] arr)\n {\n arr = new int[5] { 1, 2, 3, 4, 5 };\n }\n\n static void Main()\n {\n int[] someArray;\n InitArray(out someArray);\n\n // This is true !\n boolean isTrue = (someArray[0] == 1);\n }\n}\n</code></pre>\n\n<p>See also: <a href=\"http://msdn.microsoft.com/en-us/library/szasx730.aspx\" rel=\"noreferrer\" title=\"MSDN library: passing arrays by ref and out\">MSDN library (C#): passing arrays by ref and out</a></p>\n\n<p>See also: <a href=\"http://msdn.microsoft.com/en-us/library/0f66670z.aspx\" rel=\"noreferrer\" title=\"MSDN library: passing by reference\">MSDN library (C#): passing by by value and by reference</a></p>\n"
},
{
"answer_id": 18623099,
"author": "James Drinkard",
"author_id": 543572,
"author_profile": "https://Stackoverflow.com/users/543572",
"pm_score": 3,
"selected": false,
"text": "<p>The bottom line on pass-by-value: the called method can't change the caller's\nvariable, although for object reference variables, the called method can change the\nobject the variable referred to. What's the difference between changing the variable\nand changing the object? For object references, it means the called method can't\nreassign the caller's original reference variable and make it refer to a different object,\nor null. </p>\n\n<p>I took this code and explanation from a book on Java Certification and made some minor changes.<br>\nI think it's a\ngood illustration to the pass by value of an object. In the code below, \nreassigning g does not reassign f! At the end of the bar() method, two Foo objects\nhave been created, one referenced by the local variable f and one referenced by\nthe local (argument) variable g. </p>\n\n<p>Because the doStuff() method has a copy of the reference variable, it has a way to get \nto the original Foo object, for instance to call\nthe setName() method. But, the doStuff() method does not have a way to get to\nthe f reference variable. So doStuff() can change values within the object f refers\nto, but doStuff() can't change the actual contents (bit pattern) of f. In other\nwords, doStuff() can change the state of the object that f refers to, but it can't\nmake f refer to a different object!</p>\n\n<pre><code>package test.abc;\n\npublic class TestObject {\n\n /**\n * @param args\n */\n public static void main(String[] args) {\n bar();\n }\n\n static void bar() {\n Foo f = new Foo();\n System.out.println(\"Object reference for f: \" + f);\n f.setName(\"James\");\n doStuff(f);\n System.out.println(f.getName());\n //Can change the state of an object variable in f, but can't change the object reference for f.\n //You still have 2 foo objects.\n System.out.println(\"Object reference for f: \" + f);\n }\n\n static void doStuff(Foo g) {\n g.setName(\"Boo\");\n g = new Foo();\n System.out.println(\"Object reference for g: \" + g);\n }\n}\n\n\npackage test.abc;\n\npublic class Foo {\n public String name = \"\";\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n}\n</code></pre>\n\n<p><strong>Note that the object reference has not changed in the console output below:</strong></p>\n\n<p><strong>Console output:</strong></p>\n\n<p>Object reference for f: test.abc.Foo@62f72617</p>\n\n<p>Object reference for g: test.abc.Foo@4fe5e2c3</p>\n\n<p>Boo\nObject reference for f: test.abc.Foo@62f72617 </p>\n"
},
{
"answer_id": 18740042,
"author": "cutmancometh",
"author_id": 1917489,
"author_profile": "https://Stackoverflow.com/users/1917489",
"pm_score": 8,
"selected": false,
"text": "<p>I feel like arguing about \"pass-by-reference vs pass-by-value\" is not super-helpful.</p>\n\n<p>If you say, \"Java is pass-by-whatever (reference/value)\", in either case, you're not provide a complete answer. Here's some additional information that will hopefully aid in understanding what's happening in memory.</p>\n\n<p>Crash course on stack/heap before we get to the Java implementation:\nValues go on and off the stack in a nice orderly fashion, like a stack of plates at a cafeteria.\nMemory in the heap (also known as dynamic memory) is haphazard and disorganized. The JVM just finds space wherever it can, and frees it up as the variables that use it are no longer needed.</p>\n\n<p>Okay. First off, local primitives go on the stack. So this code:</p>\n\n<pre><code>int x = 3;\nfloat y = 101.1f;\nboolean amIAwesome = true;\n</code></pre>\n\n<p>results in this:</p>\n\n<p><img src=\"https://i.stack.imgur.com/7nGKU.png\" alt=\"primitives on the stack\"></p>\n\n<p>When you declare and instantiate an object. The actual object goes on the heap. What goes on the stack? The address of the object on the heap. C++ programmers would call this a pointer, but some Java developers are against the word \"pointer\". Whatever. Just know that the address of the object goes on the stack.</p>\n\n<p>Like so:</p>\n\n<pre><code>int problems = 99;\nString name = \"Jay-Z\";\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/yTIYp.png\" alt=\"a b*7ch aint one!\"></p>\n\n<p>An array is an object, so it goes on the heap as well. And what about the objects in the array? They get their own heap space, and the address of each object goes inside the array.</p>\n\n<pre><code>JButton[] marxBros = new JButton[3];\nmarxBros[0] = new JButton(\"Groucho\");\nmarxBros[1] = new JButton(\"Zeppo\");\nmarxBros[2] = new JButton(\"Harpo\");\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/v2b33.png\" alt=\"marx brothers\"></p>\n\n<p>So, what gets passed in when you call a method? If you pass in an object, what you're actually passing in is the address of the object. Some might say the \"value\" of the address, and some say it's just a reference to the object. This is the genesis of the holy war between \"reference\" and \"value\" proponents. What you call it isn't as important as that you understand that what's getting passed in is the address to the object.</p>\n\n<pre><code>private static void shout(String name){\n System.out.println(\"There goes \" + name + \"!\");\n}\n\npublic static void main(String[] args){\n String hisName = \"John J. Jingleheimerschmitz\";\n String myName = hisName;\n shout(myName);\n}\n</code></pre>\n\n<p>One String gets created and space for it is allocated in the heap, and the address to the string is stored on the stack and given the identifier <code>hisName</code>, since the address of the second String is the same as the first, no new String is created and no new heap space is allocated, but a new identifier is created on the stack. Then we call <code>shout()</code>: a new stack frame is created and a new identifier, <code>name</code> is created and assigned the address of the already-existing String.</p>\n\n<p><img src=\"https://i.stack.imgur.com/q0prc.png\" alt=\"la da di da da da da\"></p>\n\n<p>So, value, reference? You say \"potato\".</p>\n"
},
{
"answer_id": 18950805,
"author": "user1931858",
"author_id": 1931858,
"author_profile": "https://Stackoverflow.com/users/1931858",
"pm_score": 3,
"selected": false,
"text": "<p>Java passes parameters by value, but for object variables, the values are essentially references to objects. Since arrays are objects the following <a href=\"http://theoryapp.com/parameter-passing-in-java/\" rel=\"noreferrer\">example code</a> shows the difference.</p>\n\n<pre><code>public static void dummyIncrease(int[] x, int y)\n{\n x[0]++;\n y++;\n}\npublic static void main(String[] args)\n{\n int[] arr = {3, 4, 5};\n int b = 1;\n dummyIncrease(arr, b);\n // arr[0] is 4, but b is still 1\n}\n\nmain()\n arr +---+ +---+---+---+\n | # | ----> | 3 | 4 | 5 |\n +---+ +---+---+---+\n b +---+ ^\n | 1 | | \n +---+ |\n |\ndummyIncrease() |\n x +---+ |\n | # | ------------+\n +---+ \n y +---+ \n | 1 | \n +---+ \n</code></pre>\n"
},
{
"answer_id": 19421107,
"author": "Ganesh",
"author_id": 1910406,
"author_profile": "https://Stackoverflow.com/users/1910406",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Java is always pass by value, not pass by reference</strong></p>\n<p>First of all, we need to understand what pass by value and pass by reference are.</p>\n<p><strong>Pass by value means that you are making a copy in memory of the actual parameter's value that is passed in. This is a copy of the contents of the actual parameter</strong>.</p>\n<p><strong>Pass by reference (also called pass by address) means that a copy of the address of the actual parameter is stored</strong>.</p>\n<p>Sometimes Java can give the illusion of pass by reference. Let's see how it works by using the example below:</p>\n<pre><code>public class PassByValue {\n public static void main(String[] args) {\n Test t = new Test();\n t.name = "initialvalue";\n new PassByValue().changeValue(t);\n System.out.println(t.name);\n }\n \n public void changeValue(Test f) {\n f.name = "changevalue";\n }\n}\n\nclass Test {\n String name;\n}\n</code></pre>\n<p>The output of this program is:</p>\n<blockquote>\n<pre><code>changevalue\n</code></pre>\n</blockquote>\n<p>Let's understand step by step:</p>\n<pre><code>Test t = new Test();\n</code></pre>\n<p>As we all know it will create an object in the heap and return the reference value back to t. For example, suppose the value of t is <code>0x100234</code> (we don't know the actual JVM internal value, this is just an example) .</p>\n<p><img src=\"https://i.stack.imgur.com/AVrhI.png\" alt=\"first illustration\" /></p>\n<pre><code>new PassByValue().changeValue(t);\n</code></pre>\n<p>When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function. Since it is <strong>passing by value</strong>, it passes a copy of the variable rather than the actual reference of it. Since we said the value of t was <code>0x100234</code>, both t and f will have the same value and hence they will point to the same object.</p>\n<p><img src=\"https://i.stack.imgur.com/WwdPh.png\" alt=\"second illustration\" /></p>\n<p>If you change anything in the function using reference f it will modify the existing contents of the object. That is why we got the output <code>changevalue</code>, which is updated in the function.</p>\n<p>To understand this more clearly, consider the following example:</p>\n<pre><code>public class PassByValue {\n public static void main(String[] args) {\n Test t = new Test();\n t.name = "initialvalue";\n new PassByValue().changeRefence(t);\n System.out.println(t.name);\n }\n \n public void changeRefence(Test f) {\n f = null;\n }\n}\n\nclass Test {\n String name;\n}\n</code></pre>\n<p>Will this throw a <code>NullPointerException</code>? No, because it only passes a copy of the reference.\nIn the case of passing by reference, it could have thrown a <code>NullPointerException</code>, as seen below:</p>\n<p><img src=\"https://i.stack.imgur.com/jH6KP.png\" alt=\"third illustration\" /></p>\n<p>Hopefully this will help.</p>\n"
},
{
"answer_id": 19970416,
"author": "Bhushan",
"author_id": 1907916,
"author_profile": "https://Stackoverflow.com/users/1907916",
"pm_score": 2,
"selected": false,
"text": "<p>The Java programming language passes arguments only by value, that is,\nyou cannot change the argument value in the calling method from within\nthe called method.</p>\n\n<hr>\n\n<p>However, when an object instance is passed as an argument to a method,\nthe value of the argument is not the object itself but a reference to the\nobject. You can change the contents of the object in the called method but\nnot the object reference.</p>\n\n<hr>\n\n<p>To many people, this looks like pass-by-reference, and behaviorally, it has\nmuch in common with pass-by-reference. However, there are two reasons\nthis is inaccurate.</p>\n\n<ul>\n<li><p>Firstly, the ability to change the thing passed into a\nmethod only applies to objects, not primitive values. </p></li>\n<li><p>Second, the actual\nvalue associated with a variable of object type is the reference to the\nobject, and not the object itself. This is an important distinction in other\nways, and if clearly understood, is entirely supporting of the point that\nthe Java programming language passes arguments by value.</p></li>\n</ul>\n\n<hr>\n\n<pre><code>The following code example illustrates this point:\n1 public class PassTest {\n2\n3 // Methods to change the current values\n4 public static void changeInt(int value) {\n5 value = 55;\n6 }\n7 public static void changeObjectRef(MyDate ref) {\n8 ref = new MyDate(1, 1, 2000);\n9 }\n10 public static void changeObjectAttr(MyDate ref) {\n11 ref.setDay(4);\n12 }\n13\n14 public static void main(String args[]) {\n15 MyDate date;\n16 int val;\n17\n18 // Assign the int\n19 val = 11;\n20 // Try to change it\n21 changeInt(val);\n22 // What is the current value?\n23 System.out.println(\"Int value is: \" + val);\n24\n25 // Assign the date\n26 date = new MyDate(22, 7, 1964);\n27 // Try to change it\n28 changeObjectRef(date);\n29 // What is the current value?\n30 System.out.println(\"MyDate: \" + date);\n31\n32 // Now change the day attribute\n33 // through the object reference\n34 changeObjectAttr(date);\n35 // What is the current value?\n36 System.out.println(\"MyDate: \" + date);\n37 }\n38 }\n</code></pre>\n\n<hr>\n\n<pre><code>This code outputs the following:\njava PassTest\nInt value is: 11\nMyDate: 22-7-1964\nMyDate: 4-7-1964\nThe MyDate object is not changed by the changeObjectRef method;\nhowever, the changeObjectAttr method changes the day attribute of the\nMyDate object.\n</code></pre>\n"
},
{
"answer_id": 20125921,
"author": "Srle",
"author_id": 922581,
"author_profile": "https://Stackoverflow.com/users/922581",
"pm_score": 7,
"selected": false,
"text": "<p>In java everything is reference, so when you have something like:\n <code>Point pnt1 = new Point(0,0);</code> Java does following:</p>\n\n<ol>\n<li>Creates new Point object</li>\n<li>Creates new Point reference and initialize that reference to <em>point (refer to)</em> on previously created Point object.</li>\n<li>From here, through Point object life, you will access to that object through pnt1\n reference. So we can say that in Java you manipulate object through its reference.<br></li>\n</ol>\n\n<p><img src=\"https://i.stack.imgur.com/jM54f.png\" alt=\"enter image description here\"></p>\n\n<p><strong>Java doesn't pass method arguments by reference; it passes them by value.</strong> I will use example from <a href=\"http://www.javaworld.com/javaqa/2000-05/03-qa-0526-pass.html\" rel=\"noreferrer\">this site</a>: </p>\n\n<pre><code>public static void tricky(Point arg1, Point arg2) {\n arg1.x = 100;\n arg1.y = 100;\n Point temp = arg1;\n arg1 = arg2;\n arg2 = temp;\n}\npublic static void main(String [] args) {\n Point pnt1 = new Point(0,0);\n Point pnt2 = new Point(0,0);\n System.out.println(\"X1: \" + pnt1.x + \" Y1: \" +pnt1.y); \n System.out.println(\"X2: \" + pnt2.x + \" Y2: \" +pnt2.y);\n System.out.println(\" \");\n tricky(pnt1,pnt2);\n System.out.println(\"X1: \" + pnt1.x + \" Y1:\" + pnt1.y); \n System.out.println(\"X2: \" + pnt2.x + \" Y2: \" +pnt2.y); \n}\n</code></pre>\n\n<p>Flow of the program:</p>\n\n<pre><code>Point pnt1 = new Point(0,0);\nPoint pnt2 = new Point(0,0);\n</code></pre>\n\n<p>Creating two different Point object with two different reference associated.\n<img src=\"https://i.stack.imgur.com/5LIKC.png\" alt=\"enter image description here\"></p>\n\n<pre><code>System.out.println(\"X1: \" + pnt1.x + \" Y1: \" +pnt1.y); \nSystem.out.println(\"X2: \" + pnt2.x + \" Y2: \" +pnt2.y);\nSystem.out.println(\" \");\n</code></pre>\n\n<p>As expected output will be:</p>\n\n<pre><code>X1: 0 Y1: 0\nX2: 0 Y2: 0\n</code></pre>\n\n<p><strong>On this line 'pass-by-value' goes into the play...</strong> <br></p>\n\n<pre><code>tricky(pnt1,pnt2); public void tricky(Point arg1, Point arg2);\n</code></pre>\n\n<p>References <code>pnt1</code> and <code>pnt2</code> are <strong>passed by value</strong> to the tricky method, which means that now yours references <code>pnt1</code> and <code>pnt2</code> have their <code>copies</code> named <code>arg1</code> and <code>arg2</code>.So <code>pnt1</code> and <code>arg1</code> <em>points</em> to the same object. (Same for the <code>pnt2</code> and <code>arg2</code>)\n<img src=\"https://i.stack.imgur.com/qd1GH.png\" alt=\"enter image description here\"></p>\n\n<p>In the <code>tricky</code> method:</p>\n\n<pre><code> arg1.x = 100;\n arg1.y = 100;\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/o4WT0.png\" alt=\"enter image description here\"></p>\n\n<p>Next in the <code>tricky</code> method</p>\n\n<pre><code>Point temp = arg1;\narg1 = arg2;\narg2 = temp;\n</code></pre>\n\n<p>Here, you first create new <code>temp</code> Point reference which will <em>point</em> on same place like <code>arg1</code> reference. Then you move reference <code>arg1</code> to <em>point</em> to the same place like <code>arg2</code> reference.\nFinally <code>arg2</code> will <em>point</em> to the same place like <code>temp</code>.</p>\n\n<p><img src=\"https://i.stack.imgur.com/fX5Q3.png\" alt=\"enter image description here\"></p>\n\n<p>From here scope of <code>tricky</code> method is gone and you don't have access any more to the references: <code>arg1</code>, <code>arg2</code>, <code>temp</code>. <strong>But important note is that everything you do with these references when they are 'in life' will permanently affect object on which they are <em>point</em> to.</strong> </p>\n\n<p>So after executing method <code>tricky</code>, when you return to <code>main</code>, you have this situation:\n<img src=\"https://i.stack.imgur.com/LRETe.png\" alt=\"enter image description here\"></p>\n\n<p>So now, completely execution of program will be:</p>\n\n<pre><code>X1: 0 Y1: 0\nX2: 0 Y2: 0\nX1: 100 Y1: 100\nX2: 0 Y2: 0\n</code></pre>\n"
},
{
"answer_id": 20346109,
"author": "Aniket Thakur",
"author_id": 2396539,
"author_profile": "https://Stackoverflow.com/users/2396539",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Java passes references to objects by value.</strong></p>\n\n<p>So if any modification is done to the Object to which the reference argument points it will be reflected back on the original object.</p>\n\n<p>But if the reference argument point to another Object still the original reference will point to original Object.</p>\n"
},
{
"answer_id": 20566453,
"author": "karatedog",
"author_id": 216248,
"author_profile": "https://Stackoverflow.com/users/216248",
"pm_score": 6,
"selected": false,
"text": "<h2>A reference is always a value when represented, no matter what language you use.</h2>\n\n<p>Getting an outside of the box view, let's look at Assembly or some low level memory management. At the CPU level a <em>reference</em> to anything immediately becomes a <em>value</em> if it gets written to memory or to one of the CPU registers. (That is why <em>pointer</em> is a good definition. It is a value, which has a purpose at the same time).</p>\n\n<p>Data in memory has a <strong>Location</strong> and at that location there is a value (byte,word, whatever). In Assembly we have a convenient solution to give a <strong>Name</strong> to certain <strong>Location</strong> (aka variable), but when compiling the code, the assembler simply replaces <strong>Name</strong> with the designated location just like your browser replaces domain names with IP addresses.</p>\n\n<p>Down to the core it is technically impossible to pass a reference to anything in any language without representing it (when it immediately becomes a value).</p>\n\n<p>Lets say we have a variable Foo, its <strong>Location</strong> is at the 47th byte in memory and its <strong>Value</strong> is 5. We have another variable <strong>Ref2Foo</strong> which is at 223rd byte in memory, and its value will be 47. This Ref2Foo might be a technical variable, not explicitly created by the program. If you just look at 5 and 47 without any other information, you will see just two <strong>Values</strong>.\nIf you use them as references then to reach to <code>5</code> we have to travel:</p>\n\n<pre><code>(Name)[Location] -> [Value at the Location]\n---------------------\n(Ref2Foo)[223] -> 47\n(Foo)[47] -> 5\n</code></pre>\n\n<p>This is how jump-tables work. </p>\n\n<p>If we want to call a method/function/procedure with Foo's value, there are a few possible way to pass the variable to the method, depending on the <strong>language</strong> and its several method invocation modes:</p>\n\n<ol>\n<li>5 gets copied to one of the CPU registers (ie. EAX).</li>\n<li>5 gets PUSHd to the stack.</li>\n<li>47 gets copied to one of the CPU registers</li>\n<li>47 PUSHd to the stack.</li>\n<li>223 gets copied to one of the CPU registers.</li>\n<li>223 gets PUSHd to the stack.</li>\n</ol>\n\n<p>In every cases above a value - a <strong>copy</strong> of an existing value - has been created, it is now upto the receiving method to handle it. When you write \"Foo\" inside the method, it is either read out from EAX, or automatically <strong>dereferenced</strong>, or double dereferenced, the process depends on how the language works and/or what the type of Foo dictates. This is hidden from the developer until she circumvents the dereferencing process. So a <em>reference</em> is a <em>value</em> when represented, because a reference is a value that has to be processed (at language level).</p>\n\n<p>Now we have passed Foo to the method:</p>\n\n<ul>\n<li>in case 1. and 2. if you change Foo (<code>Foo = 9</code>) it only affects local scope as you have a copy of the Value. From inside the method we cannot even determine where in memory the original Foo was located.</li>\n<li>in case 3. and 4. if you use default language constructs and change Foo (<code>Foo = 11</code>), it could change Foo globally (depends on the language, ie. Java or like Pascal's <code>procedure findMin(x, y, z: integer;</code><strong>var m</strong><code>: integer);</code>). However if the language allows you to circumvent the dereference process, you can change <code>47</code>, say to <code>49</code>. At that point Foo seems to have been changed if you read it, because you have changed the <strong>local pointer</strong> to it. And if you were to modify this Foo inside the method (<code>Foo = 12</code>) you will probably FUBAR the execution of the program (aka. segfault) because you will write to a different memory than expected, you can even modify an area that is destined to hold executable program and writing to it will modify running code (Foo is now not at <code>47</code>). BUT Foo's value of <code>47</code> did not change globally, only the one inside the method, because <code>47</code> was also a copy to the method.</li>\n<li>in case 5. and 6. if you modify <code>223</code> inside the method it creates the same mayhem as in 3. or 4. (a pointer, pointing to a now bad value, that is again used as a pointer) but this is still a local problem, as 223 was <strong>copied</strong>. However if you are able to dereference <code>Ref2Foo</code> (that is <code>223</code>), reach to and modify the pointed value <code>47</code>, say, to <code>49</code>, it will affect Foo <strong>globally</strong>, because in this case the methods got a copy of <code>223</code> but the referenced <code>47</code> exists only once, and changing that to <code>49</code> will lead every <code>Ref2Foo</code> double-dereferencing to a wrong value.</li>\n</ul>\n\n<p>Nitpicking on insignificant details, even languages that do pass-by-reference will pass values to functions, but those functions know that they have to use it for dereferencing purposes. This pass-the-reference-as-value is just hidden from the programmer because it is practically useless and the terminology is only <em>pass-by-reference</em>.</p>\n\n<p>Strict <em>pass-by-value</em> is also useless, it would mean that a 100 Mbyte array should have to be copied every time we call a method with the array as argument, therefore Java cannot be stricly pass-by-value. Every language would pass a reference to this huge array (as a value) and either employs copy-on-write mechanism if that array can be changed locally inside the method or allows the method (as Java does) to modify the array globally (from the caller's view) and a few languages allows to modify the Value of the reference itself.</p>\n\n<p>So in short and in Java's own terminology, Java is <em>pass-by-value</em> where <em>value</em> can be: either a <strong>real value</strong> or a <strong>value</strong> that is a representation of a <strong>reference</strong>. </p>\n"
},
{
"answer_id": 21288385,
"author": "JAN",
"author_id": 779111,
"author_profile": "https://Stackoverflow.com/users/779111",
"pm_score": 3,
"selected": false,
"text": "<p>Mr @Scott Stanchfield wrote an excellent answer. Here is the class that would you to verify\nexactly what he meant:</p>\n\n<pre><code>public class Dog {\n\n String dog ;\n static int x_static;\n int y_not_static;\n\n public String getName()\n {\n return this.dog;\n }\n\n public Dog(String dog)\n {\n this.dog = dog;\n }\n\n public void setName(String name)\n {\n this.dog = name;\n }\n\n public static void foo(Dog someDog)\n {\n x_static = 1;\n // y_not_static = 2; // not possible !!\n someDog.setName(\"Max\"); // AAA\n someDog = new Dog(\"Fifi\"); // BBB\n someDog.setName(\"Rowlf\"); // CCC\n }\n\n public static void main(String args[])\n {\n Dog myDog = new Dog(\"Rover\");\n foo(myDog);\n System.out.println(myDog.getName());\n }\n}\n</code></pre>\n\n<p>So, we pass from main() a dog called <code>Rover</code>, then we assign a new address to the pointer that we passed, but at the end, the name of the dog is not <code>Rover</code>, and not <code>Fifi</code>, and certainly not <code>Rowlf</code>, but <code>Max</code>.</p>\n"
},
{
"answer_id": 24546764,
"author": "Sotirios Delimanolis",
"author_id": 438154,
"author_profile": "https://Stackoverflow.com/users/438154",
"pm_score": 6,
"selected": false,
"text": "<p>I thought I'd contribute this answer to add more details from the Specifications.</p>\n<p>First, <a href=\"https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value\">What's the difference between passing by reference vs. passing by value?</a></p>\n<blockquote>\n<p>Passing by reference means the called functions' parameter will be the\nsame as the callers' passed argument (not the value, but the identity</p>\n<ul>\n<li>the variable itself).</li>\n</ul>\n<p>Pass by value means the called functions' parameter will be a copy of\nthe callers' passed argument.</p>\n</blockquote>\n<p>Or from wikipedia, <a href=\"http://en.wikipedia.org/wiki/Call_by_reference#Call_by_reference\" rel=\"noreferrer\">on the subject of pass-by-reference</a></p>\n<blockquote>\n<p>In call-by-reference evaluation (also referred to as\npass-by-reference), a function receives an implicit reference to a\nvariable used as argument, rather than a copy of its value. This\ntypically means that the function can modify (i.e. assign to) the\nvariable used as argument—something that will be seen by its caller.</p>\n</blockquote>\n<p>And <a href=\"http://en.wikipedia.org/wiki/Call_by_value#Call_by_value\" rel=\"noreferrer\">on the subject of pass-by-value</a></p>\n<blockquote>\n<p>In call-by-value, the argument expression is evaluated, and the\nresulting value is bound to the corresponding variable in the function [...].\nIf the function or procedure is able to assign values to its\nparameters, only its local copy is assigned [...].</p>\n</blockquote>\n<p>Second, we need to know what Java uses in its method invocations. The <a href=\"http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.1\" rel=\"noreferrer\">Java Language Specification</a> states</p>\n<blockquote>\n<p>When the method or constructor is invoked (§15.12), <strong>the values of the\nactual argument expressions initialize newly created parameter\nvariables</strong>, each of the declared type, before execution of the body of\nthe method or constructor.</p>\n</blockquote>\n<p>So it assigns (or binds) the value of the argument to the corresponding parameter variable.</p>\n<p><strong>What is the value of the argument?</strong></p>\n<p>Let's consider reference types, the <a href=\"http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.4\" rel=\"noreferrer\">Java Virtual Machine Specification</a> states</p>\n<blockquote>\n<p>There are three kinds of <strong>reference types</strong>: class types, array types,\nand interface types. <strong>Their values are references to dynamically\ncreated class instances, arrays, or class instances or arrays that\nimplement interfaces, respectively.</strong></p>\n</blockquote>\n<p>The <a href=\"http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.3.1\" rel=\"noreferrer\">Java Language Specification</a> also states</p>\n<blockquote>\n<p><strong>The reference values (often just references) are pointers to these objects</strong>, and a special null reference, which refers to no object.</p>\n</blockquote>\n<p>The value of an argument (of some reference type) is a pointer to an object. Note that a variable, an invocation of a method with a reference type return type, and an instance creation expression (<code>new ...</code>) all resolve to a reference type value.</p>\n<p>So</p>\n<pre><code>public void method (String param) {}\n...\nString variable = new String("ref");\nmethod(variable);\nmethod(variable.toString());\nmethod(new String("ref"));\n</code></pre>\n<p>all bind the value of a reference to a <code>String</code> instance to the method's newly created parameter, <code>param</code>. This is exactly what the definition of pass-by-value describes. As such, <strong>Java is pass-by-value</strong>.</p>\n<p><strong>The fact that you can follow the reference to invoke a method or access a field of the referenced object is completely irrelevant to the conversation.</strong> The definition of pass-by-reference was</p>\n<blockquote>\n<p>This typically means that the function can modify (i.e. assign to) the\nvariable used as argument—something that will be seen by its caller.</p>\n</blockquote>\n<p>In Java, modifying the variable means reassigning it. In Java, if you reassigned the variable within the method, it would go unnoticed to the caller. <strong>Modifying the object referenced by the variable is a different concept entirely.</strong></p>\n<hr />\n<p>Primitive values are also defined in the Java Virtual Machine Specification, <a href=\"http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.3\" rel=\"noreferrer\">here</a>. The value of the type is the corresponding integral or floating point value, encoded appropriately (8, 16, 32, 64, etc. bits).</p>\n"
},
{
"answer_id": 24685542,
"author": "Dustin Deus",
"author_id": 1893773,
"author_profile": "https://Stackoverflow.com/users/1893773",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Understand it in 2 Steps:</strong> </p>\n\n<p>You can't change the reference to the object itself but you can work with this passed parameter as a reference to the object.</p>\n\n<p>If you want to change the value behind the reference you will only declare a new variable on the stack with the same name 'd'. Look at the references with the sign <code>@</code> and you will find out that the reference has been changed.</p>\n\n<pre><code>public static void foo(Dog d) {\n d.Name = \"belly\";\n System.out.println(d); //Reference: Dog@1540e19d\n\n d = new Dog(\"wuffwuff\");\n System.out.println(d); //Dog@677327b6\n}\npublic static void main(String[] args) throws Exception{\n Dog lisa = new Dog(\"Lisa\");\n foo(lisa);\n System.out.println(lisa.Name); //belly\n}\n</code></pre>\n"
},
{
"answer_id": 26028582,
"author": "Michał Żbikowski",
"author_id": 3961865,
"author_profile": "https://Stackoverflow.com/users/3961865",
"pm_score": 4,
"selected": false,
"text": "<p>Throughout all the answers we see that Java pass-by-value or rather as @Gevorg \nwrote: \"pass-by-copy-of-the-variable-value\" and this is the idea that we should have in mind all the time. </p>\n\n<p>I am focusing on examples that helped me understand the idea and it is rather addendum to previous answers.</p>\n\n<p>From [1] In Java you always are passing arguments by copy; that is you're always creating a new instance of the value inside the function. But there are certain behaviors that can make you think you're passing by reference.</p>\n\n<ul>\n<li><p>Passing by copy: When a variable is passed to a method/function, a copy is made (sometimes we hear that when you pass primitives, you're making copies).</p></li>\n<li><p>Passing by reference: When a variable is passed to a method/function, the code in the method/function operates on the original variable (You're still passing by copy, but references to values inside the complex object are parts of both versions of the variable, both the original and the version inside the function. The complex objects themselves are being copied, but the internal references are being retained)</p></li>\n</ul>\n\n<h2>Examples of Passing by copy/ by value</h2>\n\n<p><strong>Example from [ref 1]</strong></p>\n\n<pre><code>void incrementValue(int inFunction){\n inFunction ++;\n System.out.println(\"In function: \" + inFunction);\n}\n\nint original = 10;\nSystem.out.print(\"Original before: \" + original);\nincrementValue(original);\nSystem.out.println(\"Original after: \" + original);\n\nWe see in the console:\n > Original before: 10\n > In Function: 11\n > Original after: 10 (NO CHANGE)\n</code></pre>\n\n<p><strong>Example from [ref 2]</strong></p>\n\n<blockquote>\n <p>shows nicely the mechanism\n <a href=\"https://www.youtube.com/watch?v=W2ysz_6AyJE&list=PL6C11012B1B464EC5#t=502\" rel=\"noreferrer\">watch max 5 min</a></p>\n</blockquote>\n\n<h2>(Passing by reference) pass-by-copy-of-the-variable-value</h2>\n\n<p><strong>Example from [ref 1]</strong>\n(remember that an array is an object)</p>\n\n<pre><code>void incrementValu(int[] inFuncion){\n inFunction[0]++;\n System.out.println(\"In Function: \" + inFunction[0]);\n}\n\nint[] arOriginal = {10, 20, 30};\nSystem.out.println(\"Original before: \" + arOriginal[0]);\nincrementValue(arOriginal[]);\nSystem.out.println(\"Original before: \" + arOriginal[0]);\n\nWe see in the console:\n >Original before: 10\n >In Function: 11\n >Original before: 11 (CHANGE)\n</code></pre>\n\n<p>The complex objects themselves are being copied, but the internal references are being retained.</p>\n\n<p><strong>Example from[ref 3]</strong></p>\n\n<pre><code>package com.pritesh.programs;\n\nclass Rectangle {\n int length;\n int width;\n\n Rectangle(int l, int b) {\n length = l;\n width = b;\n }\n\n void area(Rectangle r1) {\n int areaOfRectangle = r1.length * r1.width;\n System.out.println(\"Area of Rectangle : \" \n + areaOfRectangle);\n }\n}\n\nclass RectangleDemo {\n public static void main(String args[]) {\n Rectangle r1 = new Rectangle(10, 20);\n r1.area(r1);\n }\n}\n</code></pre>\n\n<p>The area of the rectangle is 200 and the length=10 and width=20</p>\n\n<p><strong>Last thing</strong> I would like to share was this moment of the lecture:\n<strong><a href=\"https://www.youtube.com/watch?v=W8nNdNZ40EQ#t=1206\" rel=\"noreferrer\">Memory Allocation</a></strong>\nwhich I found very helpful in understanding the Java passing by value or rather “pass-by-copy-of-the-variable-value” as @Gevorg has written.</p>\n\n<ol>\n<li><a href=\"http://www.lynda.com/Android-tutorials/Passing-arguments-reference-value/86005/94989-4.html\" rel=\"noreferrer\">REF 1 Lynda.com</a></li>\n<li><a href=\"http://see.stanford.edu/see/courseinfo.aspx?coll=824a47e1-135f-4508-a5aa-866adcae1111\" rel=\"noreferrer\">REF 2 Professor Mehran Sahami</a>\n\n<ul>\n<li><a href=\"https://www.youtube.com/watch?v=W2ysz_6AyJE&list=PL6C11012B1B464EC5#t=502\" rel=\"noreferrer\">watch max 5 min</a></li>\n<li><a href=\"https://www.youtube.com/watch?v=W8nNdNZ40EQ#t=1206\" rel=\"noreferrer\">Memory Allocation</a></li>\n</ul></li>\n<li><a href=\"http://www.c4learn.com/\" rel=\"noreferrer\">REF 3 c4learn</a>\n\n<ul>\n<li><a href=\"http://www.c4learn.com/java/java-passing-object-as-parameter-to-method/\" rel=\"noreferrer\">passing-object-as-parameter-to-method</a></li>\n</ul></li>\n</ol>\n"
},
{
"answer_id": 26210057,
"author": "drew7721",
"author_id": 2997238,
"author_profile": "https://Stackoverflow.com/users/2997238",
"pm_score": 3,
"selected": false,
"text": "<p>There is a workaround in Java for the reference. Let me explain by this example:</p>\n\n<pre><code>public class Yo {\npublic static void foo(int x){\n System.out.println(x); //out 2\n x = x+2;\n System.out.println(x); // out 4\n}\npublic static void foo(int[] x){\n System.out.println(x[0]); //1\n x[0] = x[0]+2;\n System.out.println(x[0]); //3\n}\npublic static void main(String[] args) {\n int t = 2;\n foo(t);\n System.out.println(t); // out 2 (t did not change in foo)\n\n int[] tab = new int[]{1};\n foo(tab);\n System.out.println(tab[0]); // out 3 (tab[0] did change in foo)\n}}\n</code></pre>\n\n<p>I hope this helps!</p>\n"
},
{
"answer_id": 27608651,
"author": "Ramprasad",
"author_id": 1695011,
"author_profile": "https://Stackoverflow.com/users/1695011",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Simple program</strong></p>\n\n<pre><code>import java.io.*;\nclass Aclass\n{\n public int a;\n}\npublic class test\n{\n public static void foo_obj(Aclass obj)\n {\n obj.a=5;\n }\n public static void foo_int(int a)\n {\n a=3;\n }\n public static void main(String args[])\n {\n //test passing an object\n Aclass ob = new Aclass();\n ob.a=0;\n foo_obj(ob);\n System.out.println(ob.a);//prints 5\n\n //test passing an integer\n int i=0;\n foo_int(i);\n System.out.println(i);//prints 0\n }\n}\n</code></pre>\n\n<p>From a C/C++ programmer's point of view, java uses pass by value, so for primitive data types (int, char etc) changes in the function does not reflect in the calling function. But when you pass an object and in the function you change its data members or call member functions which can change the state of the object, the calling function will get the changes.</p>\n"
},
{
"answer_id": 28750315,
"author": "João Oliveira",
"author_id": 1282030,
"author_profile": "https://Stackoverflow.com/users/1282030",
"pm_score": 3,
"selected": false,
"text": "<p>Java passes everything by value!!</p>\n\n<p>//create an object by passing in a name and age:</p>\n\n<pre><code>PersonClass variable1 = new PersonClass(\"Mary\", 32);\n\nPersonClass variable2;\n</code></pre>\n\n<p>//Both variable2 and variable1 now reference the same object</p>\n\n<pre><code>variable2 = variable1; \n\n\nPersonClass variable3 = new PersonClass(\"Andre\", 45);\n</code></pre>\n\n<p>// variable1 now points to variable3</p>\n\n<pre><code>variable1 = variable3;\n</code></pre>\n\n<p>//WHAT IS OUTPUT BY THIS?</p>\n\n<pre><code>System.out.println(variable2);\nSystem.out.println(variable1);\n\nMary 32\nAndre 45\n</code></pre>\n\n<p>if you could understand this example we r done.\notherwise, please visit this webPage for detailed explanation:</p>\n\n<p><a href=\"http://www.programmerinterview.com/index.php/java-questions/does-java-pass-by-reference-or-by-value/\" rel=\"noreferrer\">webPage</a></p>\n"
},
{
"answer_id": 29133165,
"author": "Christian",
"author_id": 112670,
"author_profile": "https://Stackoverflow.com/users/112670",
"pm_score": 5,
"selected": false,
"text": "<p>Java passes parameters by VALUE, and by value <strong>ONLY</strong>.</p>\n\n<p><strong>To cut long story short:</strong></p>\n\n<blockquote>\n <p>For those coming from C#: <strong>THERE IS NO \"out\" parameter.</strong></p>\n \n <p>For those coming from PASCAL: <strong>THERE IS NO \"var\" parameter</strong>.</p>\n</blockquote>\n\n<p>It means you can't change the reference from the object itself, but you can always change the object's properties.</p>\n\n<p>A workaround is to use <code>StringBuilder</code> parameter instead <code>String</code>. And you can always use arrays!</p>\n"
},
{
"answer_id": 30201678,
"author": "spiderman",
"author_id": 3250087,
"author_profile": "https://Stackoverflow.com/users/3250087",
"pm_score": 6,
"selected": false,
"text": "<p>Let me try to explain my understanding with the help of four examples. Java is pass-by-value, and not pass-by-reference</p>\n\n<p>/**</p>\n\n<p>Pass By Value</p>\n\n<p>In Java, all parameters are passed by value, i.e. assigning a method argument is not visible to the caller.</p>\n\n<p>*/</p>\n\n<p><strong>Example 1:</strong></p>\n\n<pre><code>public class PassByValueString {\n public static void main(String[] args) {\n new PassByValueString().caller();\n }\n\n public void caller() {\n String value = \"Nikhil\";\n boolean valueflag = false;\n String output = method(value, valueflag);\n /*\n * 'output' is insignificant in this example. we are more interested in\n * 'value' and 'valueflag'\n */\n System.out.println(\"output : \" + output);\n System.out.println(\"value : \" + value);\n System.out.println(\"valueflag : \" + valueflag);\n\n }\n\n public String method(String value, boolean valueflag) {\n value = \"Anand\";\n valueflag = true;\n return \"output\";\n }\n}\n</code></pre>\n\n<p><strong>Result</strong></p>\n\n<pre><code>output : output\nvalue : Nikhil\nvalueflag : false\n</code></pre>\n\n<p><strong>Example 2:</strong></p>\n\n<p>/**\n * \n * Pass By Value\n *\n */</p>\n\n<pre><code>public class PassByValueNewString {\n public static void main(String[] args) {\n new PassByValueNewString().caller();\n }\n\n public void caller() {\n String value = new String(\"Nikhil\");\n boolean valueflag = false;\n String output = method(value, valueflag);\n /*\n * 'output' is insignificant in this example. we are more interested in\n * 'value' and 'valueflag'\n */\n System.out.println(\"output : \" + output);\n System.out.println(\"value : \" + value);\n System.out.println(\"valueflag : \" + valueflag);\n\n }\n\n public String method(String value, boolean valueflag) {\n value = \"Anand\";\n valueflag = true;\n return \"output\";\n }\n}\n</code></pre>\n\n<p><strong>Result</strong></p>\n\n<pre><code>output : output\nvalue : Nikhil\nvalueflag : false\n</code></pre>\n\n<p><strong>Example 3:</strong></p>\n\n<p>/**\n This 'Pass By Value has a feeling of 'Pass By Reference'</p>\n\n<p>Some people say primitive types and 'String' are 'pass by value'\n and objects are 'pass by reference'.</p>\n\n<p>But from this example, we can understand that it is infact pass by value only,\n keeping in mind that here we are passing the reference as the value.\n ie: reference is passed by value.\n That's why are able to change and still it holds true after the local scope.\n But we cannot change the actual reference outside the original scope.\n what that means is demonstrated by next example of PassByValueObjectCase2.</p>\n\n<p>*/</p>\n\n<pre><code>public class PassByValueObjectCase1 {\n\n private class Student {\n int id;\n String name;\n public Student() {\n }\n public Student(int id, String name) {\n super();\n this.id = id;\n this.name = name;\n }\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n @Override\n public String toString() {\n return \"Student [id=\" + id + \", name=\" + name + \"]\";\n }\n }\n\n public static void main(String[] args) {\n new PassByValueObjectCase1().caller();\n }\n\n public void caller() {\n Student student = new Student(10, \"Nikhil\");\n String output = method(student);\n /*\n * 'output' is insignificant in this example. we are more interested in\n * 'student'\n */\n System.out.println(\"output : \" + output);\n System.out.println(\"student : \" + student);\n }\n\n public String method(Student student) {\n student.setName(\"Anand\");\n return \"output\";\n }\n}\n</code></pre>\n\n<p><strong>Result</strong></p>\n\n<pre><code>output : output\nstudent : Student [id=10, name=Anand]\n</code></pre>\n\n<p><strong>Example 4:</strong></p>\n\n<p>/**</p>\n\n<p>In addition to what was mentioned in Example3 (PassByValueObjectCase1.java), we cannot change the actual reference outside the original scope.\"</p>\n\n<p>Note: I am not pasting the code for <code>private class Student</code>. The class definition for <code>Student</code> is same as Example3.</p>\n\n<p>*/</p>\n\n<pre><code>public class PassByValueObjectCase2 {\n\n public static void main(String[] args) {\n new PassByValueObjectCase2().caller();\n }\n\n public void caller() {\n // student has the actual reference to a Student object created\n // can we change this actual reference outside the local scope? Let's see\n Student student = new Student(10, \"Nikhil\");\n String output = method(student);\n /*\n * 'output' is insignificant in this example. we are more interested in\n * 'student'\n */\n System.out.println(\"output : \" + output);\n System.out.println(\"student : \" + student); // Will it print Nikhil or Anand?\n }\n\n public String method(Student student) {\n student = new Student(20, \"Anand\");\n return \"output\";\n }\n\n}\n</code></pre>\n\n<p><strong>Result</strong></p>\n\n<pre><code>output : output\nstudent : Student [id=10, name=Nikhil]\n</code></pre>\n"
},
{
"answer_id": 34924074,
"author": "Placinta Alexandru",
"author_id": 4957499,
"author_profile": "https://Stackoverflow.com/users/4957499",
"pm_score": 4,
"selected": false,
"text": "<p>Java always uses <strong>call by value</strong>. That means the method gets copy of all parameter values.</p>\n\n<p>Consider next 3 situations:</p>\n\n<h2>1) Trying to change primitive variable</h2>\n\n<pre><code>public static void increment(int x) { x++; }\n\nint a = 3;\nincrement(a);\n</code></pre>\n\n<p>x will copy value of a and will increment x, a remains the same</p>\n\n<h2>2) Trying to change primitive field of an object</h2>\n\n<pre><code>public static void increment(Person p) { p.age++; }\n\nPerson pers = new Person(20); // age = 20\nincrement(pers);\n</code></pre>\n\n<p>p will copy reference value of pers and will increment age field, variables are referencing to the same object so age is changed</p>\n\n<h2>3) Trying to change reference value of reference variables</h2>\n\n<pre><code>public static void swap(Person p1, Person p2) {\n Person temp = p1;\n p1 = p2;\n p2 = temp;\n}\n\nPerson pers1 = new Person(10);\nPerson pers2 = new Person(20);\nswap(pers1, pers2);\n</code></pre>\n\n<p>after calling swap p1, p2 copy reference values from pers1 and pers2, are swapping with values, so pers1 and pers2 remain the same</p>\n\n<p>So. you can change only fields of objects in method passing copy of reference value to this object.</p>\n"
},
{
"answer_id": 36040135,
"author": "Gee Bee",
"author_id": 5903395,
"author_profile": "https://Stackoverflow.com/users/5903395",
"pm_score": 4,
"selected": false,
"text": "<p>So many long answers. Let me give a simple one:</p>\n\n<ul>\n<li>Java always passes everything by value</li>\n<li>that means also references are passed by value</li>\n</ul>\n\n<p>In short, you can not modify value of any parameter passed, but you can call methods or change attributes of an object reference passed.</p>\n"
},
{
"answer_id": 36843568,
"author": "OverCoder",
"author_id": 2164304,
"author_profile": "https://Stackoverflow.com/users/2164304",
"pm_score": 4,
"selected": false,
"text": "<p>I made this little diagram that shows how the data gets created and passed</p>\n\n<p><a href=\"https://i.stack.imgur.com/77ppY.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/77ppY.png\" alt=\"Diagram of how data is created and passed\"></a></p>\n\n<p>Note: Primitive values are passed as a value, the first reference to to that value is the method's argument</p>\n\n<p>That means:</p>\n\n<ul>\n<li>You can change the value of <code>myObject</code> <em>inside</em> the function</li>\n<li>But you can't change what <code>myObject</code> references to, inside the function, because <code>point</code> is not <code>myObject</code></li>\n<li>Remember, both <code>point</code> and <code>myObject</code> are <strong>references</strong>, different <strong>references</strong>, however, those references <strong>point</strong> at the same <code>new Point(0,0)</code></li>\n</ul>\n"
},
{
"answer_id": 37190132,
"author": "Cdaragorn",
"author_id": 658018,
"author_profile": "https://Stackoverflow.com/users/658018",
"pm_score": 4,
"selected": false,
"text": "<p>A lot of the confusion surrounding this issue comes from the fact that Java has attempted to redefine what \"Pass by value\" and \"Pass by reference\" mean. It's important to understand that these are <a href=\"https://en.wikipedia.org/wiki/Jargon\" rel=\"noreferrer\">Industry Terms</a>, and cannot be correctly understood outside of that context. They are meant to help you as you code and are valuable to understand, so let's first go over what they mean. </p>\n\n<p>A good description of both can be found <a href=\"http://cplus.about.com/od/glossar1/g/passbyrefdefn.htm\" rel=\"noreferrer\">here</a>.</p>\n\n<p><strong>Pass By Value</strong> The value the function received is a copy of the object the caller is using. It is entirely unique to the function and anything you do to that object will only be seen within the function.</p>\n\n<p><strong>Pass By Reference</strong> The value the function received is a reference to the object the caller is using. Anything the function does to the object that value refers to will be seen by the caller and it will be working with those changes from that point on.</p>\n\n<p>As is clear from those definitions, the fact that the reference is passed by value is irrelevant. If we were to accept that definition, then these terms become meaningless and all languages everywhere are only Pass By Value.</p>\n\n<p>No matter how you pass the reference in, it can only ever be passed by value. That isn't the point. The point is that you passed a reference to your own object to the function, not a copy of it. The fact that you can throw away the reference you received is irrelevant. Again, if we accepted that definition, these terms become meaningless and everyone is always passing by value.</p>\n\n<p>And no, C++'s special \"pass by reference\" syntax is not the exclusive definition of pass by reference. It is purely a convenience syntax meant to make it so that you don't need to use pointer syntax after passing the pointer in. It is still passing a pointer, the compiler is just hiding that fact from you. It also still passes that pointer BY VALUE, the compiler is just hiding that from you.</p>\n\n<p>So, with this understanding, we can look at Java and see that it actually has both. All Java primitive types are always pass by value because you receive a copy of the caller's object and cannot modify their copy. All Java reference types are always pass by reference because you receive a reference to the caller's object and can directly modify their object. </p>\n\n<p>The fact that you cannot modify the caller's reference has nothing to do with pass by reference and is true in every language that supports pass by reference.</p>\n"
},
{
"answer_id": 37669835,
"author": "Ravi Sanwal",
"author_id": 1195605,
"author_profile": "https://Stackoverflow.com/users/1195605",
"pm_score": 3,
"selected": false,
"text": "<p>There is a very simple way to understand this.\nLets's take C++ pass by reference.</p>\n\n<pre><code>#include <iostream>\nusing namespace std;\n\nclass Foo {\n private:\n int x;\n public:\n Foo(int val) {x = val;}\n void foo()\n {\n cout<<x<<endl;\n }\n};\n\nvoid bar(Foo& ref)\n{\n ref.foo();\n ref = *(new Foo(99));\n ref.foo();\n}\n\nint main()\n{\n Foo f = Foo(1);\n f.foo();\n bar(f);\n f.foo();\n\n return 0;\n}\n</code></pre>\n\n<p>What is the outcome?</p>\n\n<pre>\n1\n1\n99\n99\n</pre>\n\n<p>So, after bar() assigned a new value to a \"reference\" passed in, it actually changed the one which was passed in from main itself, explaining the last f.foo() call from main printing 99.</p>\n\n<p>Now, lets see what java says.</p>\n\n<pre><code>public class Ref {\n\n private static class Foo {\n private int x;\n\n private Foo(int x) {\n this.x = x;\n }\n\n private void foo() {\n System.out.println(x);\n }\n }\n\n private static void bar(Foo f) {\n f.foo();\n f = new Foo(99);\n f.foo();\n }\n\n public static void main(String[] args) {\n Foo f = new Foo(1);\n System.out.println(f.x);\n bar(f);\n System.out.println(f.x);\n }\n\n}\n</code></pre>\n\n<p>It says:</p>\n\n<pre>\n1\n1\n99\n1\n</pre>\n\n<p>Voilà, the reference of Foo in main that was passed to bar, is still unchanged!</p>\n\n<p>This example clearly shows that java is not the same as C++ when we say \"pass by reference\". Essentially, java is passing \"references\" as \"values\" to functions, meaning java is pass by value.</p>\n"
},
{
"answer_id": 38550131,
"author": "user1767316",
"author_id": 1767316,
"author_profile": "https://Stackoverflow.com/users/1767316",
"pm_score": 6,
"selected": false,
"text": "<p><strong>In Java, method arguments are all passed by value :</strong></p>\n<p>Java arguments are <strong>all passed by value</strong> (the value or reference is copied when used by the method) :</p>\n<p>In the case of primitive types, Java behaviour is simple:\nThe value is copied in another instance of the primitive type.</p>\n<p>In case of Objects, this is the same:\nObject variables are references (mem buckets holding only Object’s <strong>address</strong> instead of a primitive value) that was created using the "new" keyword, and are copied like primitive types.</p>\n<p>The behaviour can appear different from primitive types: Because the copied object-variable contains the same address (to the same Object).\nObject's <strong>content/members</strong> might still be modified within a method and later access outside, giving the illusion that the (containing) Object itself was passed by reference.</p>\n<p>"String" Objects appear to be a good <strong>counter-example</strong> to the urban legend saying that "Objects are passed by reference":</p>\n<p>In effect, using a method, you will never be able, to update the value of a String passed as argument:</p>\n<p>A String Object, holds characters by an array declared <strong>final</strong> that can't be modified.\nOnly the address of the Object might be replaced by another using "new".\nUsing "new" to update the variable, will not let the Object be accessed from outside, since the variable was initially passed by value and copied.</p>\n"
},
{
"answer_id": 39709353,
"author": "Vivek Kumar",
"author_id": 5128145,
"author_profile": "https://Stackoverflow.com/users/5128145",
"pm_score": 3,
"selected": false,
"text": "<p>Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.</p>\n\n<p>Take the badSwap() method for example:</p>\n\n<pre><code> public void badSwap(int var1, int\n var2{ int temp = var1; var1 = var2; var2 =\n temp; }\n</code></pre>\n\n<p>When badSwap() returns, the variables passed as arguments will still hold their original values. The method will also fail if we change the arguments type from int to Object, since Java passes object references by value as well. Now, here is where it gets tricky:</p>\n\n<pre><code>public void tricky(Point arg1, Point arg2)\n{ arg1.x = 100; arg1.y = 100; Point temp = arg1; arg1 = arg2; arg2 = temp; }\npublic static void main(String [] args) { \n\n Point pnt1 = new Point(0,0); Point pnt2\n = new Point(0,0); System.out.println(\"X:\n \" + pnt1.x + \" Y: \" +pnt1.y);\n\n System.out.println(\"X: \" + pnt2.x + \" Y:\n \" +pnt2.y); System.out.println(\" \");\n\n tricky(pnt1,pnt2);\n System.out.println(\"X: \" + pnt1.x + \" Y:\" + pnt1.y);\n\n System.out.println(\"X: \" + pnt2.x + \" Y: \" +pnt2.y); }\n</code></pre>\n\n<p>If we execute this main() method, we see the following output:</p>\n\n<p>X: 0 Y: 0 X: 0 Y: 0 X: 100 Y: 100 X: 0 Y: 0</p>\n\n<p>The method successfully alters the value ofpnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In themain() method, pnt1 and pnt2 are nothing more than object references. When you passpnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. Figure 1 below shows two references pointing to the same object after Java passes an object to a method.</p>\n\n<p>Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail. As Figure 2 illustrates, the method references swap, but not the original references. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.</p>\n"
},
{
"answer_id": 39767073,
"author": "khakishoiab",
"author_id": 5797598,
"author_profile": "https://Stackoverflow.com/users/5797598",
"pm_score": 4,
"selected": false,
"text": "<p>A simple test to check whether a language supports pass-by-reference is simply writing a traditional swap.\nCan you write a traditional swap(a,b) method/function in Java?</p>\n\n<p>A traditional swap method or function takes two arguments and swaps them such that variables passed into the function are changed outside the function. Its basic structure looks like</p>\n\n<p>(Non-Java) Basic swap function structure</p>\n\n<pre><code>swap(Type arg1, Type arg2) {\n Type temp = arg1;\n arg1 = arg2;\n arg2 = temp;\n}\n</code></pre>\n\n<p>If you can write such a method/function in your language such that calling</p>\n\n<pre><code>Type var1 = ...;\nType var2 = ...;\nswap(var1,var2);\n</code></pre>\n\n<p>actually switches the values of the variables var1 and var2, the language supports pass-by-reference.\nBut <strong>Java does not allow such a thing</strong> as it supports passing the values only and not pointers or references.</p>\n"
},
{
"answer_id": 40593867,
"author": "Soner from The Ottoman Empire",
"author_id": 4990642,
"author_profile": "https://Stackoverflow.com/users/4990642",
"pm_score": 4,
"selected": false,
"text": "<p>The major cornerstone knowledge must be the quoted one,</p>\n\n<blockquote>\n <p>When an object reference is passed to a method, the reference itself\n is passed by use of <em>call-by-value</em>. However, since the value being\n passed refers to an object, the copy of that value will still refer to\n the same object referred to by its corresponding argument.</p>\n</blockquote>\n\n<p>Java: A Beginner's Guide, Sixth Edition, Herbert Schildt</p>\n"
},
{
"answer_id": 40631632,
"author": "Taleev Aalam",
"author_id": 7051714,
"author_profile": "https://Stackoverflow.com/users/7051714",
"pm_score": 3,
"selected": false,
"text": "<p>It seems everything is call by value in java as i have tried to understand by the following program</p>\n<p><strong>Class-S</strong></p>\n<pre><code>class S{\nString name="alam";\npublic void setName(String n){\nthis.name=n; \n}}\n</code></pre>\n<p><strong>Class-Sample</strong></p>\n<pre><code> public class Sample{\n public static void main(String args[]){\n S s=new S();\n S t=new S();\n System.out.println(s.name);\n System.out.println(t.name);\n t.setName("taleev");\n System.out.println(t.name);\n System.out.println(s.name);\n s.setName("Harry");\n System.out.println(t.name);\n System.out.println(s.name);\n }}\n</code></pre>\n<p><strong>Output</strong></p>\n<blockquote>\n<p>alam</p>\n<p>alam</p>\n<p>taleev</p>\n<p>alam</p>\n<p>taleev</p>\n<p>harry</p>\n</blockquote>\n<p>As we have define class S with instance variable name with value <strong>taleev</strong> so for\nall the objects that we initialize from it will have the name variable with value of <strong>taleev</strong> but if we change the name's value of any objects then it is changing the name of only that copy of the class(Object) not for every class so after that also when we do <strong>System.out.println(s.name)</strong> it is printing <strong>taleev</strong> only we can not change the name's value that we have defined originally, and the value that we are changing is the object's value not the instance variable value so once we have define instance variable we are unable to change it</p>\n<p>So i think that is how it shows that java deals with <strong>values</strong> only not with the <strong>references</strong></p>\n<p>The memory allocation for the primitive variables can be understood by <a href=\"http://www.informit.com/articles/article.aspx?p=31755&seqNum=8\" rel=\"nofollow noreferrer\">this</a></p>\n"
},
{
"answer_id": 41393112,
"author": "Rahul Kumar",
"author_id": 4958222,
"author_profile": "https://Stackoverflow.com/users/4958222",
"pm_score": 4,
"selected": false,
"text": "<p>Java, for sure, without a doubt, is \"pass by value\". Also, since Java is (mostly) object-oriented and objects work with references, it's easy to get confused and think of it to be \"pass by reference\"</p>\n\n<p>Pass by value means you pass the value to the method and if the method changes the passed value, the real entity doesn't change. Pass by reference, on the other hand, means a reference is passed to the method, and if the method changes it, the passed object also changes.</p>\n\n<p>In Java, usually when we pass an object to a method, we basically pass the reference of the object as-a-value because that's how Java works; it works with references and addresses as far as Object in the heap goes.</p>\n\n<p>But to test if it is really pass by value or pass by reference, you can use a primitive type and references:</p>\n\n<pre><code>@Test\npublic void sampleTest(){\n int i = 5;\n incrementBy100(i);\n System.out.println(\"passed ==> \"+ i);\n Integer j = new Integer(5);\n incrementBy100(j);\n System.out.println(\"passed ==> \"+ j);\n}\n/**\n * @param i\n */\nprivate void incrementBy100(int i) {\n i += 100;\n System.out.println(\"incremented = \"+ i);\n}\n</code></pre>\n\n<p>The output is:</p>\n\n<pre><code>incremented = 105\npassed ==> 5\nincremented = 105\npassed ==> 5\n</code></pre>\n\n<p>So in both cases, whatever happens inside the method doesn't change the real Object, because the value of that object was passed, and not a reference to the object itself.</p>\n\n<p>But when you pass a custom object to a method, and the method and changes it, it will change the real object too, because even when you passed the object, you passed it's reference as a value to the method. Let's try another example:</p>\n\n<pre><code>@Test\npublic void sampleTest2(){\n Person person = new Person(24, \"John\");\n System.out.println(person);\n alterPerson(person);\n System.out.println(person);\n}\n\n/**\n * @param person\n */\nprivate void alterPerson(Person person) {\n person.setAge(45);\n Person altered = person;\n altered.setName(\"Tom\");\n}\n\nprivate static class Person{\n private int age;\n private String name; \n\n public Person(int age, String name) {\n this.age=age;\n this.name =name;\n }\n\n public int getAge() {\n return age;\n }\n\n public void setAge(int age) {\n this.age = age;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n @Override\n public String toString() {\n StringBuilder builder = new StringBuilder();\n builder.append(\"Person [age=\");\n builder.append(age);\n builder.append(\", name=\");\n builder.append(name);\n builder.append(\"]\");\n return builder.toString();\n }\n\n}\n</code></pre>\n\n<p>In this case, the output is:</p>\n\n<pre><code>Person [age=24, name=John]\nPerson [age=45, name=Tom]\n</code></pre>\n"
},
{
"answer_id": 41901960,
"author": "Raja",
"author_id": 1952852,
"author_profile": "https://Stackoverflow.com/users/1952852",
"pm_score": 3,
"selected": false,
"text": "<p>I tried to simplify the examples above, keeping only the essense of the problem.\nLet me present this as a story that is easy to remember and apply correctly.\nThe story goes like this:\nYou have a pet dog, Jimmy, whose tail is 12 inches long.\nYou leave it with a vet for a few weeks while you are travelling abroad.</p>\n\n<p>The vet doesn't like the long tail of Jimmy, so he wants to cut it by half.\nBut being a good vet, he knows that he has no right to mutilate other people's dogs.\nSo he first makes a clone of the dog (with the <em>new</em> key word) and cuts the tail of the clone.\nWhen the dog finally returns to you, it has the original 12 inch tail in tact. Happy ending !</p>\n\n<p>The next time you travel, you take the dog, unwittingly, to a wicked vet. \nHe is also a hater of long tails, so he cuts it down to a miserable 2 inches. \nBut he does this to your dear Jimmy, not a clone of it.\nWhen you return, you are shocked to see Jimmy pathetically wagging a 2 inch stub.</p>\n\n<p>Moral of the story: When you pass on your pet, you are giving away whole and unfettered\ncustody of the pet to the vet. He is free to play any kind of havoc with it.\nPassing by <em>value</em>, by <em>reference</em>, by <em>pointer</em> are all just technical wrangling. \nUnless the vet clones it first, he ends up mutilating the original dog.</p>\n\n<pre><code>public class Doggie {\n\n public static void main(String...args) {\n System.out.println(\"At the owner's home:\");\n Dog d = new Dog(12);\n d.wag();\n goodVet(d);\n System.out.println(\"With the owner again:)\");\n d.wag();\n badVet(d);\n System.out.println(\"With the owner again(:\");\n d.wag();\n }\n\n public static void goodVet (Dog dog) {\n System.out.println(\"At the good vet:\");\n dog.wag();\n dog = new Dog(12); // create a clone\n dog.cutTail(6); // cut the clone's tail\n dog.wag();\n }\n\n public static void badVet (Dog dog) {\n System.out.println(\"At the bad vet:\");\n dog.wag();\n dog.cutTail(2); // cut the original dog's tail\n dog.wag();\n } \n}\n\nclass Dog {\n\n int tailLength;\n\n public Dog(int originalLength) {\n this.tailLength = originalLength;\n }\n\n public void cutTail (int newLength) {\n this.tailLength = newLength;\n }\n\n public void wag() {\n System.out.println(\"Wagging my \" +tailLength +\" inch tail\");\n }\n}\n\nOutput:\nAt the owner's home:\nWagging my 12 inch tail\nAt the good vet:\nWagging my 12 inch tail\nWagging my 6 inch tail\nWith the owner again:)\nWagging my 12 inch tail\nAt the bad vet:\nWagging my 12 inch tail\nWagging my 2 inch tail\nWith the owner again(:\nWagging my 2 inch tail\n</code></pre>\n"
},
{
"answer_id": 43113746,
"author": "Basheer AL-MOMANI",
"author_id": 4251431,
"author_profile": "https://Stackoverflow.com/users/4251431",
"pm_score": 4,
"selected": false,
"text": "<p>Unlike some other languages, Java does not allow you to choose between pass-by-value and pass-by-reference.</p>\n\n<p>All arguments are passed by value. </p>\n\n<p>A method call can pass two <code>types of values</code>to a method</p>\n\n<ul>\n<li>copies of primitive values (e.g., values of type int and double)</li>\n<li>copies of references to objects.</li>\n</ul>\n\n<p><code>Objects themselves cannot be passed to methods</code>. When a method modifies a primitive-type parameter, changes to the parameter have no effect on the original argument value in the calling method.</p>\n\n<p>This is also true for reference-type parameters. If you modify a reference-type parameter so that it refers to another object, only the parameter refers to the new object—the reference stored in the caller’s variable still refers to the original object.</p>\n\n<p>References: <a href=\"https://www.safaribooksonline.com/library/view/javatm-how-to/9780133813036/ch07lev2sec11.html\" rel=\"noreferrer\">Java™ How To Program (Early Objects), Tenth Edition</a> </p>\n"
},
{
"answer_id": 43290680,
"author": "Himanshu arora",
"author_id": 3664592,
"author_profile": "https://Stackoverflow.com/users/3664592",
"pm_score": 6,
"selected": false,
"text": "<p>Java is a pass by value(stack memory)</p>\n<p>How it works</p>\n<ul>\n<li><p>Let's first understand that where java stores primitive data type and object data type.</p>\n</li>\n<li><p>Primitive data types itself and object references are stored in the stack.\nObjects themselves are stored in the heap.</p>\n</li>\n<li><p>It means, Stack memory stores primitive data types and also the\naddresses of objects.</p>\n</li>\n<li><p>And you always pass a copy of the bits of the value of the reference.</p>\n</li>\n<li><p>If it's a primitive data type then these copied bits contain the value of the primitive data type itself, That's why when we change the value of argument inside the method then it does not reflect the changes outside.</p>\n</li>\n<li><p>If it's an object data type like <strong>Foo foo=new Foo()</strong> then in this case copy of the address of the object passes like file shortcut , suppose we have a text file <strong>abc.txt</strong> at <strong>C:\\desktop</strong> and suppose we make shortcut of the same file and put this inside <strong>C:\\desktop\\abc-shortcut</strong> so when you access the file from <strong>C:\\desktop\\abc.txt</strong> and write <strong>'Stack Overflow'</strong> and close the file and again you open the file from shortcut then you write <strong>' is the largest online community for programmers to learn'</strong> then total file change will be <strong>'Stack Overflow is the largest online community for programmers to learn'</strong> which means it doesn't matter from where you open the file , each time we were accessing the same file , here we can assume <strong>Foo</strong> as a file and suppose foo stored at <strong>123hd7h</strong>(original address like <strong>C:\\desktop\\abc.txt</strong> ) address and <strong>234jdid</strong>(copied address like <strong>C:\\desktop\\abc-shortcut</strong> which actually contains the original address of the file inside) ..\nSo for better understanding make shortcut file and feel.</p>\n</li>\n</ul>\n"
},
{
"answer_id": 46026822,
"author": "Supriya",
"author_id": 4233180,
"author_profile": "https://Stackoverflow.com/users/4233180",
"pm_score": 4,
"selected": false,
"text": "<p>Java is pass by value. </p>\n\n<p>There are already great answers on this thread. Somehow, I was never clear on pass by value/reference with respect to primitive data types and with respect to objects. Therefore, I tested it out for my satisfaction and clarity with the following piece of code; might help somebody seeking similar clarity:</p>\n\n<pre><code>class Test {\n\npublic static void main (String[] args) throws java.lang.Exception\n{\n // Primitive type\n System.out.println(\"Primitve:\");\n int a = 5;\n primitiveFunc(a);\n System.out.println(\"Three: \" + a); //5\n\n //Object\n System.out.println(\"Object:\");\n DummyObject dummyObject = new DummyObject();\n System.out.println(\"One: \" + dummyObject.getObj()); //555\n objectFunc(dummyObject);\n System.out.println(\"Four: \" + dummyObject.getObj()); //666 (555 if line in method uncommented.)\n\n}\n\nprivate static void primitiveFunc(int b) {\n System.out.println(\"One: \" + b); //5\n b = 10;\n System.out.println(\"Two:\" + b); //10\n}\n\nprivate static void objectFunc(DummyObject b) {\n System.out.println(\"Two: \" + b.getObj()); //555\n //b = new DummyObject();\n b.setObj(666);\n System.out.println(\"Three:\" + b.getObj()); //666\n}\n\n}\n\nclass DummyObject {\n private int obj = 555;\n public int getObj() { return obj; }\n public void setObj(int num) { obj = num; }\n}\n</code></pre>\n\n<p>If the line <code>b = new DummyObject()</code> is uncommented, the modifications made thereafter are made on a <em>new</em> object, a new instantiation. Hence, it is not reflected in the place where the method is called from. However, otherwise, the change is reflected as the modifications are only made on a \"reference\" of the object, i.e - b points to the same dummyObject. </p>\n\n<p>Illustrations in one of the answers in this thread (<a href=\"https://stackoverflow.com/a/12429953/4233180\">https://stackoverflow.com/a/12429953/4233180</a>) can help gain a deeper understanding.</p>\n"
},
{
"answer_id": 46077533,
"author": "Raj S. Rusia",
"author_id": 7178104,
"author_profile": "https://Stackoverflow.com/users/7178104",
"pm_score": 5,
"selected": false,
"text": "<p>One of the biggest confusion in Java programming language is whether Java is <strong>Pass by Value</strong> or <strong>Pass by Reference</strong>.</p>\n\n<p>First of all, we should understand what is meant by pass by value or pass by reference.</p>\n\n<p><strong>Pass by Value:</strong> The method parameter values are copied to another variable and then the copied object is passed, that’s why it’s called pass by value.</p>\n\n<p><strong>Pass by Reference:</strong> An alias or reference to the actual parameter is passed to the method, that’s why it’s called pass by reference.</p>\n\n<p>Let’s say we have a class Balloon like below.</p>\n\n<pre><code>public class Balloon {\n\n private String color;\n\n public Balloon(){}\n\n public Balloon(String c){\n this.color=c;\n }\n\n public String getColor() {\n return color;\n }\n\n public void setColor(String color) {\n this.color = color;\n }\n}\n</code></pre>\n\n<p>And we have a simple program with a generic method to swap two objects, the class looks like below.</p>\n\n<pre><code>public class Test {\n\n public static void main(String[] args) {\n\n Balloon red = new Balloon(\"Red\"); //memory reference 50\n Balloon blue = new Balloon(\"Blue\"); //memory reference 100\n\n swap(red, blue);\n System.out.println(\"red color=\"+red.getColor());\n System.out.println(\"blue color=\"+blue.getColor());\n\n foo(blue);\n System.out.println(\"blue color=\"+blue.getColor());\n\n }\n\n private static void foo(Balloon balloon) { //baloon=100\n balloon.setColor(\"Red\"); //baloon=100\n balloon = new Balloon(\"Green\"); //baloon=200\n balloon.setColor(\"Blue\"); //baloon = 200\n }\n\n //Generic swap method\n public static void swap(Object o1, Object o2){\n Object temp = o1;\n o1=o2;\n o2=temp;\n }\n}\n</code></pre>\n\n<p>When we execute the above program, we get following output.</p>\n\n<pre><code>red color=Red\nblue color=Blue\nblue color=Red\n</code></pre>\n\n<p>If you look at the first two lines of the output, it’s clear that swap method didn’t work. This is because Java is passed by value, this swap() method test can be used with any programming language to check whether it’s pass by value or pass by reference.</p>\n\n<p>Let’s analyze the program execution step by step.</p>\n\n<pre><code>Balloon red = new Balloon(\"Red\");\nBalloon blue = new Balloon(\"Blue\");\n</code></pre>\n\n<p>When we use the new operator to create an instance of a class, the instance is created and the variable contains the reference location of the memory where the object is saved. For our example, let’s assume that “red” is pointing to 50 and “blue” is pointing to 100 and these are the memory location of both Balloon objects.</p>\n\n<p>Now when we are calling swap() method, two new variables o1 and o2 are created pointing to 50 and 100 respectively.</p>\n\n<p>So below code snippet explains what happened in the swap() method execution.</p>\n\n<pre><code>public static void swap(Object o1, Object o2){ //o1=50, o2=100\n Object temp = o1; //temp=50, o1=50, o2=100\n o1=o2; //temp=50, o1=100, o2=100\n o2=temp; //temp=50, o1=100, o2=50\n} //method terminated\n</code></pre>\n\n<p>Notice that we are changing values of o1 and o2 but they are copies of “red” and “blue” reference locations, so actually, there is no change in the values of “red” and “blue” and hence the output.</p>\n\n<p>If you have understood this far, you can easily understand the cause of confusion. Since the variables are just the reference to the objects, we get confused that we are passing the reference so Java is passed by reference. However, we are passing a copy of the reference and hence it’s pass by value. I hope it clears all the doubts now.</p>\n\n<p>Now let’s analyze <strong>foo()</strong> method execution.</p>\n\n<pre><code>private static void foo(Balloon balloon) { //baloon=100\n balloon.setColor(\"Red\"); //baloon=100\n balloon = new Balloon(\"Green\"); //baloon=200\n balloon.setColor(\"Blue\"); //baloon = 200\n}\n</code></pre>\n\n<p>The first line is the important one when we call a method the method is called on the Object at the reference location. At this point, the balloon is pointing to 100 and hence it’s color is changed to Red.</p>\n\n<p>In the next line, balloon reference is changed to 200 and any further methods executed are happening on the object at memory location 200 and not having any effect on the object at memory location 100. This explains the third line of our program output printing blue color=Red.</p>\n\n<p>I hope above explanation clear all the doubts, just remember that variables are references or pointers and its copy is passed to the methods, so Java is always passed by value. It would be more clear when you will learn about Heap and Stack memory and where different objects and references are stored.</p>\n"
},
{
"answer_id": 46871427,
"author": "NAGHMAAN MOHASEEN",
"author_id": 8808036,
"author_profile": "https://Stackoverflow.com/users/8808036",
"pm_score": 4,
"selected": false,
"text": "<h3>Java is strictly passed by value</h3>\n\n<p>When I say <strong><em>pass by value</em></strong> it means whenever caller has invoked the callee the arguments(ie: the data to be passed to the other function) <strong>is copied</strong> and placed in the formal parameters (callee's local variables for receiving the input). Java makes data communications from one function to other function only in a pass by value environment.</p>\n\n<p>An important point would be to know that even C language is strictly passed by value only:<br>\n<em>ie:</em> Data is copied from caller to the callee and more ever the operation performed by the callee are on the same memory location and \nwhat we pass them is the address of that location that we obtain from (&) operator and the identifier used in the formal parameters are declared to be a pointer variable (*) using which we can get inside the memory location for accessing the data in it.</p>\n\n<p>Hence here the formal parameter is nothing but mere aliases for that location. And any modifications done on that location is visible where ever that scope of the variable (that identifies that location) is alive.</p>\n\n<p>In Java, there is no concept of pointers (<em>ie:</em> there is nothing called a pointer variable), although we can think of reference variable as a pointer technically in java we call it as a handle. The reason why we call the pointer to an address as a handle in java is because a pointer variable is capable of performing not just single dereferencing but multiple dereferencing \nfor example: <code>int *p;</code> in P means p points to an integer\nand <code>int **p;</code> in C means p is pointer to a pointer to an integer\nwe dont have this facility in Java, so its absolutely correct and technically legitimate to say it as an handle, also there are rules for pointer arithmetic in C. Which allows performing arithmetic operation on pointers with constraints on it. </p>\n\n<p>In C we call such mechanism of passing address and receiving them with pointer variables as <em>pass by reference</em> since we are passing their addresses and receiving them as pointer variable in formal parameter but at the compiler level that address is copied into pointer variable (since data here is address even then its data ) hence we can be 100% sure that C is Strictly passed by value (as we are passing data only)</p>\n\n<p>(and if we pass the data directly in C we call that as pass by value.)</p>\n\n<p>In java when we do the same we do it with the handles; since they are not called pointer variables like in (as discussed above) even though we are passing the references we cannot say its pass by reference since we are not collecting that with a pointer variable in Java.</p>\n\n<p>Hence Java <strong>strictly use pass by value mechanism</strong> </p>\n"
},
{
"answer_id": 47844599,
"author": "Premraj",
"author_id": 1697099,
"author_profile": "https://Stackoverflow.com/users/1697099",
"pm_score": 4,
"selected": false,
"text": "<p>Data is shared between functions by passing parameters. Now, there are 2 ways of passing parameters:</p>\n<ul>\n<li><p><strong>passed by reference :</strong> caller and callee use same variable for parameter.</p>\n</li>\n<li><p><strong>passed by value :</strong> caller and callee have two independent variables with same value.</p>\n</li>\n</ul>\n<p>Java uses <em><strong>pass by value</strong></em></p>\n<ul>\n<li>When passing primitive data, it copies the value of primitive data type.</li>\n<li>When passing object, it copies the address of object and passes to callee method variable.</li>\n</ul>\n<p>Java follows the following rules in storing variables:</p>\n<ul>\n<li>Local variables like primitives and object references are created on Stack memory.</li>\n<li>Objects are created on Heap memory.</li>\n</ul>\n<p>Example using primitive data type:</p>\n<pre><code>public class PassByValuePrimitive {\n public static void main(String[] args) {\n int i=5;\n System.out.println(i); //prints 5\n change(i);\n System.out.println(i); //prints 5\n }\n \n \n private static void change(int i) {\n System.out.println(i); //prints 5\n i=10;\n System.out.println(i); //prints 10\n \n }\n}\n</code></pre>\n<p>Example using object:</p>\n<pre><code>public class PassByValueObject {\n public static void main(String[] args) {\n List<String> list = new ArrayList<>();\n list.add("prem");\n list.add("raj");\n new PassByValueObject().change(list);\n System.out.println(list); // prints [prem, raj, ram]\n \n }\n \n \n private void change(List list) {\n System.out.println(list.get(0)); // prem\n list.add("ram");\n list=null;\n System.out.println(list.add("bheem")); //gets NullPointerException\n }\n}\n</code></pre>\n"
},
{
"answer_id": 48591063,
"author": "Felypp Oliveira",
"author_id": 1977836,
"author_profile": "https://Stackoverflow.com/users/1977836",
"pm_score": 5,
"selected": false,
"text": "<p>This is the best way to answer the question imo...</p>\n\n<p>First, we must understand that, in Java, the <em>parameter passing behavior</em>...</p>\n\n<pre><code>public void foo(Object param)\n{\n // some code in foo...\n}\n\npublic void bar()\n{\n Object obj = new Object();\n\n foo(obj);\n}\n</code></pre>\n\n<p>is exactly the same as...</p>\n\n<pre><code>public void bar()\n{\n Object obj = new Object();\n\n Object param = obj;\n\n // some code in foo...\n}\n</code></pre>\n\n<p>not considering stack locations, which aren't relevant in this discussion.</p>\n\n<p>So, in fact, what we're looking for in Java is how <em>variable assignment</em> works. I found it in <a href=\"https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html\" rel=\"noreferrer\">the docs</a> :</p>\n\n<blockquote>\n <p>One of the most common operators that you'll encounter is the simple assignment operator \"=\" [...] <b>it assigns the value</b> on its right to the operand on its left:</p>\n \n <p>int cadence = 0;<br>\n int speed = 0;<br>\n int gear = 1; </p>\n \n <p>This operator can also be used on objects to assign <b>object references</b> [...]</p>\n</blockquote>\n\n<p>It's clear how this operator acts in two distinct ways: assign values and assign references. The last, when it's an object... the first, when it isn't an object, that is, when it's a primitive. But so, can we understand that Java's function params can be <em>pass-by-value</em> and <em>pass-by-reference</em>? </p>\n\n<p>The truth is in the code. Let's try it:</p>\n\n<pre><code>public class AssignmentEvaluation\n{\n static public class MyInteger\n {\n public int value = 0;\n }\n\n static public void main(String[] args)\n {\n System.out.println(\"Assignment operator evaluation using two MyInteger objects named height and width\\n\");\n\n MyInteger height = new MyInteger();\n MyInteger width = new MyInteger();\n\n System.out.println(\"[1] Assign distinct integers to height and width values\");\n\n height.value = 9;\n width.value = 1;\n\n System.out.println(\"-> height is \" + height.value + \" and width is \" + width.value + \", we are different things! \\n\");\n\n System.out.println(\"[2] Assign to height's value the width's value\");\n\n height.value = width.value;\n\n System.out.println(\"-> height is \" + height.value + \" and width is \" + width.value + \", are we the same thing now? \\n\");\n\n System.out.println(\"[3] Assign to height's value an integer other than width's value\");\n\n height.value = 9;\n\n System.out.println(\"-> height is \" + height.value + \" and width is \" + width.value + \", we are different things yet! \\n\");\n\n System.out.println(\"[4] Assign to height the width object\");\n\n height = width;\n\n System.out.println(\"-> height is \" + height.value + \" and width is \" + width.value + \", are we the same thing now? \\n\");\n\n System.out.println(\"[5] Assign to height's value an integer other than width's value\");\n\n height.value = 9;\n\n System.out.println(\"-> height is \" + height.value + \" and width is \" + width.value + \", we are the same thing now! \\n\");\n\n System.out.println(\"[6] Assign to height a new MyInteger and an integer other than width's value\");\n\n height = new MyInteger();\n height.value = 1;\n\n System.out.println(\"-> height is \" + height.value + \" and width is \" + width.value + \", we are different things again! \\n\");\n }\n}\n</code></pre>\n\n<p>This is the output of my run:</p>\n\n<pre>\nAssignment operator evaluation using two MyInteger objects named height and width\n\n[1] Assign distinct integers to height and width values\n-> height is 9 and width is 1, we are different things! \n\n[2] Assign to height's value the width's value\n-> height is 1 and width is 1, are we the same thing now? \n\n[3] Assign to height's value an integer other than width's value\n-> height is 9 and width is 1, we are different things yet! \n\n[4] Assign to height the width object\n-> height is 1 and width is 1, are we the same thing now? \n\n[5] Assign to height's value an integer other than width's value\n-> height is 9 and width is 9, we are the same thing now! \n\n[6] Assign to height a new MyInteger and an integer other than width's value\n-> height is 1 and width is 9, we are different things again! \n</pre>\n\n<p>In <em>[2]</em> we have distinct objects and assign one variable's value to the other. But after assigning a new value in <em>[3]</em> the objects had different values, which means that in <em>[2]</em> the assigned value was a copy of the primitive variable, usually called <strong>pass-by-value</strong>, otherwise, the values printed in <em>[3]</em> should be the same.</p>\n\n<p>In <em>[4]</em> we still have distinct objects and assign one object to the other. And after assigning a new value in <em>[5]</em> the objects had the same values, which means that in <em>[4]</em> the assigned object was not a copy of the other, which should be called <strong>pass-by-reference</strong>. But, if we look carefully in <em>[6]</em>, we can't be so sure that no copy was done... ?????</p>\n\n<p>We can't be so sure because in <em>[6]</em> the objects were the same, then we assigned a new object to one of them, and after, the objects had different values! How can they be distinct now if they were the same? They should be the same here too! ?????</p>\n\n<p>We'll need to remember <a href=\"https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html\" rel=\"noreferrer\">the docs</a> to understand what's going on:</p>\n\n<blockquote>\n <p>This operator can also be used on objects to assign <b>object references</b></p>\n</blockquote>\n\n<p>So our two variables were storing references... our variables had the same reference after <em>[4]</em> and different references after <em>[6]</em>... if such a thing is possible, this means that assignment of objects is done by copy of the object's reference, otherwise, if it was not a copy of reference, the printed value of the variables in <em>[6]</em> should be the same. So objects (references), just like primitives, are copied to variables through assignment, what people usually call <em>pass-by-value</em>. That's the only <em>pass-by-</em> in Java.</p>\n"
},
{
"answer_id": 49330809,
"author": "mc01",
"author_id": 3216970,
"author_profile": "https://Stackoverflow.com/users/3216970",
"pm_score": 3,
"selected": false,
"text": "<h2>PT 1: Of Realty Listings</h2>\n<p>There is a blue, 120sq-ft "Tiny House" currently parked at 1234 Main St with a nicely manicured lawn & flower bed out front.</p>\n<p>A Realtor with a local firm is hired and told to keep a listing for that house.</p>\n<p>Let's call that Realtor "Bob." Hi Bob.</p>\n<p>Bob keeps his Listing, which he calls <code>tinyHouseAt1234Main</code>, up to date with a webcam that allows him to note any changes to the actual house in real time. He also keeps a tally of how many people have asked about the listing.\nBob's integer <code>viewTally</code> for the house is at 42 today.</p>\n<p>Whenever someone wants info about the blue Tiny House at 1234 Main St, they ask Bob.</p>\n<p>Bob looks up his Listing <code>tinyHouseAt1234Main</code> and tells them all about it - the color, the nice lawn, the loft bed and the composting toilet, etc. Then he adds their inquiry to his <code>viewTally</code>. He doesn't tell them the real, physical address though, because Bob's firm specializes in Tiny Houses that could be moved at any time. The tally is now 43.</p>\n<p>At another firm, Realtors might explicitly say their listing "points" to the house at 1234 Main St, denoting this with a little <code>*</code> next to it, because they mainly deal with houses that rarely ever move (though presumably there are reasons for doing so). Bob's firm doesn't bother doing this.</p>\n<p>Now, of course Bob doesn't physically go and put the <em>actual</em> house on a truck to show it to clients directly - that would be impractical and a ridiculous waste of resources. Passing a full copy of his tally sheet is one thing, but passing around the whole house all the time is costly and ridiculous.</p>\n<p>(Aside: Bob's firm also doesn't 3D print new & unique copies of a listed house every single time someone asks about it. That's what the upstart, similarly named web-based firm & its spinoffs do - that's expensive and slower, and people often get the 2 firms confused, but they're quite popular anyway).</p>\n<p>At some other, older firms closer to the Sea, a realtor like Bob might not even exist to manage the Listings. Clients might instead consult the Rolodex "Annie" (<code>&</code> for short) for the direct address of the house. Instead of reading off the referenced house details from the listing like Bob does, clients instead get the house address from Annie (<code>&</code>), and go directly to 1234 Main St, sometimes w/no idea what they might find there.</p>\n<p>One day, Bob's firm begins offering a new automated service that needs the listing for a house the client is interested in.</p>\n<p>Well, the person with that info is Bob, so the client has Bob call up the service and send it a copy of the listing.</p>\n<p><code>jobKillingAutomatedListingService(Listing tinyHouseAt1234Main, int viewTally)</code> Bob sends along ...</p>\n<p>The service, on its end, calls this Listing <code>houseToLookAt</code>, but really what it receives is an exact copy of Bob's listing, with the exact same VALUEs in it, that refer to the house at 1234 Main St.</p>\n<p>This new service also has its own internal tally of how many people have viewed the listing. The service accepts Bob's tally out of professional courtesy, but it doesn't really care and overwrites it entirely with its own local copy anyway. It's tally for today is 1, while Bob's is still 43.</p>\n<p>The realty firms call this "pass-by-value" since Bob's passing the current value of his <code>viewTally</code> and his Listing <code>tinyHouseAt1234Main</code>. He's not actually passing along the entire physical house, because that's impractical. Nor is he passing the real physical address like Annie(<code>&</code>) would do.</p>\n<p>But he IS passing a copy of <em>the value OF</em> the reference he has to the house. Seems like a silly pedantic difference in some ways, but that's how his firm works ...\n..............</p>\n<h2>PT II: Where things get confusing and dangerous ...</h2>\n<p>The new automated service, not being all functional and math-oriented like some other trendy financial & scientific firms, can have unforeseen side effects...</p>\n<p>Once given a Listing object it allows clients to <em>actually</em> repaint the REAL house at 1234 Main St, using a remote drone robot fleet! It allows clients to control a robot bulldozer to ACTUALLY dig up the flower bed! This is madness!!!</p>\n<p>The service also lets clients completely redirect <code>houseToLookAt</code> to some other house at another address, without involving Bob or his listing. All of a sudden they could be looking at 4321 Elm St. instead, which has no connection whatsoever to Bob's listing (thankfully they can't do anymore damage).</p>\n<p>Bob watches all this on his realtime webcam.\nResigned to the drudgery of his sole job responsibility, he tells clients about the new ugly paint job & sudden lack of curb appeal. His Listing <em>is</em> still for 1234 Main St., after all. The new service's <code>houseToLookAt</code> couldn't change that. Bob reports the details of his <code>tinyHouseAt1234Main</code> accurately and dutifully as always, until he gets fired or the house is destroyed entirely by The Nothing.</p>\n<p>Really the only thing the service CAN'T do with its <code>houseToLookAt</code> copy of the Bob's original listing is change the address from 1234 Main St. to some other address, or to a void of nothingness, or to some random type of object like a Platypus. Bob's Listing still always points to 1234 Main St, for whatever it's still worth. He passes its current value around like always.</p>\n<p>This bizarre side-effect of passing a listing to the new automated service is confusing for people who ask about how it works. Really, what's the difference between the ability to remotely control robots that alter the state of the house at 1234 Main, vs. <em>actually</em> physically going there and wreaking havoc because Annie gave you the address??</p>\n<p>Seems like kind of a nitpicky semantic argument if what you generally care about is the <em>state</em> of the house in the listing being copied and passed around, right?</p>\n<p>I mean, if you were in the business of actually picking up houses and physically moving them to other addresses (not like mobile or Tiny Homes where that's sort of an expected function of the platform), or you were accessing, renaming, and shuffling entire neighborhoods like some sort of low-level God-playing madman, THEN maybe you'd care more about passing around those specific address references instead of just copies of the the latest value of the house details ...</p>\n"
},
{
"answer_id": 49640653,
"author": "Michael",
"author_id": 4109266,
"author_profile": "https://Stackoverflow.com/users/4109266",
"pm_score": 5,
"selected": false,
"text": "<p>Unlike some other languages, Java does not allow you to choose between pass-by-value and pass-by-reference—all arguments are passed by value. A method call can pass two types of values to a method—copies of primitive values (e.g., values of int and double) and copies of references to objects.</p>\n\n<p>When a method modifies a primitive-type parameter, changes to the parameter have no effect on the original argument value in the calling method.</p>\n\n<p>When it comes to objects, objects themselves cannot be passed to methods. So we pass the reference(address) of the object. We can manipulate the original object using this reference.</p>\n\n<p><strong>How Java creates and stores objects:</strong> When we create an object we store the object’s address in a reference variable. Let's analyze the following statement.</p>\n\n<pre><code>Account account1 = new Account();\n</code></pre>\n\n<p>“Account account1” is the type and name of the reference variable, “=” is the assignment operator, “new” asks for the required amount of space from the system. The constructor to the right of keyword new which creates the object is called implicitly by the keyword new. Address of the created object(result of right value, which is an expression called \"class instance creation expression\") is assigned to the left value (which is a reference variable with a name and a type specified) using the assign operator.</p>\n\n<p>Although an object’s reference is passed by value, a method can still interact with the referenced object by calling its public methods using the copy of the object’s reference. Since the reference stored in the parameter is a copy of the reference that was passed as an argument, the parameter in the called method and the argument in the calling method refer to the same object in memory.</p>\n\n<p>Passing references to arrays, instead of the array objects themselves, makes sense for performance reasons. Because everything in Java is passed by value, if array objects were passed,\na copy of each element would be passed. For large arrays, this would waste time and consume\nconsiderable storage for the copies of the elements.</p>\n\n<p>In the image below you can see we have two reference variables(These are called pointers in C/C++, and I think that term makes it easier to understand this feature.) in the main method. Primitive and reference variables are kept in stack memory(left side in images below). array1 and array2 reference variables \"point\" (as C/C++ programmers call it) or reference to a and b arrays respectively, which are objects (values these reference variables hold are addresses of objects) in heap memory (right side in images below).</p>\n\n<p><a href=\"https://i.stack.imgur.com/sF7QZ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/sF7QZ.png\" alt=\"Pass by value example 1\"></a></p>\n\n<p>If we pass the value of array1 reference variable as an argument to the reverseArray method, a reference variable is created in the method and that reference variable starts pointing to the same array (a). </p>\n\n<pre><code>public class Test\n{\n public static void reverseArray(int[] array1)\n {\n // ...\n }\n\n public static void main(String[] args)\n {\n int[] array1 = { 1, 10, -7 };\n int[] array2 = { 5, -190, 0 };\n\n reverseArray(array1);\n }\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/W1wgZ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/W1wgZ.png\" alt=\"Pass by value example 2\"></a></p>\n\n<p>So, if we say </p>\n\n<pre><code>array1[0] = 5;\n</code></pre>\n\n<p>in reverseArray method, it will make a change in array a.</p>\n\n<p>We have another reference variable in reverseArray method (array2) that points to an array c. If we were to say </p>\n\n<pre><code>array1 = array2;\n</code></pre>\n\n<p>in reverseArray method, then the reference variable array1 in method reverseArray would stop pointing to array a and start pointing to array c (Dotted line in second image).</p>\n\n<p>If we return value of reference variable array2 as the return value of method reverseArray and assign this value to reference variable array1 in main method, array1 in main will start pointing to array c.</p>\n\n<p>So let's write all the things we have done at once now.</p>\n\n<pre><code>public class Test\n{\n public static int[] reverseArray(int[] array1)\n {\n int[] array2 = { -7, 0, -1 };\n\n array1[0] = 5; // array a becomes 5, 10, -7\n\n array1 = array2; /* array1 of reverseArray starts\n pointing to c instead of a (not shown in image below) */\n return array2;\n }\n\n public static void main(String[] args)\n {\n int[] array1 = { 1, 10, -7 };\n int[] array2 = { 5, -190, 0 };\n\n array1 = reverseArray(array1); /* array1 of \n main starts pointing to c instead of a */\n }\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/5hRyX.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/5hRyX.png\" alt=\"enter image description here\"></a></p>\n\n<p>And now that reverseArray method is over, its reference variables(array1 and array2) are gone. Which means we now only have the two reference variables in main method array1 and array2 which point to c and b arrays respectively. No reference variable is pointing to object (array) a. So it is eligible for garbage collection.</p>\n\n<p>You could also assign value of array2 in main to array1. array1 would start pointing to b.</p>\n"
},
{
"answer_id": 50391764,
"author": "asok",
"author_id": 5092157,
"author_profile": "https://Stackoverflow.com/users/5092157",
"pm_score": 3,
"selected": false,
"text": "<p>Java is only passed by value. there is no pass by reference, for example, you can see the following example.</p>\n\n<pre><code>package com.asok.cop.example.task;\npublic class Example {\n int data = 50;\n\n void change(int data) {\n data = data + 100;// changes will be in the local variable \n System.out.println(\"after add \" + data);\n }\n\n public static void main(String args[]) {\n Example op = new Example();\n System.out.println(\"before change \" + op.data);\n op.change(500);\n System.out.println(\"after change \" + op.data);\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>before change 50\nafter add 600\nafter change 50\n</code></pre>\n\n<p>as Michael says in the comments:</p>\n\n<blockquote>\n <p>objects are still passed by value even though operations on them behave like pass-by-reference. Consider <code>void changePerson(Person person){ person = new Person(); }</code> the callers reference to the person object will remain unchanged. Objects themselves are passed by value but their members can be affected by changes. To be true pass-by-reference, we would have to be able to reassign the argument to a new object and have the change be reflected in the caller.</p>\n</blockquote>\n"
},
{
"answer_id": 51522896,
"author": "georgeawg",
"author_id": 5535245,
"author_profile": "https://Stackoverflow.com/users/5535245",
"pm_score": 4,
"selected": false,
"text": "<h2>Java passes primitive types by value and class types by reference</h2>\n\n<p>Now, people like to bicker endlessly about whether \"pass by reference\" is the correct way to describe what Java et al. actually do. The point is this:</p>\n\n<ol>\n<li>Passing an object does not copy the object.</li>\n<li>An object passed to a function can have its members modified by the function.</li>\n<li>A primitive value passed to a function cannot be modified by the function. A copy is made.</li>\n</ol>\n\n<p>In my book that's called passing by reference.</p>\n\n<p>— <a href=\"https://www.quora.com/profile/Brian-Bi\" rel=\"noreferrer\">Brian Bi</a> - <a href=\"https://www.quora.com/Which-programming-languages-are-pass-by-reference#\" rel=\"noreferrer\">Which programming languages are pass by reference?</a></p>\n"
},
{
"answer_id": 54373107,
"author": "Sanjeev",
"author_id": 1028560,
"author_profile": "https://Stackoverflow.com/users/1028560",
"pm_score": 7,
"selected": false,
"text": "<p>There are already great answers that cover this. I wanted to make a small contribution by sharing a <strong>very simple example</strong> (which will compile) contrasting the behaviors between Pass-by-reference in c++ and Pass-by-value in Java.</p>\n<p>A few points:</p>\n<ol>\n<li>The term "reference" is a overloaded with two separate meanings. In Java it simply means a pointer, but in the context of "Pass-by-reference" it means a handle to the original variable which was passed in.</li>\n<li><strong>Java is Pass-by-value</strong>. Java is a descendent of C (among other languages). Before C, several (but not all) earlier languages like FORTRAN and COBOL supported PBR, but C did not. PBR allowed these other languages to make changes to the passed variables inside sub-routines. In order to accomplish the same thing (i.e. change the values of variables inside functions), C programmers passed pointers to variables into functions. Languages inspired by C, such as Java, borrowed this idea and continue to pass pointer to methods as C did, except that Java calls its pointers References. Again, this is a different use of the word "Reference" than in "Pass-By-Reference".</li>\n<li><strong>C++ allows Pass-by-reference</strong> by declaring a reference parameter using the "&" character (which happens to be the same character used to indicate "the address of a variable" in both C and C++). For example, if we pass in a pointer by reference, the parameter and the argument are not just pointing to the same object. Rather, they are the same variable. If one gets set to a different address or to null, so does the other.</li>\n<li>In the C++ example below I'm passing a <strong>pointer</strong> to a null terminated string <strong>by reference</strong>. And in the Java example below I'm passing a Java reference to a String (again, the same as a pointer to a String) by value. Notice the output in the comments.</li>\n</ol>\n<p>C++ pass by reference example:</p>\n<pre><code>using namespace std;\n#include <iostream>\n\nvoid change (char *&str){ // the '&' makes this a reference parameter\n str = NULL;\n}\n\nint main()\n{\n char *str = "not Null";\n change(str);\n cout<<"str is " << str; // ==>str is <null>\n}\n</code></pre>\n<p>Java pass "a Java reference" by value example</p>\n<pre><code>public class ValueDemo{\n \n public void change (String str){\n str = null;\n }\n\n public static void main(String []args){\n ValueDemo vd = new ValueDemo();\n String str = "not null";\n vd.change(str);\n System.out.println("str is " + str); // ==> str is not null!!\n // Note that if "str" was\n // passed-by-reference, it\n // WOULD BE NULL after the\n // call to change().\n }\n}\n</code></pre>\n<p><strong>EDIT</strong></p>\n<p>Several people have written comments which seem to indicate that either they are not looking at my examples or they don't get the c++ example. Not sure where the disconnect is, but guessing the c++ example is not clear. I'm posting the same example in pascal because I think pass-by-reference looks cleaner in pascal, but I could be wrong. I might just be confusing people more; I hope not.</p>\n<p>In pascal, parameters passed-by-reference are called "var parameters". In the procedure setToNil below, please note the keyword 'var' which precedes the parameter 'ptr'. When a pointer is passed to this procedure, it will be passed <strong>by reference</strong>. Note the behavior: when this procedure sets ptr to nil (that's pascal speak for NULL), it will set the argument to nil--you can't do that in Java.</p>\n<pre><code>program passByRefDemo;\ntype \n iptr = ^integer;\nvar\n ptr: iptr;\n \n procedure setToNil(var ptr : iptr);\n begin\n ptr := nil;\n end;\n\nbegin\n new(ptr);\n ptr^ := 10;\n setToNil(ptr);\n if (ptr = nil) then\n writeln('ptr seems to be nil'); { ptr should be nil, so this line will run. }\nend.\n</code></pre>\n<p><strong>EDIT 2</strong></p>\n<p>Some excerpts from <strong>"THE Java Programming Language"</strong> by Ken Arnold, <strong>James Gosling (the guy who invented Java)</strong>, and David Holmes, chapter 2, section 2.6.5</p>\n<blockquote>\n<p><strong>All parameters to methods are passed "by value"</strong>. In other words,\nvalues of parameter variables in a method are copies of the invoker\nspecified as arguments.</p>\n</blockquote>\n<p>He goes on to make the same point regarding objects . . .</p>\n<blockquote>\n<p>You should note that when the parameter is an object reference, it is\nthe object reference-not the object itself-that is <strong>passed "by value"</strong>.</p>\n</blockquote>\n<p>And towards the end of the same section he makes a broader statement about java being only pass by value and never pass by reference.</p>\n<blockquote>\n<p>The Java programming language <strong>does not pass objects by reference; it</strong>\n<strong>passes object references by value</strong>. Because two copies of the same\nreference refer to the same actual object, changes made through one\nreference variable are visible through the other. There is exactly one\nparameter passing mode-<strong>pass by value</strong>-and that helps keep things\nsimple.</p>\n</blockquote>\n<p>This section of the book has a great explanation of parameter passing in Java and of the distinction between pass-by-reference and pass-by-value and it's by the creator of Java. I would encourage anyone to read it, especially if you're still not convinced.</p>\n<p>I think the difference between the two models is very subtle and unless you've done programming where you actually used pass-by-reference, it's easy to miss where two models differ.</p>\n<p>I hope this settles the debate, but probably won't.</p>\n<p><strong>EDIT 3</strong></p>\n<p>I might be a little obsessed with this post. Probably because I feel that the makers of Java inadvertently spread misinformation. If instead of using the word "reference" for pointers they had used something else, say\ndingleberry, there would've been no problem. You could say, "Java passes dingleberries by value and not by reference", and nobody would be confused.</p>\n<p>That's the reason only Java developers have issue with this. They look at the word "reference" and think they know exactly what that means, so they don't even bother to consider the opposing argument.</p>\n<p>Anyway, I noticed a comment in an older post, which made a balloon analogy which I really liked. So much so that I decided to glue together some clip-art to make a set of cartoons to illustrate the point.</p>\n<p><strong>Passing a reference by value</strong>--Changes to the reference are not reflected in the caller's scope, but the changes to the object are. This is because the reference is copied, but the both the original and the copy refer to the same object.\n<a href=\"https://i.stack.imgur.com/RvkqU.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/RvkqU.png\" alt=\"Passing Object references By Value\" /></a></p>\n<p><strong>Pass by reference</strong>--There is no copy of the reference. Single reference is shared by both the caller and the function being called. Any changes to the reference or the Object's data are reflected in the caller's scope.\n<a href=\"https://i.stack.imgur.com/SHXkC.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/SHXkC.png\" alt=\"Pass by reference\" /></a></p>\n<p><strong>EDIT 4</strong></p>\n<p>I have seen posts on this topic which describe the low level implementation of parameter passing in Java, which I think is great and very helpful because it makes an abstract idea concrete. However, to me the question is more about <strong>the behavior described in the language specification</strong> than about the technical implementation of the behavior. This is an exerpt from the <a href=\"https://docs.oracle.com/javase/specs/jls/se19/html/jls-8.html#jls-8.4.1\" rel=\"noreferrer\">Java Language Specification, section 8.4.1</a> :</p>\n<blockquote>\n<p>When the method or constructor is invoked (§15.12), <strong>the values of the\nactual argument expressions initialize newly created parameter\nvariables, each of the declared type, before execution of the body of\nthe method or constructor.</strong> The Identifier that appears in the\nDeclaratorId may be used as a simple name in the body of the method or\nconstructor to refer to the formal parameter.</p>\n</blockquote>\n<p>Which means, java creates a copy of the passed parameters before executing a method. Like most people who studied compilers in college, I used <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201100886\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">"The Dragon Book"</a> which is <strong>THE</strong> compilers book. It has a good description of "Call-by-value" and "Call-by-Reference" in Chapter 1. The Call-by-value description matches up with Java Specs exactly.</p>\n<p>Back when I studied compilers-in the 90's, I used the first edition of the book from 1986 which pre-dated Java by about 9 or 10 years. However, I just ran across a copy of the <a href=\"https://rads.stackoverflow.com/amzn/click/com/B009TGD06W\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">2nd Eddition</a> from 2007 <strong>which actually mentions Java!</strong> Section 1.6.6 labeled "Parameter Passing Mechanisms" describes parameter passing pretty nicely. Here is an excerpt under the heading "Call-by-value" which mentions Java:</p>\n<blockquote>\n<p>In call-by-value, the actual parameter is evaluated (if it is an\nexpression) or copied (if it is a variable). The value is placed in\nthe location belonging to the corresponding formal parameter of the\ncalled procedure. <strong>This method is used in C and Java, and is a common\noption in C++ , as well as in most other languages.</strong></p>\n</blockquote>\n"
},
{
"answer_id": 55923549,
"author": "moldovean",
"author_id": 959876,
"author_profile": "https://Stackoverflow.com/users/959876",
"pm_score": 4,
"selected": false,
"text": "<p>Long story short: </p>\n\n<ol>\n<li>Non-primitives: Java passes the <em>Value of the Reference</em>. </li>\n<li>Primitives: just value. </li>\n</ol>\n\n<p>The End.</p>\n\n<p>(2) is too easy. Now if you want to think of what (1) implies, imagine you have a class Apple:</p>\n\n<pre><code>class Apple {\n private double weight;\n public Apple(double weight) {\n this.weight = weight;\n }\n // getters and setters ...\n\n}\n</code></pre>\n\n<p>then when you pass an instance of this class to the main method:</p>\n\n<pre><code>class Main {\n public static void main(String[] args) {\n Apple apple = new Apple(3.14);\n transmogrify(apple);\n System.out.println(apple.getWeight()+ \" the goose drank wine...\";\n\n }\n\n private static void transmogrify(Apple apple) {\n // does something with apple ...\n apple.setWeight(apple.getWeight()+0.55);\n }\n}\n</code></pre>\n\n<p>oh.. but you probably know that, you're interested in what happens when you do something like this:</p>\n\n<pre><code>class Main {\n public static void main(String[] args) {\n Apple apple = new Apple(3.14);\n transmogrify(apple);\n System.out.println(\"Who ate my: \"+apple.getWeight()); // will it still be 3.14? \n\n }\n\n private static void transmogrify(Apple apple) {\n // assign a new apple to the reference passed...\n apple = new Apple(2.71);\n }\n\n\n}\n</code></pre>\n"
},
{
"answer_id": 57068881,
"author": "Amit Sharma",
"author_id": 9892438,
"author_profile": "https://Stackoverflow.com/users/9892438",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Java passes parameters by value, There is no option of passing a reference in Java.</strong></p>\n\n<p>But at the complier binding level layer, It uses reference internally not exposed to the user.</p>\n\n<p>It is essential as it saves a lot of memory and improves speed.</p>\n"
},
{
"answer_id": 57229012,
"author": "natwar kumar",
"author_id": 3957354,
"author_profile": "https://Stackoverflow.com/users/3957354",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public class Test {\n\n static class Dog {\n String name;\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((name == null) ? 0 : name.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n Dog other = (Dog) obj;\n if (name == null) {\n if (other.name != null)\n return false;\n } else if (!name.equals(other.name))\n return false;\n return true;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String nb) {\n this.name = nb;\n }\n\n Dog(String sd) {\n this.name = sd;\n }\n }\n /**\n * \n * @param args\n */\n public static void main(String[] args) {\n Dog aDog = new Dog(\"Max\");\n\n // we pass the object to foo\n foo(aDog);\n Dog oldDog = aDog;\n\n System.out.println(\" 1: \" + aDog.getName().equals(\"Max\")); // false\n System.out.println(\" 2 \" + aDog.getName().equals(\"huahua\")); // false\n System.out.println(\" 3 \" + aDog.getName().equals(\"moron\")); // true\n System.out.println(\" 4 \" + \" \" + (aDog == oldDog)); // true\n\n // part2\n Dog aDog1 = new Dog(\"Max\");\n\n foo(aDog1, 5);\n Dog oldDog1 = aDog;\n\n System.out.println(\" 5 : \" + aDog1.getName().equals(\"huahua\")); // true\n System.out.println(\" part2 : \" + (aDog1 == oldDog1)); // false\n\n Dog oldDog2 = foo(aDog1, 5, 6);\n System.out.println(\" 6 \" + (aDog1 == oldDog2)); // true\n System.out.println(\" 7 \" + (aDog1 == oldDog)); // false\n System.out.println(\" 8 \" + (aDog == oldDog2)); // false\n }\n\n /**\n * \n * @param d\n */\n public static void foo(Dog d) {\n System.out.println(d.getName().equals(\"Max\")); // true\n\n d.setName(\"moron\");\n\n d = new Dog(\"huahua\");\n System.out.println(\" -:- \" + d.getName().equals(\"huahua\")); // true\n }\n\n /**\n * \n * @param d\n * @param a\n */\n public static void foo(Dog d, int a) {\n d.getName().equals(\"Max\"); // true\n\n d.setName(\"huahua\");\n }\n\n /**\n * \n * @param d\n * @param a\n * @param b\n * @return\n */\n public static Dog foo(Dog d, int a, int b) {\n d.getName().equals(\"Max\"); // true\n d.setName(\"huahua\");\n return d;\n }\n}\n</code></pre>\n\n<p>The sample code to demonstrate the impact of changes to the object at different functions . </p>\n"
},
{
"answer_id": 57616177,
"author": "grindlewald",
"author_id": 10240338,
"author_profile": "https://Stackoverflow.com/users/10240338",
"pm_score": 3,
"selected": false,
"text": "<p>First let's understand Memory allocation in Java:\nStack and Heap are part of Memory that JVM allocates for different purposes. The stack memory is pre-allocated to thread, when it is created, therefore, a thread cannot access the Stack of other thread. But Heap is available to all threads in a program.</p>\n\n<p>For a thread, Stack stores all local data, metadata of program, primitive type data and object reference. And, Heap is responsible for storage of actual object.</p>\n\n<pre><code>Book book = new Book(\"Effective Java\");\n</code></pre>\n\n<p>In the above example, the reference variable is \"book\" which is stored in stack. The instance created by new operator -> new Book(\"Effective Java\") is stored in Heap. The ref variable \"book\" has address of the object allocated in Heap. Let's say the address is 1001.</p>\n\n<p><a href=\"https://i.stack.imgur.com/uw7tE.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/uw7tE.png\" alt=\"enter image description here\"></a></p>\n\n<p>Consider passing a primitive data type i.e. int, float, double etc.</p>\n\n<pre><code>public class PrimitiveTypeExample { \n public static void main(string[] args) {\n int num = 10;\n System.out.println(\"Value before calling method: \" + num);\n printNum(num);\n System.out.println(\"Value after calling method: \" + num);\n }\n public static void printNum(int num){\n num = num + 10;\n System.out.println(\"Value inside printNum method: \" + num);\n }\n}\n</code></pre>\n\n<p>Output is:\nValue before calling method: 10\nValue inside printNum method: 20\nValue after calling method: 10</p>\n\n<p>int num =10; -> this allocates the memory for \"int\" in Stack of the running thread, because, it is a primitive type. Now when printNum(..) is called, a private stack is created within the same thread. When \"num\" is passed to this method, a copy of \"num\" is created in the method stack frame.\nnum = num+10; -> this adds 10 and modifies the the int variable within the method stack frame.\nTherefore, the original num outside the method stack frame remains unchanged.</p>\n\n<p>Consider, the example of passing the object of a custom class as an argument.</p>\n\n<p><a href=\"https://i.stack.imgur.com/J1XRW.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/J1XRW.png\" alt=\"enter image description here\"></a></p>\n\n<p>In the above example, ref variable \"book\" resides in stack of thread executing the program, and the object of class Book is created in Heap space when program executes new Book(). This memory location in Heap is referred by \"book\". When \"book\" is passed as method argument, a copy of \"book\" is created in private stack frame of method within the same stack of thread. Therefore, the copied reference variable points to the same object of class \"Book\" in the Heap.</p>\n\n<p><a href=\"https://i.stack.imgur.com/ggqd5.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ggqd5.png\" alt=\"enter image description here\"></a></p>\n\n<p>The reference variable within method stack frame sets a new value to same object. Therefore, it is reflected when original ref variable \"book\" gets its value.\nNote that in case of passing reference variable, if it is initialized again in called method, it then points to new memory location and any operation does not affect the previous object in the Heap.</p>\n\n<p>Therefore, when anything is passed as method argument, it is always the Stack entity - either primitive or reference variable. We never pass something that is stored in Heap. Hence, in Java, we always pass the value in the stack, and it is pass by value.</p>\n"
},
{
"answer_id": 58038425,
"author": "Rose",
"author_id": 11725130,
"author_profile": "https://Stackoverflow.com/users/11725130",
"pm_score": 2,
"selected": false,
"text": "<p>I think this simple explanation might help you understand as I wanted to understand this same thing when I was struggling through this.</p>\n\n<p>When you pass a primitive data to a function call it's content is being copied to the function's argument and when you pass an object it's reference is being copied to the function's argument. Speaking of object, you can't change the copied reference-<em>the argument variable is referencing to</em> in the calling function.</p>\n\n<p>Consider this simple example, String is an object in java and when you change the content of a string the reference variable will now point to some new reference as String objects are immutable in java.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>String name=\"Mehrose\"; // name referencing to 100\n\nChangeContenet(String name){\n name=\"Michael\"; // refernce has changed to 1001\n\n} \nSystem.out.print(name); //displays Mehrose\n</code></pre>\n\n<p>Fairly simple because as I mentioned you are not allowed to change the copied reference in the calling function. But the problem is with the array when you pass an array of String/Object. Let us see.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>String names[]={\"Mehrose\",\"Michael\"};\n\nchangeContent(String[] names){\n names[0]=\"Rose\";\n names[1]=\"Janet\"\n\n}\n\nSystem.out.println(Arrays.toString(names)); //displays [Rose,Janet]\n</code></pre>\n\n<p>As we said that we can't change the copied reference in the function call and we also have seen in the case of a single String object. The reason is names[] variable referencing to let's say 200 and names[0] referencing to 205 and so on. You see we didn't change the names[] reference it still points to the old same reference still after the function call but now names[0] and names[1] reference has been changed. We Still stand on our definition that we can't change the reference variable's reference so we didn't.</p>\n\n<p>The same thing happens when you pass a Student object to a method and you are still able to change the Student name or other attributes, the point is we are not changing the actual Student object rather we are changing the contents of it</p>\n\n<p>You can't do this</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Student student1= new Student(\"Mehrose\");\n\nchangeContent(Student Obj){\n obj= new Student(\"Michael\") //invalid\n obj.setName(\"Michael\") //valid\n\n}\n</code></pre>\n"
},
{
"answer_id": 58704042,
"author": "DeC",
"author_id": 7888956,
"author_profile": "https://Stackoverflow.com/users/7888956",
"pm_score": 3,
"selected": false,
"text": "<p>A: Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.</p>\n\n<p>Take the badSwap() method for example:</p>\n\n<pre><code>public void badSwap(int var1, int var2)\n{\n int temp = var1;\n var1 = var2;\n var2 = temp;\n}\n</code></pre>\n\n<p>When badSwap() returns, the variables passed as arguments will still hold their original values. The method will also fail if we change the arguments type from int to Object, since Java passes object references by value as well. Now, here is where it gets tricky:</p>\n\n<pre><code>public void tricky(Point arg1, Point arg2)\n{\n arg1.x = 100;\n arg1.y = 100;\n Point temp = arg1;\n arg1 = arg2;\n arg2 = temp;\n}\npublic static void main(String [] args)\n{\n Point pnt1 = new Point(0,0);\n Point pnt2 = new Point(0,0);\n System.out.println(\"X: \" + pnt1.x + \" Y: \" +pnt1.y); \n System.out.println(\"X: \" + pnt2.x + \" Y: \" +pnt2.y);\n System.out.println(\" \");\n tricky(pnt1,pnt2);\n System.out.println(\"X: \" + pnt1.x + \" Y:\" + pnt1.y); \n System.out.println(\"X: \" + pnt2.x + \" Y: \" +pnt2.y); \n}\n</code></pre>\n\n<p>If we execute this main() method, we see the following output:</p>\n\n<pre><code>X: 0 Y: 0\nX: 0 Y: 0\nX: 100 Y: 100\nX: 0 Y: 0\n</code></pre>\n\n<p>The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. Figure 1 below shows two references pointing to the same object after Java passes an object to a method.</p>\n\n<p><a href=\"https://i.stack.imgur.com/wLEj7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wLEj7.png\" alt=\"enter image description here\"></a><br>\nFigure 1. After being passed to a method, an object will have at least two references</p>\n\n<p>Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail.The method references swap, but not the original references. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.</p>\n"
},
{
"answer_id": 60141523,
"author": "Mr.Robot",
"author_id": 5486740,
"author_profile": "https://Stackoverflow.com/users/5486740",
"pm_score": 4,
"selected": false,
"text": "<p>I see that all answers contain the same: pass by value. However, a recent Brian Goetz update on project Valhalla actually answers it differently:</p>\n<blockquote>\n<p>Indeed, it is a common “gotcha” question about whether Java objects are passed by value or by reference, and <strong>the answer is “neither”: object references are passed by value.</strong></p>\n</blockquote>\n<p>You can read more here: <a href=\"http://cr.openjdk.java.net/%7Ebriangoetz/valhalla/sov/02-object-model.html\" rel=\"noreferrer\">State of Valhalla. Section 2: Language Model</a></p>\n<p><strong>Edit:</strong> Brian Goetz is Java Language Architect, leading such projects as Project Valhalla and Project Amber.</p>\n<p><strong>Edit-2020-12-08</strong>: Updated <a href=\"https://github.com/openjdk/valhalla-docs/blob/main/site/design-notes/state-of-valhalla/02-object-model.md\" rel=\"noreferrer\">State of Valhalla</a></p>\n"
},
{
"answer_id": 64289407,
"author": "Alexandr",
"author_id": 511804,
"author_profile": "https://Stackoverflow.com/users/511804",
"pm_score": 2,
"selected": false,
"text": "<p>I'd say it in another way:</p>\n<p>In java references are passed (but not objects) and these references are passed-by-value (the reference itself is copied and you have 2 references as a result and you have no control under the 1st reference in the method).</p>\n<p>Just saying: pass-by-value might be not clear enough for beginners. For instance in Python the same situation but there are articles, which describe that they call it <code>pass-by-reference</code>, only cause references are used.</p>\n"
},
{
"answer_id": 64409378,
"author": "Duleepa Wickramasinghe",
"author_id": 6582191,
"author_profile": "https://Stackoverflow.com/users/6582191",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Java always passes parameters by value.</strong>\n<br>All object references in Java are passed by value. This means that a copy of the value will be passed to a method. But the trick is that passing a copy of the value also changes the real value of the object.</p>\n<p>Please refer to the below example,</p>\n<pre><code>public class ObjectReferenceExample {\n\n public static void main(String... doYourBest) {\n Student student = new Student();\n transformIntoHomer(student);\n System.out.println(student.name);\n }\n\n static void transformIntoDuleepa(Student student) {\n student.name = "Duleepa";\n }\n}\nclass Student {\n String name;\n}\n</code></pre>\n<p>In this case, it will be Duleepa!\n<br>The reason is that Java object variables are simply references that point to real objects in the memory heap.\nTherefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.</p>\n"
},
{
"answer_id": 64946506,
"author": "Pallav Khare",
"author_id": 11913248,
"author_profile": "https://Stackoverflow.com/users/11913248",
"pm_score": 3,
"selected": false,
"text": "<p>Java is always pass by value, not pass by reference</p>\n<p>First of all, we need to understand what pass by value and pass by reference are.</p>\n<p><strong>Pass by value</strong> means that you are making a copy in memory of the actual parameter's value that is passed in. This is a copy of the contents of the actual parameter.</p>\n<p><strong>Pass by reference</strong> (also called pass by address) means that a copy of the address of the actual parameter is stored.</p>\n<p>Sometimes Java can give the illusion of pass by reference. Let's see how it works by using the example below:</p>\n<pre><code>public class PassByValue {\n public static void main(String[] args) {\n Test t = new Test();\n t.name = "initialvalue";\n new PassByValue().changeValue(t);\n System.out.println(t.name);\n }\n \n public void changeValue(Test f) {\n f.name = "changevalue";\n }\n}\n\nclass Test {\n String name;\n}\n</code></pre>\n<p>The output of this program is:</p>\n<pre><code>changevalue\nLet's understand step by step:\n</code></pre>\n<p>Test t = new Test();\nAs we all know it will create an object in the heap and return the reference value back to t. For example, suppose the value of t is 0x100234 (we don't know the actual JVM internal value, this is just an example) .</p>\n<p>first illustration</p>\n<pre><code>new PassByValue().changeValue(t);\n</code></pre>\n<p>When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function. Since it is passing by value, it passes a copy of the variable rather than the actual reference of it. Since we said the value of t was 0x100234, both t and f will have the same value and hence they will point to the same object.</p>\n<p>second illustration</p>\n<p>If you change anything in the function using reference f it will modify the existing contents of the object. That is why we got the output changevalue, which is updated in the function.</p>\n<p>To understand this more clearly, consider the following example:</p>\n<pre><code>public class PassByValue {\n public static void main(String[] args) {\n Test t = new Test();\n t.name = "initialvalue";\n new PassByValue().changeRefence(t);\n System.out.println(t.name);\n }\n \n public void changeRefence(Test f) {\n f = null;\n }\n}\n\nclass Test {\n String name;\n}\n</code></pre>\n<p>Will this throw a NullPointerException? No, because it only passes a copy of the reference. In the case of passing by reference, it could have thrown a NullPointerException, as seen below:</p>\n<p>third illustration</p>\n<p>Hopefully this will help.</p>\n"
},
{
"answer_id": 65460603,
"author": "jack",
"author_id": 8932910,
"author_profile": "https://Stackoverflow.com/users/8932910",
"pm_score": 4,
"selected": false,
"text": "<p>Not to repeat, but one point to those who might still be confused after reading many answers:</p>\n<ul>\n<li><code>pass by value</code> in Java is <strong>NOT EQUAL</strong> to <code>pass by value</code> in C++, though it sounds like that, which is probably why there's confusion</li>\n</ul>\n<p>Breaking it down:</p>\n<ul>\n<li><code>pass by value</code> in C++ means passing the value of the object (if object), literarily the copy of the object</li>\n<li><code>pass by value</code> in Java means passing the address value of the object (if object), not really the "value" (a copy) of the object like C++</li>\n<li>By <code>pass by value</code> in Java, operating on an object (e.g. <code>myObj.setName("new")</code>) inside a function <strong>has effects</strong> on the object outside the function; by <code>pass by value</code> in C++, it has <strong>NO</strong> effects on the one outside.</li>\n<li>However, by <code>pass by reference</code> in C++, operating on an object in a function <strong>DOES</strong> have effects on the one outside! Similar (<em>just similar, not the same</em>) to <code>pass by value</code> in Java, no?.. and people always repeat "<em>there's no pass by reference in Java</em>", => <strong>BOOM, confusion starts...</strong></li>\n</ul>\n<p>So, friends, all is just about the <strong>difference</strong> of terminology definition (across languages), you just need to know how it works and that's it (<em>though sometimes a bit confusing how it's called I admit</em>)!</p>\n"
},
{
"answer_id": 66506089,
"author": "ömer.bozkurt",
"author_id": 5003351,
"author_profile": "https://Stackoverflow.com/users/5003351",
"pm_score": 0,
"selected": false,
"text": "<p>If you want it to put into a single sentence to understand and remember easily, simplest answer:</p>\n<p>Java is always <strong>pass the value with a new reference</strong></p>\n<p>(So you can modify the original object but can not access the original reference)</p>\n"
},
{
"answer_id": 66523582,
"author": "charles",
"author_id": 4086871,
"author_profile": "https://Stackoverflow.com/users/4086871",
"pm_score": 2,
"selected": false,
"text": "<p>Here a more precise definition:</p>\n<ul>\n<li><strong>Pass/call by value:</strong> Formal parameter is like a local variable in\nscope of function, it evaluates to actual parameter at the moment of\nfunction call.</li>\n<li><strong>Pass/call by reference:</strong> Formal parameter is just a alias for the real\nvalue, any change of it in the scope of function can have side\neffects outside in any other part of code.</li>\n</ul>\n<p>So in C/C++ you can create a function that swaps two values passed using the references:</p>\n<pre><code>void swap(int& a, int& b) \n{\n int tmp = a; \n a = b; \n b = tmp; \n}\n</code></pre>\n<p>You can see it has a unique reference to a and b, so we do not have a copy, tmp just hold unique references.</p>\n<p>The same function in java does not have side effects, the parameter passing is just like the code above without references.</p>\n<p>Although java work with pointers/references, the parameters are not unique pointers, in each attribution, they are copied instead just assigned like C/C++</p>\n"
},
{
"answer_id": 66649532,
"author": "Alex de Kruijff",
"author_id": 12486085,
"author_profile": "https://Stackoverflow.com/users/12486085",
"pm_score": 1,
"selected": false,
"text": "<p>There are only two versions:</p>\n<ul>\n<li>You can pass the value i.e. (4,5)</li>\n<li>You can pass an address i.e. 0xF43A</li>\n</ul>\n<p>Java passes primivates as values and objects as addresses. Those who say, "address are values too", do not make a distinction between the two. Those who focus on the effect of the swap functions focus on what happens after the passing is done.</p>\n<p>In C++ you can do the following:</p>\n<pre><code>Point p = Point(4,5);\n</code></pre>\n<p>This reserves 8 bytes on the stack and stores (4,5) in it.</p>\n<pre><code>Point *x = &p;\n</code></pre>\n<p>This reserves 4 bytes on the stack and stores 0xF43A in it.</p>\n<pre><code>Point &y = p;\n</code></pre>\n<p>This reserves 4 bytes on the stack and stores 0xF43A in it.</p>\n<ol>\n<li><p>I think everyone will agree that a call to f(p) is a pass-by-value if the definition of f is f(Point p). In this case an additional 8 bytes being reserved and (4,5) being copied into it. When f changes p the the the original is guarantieed to be unchanged when f returns.</p>\n</li>\n<li><p>I think that everyone will agree that a call to f(p) is a pass-by-reference if the definition of f is f(Point &p). In this case an additional 4 bytes being reserved and 0xF43A being copied into it. When f changes p the the original is guarantieed to be changed when f returns.</p>\n</li>\n<li><p>A call to f(&p) is also pass-by-reference if the definition of f is f(Point *p). In this case an additional 4 bytes being reserved and 0xF43A being copied into it. When f changes *p the the original is guarantieed to be changed when f returns.</p>\n</li>\n<li><p>A call to f(x) is also pass-by-reference if the definition of f is f(Point *p). In this case an additional 4 bytes being reserved and 0xF43A being copied into it. When f changes *p the the original is guarantieed to be changed when f returns.</p>\n</li>\n<li><p>A call to f(y) is also pass-by-reference if the definition of f is f(Point &p). In this case an additional 4 bytes being reserved and 0xF43A being copied into it. When f changes p the the original is guarantieed to be changed when f returns.</p>\n</li>\n</ol>\n<p>Sure what happens after the passing is done differs, but that is only a language construct. In the case of pointer you have to use -> to access the members and in the case of references you have to use .. If you want to swap the values of the original then you can do tmp=a; a=b; b=tmp; in the case of references and tmp=*a; *b=tmp; *a=tmp for pointers. And in Java you would have do: tmp.set(a); a.set(b); b.set(tmp). Focussing on the assignment statement statement is silly. You can do the exact same thing in Java if you write a little bit of code.</p>\n<p>So Java passes primivates by values and objects by references. And Java copy values to achieve that, but so does C++.</p>\n<p>For completeness:</p>\n<pre><code>Point p = new Point(4,5);\n</code></pre>\n<p>This reserves 4 bytes on the stack and stores 0xF43A in it and reserves 8 bytes on the heap and stores (4,5) in it.</p>\n<p>If you want to swap the memory locations like so</p>\n<pre><code>void swap(int& a, int& b) {\n int *tmp = &a;\n &a = &b;\n &b = tmp;\n}\n</code></pre>\n<p>Then you will find that you run into the limitations of your hardware.</p>\n"
},
{
"answer_id": 67232841,
"author": "v010dya",
"author_id": 2893496,
"author_profile": "https://Stackoverflow.com/users/2893496",
"pm_score": -1,
"selected": false,
"text": "<p>Every single answer here is tying to take pass pointer by reference from other languages and show how it is impossible to do in Java. For whatever reason nobody is attempting to show how to implement pass-object-by-value from other languages.</p>\n<p>This code shows how something like this can be done:</p>\n<pre><code>public class Test\n{\n private static void needValue(SomeObject so) throws CloneNotSupportedException\n {\n SomeObject internalObject = so.clone();\n so=null;\n \n // now we can edit internalObject safely.\n internalObject.set(999);\n }\n public static void main(String[] args)\n {\n SomeObject o = new SomeObject(5);\n System.out.println(o);\n try\n {\n needValue(o);\n }\n catch(CloneNotSupportedException e)\n {\n System.out.println("Apparently we cannot clone this");\n }\n System.out.println(o);\n }\n}\n\npublic class SomeObject implements Cloneable\n{\n private int val;\n public SomeObject(int val)\n {\n this.val = val;\n }\n public void set(int val)\n {\n this.val = val;\n }\n public SomeObject clone()\n {\n return new SomeObject(val);\n }\n public String toString()\n {\n return Integer.toString(val);\n }\n}\n</code></pre>\n<p>Here we have a function <code>needValue</code> and what it does is right away create a clone of the object, which needs be implemented in the class of the object itself and the class needs to be marked as <code>Cloneable</code>. It is not essential to set <code>so</code> to <code>null</code> after that, but i have done so here to show that we are not going to be using that reference after that.</p>\n<p>It may well be that Java does not have pass-by-reference semantics, but to call the language "pass-by-value" is along the lines of wishful thinking.</p>\n"
},
{
"answer_id": 67294696,
"author": "frostcs",
"author_id": 1027385,
"author_profile": "https://Stackoverflow.com/users/1027385",
"pm_score": 3,
"selected": false,
"text": "<p><strong>For simplicity and verbosity</strong>\nIts <code>pass reference by value</code>:</p>\n<pre><code>public static void main(String[] args) {\n Dog aDog = new Dog("Max");\n Dog oldDog = aDog;\n\n // we pass the object to foo\n foo(aDog);\n // aDog variable is still pointing to the "Max" dog when foo(...) returns\n aDog.getName().equals("Max"); // true\n aDog.getName().equals("Fifi"); // false\n aDog == oldDog; // true\n}\n\npublic static void foo(Dog d) {\n d.getName().equals("Max"); // true\n // change d inside of foo() to point to a new Dog instance "Fifi"\n d = new Dog("Fifi");\n d.getName().equals("Fifi"); // true\n}\n</code></pre>\n"
},
{
"answer_id": 68760297,
"author": "Wellington Costa",
"author_id": 8576876,
"author_profile": "https://Stackoverflow.com/users/8576876",
"pm_score": 2,
"selected": false,
"text": "<p>Java uses pass-by-value, but the effects differ whether you are using primitive or a reference type.</p>\n<p>When you pass a primitive type as an argument to a method, it's getting a copy of the primitive and any changes inside the block of the method won't change the original variable.</p>\n<p>When you pass a reference type as an argument to a method, it's still getting a copy but it's a copy of the reference to the object <strong>(in other words, you are getting a copy of the memory address in the heap where the object is located)</strong>, so any changes in the object inside the block of the method will affect the original object outside the block.</p>\n"
},
{
"answer_id": 69063599,
"author": "Sam Ginrich",
"author_id": 9437799,
"author_profile": "https://Stackoverflow.com/users/9437799",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Guess, the common canon is wrong based on inaccurate language</strong></p>\n<p>Authors of a programming language do not have the authority to rename established programming concept.</p>\n<p>Primitive Java types <code>byte, char, short, int, long float, double</code> are definitely passed by value.</p>\n<p>All other types are <code>Objects</code>: Object members and parameters technically <strong>are references</strong>.</p>\n<p>So these "references" are passed "by value", but there occurs no object construction on the stack. Any change of object members (or elements in case of an array) apply to the same original Object; such reference precisely meets the logic of pointer of an instance passed to some function in any C-dialect, where we used to call this <strong>passing an object by reference</strong></p>\n<p>Especially we do have this thing <strong>java.lang.NullPointerException</strong>, which makes no sense in a pure by-value-concept</p>\n"
},
{
"answer_id": 70586240,
"author": "Sam Ginrich",
"author_id": 9437799,
"author_profile": "https://Stackoverflow.com/users/9437799",
"pm_score": -1,
"selected": false,
"text": "<p>After following an exhaustive discussion, I think it's time to put all serious results together in a snippet.</p>\n<pre><code>/**\n * \n * @author Sam Ginrich\n * \n * All Rights Reserved!\n * \n */\npublic class JavaIsPassByValue\n{\n\n static class SomeClass\n {\n int someValue;\n\n public SomeClass(int someValue)\n {\n this.someValue = someValue;\n }\n }\n\n static void passReferenceByValue(SomeClass someObject)\n {\n if (someObject == null)\n {\n throw new NullPointerException(\n "This Object Reference was passed by Value,\\r\\n that's why you don't get a value from it.");\n }\n someObject.someValue = 49;\n }\n\n public static void main(String[] args)\n {\n SomeClass someObject = new SomeClass(27);\n System.out.println("Here is the original value: " + someObject.someValue);\n\n passReferenceByValue(someObject);\n System.out.println(\n "\\nAs ´Java is pass by value´,\\r\\n everything without exception is passed by value\\r\\n and so an object's attribute cannot change: "\n + someObject.someValue);\n\n System.out.println();\n passReferenceByValue(null);\n }\n</code></pre>\n<p>}</p>\n<p>One can easily see from the output, that in Java everything is passed by value, so simple!</p>\n<pre><code>Here is the original value: 27\n\nAs ´Java is pass by value´,\n everything without exception is passed by value\n and so an object´s attribute cannot change: 49\n\n'Exception in thread "main" java.lang.NullPointerException: This Object Reference was passed by value,\n that´s why you don´t get a value from it. \n at JavaIsPassByValue.passReferenceByValue(JavaIsPassByValue.java:26)\n at JavaIsPassByValue.main(JavaIsPassByValue.java:43)\n</code></pre>\n"
},
{
"answer_id": 70791100,
"author": "Alexander Kalinowski",
"author_id": 17676158,
"author_profile": "https://Stackoverflow.com/users/17676158",
"pm_score": -1,
"selected": false,
"text": "<p><strong>"I am a Junior Java Developer and I would like to know if Java uses Call-by-Value or Call-by-Reference?"</strong></p>\n<p>There is no universal answer to that and there cannot be for it's a <strong>false dichotomy</strong>. We have 2 different terms (Call-by-Value/Call-by-Reference) but at least 3(!) different ways of handling said data when passing it to a method:</p>\n<ol>\n<li>Our data is copied and the copy fed to a method. Changes to the copy do not propagate outside.(Think an <code>int</code> in Java or C++ or C#.)</li>\n<li>A pointer (the memory address) of our data is fed to the method instead. Changes to our data do propagate outside. We can also point to some new instance, leaving our original data dangling. (Think pointers in C++.)</li>\n<li>Like #2, except we can only change the original data but not what our pointer is pointing too. (Think instances passed as parameters in Java.)</li>\n</ol>\n<p>It's uncontentious in the OO world that #1 is <em>Call-by-Value</em> and #2 is <em>Call-by-Reference</em>.\nHowever, since we have only two terms for three options, there is no clear delineation between the two terms, thanks to option #3.</p>\n<p><strong>"What does that mean for me?"</strong></p>\n<p>It means that within the Java sphere you may reasonably assume #3 to be assumed under Call-by-Value (or the more verbal gymnastics term, Call-References-by-Value).</p>\n<p>However, in the wider OO world, it means you have to ask for an <em>explicit</em> delineation between Call-by-Value and Call-by-Reference, specifically how the other party classifies #3.</p>\n<p><strong>"But I read that the JLS defines it as Call-by-Value!"</strong></p>\n<p>Which is why your initial assumption when dealing with Java developers should be the above. The JLS has much less authority outside of Java, however.</p>\n<p><strong>"Why would Java developers insist on their own terminology?"</strong></p>\n<p>It's not for me to speculate but I think it's fair to point out that there is some potential problems with #2 (what is clearly Call-by-Reference), as hinted at, leading to Call-by-Reference not having the best of reputation everywhere.</p>\n<p><strong>"Is there a solution to this mess?"</strong></p>\n<p>3 options, only 2 ubiquitous names. The obvious exit is a 3rd term that gains equal wide-spread use as Call-by-Value and Call-by-Reference (and which is less confusing than Call-References-by-Value, perhaps <a href=\"https://www.sciencedirect.com/topics/computer-science/call-by-reference\" rel=\"nofollow noreferrer\">Call-by-Sharing</a>). Until then you need to presume or <strong>ask</strong>, as outlined above.</p>\n<p><em>Ultimately, it does not matter what we call it, for as long as we understand each other and there is no confusion.</em></p>\n"
},
{
"answer_id": 73769927,
"author": "ADITYA AHLAWAT",
"author_id": 15142774,
"author_profile": "https://Stackoverflow.com/users/15142774",
"pm_score": -1,
"selected": false,
"text": "<p><strong>Is Java a pass-by-value or reference? Prove it.</strong></p>\n<p>Java strictly enforces pass-by-value. Passing the parameters by using pass-by-values does not affect/alter the original variable. In the following program, we have initialized a variable called 'x' with some value and used the pass-by-value technique to demonstrate how the value of the variable remains unchanged.</p>\n<p><strong>Code:</strong></p>\n<pre><code>public class Main \n{ \n public static void main(String[] args)\n { \n //Original value of 'x' will remain unchanged \n // in case of call-by-value \n \n int x = 5;\n System.out.println( "Value of x before call-by-value: " + x);\n // 5\n\n processData(x);\n System.out.println("Value of x after call-by-value: " + x);\n // 5\n }\n public static void processData(int x) \n { \n x=x+10; \n }\n}\n</code></pre>\n<p>Now coming to the meaning - the value of x did not change in the main function - this is called pass by value.</p>\n<p>If the value changes in the main function it is called pass by reference.</p>\n<p><a href=\"https://pediaa.com/what-is-the-difference-between-pass-by-value-and-pass-by-reference/\" rel=\"nofollow noreferrer\">difference between pass by value and pass by reference</a></p>\n<p><strong>What is Pass by Value?</strong></p>\n<p>In pass by value, the value of a function parameter is copied to another location of the memory. When accessing or modifying the variable within the function, it accesses only the copy. Thus, there is no effect on the original value.</p>\n<p><strong>What is Pass by Reference?</strong></p>\n<p>In pass by reference, the memory address is passed to that function. In other words, the function gets access to the actual variable.</p>\n<p>Difference Between Pass by Value and Pass by Reference</p>\n<p><strong>Definition</strong></p>\n<p>Pass by value refers to a mechanism of copying the function parameter value to another variable while the pass by reference refers to a mechanism of passing the actual parameters to the function. Thus, this is the main difference between pass by value and pass by reference.</p>\n<p><strong>Changes</strong></p>\n<p>In pass by value, the changes made inside the function are not reflected in the original value. On the other hand, in pass by reference, the changes made inside the function are reflected in the original value. Hence, this is another difference between pass by value and pass by reference.</p>\n<p><strong>Actual Parameter</strong></p>\n<p>Moreover, pass by value makes a copy of the actual parameter. However, in pass by reference, the address of the actual parameter passes to the function.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4315/"
] | I always thought Java uses **pass-by-reference**.
However, I've seen [a blog post](http://javadude.com/articles/passbyvalue.htm) that claims that Java uses **pass-by-value**.
I don't think I understand the distinction they're making.
What is the explanation? | The terms "pass-by-value" and "pass-by-reference" have special, [precisely defined](https://en.wikipedia.org/w/index.php?title=Pass-by-value) meanings in computer science. These meanings differ from the intuition many people have when first hearing the terms. Much of the confusion in this discussion seems to come from this fact.
The terms "pass-by-value" and "pass-by-reference" are talking about *variables.* Pass-by-value means that the *value* of a variable is passed to a function/method. Pass-by-reference means that a *reference* to that variable is passed to the function. The latter gives the function a way to change the contents of the variable.
By those definitions, Java is always **pass-by-value**. Unfortunately, when we deal with variables holding objects we are really dealing with object-handles called *references* which are passed-by-value as well. This terminology and semantics easily confuse many beginners.
It goes like this:
```
public static void main(String[] args) {
Dog aDog = new Dog("Max");
Dog oldDog = aDog;
// we pass the object to foo
foo(aDog);
// aDog variable is still pointing to the "Max" dog when foo(...) returns
aDog.getName().equals("Max"); // true
aDog.getName().equals("Fifi"); // false
aDog == oldDog; // true
}
public static void foo(Dog d) {
d.getName().equals("Max"); // true
// change d inside of foo() to point to a new Dog instance "Fifi"
d = new Dog("Fifi");
d.getName().equals("Fifi"); // true
}
```
In the example above `aDog.getName()` will still return `"Max"`. The value `aDog` within `main` is not changed in the function `foo` with the `Dog` `"Fifi"` as the object reference is passed by value. If it were passed by reference, then the `aDog.getName()` in `main` would return `"Fifi"` after the call to `foo`.
Likewise:
```
public static void main(String[] args) {
Dog aDog = new Dog("Max");
Dog oldDog = aDog;
foo(aDog);
// when foo(...) returns, the name of the dog has been changed to "Fifi"
aDog.getName().equals("Fifi"); // true
// but it is still the same dog:
aDog == oldDog; // true
}
public static void foo(Dog d) {
d.getName().equals("Max"); // true
// this changes the name of d to be "Fifi"
d.setName("Fifi");
}
```
In the above example, `Fifi` is the dog's name after call to `foo(aDog)` because the object's name was set inside of `foo(...)`. Any operations that `foo` performs on `d` are such that, for all practical purposes, they are performed on `aDog`, but it is **not** possible to change the value of the variable `aDog` itself.
For more information on pass by reference and pass by value, consult the following answer: <https://stackoverflow.com/a/430958/6005228>. This explains more thoroughly the semantics and history behind the two and also explains why Java and many other modern languages appear to do both in certain cases. |
40,511 | <p>As the title already states, I'm trying to declare a nested function and return a pointer to that function. I want this function 'not' to return a new function pointer which will return the negation of whatever the original function was.</p>
<p>Here is what I have:</p>
<pre><code>someType not( someType original ) {
int isNot( ListEntry* entry ) {
return !original( entry );
}
someType resultFunc = calloc( 1024, 1 );
memcpy( resultFunc, &isNot, 1024 );
return resultFunc;
}
</code></pre>
<p>someType is defined as:</p>
<pre><code>typedef int(*someType)(ListEntry* entry)
</code></pre>
| [
{
"answer_id": 40537,
"author": "Steve Willard",
"author_id": 402,
"author_profile": "https://Stackoverflow.com/users/402",
"pm_score": 0,
"selected": false,
"text": "<p>I'm using GCC.</p>\n\n<p>You can turn on nested functions by using the flag:</p>\n\n<pre><code>-fnested-functions\n</code></pre>\n\n<p>when you compile.</p>\n"
},
{
"answer_id": 40596,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 0,
"selected": false,
"text": "<p>I also never heard of nested functions in C, but if gcc supports it, this is not going to work the way you expect. You are just simply copying the machine instructions of isNot, and that won't include the actual value of \"original\" at the time \"not\" is being called.</p>\n\n<p>You should use a C++ class to implement a <a href=\"http://en.wikipedia.org/wiki/Function_object\" rel=\"nofollow noreferrer\">function object</a> that stores a pointer that you can initialize with the value of \"original\" and return an instance of this class from \"not\".</p>\n"
},
{
"answer_id": 40757,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Steve, you have a completely wrong mental model of what is a C function. </p>\n\n<pre><code>someType resultFunc = calloc( 1024, 1 );\nmemcpy( resultFunc, &isNot, 1024 );\n</code></pre>\n\n<p>From your code fragment, I can surmise that you think that you can copy function's compiled code into a block of memory, and then reuse it. This kind of thing smells of Lisp, except even in lisp you don't do it that way.</p>\n\n<p>In fact, when you say \"&isNot\", you get a pointer to function. Copying the memory that pointer points at is counterproductive - the memory was initialized when you loaded your executable into memory, and it's not changing. In any case, writing someFunc() would cause a core dump, as the heap memory behing someFunc cannot be executed - this protects you from all sorts of viruses.</p>\n\n<p>You seem to expect an implementation of closures in C. That implementation is simply not there. Unlike Lisp or Perl or Ruby, C cannot preserve elements of a stack frame once you exited that frame. Even is nested functions are permitted in some compilers, I am sure that you cannot refer to non-global variables from inside those functions. The closes thing to closures is indeed C++ object that stores the state and implements operator(), but it's a completely different approach, and you'd still have to do things manually.</p>\n\n<p>Update: <a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Nested-Functions.html#Nested-Functions\" rel=\"noreferrer\">here</a> is the relevant portion of GCC documentation. Look for \"But this technique works only so long as the containing function (hack, in this example) does not exit.\"</p>\n"
},
{
"answer_id": 525951,
"author": "Logan Capaldo",
"author_id": 61289,
"author_profile": "https://Stackoverflow.com/users/61289",
"pm_score": 1,
"selected": false,
"text": "<p>You're not going to be able to do this in the fashion you want. You have a couple of alternative options.</p>\n\n<p>You can use macros:</p>\n\n<pre><code>#define FN_NOT(F) !F\n#define notSomeFunc FN_NOT(someFunc)\n...\nx = notSomeFunc(entry);\n</code></pre>\n\n<p>But I suspect you wanted to be able to pass the negated function around to other functions that take function pointers, so that won't work.</p>\n\n<p>You can change your interfaces to accept some extra information, eg</p>\n\n<pre><code>struct closure {\n void *env;\n int (*f)(struct closure* extra, ListEntry*);\n};\n\nstatic int isNot(struct closure* extra, ListEntry *entry) {\n someType original = extra->env;\n return !original(entry);\n}\n\nstruct closure not(someType original) {\n closure rv;\n rv.env = original;\n rv.f = &isNot;\n return rv;\n}\n</code></pre>\n\n<p>And then use it like:</p>\n\n<pre><code>struct closure inverse_fn;\ninverse_fn = not( &fn );\nif( inverse_fn.f(&inverse_fn, entry) ) {\n ...\n}\n</code></pre>\n\n<p>There are other things you can try, like JITing functions at runtime, but those sorts of techniques are going to be platform and architecture dependent. This solution is awkward, but pure C and portable.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402/"
] | As the title already states, I'm trying to declare a nested function and return a pointer to that function. I want this function 'not' to return a new function pointer which will return the negation of whatever the original function was.
Here is what I have:
```
someType not( someType original ) {
int isNot( ListEntry* entry ) {
return !original( entry );
}
someType resultFunc = calloc( 1024, 1 );
memcpy( resultFunc, &isNot, 1024 );
return resultFunc;
}
```
someType is defined as:
```
typedef int(*someType)(ListEntry* entry)
``` | Steve, you have a completely wrong mental model of what is a C function.
```
someType resultFunc = calloc( 1024, 1 );
memcpy( resultFunc, &isNot, 1024 );
```
From your code fragment, I can surmise that you think that you can copy function's compiled code into a block of memory, and then reuse it. This kind of thing smells of Lisp, except even in lisp you don't do it that way.
In fact, when you say "&isNot", you get a pointer to function. Copying the memory that pointer points at is counterproductive - the memory was initialized when you loaded your executable into memory, and it's not changing. In any case, writing someFunc() would cause a core dump, as the heap memory behing someFunc cannot be executed - this protects you from all sorts of viruses.
You seem to expect an implementation of closures in C. That implementation is simply not there. Unlike Lisp or Perl or Ruby, C cannot preserve elements of a stack frame once you exited that frame. Even is nested functions are permitted in some compilers, I am sure that you cannot refer to non-global variables from inside those functions. The closes thing to closures is indeed C++ object that stores the state and implements operator(), but it's a completely different approach, and you'd still have to do things manually.
Update: [here](http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Nested-Functions.html#Nested-Functions) is the relevant portion of GCC documentation. Look for "But this technique works only so long as the containing function (hack, in this example) does not exit." |
40,525 | <p>I'm trying to call a function after I load some XML into Actionscript, and I'm just wondering how I call that function. Example:</p>
<pre><code>//Function Declarations
function parentFunction()
{
function callMe()
{
textField.text = "lawl";
}
}
</code></pre>
<p>Now, <strong>how do I call the "callMe()" function</strong> in a different part of the code, like an onRelease function?</p>
<pre><code>on(release)
{
callMe(); //doesn't work
parentFunction().callMe(); //doesn't work
parentFunction.callMe(); //doesn't work
}
</code></pre>
<p>ActionScript 2.0 is just so wonky! Any ideas?</p>
| [
{
"answer_id": 40617,
"author": "Michael Pryor",
"author_id": 245,
"author_profile": "https://Stackoverflow.com/users/245",
"pm_score": 3,
"selected": true,
"text": "<p>Are you forced to declare callMe inside of parentFunction? I assume so because otherwise you would just do</p>\n\n<p>function parent() { }\nfunction callMe() { }</p>\n\n<p>To be clear, a function can't own another function unless you provide some scope for that function to live in.</p>\n\n<p>So in JavaScript, you would do this by using the prototype object to declare the callMe function as a method of the object that parentFunction returned.</p>\n\n<p><a href=\"http://www.howtocreate.co.uk/tutorials/javascript/objects\" rel=\"nofollow noreferrer\">http://www.howtocreate.co.uk/tutorials/javascript/objects</a></p>\n\n<p>For ActionScript, read this article on Adobe's website:\n<a href=\"http://www.adobe.com/devnet/flex/articles/as_collections_03.html\" rel=\"nofollow noreferrer\">http://www.adobe.com/devnet/flex/articles/as_collections_03.html</a></p>\n\n<p>EDIT: After some more reading it appears the way you did things, you are actually declaring callMe as a <strong>private</strong> function. See this article which should make the whole <a href=\"http://www.crockford.com/javascript/private.html\" rel=\"nofollow noreferrer\">private/public javascript issue</a> a lot more understandable.</p>\n"
},
{
"answer_id": 40729,
"author": "MattSayar",
"author_id": 557,
"author_profile": "https://Stackoverflow.com/users/557",
"pm_score": 0,
"selected": false,
"text": "<p>I'm an idiot. I forgot the whole \"a function can't own another function\" thing, so I figured out another way to do it. Thanks!</p>\n"
},
{
"answer_id": 113517,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Of course a function can \"own\" another function. this is ECMAScript remember. Just declare a variable inside your function and assign a function to it. You can then call your function by using the \"call\" method.</p>\n\n<p>function foo()\n{\n trace(\"foo\");</p>\n\n<pre><code>var bar = function()\n{\n trace(\"bar\");\n};\n\nbar.call();\n</code></pre>\n\n<p>}</p>\n\n<p>foo();</p>\n"
},
{
"answer_id": 286276,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>//v--- on the frame\nfunction callMe(){\ntextArea.text='lawl';\n}\n//v---- for button\non(release){\ncallMe();\n}\n\n--- or -----\n</code></pre>\n\n<hr>\n\n<pre><code>//CUSTOM!!\n//v---- on frame\nfunction callMe(say){\ntextArea.text=say;\n}\n//v--- for button\non(release){\ncallMe('lawl');\n}\n</code></pre>\n"
},
{
"answer_id": 3237366,
"author": "freak_ts",
"author_id": 390454,
"author_profile": "https://Stackoverflow.com/users/390454",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry for bad english, \nSet a handler for (Menu-)Buttons, whitch are located in a MC.</p>\n\n<p>MC \"Buttons\" on Stage (with 3 \"testbtn\" in it) @ first frame:</p>\n\n<pre><code>function SetMethod(Method:Function){\n //trace(Method.call()); \n //or something like:\n testbtn1.addEventListener(MouseEvent.CLICK, Method);\n testbtn2.addEventListener(MouseEvent.CLICK, Method);\n testbtn3.addEventListener(MouseEvent.CLICK, Method);\n}\n</code></pre>\n\n<p>Stage (with MC \"Butttons\" in it) @ first frame:</p>\n\n<pre><code>function TheMenuListener(evt:Event):void{\n trace(evt.target.name);\n\n}\n...\nButtons.SetMethod(this.TheMenuListener); \n</code></pre>\n\n<p>returns the testbtn.name</p>\n\n<p>Edit: Oh, it´s for AS3, but maybe helps!</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/557/"
] | I'm trying to call a function after I load some XML into Actionscript, and I'm just wondering how I call that function. Example:
```
//Function Declarations
function parentFunction()
{
function callMe()
{
textField.text = "lawl";
}
}
```
Now, **how do I call the "callMe()" function** in a different part of the code, like an onRelease function?
```
on(release)
{
callMe(); //doesn't work
parentFunction().callMe(); //doesn't work
parentFunction.callMe(); //doesn't work
}
```
ActionScript 2.0 is just so wonky! Any ideas? | Are you forced to declare callMe inside of parentFunction? I assume so because otherwise you would just do
function parent() { }
function callMe() { }
To be clear, a function can't own another function unless you provide some scope for that function to live in.
So in JavaScript, you would do this by using the prototype object to declare the callMe function as a method of the object that parentFunction returned.
<http://www.howtocreate.co.uk/tutorials/javascript/objects>
For ActionScript, read this article on Adobe's website:
<http://www.adobe.com/devnet/flex/articles/as_collections_03.html>
EDIT: After some more reading it appears the way you did things, you are actually declaring callMe as a **private** function. See this article which should make the whole [private/public javascript issue](http://www.crockford.com/javascript/private.html) a lot more understandable. |
40,535 | <p>I need to determine if I'm on a particular view. My use case is that I'd like to decorate navigation elements with an "on" class for the current view. Is there a built in way of doing this?</p>
| [
{
"answer_id": 40538,
"author": "Jim Geurts",
"author_id": 3085,
"author_profile": "https://Stackoverflow.com/users/3085",
"pm_score": 2,
"selected": false,
"text": "<p>My current solution is with extension methods:</p>\n\n<pre><code>public static class UrlHelperExtensions\n{\n /// <summary>\n /// Determines if the current view equals the specified action\n /// </summary>\n /// <typeparam name=\"TController\">The type of the controller.</typeparam>\n /// <param name=\"helper\">Url Helper</param>\n /// <param name=\"action\">The action to check.</param>\n /// <returns>\n /// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.\n /// </returns>\n public static bool IsAction<TController>(this UrlHelper helper, LambdaExpression action) where TController : Controller\n {\n MethodCallExpression call = action.Body as MethodCallExpression;\n if (call == null)\n {\n throw new ArgumentException(\"Expression must be a method call\", \"action\");\n }\n\n return (call.Method.Name.Equals(helper.ViewContext.ViewName, StringComparison.OrdinalIgnoreCase) &&\n typeof(TController) == helper.ViewContext.Controller.GetType());\n }\n\n /// <summary>\n /// Determines if the current view equals the specified action\n /// </summary>\n /// <param name=\"helper\">Url Helper</param>\n /// <param name=\"actionName\">Name of the action.</param>\n /// <returns>\n /// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.\n /// </returns>\n public static bool IsAction(this UrlHelper helper, string actionName)\n {\n if (String.IsNullOrEmpty(actionName))\n {\n throw new ArgumentException(\"Please specify the name of the action\", \"actionName\");\n }\n string controllerName = helper.ViewContext.RouteData.GetRequiredString(\"controller\");\n return IsAction(helper, actionName, controllerName);\n }\n\n /// <summary>\n /// Determines if the current view equals the specified action\n /// </summary>\n /// <param name=\"helper\">Url Helper</param>\n /// <param name=\"actionName\">Name of the action.</param>\n /// <param name=\"controllerName\">Name of the controller.</param>\n /// <returns>\n /// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.\n /// </returns>\n public static bool IsAction(this UrlHelper helper, string actionName, string controllerName)\n {\n if (String.IsNullOrEmpty(actionName))\n {\n throw new ArgumentException(\"Please specify the name of the action\", \"actionName\");\n }\n if (String.IsNullOrEmpty(controllerName))\n {\n throw new ArgumentException(\"Please specify the name of the controller\", \"controllerName\");\n }\n\n if (!controllerName.EndsWith(\"Controller\", StringComparison.OrdinalIgnoreCase))\n {\n controllerName = controllerName + \"Controller\";\n }\n\n bool isOnView = helper.ViewContext.ViewName.SafeEquals(actionName, StringComparison.OrdinalIgnoreCase);\n return isOnView && helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 45103,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 1,
"selected": false,
"text": "<p>Here is something a little different, use a FilterAttribute:</p>\n\n<pre><code> [NavigationLocationFilter(\"Products\")]\n public ViewResult List()\n {\n return View();\n }\n</code></pre>\n\n<p>...</p>\n\n<pre><code>public class NavigationLocationFilterAttribute : ActionFilterAttribute\n{\n public string CurrentLocation { get; set; }\n\n public NavigationLocationFilterAttribute(string currentLocation)\n {\n CurrentLocation = currentLocation;\n }\n\n public override void OnActionExecuting(ActionExecutingContext filterContext)\n {\n var controller = (Controller)filterContext.Controller;\n controller.ViewData.Add(\"NavigationLocation\", CurrentLocation);\n }\n}\n</code></pre>\n\n<p>...</p>\n\n<p>And in the view:</p>\n\n<pre><code><%= ViewData[\"NavigationLocation\"] %>\n</code></pre>\n"
},
{
"answer_id": 2745475,
"author": "memical",
"author_id": 322622,
"author_profile": "https://Stackoverflow.com/users/322622",
"pm_score": 4,
"selected": true,
"text": "<p>Here what i am using. I think this is actually generated by the MVC project template in VS:</p>\n\n<pre><code>public static bool IsCurrentAction(this HtmlHelper helper, string actionName, string controllerName)\n {\n string currentControllerName = (string)helper.ViewContext.RouteData.Values[\"controller\"];\n string currentActionName = (string)helper.ViewContext.RouteData.Values[\"action\"];\n\n if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase))\n return true;\n\n return false;\n }\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3085/"
] | I need to determine if I'm on a particular view. My use case is that I'd like to decorate navigation elements with an "on" class for the current view. Is there a built in way of doing this? | Here what i am using. I think this is actually generated by the MVC project template in VS:
```
public static bool IsCurrentAction(this HtmlHelper helper, string actionName, string controllerName)
{
string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
string currentActionName = (string)helper.ViewContext.RouteData.Values["action"];
if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase))
return true;
return false;
}
``` |
40,545 | <p>Is there is any way to change the datasource location for a report and all of it's subreports without having to open each of them manually?</p>
| [
{
"answer_id": 40704,
"author": "David Cumps",
"author_id": 4329,
"author_profile": "https://Stackoverflow.com/users/4329",
"pm_score": -1,
"selected": false,
"text": "<p>I'm guessing you're talking about .rdl files from Reporting Services? (If not, my answer might be wrong)</p>\n\n<p>They're basically just XML, so you could load each one of them in and do an XPath query to get the node that contains the datasource and update it.</p>\n"
},
{
"answer_id": 40722,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 1,
"selected": false,
"text": "<p>Linked sub-reports (at least in CR XI) share the main report's datasource - presumably your report is already configured so that's not an option for you? </p>\n"
},
{
"answer_id": 40903,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 1,
"selected": false,
"text": "<p>@Unsliced I think the problem he is getting at is when you take a crystal report someone developed against another database, and you bring it up in Crystal Reports XI, you have to do a Change Datasource for each field, including those in subreports. If you just change source on the top level of the report, it often errors. (I think that is a known issue in Crystal Reports).</p>\n"
},
{
"answer_id": 41979,
"author": "Jas",
"author_id": 777,
"author_profile": "https://Stackoverflow.com/users/777",
"pm_score": 3,
"selected": false,
"text": "<p>Here is how I set my connections at runtime. I get the connection info from a config location.</p>\n\n<pre><code> #'SET REPORT CONNECTION INFO\n For i = 0 To rsource.ReportDocument.DataSourceConnections.Count - 1\n rsource.ReportDocument.DataSourceConnections(i).SetConnection(crystalServer, crystalDB, crystalUser, crystalPassword)\n Next\n\n For 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\n Next\n</code></pre>\n"
},
{
"answer_id": 157954,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 2,
"selected": false,
"text": "<p>If you are just doing this as a one-shot deal, my suggestion might not help. But, if you change data sources frequently, it might be useful.</p>\n\n<p>Disclaimer: I haven't worked with Crystal since version 9.0, so I don't know if they have improved on this. I always used <a href=\"http://msdn.microsoft.com/en-us/library/e38h511e(VS.71).aspx\" rel=\"nofollow noreferrer\">UDL files</a>. Basically, it is a pointer to a data source. Set up your report to point to the UDL, and the UDL points to the data source. If the source changes, just update the UDL.</p>\n\n<p>This is incredibly useful if you have multiple reports. You only have to update one file when the server changes.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4286/"
] | Is there is any way to change the datasource location for a report and all of it's subreports without having to open each of them manually? | Here is how I set my connections at runtime. I get the connection info from a config location.
```
#'SET REPORT CONNECTION INFO
For i = 0 To rsource.ReportDocument.DataSourceConnections.Count - 1
rsource.ReportDocument.DataSourceConnections(i).SetConnection(crystalServer, crystalDB, crystalUser, crystalPassword)
Next
For i = 0 To rsource.ReportDocument.Subreports.Count - 1
For x = 0 To rsource.ReportDocument.Subreports(i).DataSourceConnections.Count - 1
rsource.ReportDocument.OpenSubreport(rsource.ReportDocument.Subreports(i).Name).DataSourceConnections(x).SetConnection(crystalServer, crystalDB, crystalUser, crystalPassword)
Next
Next
``` |
40,568 | <p>Are square brackets in URLs allowed?</p>
<p>I noticed that <a href="http://hc.apache.org/httpclient-3.x/index.html" rel="noreferrer">Apache commons HttpClient</a> (3.0.1) throws an IOException, wget and Firefox however accept square brackets.</p>
<p>URL example:</p>
<pre><code>http://example.com/path/to/file[3].html
</code></pre>
<p>My HTTP client encounters such URLs but I'm not sure whether to patch the code or to throw an exception (as it actually should be).</p>
| [
{
"answer_id": 40571,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 1,
"selected": false,
"text": "<p>Best to URL encode those, as they are clearly not supported in all web servers. Sometimes, even when there is a standard, not everyone follows it.</p>\n"
},
{
"answer_id": 40583,
"author": "1729",
"author_id": 4319,
"author_profile": "https://Stackoverflow.com/users/4319",
"pm_score": 3,
"selected": false,
"text": "<p>Pretty much the only characters not allowed in pathnames are # and ? as they signify the end of the path.</p>\n\n<p>The uri rfc will have the definative answer:</p>\n\n<p><a href=\"http://www.ietf.org/rfc/rfc1738.txt\" rel=\"noreferrer\">http://www.ietf.org/rfc/rfc1738.txt</a></p>\n\n<blockquote>\n <p>Unsafe:</p>\n \n <p>Characters can be unsafe for a number of reasons. The space\n character is unsafe because significant spaces may disappear and\n insignificant spaces may be introduced when URLs are transcribed or\n typeset or subjected to the treatment of word-processing programs.\n The characters \"<\" and \">\" are unsafe because they are used as the\n delimiters around URLs in free text; the quote mark (\"\"\") is used to\n delimit URLs in some systems. The character \"#\" is unsafe and should\n always be encoded because it is used in World Wide Web and in other\n systems to delimit a URL from a fragment/anchor identifier that might\n follow it. The character \"%\" is unsafe because it is used for\n encodings of other characters. Other characters are unsafe because\n gateways and other transport agents are known to sometimes modify\n such characters. These characters are \"{\", \"}\", \"|\", \"\\\", \"^\", \"~\",\n \"[\", \"]\", and \"`\".</p>\n \n <p>All unsafe characters must always be encoded within a URL. For\n example, the character \"#\" must be encoded within URLs even in\n systems that do not normally deal with fragment or anchor\n identifiers, so that if the URL is copied into another system that\n does use them, it will not be necessary to change the URL encoding.</p>\n</blockquote>\n\n<p>The answer is that they <em>should</em> be hex encoded, but knowing postel's law, most things will accept them verbatim.</p>\n"
},
{
"answer_id": 40589,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 1,
"selected": false,
"text": "<p>According to the <a href=\"http://www.w3.org/Addressing/URL/url-spec.txt\" rel=\"nofollow noreferrer\">URL specification</a>, the square brackets are not valid URL characters.</p>\n\n<p>Here's the relevant snippets:</p>\n\n<blockquote>\n <p>The \"national\" and \"punctuation\" characters do not appear in any\n productions and therefore may not appear in URLs.<br>\n national { | } | vline | [ | ] | \\ | ^ | ~<br>\n punctuation < | > </p>\n</blockquote>\n"
},
{
"answer_id": 40595,
"author": "Lee",
"author_id": 3556,
"author_profile": "https://Stackoverflow.com/users/3556",
"pm_score": 3,
"selected": false,
"text": "<p>Any browser or web-enabled software that accepts URLs and is not throwing an exception when special characters are introduced is almost guaranteed to be encoding the special characters behind the scenes. Curly brackets, square brackets, spaces, etc all have special encoded ways of representing them so as not to produce conflicts. As per the previous answers, the safest way to deal with these is to URL-encode them before handing them off to something that will try to resolve the URL.</p>\n"
},
{
"answer_id": 66579,
"author": "rjray",
"author_id": 6421,
"author_profile": "https://Stackoverflow.com/users/6421",
"pm_score": 2,
"selected": false,
"text": "<p>For using the HttpClient commons class, you want to look into the org.apache.commons.httpclient.util.URIUtil class, specifically the encode() method. Use it to URI-encode the URL before trying to fetch it.</p>\n"
},
{
"answer_id": 1016737,
"author": "Justin Cormack",
"author_id": 15495,
"author_profile": "https://Stackoverflow.com/users/15495",
"pm_score": 7,
"selected": true,
"text": "<p><a href=\"http://www.ietf.org/rfc/rfc3986.txt\" rel=\"noreferrer\">RFC 3986</a> states</p>\n\n<blockquote>\n <p>A host identified by an Internet\n Protocol literal address, version 6\n [RFC3513] or later, is distinguished\n by enclosing the IP literal within\n square brackets (\"[\" and \"]\"). This\n is the only place where square bracket\n characters are allowed in the URI\n syntax.</p>\n</blockquote>\n\n<p>So you should not be seeing such URI's in the wild in theory, as they should arrive encoded.</p>\n"
},
{
"answer_id": 1718238,
"author": "MM.",
"author_id": 126603,
"author_profile": "https://Stackoverflow.com/users/126603",
"pm_score": 4,
"selected": false,
"text": "<p>I know this question is a bit old, but I just wanted to note that PHP uses brackets to pass arrays in a URL.</p>\n\n<pre><code>http://www.example.com/foo.php?bar[]=1&bar[]=2&bar[]=3\n</code></pre>\n\n<p>In this case <code>$_GET['bar']</code> will contain <code>array(1, 2, 3)</code>.</p>\n"
},
{
"answer_id": 3037298,
"author": "Casebash",
"author_id": 165495,
"author_profile": "https://Stackoverflow.com/users/165495",
"pm_score": 2,
"selected": false,
"text": "<p>StackOverflow seems to not encode them:</p>\n\n<p><a href=\"https://stackoverflow.com/search?q=square+brackets+[url]\">https://stackoverflow.com/search?q=square+brackets+[url]</a></p>\n"
},
{
"answer_id": 38709035,
"author": "sixtytrees",
"author_id": 6447563,
"author_profile": "https://Stackoverflow.com/users/6447563",
"pm_score": 1,
"selected": false,
"text": "<p>Square brackets are considered unsafe, but majority of browsers will parse those correctly. Having said that it is better to replace square brackets with some other characters.</p>\n"
},
{
"answer_id": 44901804,
"author": "oHo",
"author_id": 938111,
"author_profile": "https://Stackoverflow.com/users/938111",
"pm_score": 5,
"selected": false,
"text": "<p>Square brackets <code>[</code> and <code>]</code> in URLs are not often supported.</p>\n\n<h3>Replace them by <code>%5B</code> and <code>%5D</code>:</h3>\n\n<ul>\n<li><p>Using a command line, the following example is based on <code>bash</code> and <code>sed</code>:</p>\n\n<pre><code>url='http://example.com?day=[0-3][0-9]'\nencoded_url=\"$( sed 's/\\[/%5B/g;s/]/%5D/g' <<< \"$url\")\"\n</code></pre></li>\n<li><p>Using Java <a href=\"https://docs.oracle.com/javase/8/docs/api/java/net/URLEncoder.html#encode-java.lang.String-java.lang.String-\" rel=\"noreferrer\"><strong><code>URLEncoder.encode(String s, String enc)</code></strong></a></p></li>\n<li><p>Using PHP <a href=\"http://php.net/manual/en/function.rawurlencode.php\" rel=\"noreferrer\"><strong><code>rawurlencode()</code></strong></a> or <a href=\"http://php.net/manual/en/function.urlencode.php\" rel=\"noreferrer\"><strong><code>urlencode()</code></strong></a></p>\n\n<pre><code><?php\necho '<a href=\"http://example.com/day/',\n rawurlencode('[0-3][0-9]'), '\">';\n?>\n</code></pre>\n\n<p>output:</p>\n\n<pre><code><a href=\"http://example.com/day/%5B0-3%5D%5B0-9%5D\">\n</code></pre>\n\n<p>or:</p>\n\n<pre><code><?php\n$query_string = 'day=' . urlencode('[0-3][0-9]') .\n '&month=' . urlencode('[0-1][0-9]');\necho '<a href=\"http://example.com?',\n htmlentities($query_string), '\">';\n?>\n</code></pre></li>\n<li><p>Using your favorite programming language... Please extend this answer by posting a comment or editing directly this answer to add the function you use from your programming language ;-)</p></li>\n</ul>\n\n<p>For more details, see the <a href=\"https://www.ietf.org/rfc/rfc3986.txt\" rel=\"noreferrer\"><strong>RFC 3986</strong></a> specifying the URL syntax. The <strong>Appendix A</strong> is about <code>%-encoding</code> in the query string (brackets as belonging to <em>“gen-delims”</em> to be <code>%-encoded</code>).</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4308/"
] | Are square brackets in URLs allowed?
I noticed that [Apache commons HttpClient](http://hc.apache.org/httpclient-3.x/index.html) (3.0.1) throws an IOException, wget and Firefox however accept square brackets.
URL example:
```
http://example.com/path/to/file[3].html
```
My HTTP client encounters such URLs but I'm not sure whether to patch the code or to throw an exception (as it actually should be). | [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt) states
>
> A host identified by an Internet
> Protocol literal address, version 6
> [RFC3513] or later, is distinguished
> by enclosing the IP literal within
> square brackets ("[" and "]"). This
> is the only place where square bracket
> characters are allowed in the URI
> syntax.
>
>
>
So you should not be seeing such URI's in the wild in theory, as they should arrive encoded. |
40,577 | <p>In Ruby, I'm trying to do the following.</p>
<pre><code>def self.stats(since)
return Events.find(:all, :select => 'count(*) as this_count', :conditions => ['Date(event_date) >= ?', (Time.now - since)]).first.this_count
end
</code></pre>
<p>where "since" is a string representing an amount of time ('1 hour', '1 day', '3 days') and so on. Any suggestions?</p>
| [
{
"answer_id": 40580,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "<p>Try using <a href=\"http://chronic.rubyforge.org/\" rel=\"nofollow noreferrer\">Chronic</a> to parse the date strings into actual datetime objects.</p>\n"
},
{
"answer_id": 40822,
"author": "Wieczo",
"author_id": 4195,
"author_profile": "https://Stackoverflow.com/users/4195",
"pm_score": 3,
"selected": true,
"text": "<p>I hacked this together with the ActiveSupport gem:</p>\n\n<pre><code>require 'active_support'\n\ndef string_to_date(date_string)\n parts = date_string.split\n return parts[0].to_i.send(parts[1])\nend\nsinces = ['1 hour', '1 day', '3 days']\n\nsinces.each do |since|\n puts \"#{since} ago: #{string_to_date(since).ago(Time.now)}\"\nend\n</code></pre>\n\n<p>[edit] To answer your question, you might try it like that:</p>\n\n<pre><code>:conditions => ['Date)event_date) >= ?', (string_to_date(since).ago(Time.now))]\n</code></pre>\n"
},
{
"answer_id": 20395024,
"author": "RubenCaro",
"author_id": 1883905,
"author_profile": "https://Stackoverflow.com/users/1883905",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with <a href=\"https://stackoverflow.com/a/40580/1933902\">John Millikin</a>. <a href=\"http://chronic.rubyforge.org/\" rel=\"nofollow noreferrer\">Chronic</a>, or even your own helpers, would be a much lighter and effective dependency to carry than whole ActiveSupport, assuming you are not already trapped inside Rails.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
] | In Ruby, I'm trying to do the following.
```
def self.stats(since)
return Events.find(:all, :select => 'count(*) as this_count', :conditions => ['Date(event_date) >= ?', (Time.now - since)]).first.this_count
end
```
where "since" is a string representing an amount of time ('1 hour', '1 day', '3 days') and so on. Any suggestions? | I hacked this together with the ActiveSupport gem:
```
require 'active_support'
def string_to_date(date_string)
parts = date_string.split
return parts[0].to_i.send(parts[1])
end
sinces = ['1 hour', '1 day', '3 days']
sinces.each do |since|
puts "#{since} ago: #{string_to_date(since).ago(Time.now)}"
end
```
[edit] To answer your question, you might try it like that:
```
:conditions => ['Date)event_date) >= ?', (string_to_date(since).ago(Time.now))]
``` |
40,590 | <p>Both the jQuery and Prototpye JavaScript libraries refuse to allow me to use a variable to select an list item element by index number although they accept a hard coded number. </p>
<p>For example, in Prototype this works:</p>
<pre><code>$$('li')[5].addClassName('active');
</code></pre>
<p>But this will not work no matter how I try to cast the variable as a number or integer:</p>
<pre><code>$$('li')[currentPage].addClassName('active');
</code></pre>
<p>In jQuery I get similar weirdness. This will work:</p>
<pre><code>jQuery('li').eq(5).addClass("active");
</code></pre>
<p>But this will not work again even though the value of currentPage is 5 and its type is number:</p>
<pre><code>jQuery('li').eq(currentPage).addClass("active");
</code></pre>
<p>I'm trying to create a JavaScript pagination system and I need to set the class on the active page button. The list item elements are created dynamically depending upon the number of pages I need.</p>
| [
{
"answer_id": 40599,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p>Are you certain that <code>currentPage</code> is an integer? Try something like:</p>\n\n<pre><code>var currentPage = 5;\njQuery('li').eq(currentPage);\n</code></pre>\n\n<p>as a simple sanity check. If that works, you should try casting to <code>Integer</code>.</p>\n"
},
{
"answer_id": 40627,
"author": "Dan Cramer",
"author_id": 3274,
"author_profile": "https://Stackoverflow.com/users/3274",
"pm_score": 2,
"selected": false,
"text": "<p>Make sure that the currentPage variable is correctly scoped in the code where it is being accessed. Could the variable be changed somewhere else in the code before you are accessing it? Tools like <a href=\"https://addons.mozilla.org/firefox/addon/1843\" rel=\"nofollow noreferrer\">Firebug</a> can help you to add a breakpoint at the point of execution and see the value of your variable.</p>\n"
},
{
"answer_id": 40800,
"author": "user2601",
"author_id": 2601,
"author_profile": "https://Stackoverflow.com/users/2601",
"pm_score": 3,
"selected": true,
"text": "<p>It looks like I just needed to be more specific in my element selector although it is weird that a hard coded number would work.</p>\n\n<pre><code>jQuery('#pagination-digg li').eq(currentPage).addClass(\"active\");\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4320/"
] | Both the jQuery and Prototpye JavaScript libraries refuse to allow me to use a variable to select an list item element by index number although they accept a hard coded number.
For example, in Prototype this works:
```
$$('li')[5].addClassName('active');
```
But this will not work no matter how I try to cast the variable as a number or integer:
```
$$('li')[currentPage].addClassName('active');
```
In jQuery I get similar weirdness. This will work:
```
jQuery('li').eq(5).addClass("active");
```
But this will not work again even though the value of currentPage is 5 and its type is number:
```
jQuery('li').eq(currentPage).addClass("active");
```
I'm trying to create a JavaScript pagination system and I need to set the class on the active page button. The list item elements are created dynamically depending upon the number of pages I need. | It looks like I just needed to be more specific in my element selector although it is weird that a hard coded number would work.
```
jQuery('#pagination-digg li').eq(currentPage).addClass("active");
``` |
40,637 | <p>I'm building an excel template (*.xlt) for a user here, and one of the things I want to do is have it insert the current date when a new document is created (ie, when they double-click the file in windows explorer). How do I do this?</p>
<p><strong>Update:</strong> I should have added that I would prefer not to use any vba (macro). If that's the only option, then so be it, but I'd really like to avoid forcing my user to remember to click some 'allow macro content' button.</p>
| [
{
"answer_id": 40674,
"author": "1729",
"author_id": 4319,
"author_profile": "https://Stackoverflow.com/users/4319",
"pm_score": 2,
"selected": false,
"text": "<p>You can edit the default template for excel - </p>\n\n<p>There is a file called <code>Book.xlt</code> in the <code>XLSTART</code> directory, normally located at <code>C:\\Program Files\\Microsoft Office\\Office\\XLStart\\</code></p>\n\n<p>You should be able to add a macro called Workbook_Open</p>\n\n<pre><code>Private Sub Workbook_Open()\n If ActiveWorkBook.Sheets(1).Range(\"A1\") = \"\" Then\n ActiveWorkBook.Sheets(1).Range(\"A1\") = Now\n End If\nEnd Sub\n</code></pre>\n\n<p>My VBA is a little rusty, but you might find something like this works.</p>\n"
},
{
"answer_id": 40785,
"author": "Graham",
"author_id": 1826,
"author_profile": "https://Stackoverflow.com/users/1826",
"pm_score": 3,
"selected": true,
"text": "<p>You could use the worksheet function =TODAY(), but obviously this would be updated to the current date whenever the workbook is recalculated.</p>\n\n<p>The only other method I can think of is, as 1729 said, to code the Workbook_Open event:</p>\n\n<pre><code>Private Sub Workbook_Open()\n ThisWorkbook.Worksheets(\"Sheet1\").Range(\"A1\").Value = Date\nEnd Sub\n</code></pre>\n\n<p>You can reduce the problem of needing the user to accept macros each time by digitaly signing the template (in VBA IDE Tools | Digital Signature...) and select a digital certificate, however, you will need to get a certificate from a commercial certification authority (see <a href=\"http://msdn.microsoft.com/en-us/library/ms995347.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms995347.aspx</a>). The user will need to select to always trust this certificate the first time they run the template, but thereafter, they will not be prompted again.</p>\n"
},
{
"answer_id": 43285,
"author": "paulmorriss",
"author_id": 2983,
"author_profile": "https://Stackoverflow.com/users/2983",
"pm_score": 0,
"selected": false,
"text": "<p>To avoid VBA, and if you think your users might follow instructions, you could ask them to copy the date and then paste special->values to set the date so that it won't change in future.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] | I'm building an excel template (\*.xlt) for a user here, and one of the things I want to do is have it insert the current date when a new document is created (ie, when they double-click the file in windows explorer). How do I do this?
**Update:** I should have added that I would prefer not to use any vba (macro). If that's the only option, then so be it, but I'd really like to avoid forcing my user to remember to click some 'allow macro content' button. | You could use the worksheet function =TODAY(), but obviously this would be updated to the current date whenever the workbook is recalculated.
The only other method I can think of is, as 1729 said, to code the Workbook\_Open event:
```
Private Sub Workbook_Open()
ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = Date
End Sub
```
You can reduce the problem of needing the user to accept macros each time by digitaly signing the template (in VBA IDE Tools | Digital Signature...) and select a digital certificate, however, you will need to get a certificate from a commercial certification authority (see <http://msdn.microsoft.com/en-us/library/ms995347.aspx>). The user will need to select to always trust this certificate the first time they run the template, but thereafter, they will not be prompted again. |
40,651 | <p>I've inherited a large VB6 app at my current workplace. I'm kinda learning VB6 on the job and there are a number of problems I'm having. The major issue at the moment is I can't figure out how to check if a key exists in a Collection object. Can anyone help?</p>
| [
{
"answer_id": 40659,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 3,
"selected": false,
"text": "<p>I've always done it with a function like this:</p>\n\n<pre><code>public function keyExists(myCollection as collection, sKey as string) as Boolean\n on error goto handleerror:\n\n dim val as variant\n\n val = myCollection(sKey)\n keyExists = true\n exit sub\nhandleerror:\n keyExists = false\nend function\n</code></pre>\n"
},
{
"answer_id": 40751,
"author": "Tom Mayfield",
"author_id": 2314,
"author_profile": "https://Stackoverflow.com/users/2314",
"pm_score": 5,
"selected": false,
"text": "<p>@Mark Biek Your keyExists closely matches my standard Exists() function. To make the class more useful for COM-exposed collections and checking for numeric indexes, I'd recommend changing sKey and myCollection to not be typed. If the function is going to be used with a collection of objects, 'set' is required (on the line where val is set).</p>\n\n<p><strong>EDIT</strong>: It was bugging me that I've never noticed different requirements for an object-based and value-based Exists() function. I very rarely use collections for non-objects, but this seemed such a perfect bottleneck for a bug that would be so hard to track down when I needed to check for existence. Because error handling will fail if an error handler is already active, two functions are required to get a new error scope. Only the Exists() function need ever be called:</p>\n\n<pre><code>Public Function Exists(col, index) As Boolean\nOn Error GoTo ExistsTryNonObject\n Dim o As Object\n\n Set o = col(index)\n Exists = True\n Exit Function\n\nExistsTryNonObject:\n Exists = ExistsNonObject(col, index)\nEnd Function\n\nPrivate Function ExistsNonObject(col, index) As Boolean\nOn Error GoTo ExistsNonObjectErrorHandler\n Dim v As Variant\n\n v = col(index)\n ExistsNonObject = True\n Exit Function\n\nExistsNonObjectErrorHandler:\n ExistsNonObject = False\nEnd Function\n</code></pre>\n\n<p>And to verify the functionality:</p>\n\n<pre><code>Public Sub TestExists()\n Dim c As New Collection\n\n Dim b As New Class1\n\n c.Add \"a string\", \"a\"\n c.Add b, \"b\"\n\n Debug.Print \"a\", Exists(c, \"a\") ' True '\n Debug.Print \"b\", Exists(c, \"b\") ' True '\n Debug.Print \"c\", Exists(c, \"c\") ' False '\n Debug.Print 1, Exists(c, 1) ' True '\n Debug.Print 2, Exists(c, 2) ' True '\n Debug.Print 3, Exists(c, 3) ' False '\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 40831,
"author": "jevakallio",
"author_id": 4333,
"author_profile": "https://Stackoverflow.com/users/4333",
"pm_score": 3,
"selected": false,
"text": "<p>As pointed out by Thomas, you need to Set an object instead of Let. Here's a general function from my library that works for value and object types:</p>\n\n<pre><code>Public Function Exists(ByVal key As Variant, ByRef col As Collection) As Boolean\n\n'Returns True if item with key exists in collection\n\nOn Error Resume Next\n\nConst ERR_OBJECT_TYPE As Long = 438\nDim item As Variant\n\n'Try reach item by key\nitem = col.item(key)\n\n'If no error occurred, key exists\nIf Err.Number = 0 Then\n Exists = True\n\n'In cases where error 438 is thrown, it is likely that\n'the item does exist, but is an object that cannot be Let\nElseIf Err.Number = ERR_OBJECT_TYPE Then\n\n 'Try reach object by key\n Set item = col.item(key)\n\n 'If an object was found, the key exists\n If Not item Is Nothing Then\n Exists = True\n End If\n\nEnd If\n\nErr.Clear\n\nEnd Function\n</code></pre>\n\n<p>As also advised by Thomas, you can change the Collection type to Object to generalize this. The .Item(key) syntax is shared by most collection classes, so that might actually be useful.</p>\n\n<p><strong>EDIT</strong> Seems like I was beaten to the punch somewhat by Thomas himself. However for easier reuse I personally prefer a single function with no private dependencies.</p>\n"
},
{
"answer_id": 52752,
"author": "Kaniu",
"author_id": 3236,
"author_profile": "https://Stackoverflow.com/users/3236",
"pm_score": 2,
"selected": false,
"text": "<p>Using the error handler to catch cases when the key does not exists in the Collection can make debugging with \"break on all errors\" option quite annoying. To avoid unwanted errors I quite often create a class which has the stored objects in a Collection and all keys in a Dictionary. Dictionary has exists(key) -function so I can call that before trying to get an object from the collection. You can only store strings in a Dictionary, so a Collection is still needed if you need to store objects.</p>\n"
},
{
"answer_id": 883192,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Better solution would be to write a TryGet function. A lot of the time you are going to be checking exists, and then getting the item. Save time by doing it at the same time.</p>\n\n<pre><code>public Function TryGet(key as string, col as collection) as Variant\n on error goto errhandler\n Set TryGet= col(key)\n exit function\nerrhandler:\n Set TryGet = nothing \nend function\n</code></pre>\n"
},
{
"answer_id": 1825403,
"author": "Vijay",
"author_id": 107537,
"author_profile": "https://Stackoverflow.com/users/107537",
"pm_score": 2,
"selected": false,
"text": "<p>see\n<a href=\"http://www.visualbasic.happycodings.com/Other/code10.html\" rel=\"nofollow noreferrer\">http://www.visualbasic.happycodings.com/Other/code10.html</a>\nthe implementation here has the advantage of also optionally returning the found element, and works with object/native types (according to the comments).</p>\n\n<p>reproduced here since the link is no longer available:</p>\n\n<p>Determine if an item exists in a collection</p>\n\n<p>The following code shows you how to determine if an item exists within a collection.</p>\n\n<pre><code>Option Explicit\n\n'Purpose : Determines if an item already exists in a collection\n'Inputs : oCollection The collection to test for the existance of the item\n' vIndex The index of the item.\n' [vItem] See Outputs\n'Outputs : Returns True if the item already exists in the collection.\n' [vItem] The value of the item, if it exists, else returns \"empty\".\n'Notes :\n'Example :\n\nFunction CollectionItemExists(vIndex As Variant, oCollection As Collection, Optional vItem As Variant) As Boolean\n On Error GoTo ErrNotExist\n\n 'Clear output result\n If IsObject(vItem) Then\n Set vItem = Nothing\n Else\n vItem = Empty\n End If\n\n If VarType(vIndex) = vbString Then\n 'Test if item exists\n If VarType(oCollection.Item(CStr(vIndex))) = vbObject Then\n 'Return an object\n Set vItem = oCollection.Item(CStr(vIndex))\n Else\n 'Return an standard variable\n vItem = oCollection.Item(CStr(vIndex))\n End If\n Else\n 'Test if item exists\n If VarType(oCollection.Item(Int(vIndex))) = vbObject Then\n 'Return an object\n Set vItem = oCollection.Item(Int(vIndex))\n Else\n 'Return an standard variable\n vItem = oCollection.Item(Int(vIndex))\n End If\n End If\n 'Return success\n CollectionItemExists = True\n Exit Function\nErrNotExist:\n CollectionItemExists = False\n On Error GoTo 0\nEnd Function\n\n'Demonstration routine\nSub Test()\n Dim oColl As New Collection, oValue As Variant\n\n oColl.Add \"red1\", \"KEYA\"\n oColl.Add \"red2\", \"KEYB\"\n 'Return the two items in the collection\n Debug.Print CollectionItemExists(\"KEYA\", oColl, oValue)\n Debug.Print \"Returned: \" & oValue\n Debug.Print \"-----------\"\n Debug.Print CollectionItemExists(2, oColl, oValue)\n Debug.Print \"Returned: \" & oValue\n 'Should fail\n Debug.Print CollectionItemExists(\"KEYC\", oColl, oValue)\n Debug.Print \"Returned: \" & oValue\n Set oColl = Nothing\nEnd Sub\n</code></pre>\n\n<ul>\n<li>See more at: <a href=\"https://web.archive.org/web/20140723190623/http://visualbasic.happycodings.com/other/code10.html#sthash.MlGE42VM.dpuf\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20140723190623/http://visualbasic.happycodings.com/other/code10.html#sthash.MlGE42VM.dpuf</a></li>\n</ul>\n"
},
{
"answer_id": 1825433,
"author": "Christian Hayter",
"author_id": 115413,
"author_profile": "https://Stackoverflow.com/users/115413",
"pm_score": 5,
"selected": false,
"text": "<p>My standard function is very simple. This will work regardless of the element type, since it doesn't bother doing any assignment, it merely executes the collection property get.</p>\n\n<pre><code>Public Function Exists(ByVal oCol As Collection, ByVal vKey As Variant) As Boolean\n\n On Error Resume Next\n oCol.Item vKey\n Exists = (Err.Number = 0)\n Err.Clear\n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 9535221,
"author": "R. van Drie",
"author_id": 1245312,
"author_profile": "https://Stackoverflow.com/users/1245312",
"pm_score": 2,
"selected": false,
"text": "<p>The statement \"error handling will fail if an error handler is already active\" is only partly right.</p>\n\n<p>You can have multiple error handlers within your routine.<br/>\nSo, one could accommodate the same functionality in only one function.<br/>\nJust rewrite your code like this:</p>\n\n<pre><code>Public Function Exists(col, index) As Boolean\nDim v As Variant\n\nTryObject:\n On Error GoTo ExistsTryObject\n Set v = col(index)\n Exists = True\n Exit Function\n\nTryNonObject:\n On Error GoTo ExistsTryNonObject\n\n v = col(index)\n Exists = True\n Exit Function\n\nExistsTryObject:\n ' This will reset your Err Handler\n Resume TryNonObject\n\nExistsTryNonObject:\n Exists = False\nEnd Function\n</code></pre>\n\n<p>However, if you were to only incorporate the code in the TryNonObject section of the routine, this would yield the same information.<br/>\nIt will succeed for both Objects, and non-objects.\nIt will speed up your code for non-objects, however, since you would only have to perform one single statement to assert that the item exists within the collection.</p>\n"
},
{
"answer_id": 15221341,
"author": "Martin",
"author_id": 1261136,
"author_profile": "https://Stackoverflow.com/users/1261136",
"pm_score": 0,
"selected": false,
"text": "<p>While looking for a function like this i designed it as following.\nThis should work with objects and non-objects without assigning new variables.</p>\n\n<pre><code>Public Function Exists(ByRef Col As Collection, ByVal Key) As Boolean\n On Error GoTo KeyError\n If Not Col(Key) Is Nothing Then\n Exists = True\n Else\n Exists = False\n End If\n\n Exit Function\nKeyError:\n Err.Clear\n Exists = False\nEnd Function\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4315/"
] | I've inherited a large VB6 app at my current workplace. I'm kinda learning VB6 on the job and there are a number of problems I'm having. The major issue at the moment is I can't figure out how to check if a key exists in a Collection object. Can anyone help? | @Mark Biek Your keyExists closely matches my standard Exists() function. To make the class more useful for COM-exposed collections and checking for numeric indexes, I'd recommend changing sKey and myCollection to not be typed. If the function is going to be used with a collection of objects, 'set' is required (on the line where val is set).
**EDIT**: It was bugging me that I've never noticed different requirements for an object-based and value-based Exists() function. I very rarely use collections for non-objects, but this seemed such a perfect bottleneck for a bug that would be so hard to track down when I needed to check for existence. Because error handling will fail if an error handler is already active, two functions are required to get a new error scope. Only the Exists() function need ever be called:
```
Public Function Exists(col, index) As Boolean
On Error GoTo ExistsTryNonObject
Dim o As Object
Set o = col(index)
Exists = True
Exit Function
ExistsTryNonObject:
Exists = ExistsNonObject(col, index)
End Function
Private Function ExistsNonObject(col, index) As Boolean
On Error GoTo ExistsNonObjectErrorHandler
Dim v As Variant
v = col(index)
ExistsNonObject = True
Exit Function
ExistsNonObjectErrorHandler:
ExistsNonObject = False
End Function
```
And to verify the functionality:
```
Public Sub TestExists()
Dim c As New Collection
Dim b As New Class1
c.Add "a string", "a"
c.Add b, "b"
Debug.Print "a", Exists(c, "a") ' True '
Debug.Print "b", Exists(c, "b") ' True '
Debug.Print "c", Exists(c, "c") ' False '
Debug.Print 1, Exists(c, 1) ' True '
Debug.Print 2, Exists(c, 2) ' True '
Debug.Print 3, Exists(c, 3) ' False '
End Sub
``` |
40,663 | <p>I'm trying to find a way to validate a large XML file against an XSD. I saw the question <a href="https://stackoverflow.com/questions/15732/whats-the-best-way-to-validate-an-xml-file-against-an-xsd-file">...best way to validate an XML...</a> but the answers all pointed to using the Xerces library for validation. The only problem is, when I use that library to validate a 180 MB file then I get an OutOfMemoryException.</p>
<p>Are there any other tools,libraries, strategies for validating a larger than normal XML file?</p>
<p>EDIT: The SAX solution worked for java validation, but the other two suggestions for the libxml tool were very helpful as well for validation outside of java.</p>
| [
{
"answer_id": 40678,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 6,
"selected": true,
"text": "<p>Instead of using a DOMParser, use a SAXParser. This reads from an input stream or reader so you can keep the XML on disk instead of loading it all into memory.</p>\n\n<pre><code>SAXParserFactory factory = SAXParserFactory.newInstance();\nfactory.setValidating(true);\nfactory.setNamespaceAware(true);\n\nSAXParser parser = factory.newSAXParser();\n\nXMLReader reader = parser.getXMLReader();\nreader.setErrorHandler(new SimpleErrorHandler());\nreader.parse(new InputSource(new FileReader (\"document.xml\")));\n</code></pre>\n"
},
{
"answer_id": 40681,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p>Use <a href=\"http://xmlsoft.org/\" rel=\"noreferrer\">libxml</a>, which performs validation <em>and</em> has a streaming mode.</p>\n"
},
{
"answer_id": 40956,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 2,
"selected": false,
"text": "<p>Personally I like to use <a href=\"http://xmlstar.sourceforge.net/\" rel=\"nofollow noreferrer\">XMLStarlet</a> which has a command line interface, and works on streams. It is a set of tools built on Libxml2.</p>\n"
},
{
"answer_id": 628133,
"author": "GaZ",
"author_id": 62667,
"author_profile": "https://Stackoverflow.com/users/62667",
"pm_score": 1,
"selected": false,
"text": "<p>SAX and libXML will help, as already mentioned. You could also try increasing the maximum heap size for the JVM using the -Xmx option. E.g. to set the maximum heap size to 512MB: <code>java -Xmx512m com.foo.MyClass</code></p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3274/"
] | I'm trying to find a way to validate a large XML file against an XSD. I saw the question [...best way to validate an XML...](https://stackoverflow.com/questions/15732/whats-the-best-way-to-validate-an-xml-file-against-an-xsd-file) but the answers all pointed to using the Xerces library for validation. The only problem is, when I use that library to validate a 180 MB file then I get an OutOfMemoryException.
Are there any other tools,libraries, strategies for validating a larger than normal XML file?
EDIT: The SAX solution worked for java validation, but the other two suggestions for the libxml tool were very helpful as well for validation outside of java. | Instead of using a DOMParser, use a SAXParser. This reads from an input stream or reader so you can keep the XML on disk instead of loading it all into memory.
```
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setErrorHandler(new SimpleErrorHandler());
reader.parse(new InputSource(new FileReader ("document.xml")));
``` |
40,665 | <p>I'm maintaining some code that uses a *= operator in a query to a Sybase database and I can't find documentation on it. Does anyone know what *= does? I assume that it is some sort of a join.</p>
<pre><code>select * from a, b where a.id *= b.id</code></pre>
<p>I can't figure out how this is different from:</p>
<pre><code>select * from a, b where a.id = b.id</code></pre>
| [
{
"answer_id": 40671,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "<p>It means outer join, a simple = means inner join.</p>\n\n<pre><code>*= is LEFT JOIN and =* is RIGHT JOIN.\n</code></pre>\n\n<p>(or vice versa, I keep forgetting since I'm not using it any more, and Google isn't helpful when searching for *=)</p>\n"
},
{
"answer_id": 40684,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 5,
"selected": true,
"text": "<p>From <a href=\"http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc34982_1500/html/mig_gde/mig_gde160.htm\" rel=\"noreferrer\">http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc34982_1500/html/mig_gde/mig_gde160.htm</a>:</p>\n\n<p>Inner and outer tables</p>\n\n<p>The terms outer table and inner table describe the placement of the tables in an outer join:</p>\n\n<ul>\n<li><p>In a left join, the outer table and inner table are the left and right tables respectively. The outer table and inner table are also referred to as the row-preserving and null-supplying tables, respectively.</p></li>\n<li><p>In a right join, the outer table and inner table are the right and left tables respectively.</p></li>\n</ul>\n\n<p>For example, in the queries below, T1 is the outer table and T2 is the inner table:</p>\n\n<ul>\n<li>T1 left join T2</li>\n<li>T2 right join T1</li>\n</ul>\n\n<p>Or, using Transact-SQL syntax:</p>\n\n<ul>\n<li>T1 *= T2</li>\n<li>T2 =* T1</li>\n</ul>\n"
},
{
"answer_id": 40698,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<p>Of course, you <em>should</em> write it this way:</p>\n\n<pre><code>SELECT *\nFROM a\nLEFT JOIN b ON b.id=a.id\n</code></pre>\n\n<p>The a,b syntax is evil.</p>\n"
},
{
"answer_id": 40700,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 1,
"selected": false,
"text": "<pre><code>select * from a, b where a.id = b.id</code></pre>\n\n<p>Requires that a row exist in where b.id = a.id in order to return an answer</p>\n\n<pre><code>select * from a, b where a.id *= b.id</code></pre>\n\n<p>Will fill the columns from b with nulls when there wasn't a row in b where b.id = a.id.</p>\n"
},
{
"answer_id": 40702,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 3,
"selected": false,
"text": "<p>ANSI-82 syntax </p>\n\n<pre><code>select \n * \nfrom \n a\n , b \n\nwhere \n a.id *= b.id\n</code></pre>\n\n<p>ANSI-92</p>\n\n<pre><code>select \n * \nfrom \n a\n left outer join b \n on a.id = b.id\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
] | I'm maintaining some code that uses a \*= operator in a query to a Sybase database and I can't find documentation on it. Does anyone know what \*= does? I assume that it is some sort of a join.
```
select * from a, b where a.id *= b.id
```
I can't figure out how this is different from:
```
select * from a, b where a.id = b.id
``` | From <http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc34982_1500/html/mig_gde/mig_gde160.htm>:
Inner and outer tables
The terms outer table and inner table describe the placement of the tables in an outer join:
* In a left join, the outer table and inner table are the left and right tables respectively. The outer table and inner table are also referred to as the row-preserving and null-supplying tables, respectively.
* In a right join, the outer table and inner table are the right and left tables respectively.
For example, in the queries below, T1 is the outer table and T2 is the inner table:
* T1 left join T2
* T2 right join T1
Or, using Transact-SQL syntax:
* T1 \*= T2
* T2 =\* T1 |
40,692 | <p>Is it possible to create a REST web service using ASP.NET 2.0? The articles and blog entries I am finding all seem to indicate that ASP.NET 3.5 with WCF is required to create REST web services with ASP.NET.</p>
<p>If it is possible to create REST web services in ASP.NET 2.0 can you provide an example.</p>
<p>Thanks!</p>
| [
{
"answer_id": 40701,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>I'm only just beginning to use them, but from what I've seen 2.0 pretty assumes SOAP.</p>\n"
},
{
"answer_id": 40726,
"author": "Ubiguchi",
"author_id": 2562,
"author_profile": "https://Stackoverflow.com/users/2562",
"pm_score": 1,
"selected": false,
"text": "<p>You can certainly create RESTful web services in ASP.NET 2.0, for <a href=\"http://blogs.msdn.com/dseven/archive/2007/02/10/boise-code-camp-enabling-rest-in-asp-net.aspx\" rel=\"nofollow noreferrer\">example</a>, but there are no high-level APIs to do all the donkey work for you, as provided by WCF in .NET 3.5.</p>\n"
},
{
"answer_id": 40728,
"author": "Nathan Lee",
"author_id": 3453,
"author_profile": "https://Stackoverflow.com/users/3453",
"pm_score": 4,
"selected": true,
"text": "<p>I have actually created a REST web service with asp.net 2.0. Its really no different than creating a web page.</p>\n\n<p>When I did it, I really didn't have much time to research how to do it with an asmx file so I did it in a standard aspx file. I know thier is extra overhead by doing it this way but as a first revision it was fine.</p>\n\n<pre><code>protected void PageLoad(object sender, EventArgs e)\n{\n using (XmlWriter xm = XmlWriter.Create(Response.OutputStream, GetXmlSettings()))\n {\n //do your stuff\n xm.Flush();\n }\n}\n\n /// <summary>\n /// Create Xml Settings object to properly format the output of the xml doc.\n /// </summary>\n private static XmlWriterSettings GetXmlSettings()\n {\n XmlWriterSettings xmlSettings = new XmlWriterSettings();\n xmlSettings.Indent = true;\n xmlSettings.IndentChars = \" \";\n return xmlSettings;\n }\n</code></pre>\n\n<p>That should be enough to get you started, I will try and post more later.</p>\n\n<p>Also if you need basic authentication for your web service it can be done, but it needs to be done manually if you aren't using active directory.</p>\n"
},
{
"answer_id": 40731,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>Well, of course you could always implement the spec yourself. It's just that there's nothing built-in to support it. If you use Nathan Lee's solution, do it as an http handler (.ashx) rather than an aspx. You can just about copy/paste his code into a new handler file.</p>\n"
},
{
"answer_id": 40748,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>You can do RESTful web services easily by implementing the spec using IHTTPHandlers.</p>\n"
},
{
"answer_id": 41151,
"author": "jdiaz",
"author_id": 831,
"author_profile": "https://Stackoverflow.com/users/831",
"pm_score": 2,
"selected": false,
"text": "<p>It is definitely possible to create RESTful web services using ASP.NET. If you are starting a new project I would definitely look into creating RESTful web services using WCF. The 3.5 .NET Framework allows you to specify RESTful endpoint along with a regular old SOAP endpoint and still deliver the same service.</p>\n\n<p>All you really have to do is enable an endpointbehavior that calls out <code><webHttp /></code></p>\n\n<p>Here is a good series on creating RESTful web services using WCF: </p>\n\n<p><a href=\"http://blogs.msdn.com/bags/archive/2008/08/05/rest-in-wcf-blog-series-index.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/bags/archive/2008/08/05/rest-in-wcf-blog-series-index.aspx</a></p>\n"
},
{
"answer_id": 1545720,
"author": "Piers",
"author_id": 187407,
"author_profile": "https://Stackoverflow.com/users/187407",
"pm_score": 1,
"selected": false,
"text": "<p>Also check out using ASP.Net MVC. I've written some articles on this at my blog:</p>\n\n<p><a href=\"http://shouldersofgiants.co.uk/Blog/\" rel=\"nofollow noreferrer\">http://shouldersofgiants.co.uk/Blog/</a></p>\n\n<p>Look for my Creating a RESTful Web Service Using ASP.Net MVC series</p>\n"
},
{
"answer_id": 11249993,
"author": "user1186065",
"author_id": 1186065,
"author_profile": "https://Stackoverflow.com/users/1186065",
"pm_score": 0,
"selected": false,
"text": "<p>You can create RESTful service using </p>\n\n<p>1) WCF REST service\n2) ASP.NET Web API</p>\n\n<p>If you all care about RESTful service, ASP.NET web api is that you should go with. But if you need service that supports both SOAP webservice and RESTful then WCF REST would be a good choice. </p>\n\n<p>There are some articles that discuss about one versus another. This <a href=\"http://patelshailesh.com/index.php/what-is-resful-service-and-designning-restful-service-using-asp-net\" rel=\"nofollow\">article</a> may be helpful. </p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3498/"
] | Is it possible to create a REST web service using ASP.NET 2.0? The articles and blog entries I am finding all seem to indicate that ASP.NET 3.5 with WCF is required to create REST web services with ASP.NET.
If it is possible to create REST web services in ASP.NET 2.0 can you provide an example.
Thanks! | I have actually created a REST web service with asp.net 2.0. Its really no different than creating a web page.
When I did it, I really didn't have much time to research how to do it with an asmx file so I did it in a standard aspx file. I know thier is extra overhead by doing it this way but as a first revision it was fine.
```
protected void PageLoad(object sender, EventArgs e)
{
using (XmlWriter xm = XmlWriter.Create(Response.OutputStream, GetXmlSettings()))
{
//do your stuff
xm.Flush();
}
}
/// <summary>
/// Create Xml Settings object to properly format the output of the xml doc.
/// </summary>
private static XmlWriterSettings GetXmlSettings()
{
XmlWriterSettings xmlSettings = new XmlWriterSettings();
xmlSettings.Indent = true;
xmlSettings.IndentChars = " ";
return xmlSettings;
}
```
That should be enough to get you started, I will try and post more later.
Also if you need basic authentication for your web service it can be done, but it needs to be done manually if you aren't using active directory. |
40,705 | <p>At the beginning of all my executable Python scripts I put the <a href="http://en.wikipedia.org/wiki/Shebang_(Unix)" rel="noreferrer">shebang</a> line:</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>I'm running these scripts on a system where <code>env python</code> yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version:</p>
<pre><code>if sys.version_info < (2, 4):
raise ImportError("Cannot run with Python version < 2.4")
</code></pre>
<p>I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of <code>env python</code> and I don't want to force a particular version, as in:</p>
<pre><code>#!/usr/bin/env python2.4
</code></pre>
<p>I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4.</p>
<p>What's the elegant solution?</p>
<p>[Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in <code>~/bin</code> and ensuring your PATH has <code>~/bin</code> before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks?</p>
| [
{
"answer_id": 40715,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>\"env\" simply executes the first thing it finds in the PATH env var. To switch to different python, prepend the directory for that python's executable to the path before invoking your script.</p>\n"
},
{
"answer_id": 40721,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 2,
"selected": false,
"text": "<p>If you are running the scripts then you can set your PATH variable to point to a private bin directory first:</p>\n\n<pre><code>$ mkdir ~/bin\n$ ln -s `which python2.4` ~/bin/python\n$ export PATH=~/bin:$PATH\n</code></pre>\n\n<p>Then when you execute your python script it'll use python 2.4. You'll have to change your login scripts to change your PATH.</p>\n\n<p>Alternatively run your python script with the explicit interpreter you want:</p>\n\n<pre><code>$ /path/to/python2.4 <your script>\n</code></pre>\n"
},
{
"answer_id": 42516,
"author": "morais",
"author_id": 2846,
"author_profile": "https://Stackoverflow.com/users/2846",
"pm_score": 2,
"selected": false,
"text": "<p>Pretty hackish solution - if your check fails, use this function (which probably could be significantly improved) to determine the best interpreter available, determine if it is acceptable, and if so relaunch your script with os.system or something similar and your sys.argv using the new interpreter.</p>\n\n<pre><code>import os\nimport glob\ndef best_python():\n plist = []\n for i in os.getenv(\"PATH\").split(\":\"):\n for j in glob.glob(os.path.join(i, \"python2.[0-9]\")):\n plist.append(os.path.join(i, j))\n plist.sort()\n plist.reverse()\n if len(plist) == 0: return None\n return plist[0]\n</code></pre>\n"
},
{
"answer_id": 42794,
"author": "cdleary",
"author_id": 3594,
"author_profile": "https://Stackoverflow.com/users/3594",
"pm_score": 0,
"selected": false,
"text": "<p>@morais: That's an interesting idea, but I think maybe we can take it one step farther. Maybe there's a way to use <a href=\"http://pypi.python.org/pypi/virtualenv\" rel=\"nofollow noreferrer\">Ian Bicking's virtualenv</a> to:</p>\n\n<ul>\n<li>See if we're running in an acceptable environment to begin with, and if so, do nothing.</li>\n<li>Check if there exists a version-specific executable on the <code>PATH</code>, i.e. check if <code>python2.x</code> exists <code>for x in reverse(range(4, 10))</code>. If so, re-run the command with the better interpreter.</li>\n<li>If no better interpreter exists, use virtualenv to try and install a newer version of Python from the older version of Python and get any prerequisite packages.</li>\n</ul>\n\n<p>I have no idea if virtualenv is capable of this, so I'll go mess around with it sometime soon. :)</p>\n"
},
{
"answer_id": 19188285,
"author": "Alex Nelson",
"author_id": 1207160,
"author_profile": "https://Stackoverflow.com/users/1207160",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a solution if you're (1) absolutely set on using shebangs and (2) able to use Autotools in your build process.</p>\n\n<p>I just found last night that you can use the autoconf macro <code>AM_PATH_PYTHON</code> to find a minimal Python <strong>2</strong> binary. The how-to is <a href=\"https://stackoverflow.com/a/19173018/1207160\">here</a>.</p>\n\n<p>So, your process would be:</p>\n\n<ul>\n<li>Issue an <code>AM_PATH_PYTHON(2.4)</code> in your <code>configure.ac</code></li>\n<li>Rename all of your <code>.py</code> scripts to <code>.py.in</code> (in my experience, this doesn't confuse <code>vi</code>)</li>\n<li>Name all of those Python scripts you want to generate with <code>AC_CONFIG_FILES</code>.</li>\n<li>Instead of starting with <code>#!/usr/bin/env python</code>, use <code>#!@PYTHON@</code></li>\n</ul>\n\n<p>Then your <em>resultant</em> Python scripts will always have an appropriate shebang.</p>\n\n<p>So, you have this solution, at least possible, if not practical.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] | At the beginning of all my executable Python scripts I put the [shebang](http://en.wikipedia.org/wiki/Shebang_(Unix)) line:
```
#!/usr/bin/env python
```
I'm running these scripts on a system where `env python` yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version:
```
if sys.version_info < (2, 4):
raise ImportError("Cannot run with Python version < 2.4")
```
I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of `env python` and I don't want to force a particular version, as in:
```
#!/usr/bin/env python2.4
```
I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4.
What's the elegant solution?
[Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in `~/bin` and ensuring your PATH has `~/bin` before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks? | "env" simply executes the first thing it finds in the PATH env var. To switch to different python, prepend the directory for that python's executable to the path before invoking your script. |
40,730 | <p>How do you give a C# auto-property an initial value?</p>
<p>I either use the constructor, or revert to the old syntax. </p>
<p><strong> Using the Constructor:</strong></p>
<pre><code>class Person
{
public Person()
{
Name = "Initial Name";
}
public string Name { get; set; }
}
</code></pre>
<p><strong>Using normal property syntax</strong> (with an initial value)</p>
<pre><code>private string name = "Initial Name";
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
</code></pre>
<p>Is there a better way?</p>
| [
{
"answer_id": 40734,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 3,
"selected": false,
"text": "<p>Have you tried using the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx\" rel=\"noreferrer\">DefaultValueAttribute</a> or <a href=\"http://msdn.microsoft.com/en-us/library/53b8022e%28VS.71%29.aspx\" rel=\"noreferrer\">ShouldSerialize and Reset methods</a> in conjunction with the constructor? I feel like one of these two methods is necessary if you're making a class that might show up on the designer surface or in a property grid.</p>\n"
},
{
"answer_id": 40754,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 12,
"selected": true,
"text": "<p>In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor.</p>\n<p>Since <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history#c-version-60\" rel=\"noreferrer\">C# 6.0</a>, you can specify initial value in-line. The syntax is:</p>\n<pre><code>public int X { get; set; } = x; // C# 6 or higher\n</code></pre>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.defaultvalueattribute?view=netframework-4.8\" rel=\"noreferrer\"><code>DefaultValueAttribute</code></a> is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value).</p>\n<p>At compile time <code>DefaultValueAttribute</code> will not impact the generated IL and it will not be read to initialize the property to that value (see <a href=\"https://stackoverflow.com/questions/1980520/defaultvalue-attribute-is-not-working-with-my-auto-property\">DefaultValue attribute is not working with my Auto Property</a>).</p>\n<p>Example of attributes that impact the IL are <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threadstaticattribute?view=netframework-4.8\" rel=\"noreferrer\"><code>ThreadStaticAttribute</code></a>, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute?view=netframework-4.8\" rel=\"noreferrer\"><code>CallerMemberNameAttribute</code></a>, ...</p>\n"
},
{
"answer_id": 40882,
"author": "crucible",
"author_id": 3717,
"author_profile": "https://Stackoverflow.com/users/3717",
"pm_score": 6,
"selected": false,
"text": "<p>Sometimes I use this, if I don't want it to be actually set and persisted in my db:</p>\n\n<pre><code>class Person\n{\n private string _name; \n public string Name \n { \n get \n {\n return string.IsNullOrEmpty(_name) ? \"Default Name\" : _name;\n } \n\n set { _name = value; } \n }\n}\n</code></pre>\n\n<p>Obviously if it's not a string then I might make the object nullable ( double?, int? ) and check if it's null, return a default, or return the value it's set to.</p>\n\n<p>Then I can make a check in my repository to see if it's my default and not persist, or make a backdoor check in to see the true status of the backing value, before saving.</p>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 41146,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p><em>This is old now, and my position has changed. I'm leaving the original answer for posterity only.</em></p>\n<hr />\n<p>Personally, I don't see the point of making it a property at all if you're not going to do anything at all beyond the auto-property. Just leave it as a field. The encapsulation benefit for these item are just red herrings, because there's nothing behind them to encapsulate. If you ever need to change the underlying implementation you're still free to refactor them as properties without breaking any dependent code.</p>\n<p>Hmm... maybe this will be the subject of it's own question later</p>\n"
},
{
"answer_id": 43594,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 8,
"selected": false,
"text": "<p>When you inline an initial value for a variable it will be done implicitly in the constructor anyway.</p>\n\n<p>I would argue that this syntax was best practice in C# up to 5:</p>\n\n<pre><code>class Person \n{\n public Person()\n {\n //do anything before variable assignment\n\n //assign initial values\n Name = \"Default Name\";\n\n //do anything after variable assignment\n }\n public string Name { get; set; }\n}\n</code></pre>\n\n<p>As this gives you clear control of the order values are assigned.</p>\n\n<p>As of C#6 there is a new way:</p>\n\n<pre><code>public string Name { get; set; } = \"Default Name\";\n</code></pre>\n"
},
{
"answer_id": 44197,
"author": "Lex",
"author_id": 4109,
"author_profile": "https://Stackoverflow.com/users/4109",
"pm_score": 4,
"selected": false,
"text": "<p>In C# 6 and above you can simply use the syntax:</p>\n\n<pre><code>public object Foo { get; set; } = bar;\n</code></pre>\n\n<p>Note that to have a <code>readonly</code> property simply omit the set, as so:</p>\n\n<pre><code>public object Foo { get; } = bar;\n</code></pre>\n\n<p>You can also assign <code>readonly</code> auto-properties from the constructor.</p>\n\n<p>Prior to this I responded as below.</p>\n\n<p>I'd avoid adding a default to the constructor; leave that for dynamic assignments and avoid having two points at which the variable is assigned (i.e. the type default and in the constructor). Typically I'd simply write a normal property in such cases.</p>\n\n<p>One other option is to do what ASP.Net does and define defaults via an attribute:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx</a></p>\n"
},
{
"answer_id": 3059751,
"author": "ghiboz",
"author_id": 349045,
"author_profile": "https://Stackoverflow.com/users/349045",
"pm_score": 4,
"selected": false,
"text": "<p>little complete sample:</p>\n\n<pre><code>using System.ComponentModel;\n\nprivate bool bShowGroup ;\n[Description(\"Show the group table\"), Category(\"Sea\"),DefaultValue(true)]\npublic bool ShowGroup\n{\n get { return bShowGroup; }\n set { bShowGroup = value; }\n}\n</code></pre>\n"
},
{
"answer_id": 6143989,
"author": "Nag",
"author_id": 771935,
"author_profile": "https://Stackoverflow.com/users/771935",
"pm_score": 0,
"selected": false,
"text": "<pre><code>class Person \n{ \n /// Gets/sets a value indicating whether auto \n /// save of review layer is enabled or not\n [System.ComponentModel.DefaultValue(true)] \n public bool AutoSaveReviewLayer { get; set; }\n}\n</code></pre>\n"
},
{
"answer_id": 6444527,
"author": "Chuck Rostance",
"author_id": 810915,
"author_profile": "https://Stackoverflow.com/users/810915",
"pm_score": 8,
"selected": false,
"text": "<p><strong>Edited on 1/2/15</strong></p>\n<p><strong>C# 6</strong> :</p>\n<p>With C# 6 you can initialize auto-properties directly (finally!), there are now other answers that describe that.</p>\n<p><strong>C# 5 and below</strong>:</p>\n<p>Though the intended use of the attribute is not to actually set the values of the properties, you can use reflection to always set them anyway...</p>\n<pre><code>public class DefaultValuesTest\n{ \n public DefaultValuesTest()\n { \n foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(this))\n {\n DefaultValueAttribute myAttribute = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)];\n\n if (myAttribute != null)\n {\n property.SetValue(this, myAttribute.Value);\n }\n }\n }\n\n public void DoTest()\n {\n var db = DefaultValueBool;\n var ds = DefaultValueString;\n var di = DefaultValueInt;\n }\n\n\n [System.ComponentModel.DefaultValue(true)]\n public bool DefaultValueBool { get; set; }\n\n [System.ComponentModel.DefaultValue("Good")]\n public string DefaultValueString { get; set; }\n\n [System.ComponentModel.DefaultValue(27)]\n public int DefaultValueInt { get; set; }\n}\n</code></pre>\n"
},
{
"answer_id": 11738668,
"author": "Zack Jannsen",
"author_id": 1247236,
"author_profile": "https://Stackoverflow.com/users/1247236",
"pm_score": 2,
"selected": false,
"text": "<p>To clarify, yes, you need to set default values in the constructor for class derived objects. You will need to ensure the constructor exists with the proper access modifier for construction where used. If the object is not instantiated, e.g. it has no constructor (e.g. static methods) then the default value can be set by the field. The reasoning here is that the object itself will be created only once and you do not instantiate it. </p>\n\n<p>@Darren Kopp - good answer, clean, and correct. And to reiterate, you CAN write constructors for Abstract methods. You just need to access them from the base class when writing the constructor: </p>\n\n<p>Constructor at Base Class:</p>\n\n<pre><code>public BaseClassAbstract()\n{\n this.PropertyName = \"Default Name\";\n}\n</code></pre>\n\n<p>Constructor at Derived / Concrete / Sub-Class:</p>\n\n<pre><code>public SubClass() : base() { }\n</code></pre>\n\n<p>The point here is that the instance variable drawn from the base class may bury your base field name. Setting the current instantiated object value using \"this.\" will allow you to correctly form your object with respect to the current instance and required permission levels (access modifiers) where you are instantiating it.</p>\n"
},
{
"answer_id": 14388960,
"author": "introspected",
"author_id": 1988564,
"author_profile": "https://Stackoverflow.com/users/1988564",
"pm_score": 4,
"selected": false,
"text": "<p>My solution is to use a custom attribute that provides default value property initialization by constant or using property type initializer.</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]\npublic class InstanceAttribute : Attribute\n{\n public bool IsConstructorCall { get; private set; }\n public object[] Values { get; private set; }\n public InstanceAttribute() : this(true) { }\n public InstanceAttribute(object value) : this(false, value) { }\n public InstanceAttribute(bool isConstructorCall, params object[] values)\n {\n IsConstructorCall = isConstructorCall;\n Values = values ?? new object[0];\n }\n}\n</code></pre>\n\n<p>To use this attribute it's necessary to inherit a class from special base class-initializer or use a static helper method:</p>\n\n<pre><code>public abstract class DefaultValueInitializer\n{\n protected DefaultValueInitializer()\n {\n InitializeDefaultValues(this);\n }\n\n public static void InitializeDefaultValues(object obj)\n {\n var props = from prop in obj.GetType().GetProperties()\n let attrs = prop.GetCustomAttributes(typeof(InstanceAttribute), false)\n where attrs.Any()\n select new { Property = prop, Attr = ((InstanceAttribute)attrs.First()) };\n foreach (var pair in props)\n {\n object value = !pair.Attr.IsConstructorCall && pair.Attr.Values.Length > 0\n ? pair.Attr.Values[0]\n : Activator.CreateInstance(pair.Property.PropertyType, pair.Attr.Values);\n pair.Property.SetValue(obj, value, null);\n }\n }\n}\n</code></pre>\n\n<p>Usage example:</p>\n\n<pre><code>public class Simple : DefaultValueInitializer\n{\n [Instance(\"StringValue\")]\n public string StringValue { get; set; }\n [Instance]\n public List<string> Items { get; set; }\n [Instance(true, 3,4)]\n public Point Point { get; set; }\n}\n\npublic static void Main(string[] args)\n{\n var obj = new Simple\n {\n Items = {\"Item1\"}\n };\n Console.WriteLine(obj.Items[0]);\n Console.WriteLine(obj.Point);\n Console.WriteLine(obj.StringValue);\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Item1\n(X=3,Y=4)\nStringValue\n</code></pre>\n"
},
{
"answer_id": 20434213,
"author": "user3076134",
"author_id": 3076134,
"author_profile": "https://Stackoverflow.com/users/3076134",
"pm_score": -1,
"selected": false,
"text": "<p>I think this would do it for ya givng SomeFlag a default of false.</p>\n\n<pre><code>private bool _SomeFlagSet = false;\npublic bool SomeFlag\n{\n get\n {\n if (!_SomeFlagSet)\n SomeFlag = false; \n\n return SomeFlag;\n }\n set\n {\n if (!_SomeFlagSet)\n _SomeFlagSet = true;\n\n SomeFlag = value; \n }\n}\n</code></pre>\n"
},
{
"answer_id": 23367865,
"author": "Habib",
"author_id": 961113,
"author_profile": "https://Stackoverflow.com/users/961113",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Starting with C# 6.0</strong>, We can assign default value to auto-implemented properties. </p>\n\n<pre><code>public string Name { get; set; } = \"Some Name\";\n</code></pre>\n\n<p>We can also create read-only auto implemented property like:</p>\n\n<pre><code>public string Name { get; } = \"Some Name\";\n</code></pre>\n\n<p>See: <a href=\"http://blogs.msmvps.com/jonskeet/2014/04/04/c-6-first-reactions/\">C# 6: First reactions , Initializers for automatically implemented properties - By Jon Skeet</a></p>\n"
},
{
"answer_id": 25674677,
"author": "FloodMoo",
"author_id": 3710310,
"author_profile": "https://Stackoverflow.com/users/3710310",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public Class ClassName{\n public int PropName{get;set;}\n public ClassName{\n PropName=0; //Default Value\n }\n}\n</code></pre>\n"
},
{
"answer_id": 34720487,
"author": "Preet Singh",
"author_id": 4244007,
"author_profile": "https://Stackoverflow.com/users/4244007",
"pm_score": 2,
"selected": false,
"text": "<p>Use the constructor because \"When the constructor is finished, Construction should be finished\". properties are like states your classes hold, if you had to initialize a default state, you would do that in your constructor.</p>\n"
},
{
"answer_id": 38441949,
"author": "RayLoveless",
"author_id": 462971,
"author_profile": "https://Stackoverflow.com/users/462971",
"pm_score": 3,
"selected": false,
"text": "<p>In the constructor. The constructor's purpose is to initialized it's data members.</p>\n"
},
{
"answer_id": 38576042,
"author": "Shiva",
"author_id": 325521,
"author_profile": "https://Stackoverflow.com/users/325521",
"pm_score": 6,
"selected": false,
"text": "<h3>In C# 6.0 this is a breeze!</h3>\n\n<p>You can do it in the <code>Class</code> declaration itself, in the property declaration statements.</p>\n\n<pre><code>public class Coordinate\n{ \n public int X { get; set; } = 34; // get or set auto-property with initializer\n\n public int Y { get; } = 89; // read-only auto-property with initializer\n\n public int Z { get; } // read-only auto-property with no initializer\n // so it has to be initialized from constructor \n\n public Coordinate() // .ctor()\n {\n Z = 42;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 40325486,
"author": "brakeroo",
"author_id": 7070657,
"author_profile": "https://Stackoverflow.com/users/7070657",
"pm_score": 5,
"selected": false,
"text": "<p>In addition to the answer already accepted, for the scenario when you want to define a default property as a <em>function</em> of other properties you can use <strong><em>expression body notation</em></strong> on C#6.0 (and higher) for even more elegant and concise constructs like:</p>\n\n<pre><code>public class Person{\n\n public string FullName => $\"{First} {Last}\"; // expression body notation\n\n public string First { get; set; } = \"First\";\n public string Last { get; set; } = \"Last\";\n}\n</code></pre>\n\n<p>You can use the above in the following fashion </p>\n\n<pre><code> var p = new Person();\n\n p.FullName; // First Last\n\n p.First = \"Jon\";\n p.Last = \"Snow\";\n\n p.FullName; // Jon Snow\n</code></pre>\n\n<p>In order to be able to use the above \"=>\" notation, the property must be read only, and you do not use the get accessor keyword.</p>\n\n<p>Details on <a href=\"https://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx\" rel=\"noreferrer\">MSDN</a></p>\n"
},
{
"answer_id": 42799414,
"author": "ANewGuyInTown",
"author_id": 2727444,
"author_profile": "https://Stackoverflow.com/users/2727444",
"pm_score": 5,
"selected": false,
"text": "<p>In Version of <em>C# (6.0) & greater</em>, you can do : </p>\n\n<p><strong>For Readonly properties</strong></p>\n\n<pre><code>public int ReadOnlyProp => 2;\n</code></pre>\n\n<p><strong>For both Writable & Readable properties</strong></p>\n\n<pre><code>public string PropTest { get; set; } = \"test\";\n</code></pre>\n\n<p>In current Version of <em>C# (7.0)</em>, you can do : (The snippet rather displays how you can use expression bodied get/set accessors to make is more compact when using with backing fields)</p>\n\n<pre><code>private string label = \"Default Value\";\n\n// Expression-bodied get / set accessors.\npublic string Label\n{\n get => label;\n set => this.label = value; \n }\n</code></pre>\n"
},
{
"answer_id": 53103732,
"author": "ComeIn",
"author_id": 909122,
"author_profile": "https://Stackoverflow.com/users/909122",
"pm_score": 3,
"selected": false,
"text": "<pre><code>private string name;\npublic string Name \n{\n get \n {\n if(name == null)\n {\n name = \"Default Name\";\n }\n return name;\n }\n set\n {\n name = value;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 54750202,
"author": "SUNIL DHAPPADHULE",
"author_id": 9452616,
"author_profile": "https://Stackoverflow.com/users/9452616",
"pm_score": 3,
"selected": false,
"text": "<p><strong>You can simple put like this</strong></p>\n\n<pre><code>public sealed class Employee\n{\n public int Id { get; set; } = 101;\n}\n</code></pre>\n"
},
{
"answer_id": 61993894,
"author": "Jesse Adam",
"author_id": 2551539,
"author_profile": "https://Stackoverflow.com/users/2551539",
"pm_score": -1,
"selected": false,
"text": "<p>I know this is an old question, but it came up when I was looking for how to have a default value that gets inherited with the option to override, I came up with</p>\n\n<pre><code>//base class\npublic class Car\n{\n public virtual string FuelUnits\n {\n get { return \"gasoline in gallons\"; }\n protected set { }\n }\n}\n//derived\npublic class Tesla : Car\n{\n public override string FuelUnits => \"ampere hour\";\n}\n</code></pre>\n"
},
{
"answer_id": 67673580,
"author": "codez0mb1e",
"author_id": 1507068,
"author_profile": "https://Stackoverflow.com/users/1507068",
"pm_score": 5,
"selected": false,
"text": "<p>In <strong>C# 9.0</strong> was <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/init\" rel=\"noreferrer\">added support</a> of <code>init</code> keyword - very useful and <strong>extremly sophisticated way</strong> for declaration <em>read-only auto-properties</em>:</p>\n<p>Declare:</p>\n<pre><code>class Person \n{ \n public string Name { get; init; } = "Anonymous user";\n}\n</code></pre>\n<p>~Enjoy~ Use:</p>\n<pre><code>// 1. Person with default name\nvar anonymous = new Person();\nConsole.WriteLine($"Hello, {anonymous.Name}!");\n// > Hello, Anonymous user!\n\n\n// 2. Person with assigned value\nvar me = new Person { Name = "@codez0mb1e"};\nConsole.WriteLine($"Hello, {me.Name}!");\n// > Hello, @codez0mb1e!\n\n\n// 3. Attempt to re-assignment Name\nme.Name = "My fake"; \n// > Compilation error: Init-only property can only be assigned in an object initializer\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/946/"
] | How do you give a C# auto-property an initial value?
I either use the constructor, or revert to the old syntax.
**Using the Constructor:**
```
class Person
{
public Person()
{
Name = "Initial Name";
}
public string Name { get; set; }
}
```
**Using normal property syntax** (with an initial value)
```
private string name = "Initial Name";
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
```
Is there a better way? | In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor.
Since [C# 6.0](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history#c-version-60), you can specify initial value in-line. The syntax is:
```
public int X { get; set; } = x; // C# 6 or higher
```
[`DefaultValueAttribute`](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.defaultvalueattribute?view=netframework-4.8) is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value).
At compile time `DefaultValueAttribute` will not impact the generated IL and it will not be read to initialize the property to that value (see [DefaultValue attribute is not working with my Auto Property](https://stackoverflow.com/questions/1980520/defaultvalue-attribute-is-not-working-with-my-auto-property)).
Example of attributes that impact the IL are [`ThreadStaticAttribute`](https://learn.microsoft.com/en-us/dotnet/api/system.threadstaticattribute?view=netframework-4.8), [`CallerMemberNameAttribute`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute?view=netframework-4.8), ... |
40,737 | <p><a href="https://stackoverflow.com/questions/32230/tracking-down-where-disk-space-has-gone-on-linux">In this question</a> someone asked for ways to display disk usage in Linux. I'd like to take this one step further down the cli-path... how about a shell script that takes the output from something like a reasonable answer to the previous question and generates a graph/chart from it (output in a png file or something)? This may be a bit too much code to ask for in a regular question, but my guess is that someone already has a oneliner laying around somewhere...</p>
| [
{
"answer_id": 40862,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 1,
"selected": false,
"text": "<p>I guess there are a couple of options:</p>\n\n<ol>\n<li><p>For a pure CLI solution, use something like gnuplot. See <a href=\"http://t16web.lanl.gov/Kawano/gnuplot/intro/working-e.html\" rel=\"nofollow noreferrer\">here</a> for example usage. I haven't used gnuplot since my student days :-)</p></li>\n<li><p>Not really a pure CLI solution, but download something like <a href=\"http://www.jfree.org/jfreechart/\" rel=\"nofollow noreferrer\">JFreeChart</a> and write a simple Java app that reads stdin and creates your chart.</p></li>\n</ol>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 41081,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 2,
"selected": false,
"text": "<p>We rolled our own at work using <a href=\"http://oss.oetiker.ch/rrdtool/\" rel=\"nofollow noreferrer\">RRDtool</a> (the data storage back end to tools like MRTG). We run a perl script every 5 minutes that takes a du per partition and stuffs it into an RRD database and then uses RRD's graph function to build graphs. It takes a while to igure out how to set up the .rrd files (for instance, I had to re-learn RPN to do some of the calculations I wanted to do) but if you have some data you want to graph over time, RRD tool's a good bet.</p>\n"
},
{
"answer_id": 43733,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 4,
"selected": true,
"text": "<p>I would recommend <a href=\"http://munin.projects.linpro.no/\" rel=\"nofollow noreferrer\">munin</a>. It is designed for exactly this sort of thing - graphing CPU usage, memory usage, disc-usage and such. sort of like MRTG (but MRTG is primarily aimed at graphing router's traffic, graphing anything but bandwidth with it is very hackish)</p>\n\n<p>Writing Munin plugins is very easy (it was one of the projects goals). They can be written in almost anything (shell script, perl/python/ruby/etc, C, anything that can be execute and produce an output). The plugin output format is basically <code>disc1usage.value 1234</code>. And debugging the plugins is very easy (compared to MRTG)</p>\n\n<p>I've set it up on my laptop to monitor disc-usage, bandwidth usage (by pulling data from my ISP's control panel, it graphs my two download \"bins\", uploads and newsgroup usage), load average and number of processes. Once I got it installed (currently slightly difficult on OS X, but it's trivial on Linux/FreeBSD), I had written a plugin in a few minutes, and it worked, first time!</p>\n\n<p>I would describe how it's setup, but the munin site will do that far better than I could!</p>\n\n<p>There's an example installation <a href=\"http://munin.ping.uio.no/\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>Some alternatives are nagios and cacti. You could also write something similar using rrdtool. Munin, MRTG and Cacti are basically all far-nicer-to-use systems based around this graphing tool.</p>\n\n<p>If you want something really, really simple, you could do..</p>\n\n<pre><code>import os\nimport time\nwhile True:\n disc_usage = os.system(\"df -h / | awk '{print $3}'\")\n log = open(\"mylog.txt\")\n log.write(disc_usage + \"\\n\")\n log.close()\n time.sleep(60*5)\n</code></pre>\n\n<p>Then..</p>\n\n<pre><code>f = open(\"mylog.txt\")\nlines = f.readlines()\n\n# Convert each line to a float number\nlines = [float(cur_line) for cur_line in lines]\n\n# Get the biggest and smallest\nbiggest = max(lines)\nsmallest = min(lines)\n\nfor cur_line in lines:\n base = (cur_line - smallest) + 1 # make lowest value 1\n normalised = base / (biggest - smallest) # normalise value between 0 and 1\n line_length = int(round(normalised * 28)) # make a graph between 0 and 28 characters wide\n print \"#\" * line_length\n</code></pre>\n\n<p>That'll make a simple ascii graph of the disc usage. I <em>really really</em> don't recommend you use something like this. Why? The log file will get bigger, and bigger, and bigger. The graph will get progressively slower to graph. RRDTool uses a rolling-database system to store it's data, so the file will never get bigger than about 50-100KB, and it's consistently quick to graph as the file is a fixed length.</p>\n\n<p>In short. If you want something to easily graph almost anything, use <a href=\"http://munin.projects.linpro.no/\" rel=\"nofollow noreferrer\">munin</a>. If you want something smaller and self-contained, write something with RRDTool.</p>\n"
},
{
"answer_id": 1313955,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>If some ASCII chars are \"graphical\" enough for you, I can recommend <a href=\"http://dev.yorhel.nl/ncdu/\" rel=\"noreferrer\">ncdu</a>. It is a very nice interactive CLI tool, which helps me a lot to step down large directories without doing cd bigdir ; du -hs over and over again.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4162/"
] | [In this question](https://stackoverflow.com/questions/32230/tracking-down-where-disk-space-has-gone-on-linux) someone asked for ways to display disk usage in Linux. I'd like to take this one step further down the cli-path... how about a shell script that takes the output from something like a reasonable answer to the previous question and generates a graph/chart from it (output in a png file or something)? This may be a bit too much code to ask for in a regular question, but my guess is that someone already has a oneliner laying around somewhere... | I would recommend [munin](http://munin.projects.linpro.no/). It is designed for exactly this sort of thing - graphing CPU usage, memory usage, disc-usage and such. sort of like MRTG (but MRTG is primarily aimed at graphing router's traffic, graphing anything but bandwidth with it is very hackish)
Writing Munin plugins is very easy (it was one of the projects goals). They can be written in almost anything (shell script, perl/python/ruby/etc, C, anything that can be execute and produce an output). The plugin output format is basically `disc1usage.value 1234`. And debugging the plugins is very easy (compared to MRTG)
I've set it up on my laptop to monitor disc-usage, bandwidth usage (by pulling data from my ISP's control panel, it graphs my two download "bins", uploads and newsgroup usage), load average and number of processes. Once I got it installed (currently slightly difficult on OS X, but it's trivial on Linux/FreeBSD), I had written a plugin in a few minutes, and it worked, first time!
I would describe how it's setup, but the munin site will do that far better than I could!
There's an example installation [here](http://munin.ping.uio.no/)
Some alternatives are nagios and cacti. You could also write something similar using rrdtool. Munin, MRTG and Cacti are basically all far-nicer-to-use systems based around this graphing tool.
If you want something really, really simple, you could do..
```
import os
import time
while True:
disc_usage = os.system("df -h / | awk '{print $3}'")
log = open("mylog.txt")
log.write(disc_usage + "\n")
log.close()
time.sleep(60*5)
```
Then..
```
f = open("mylog.txt")
lines = f.readlines()
# Convert each line to a float number
lines = [float(cur_line) for cur_line in lines]
# Get the biggest and smallest
biggest = max(lines)
smallest = min(lines)
for cur_line in lines:
base = (cur_line - smallest) + 1 # make lowest value 1
normalised = base / (biggest - smallest) # normalise value between 0 and 1
line_length = int(round(normalised * 28)) # make a graph between 0 and 28 characters wide
print "#" * line_length
```
That'll make a simple ascii graph of the disc usage. I *really really* don't recommend you use something like this. Why? The log file will get bigger, and bigger, and bigger. The graph will get progressively slower to graph. RRDTool uses a rolling-database system to store it's data, so the file will never get bigger than about 50-100KB, and it's consistently quick to graph as the file is a fixed length.
In short. If you want something to easily graph almost anything, use [munin](http://munin.projects.linpro.no/). If you want something smaller and self-contained, write something with RRDTool. |
40,787 | <p>I'd like to keep a "compile-counter" for one of my projects. I figured a quick and dirty way to do this would be to keep a text file with a plain number in it, and then simply call upon a small script to increment this each time I compile.</p>
<p>How would I go about doing this using the regular Windows command line?</p>
<p>I don't really feel like installing some extra shell to do this but if you have any other super simple suggestions that would accomplish just this, they're naturally appreciated as well.</p>
| [
{
"answer_id": 40826,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 2,
"selected": false,
"text": "<p>It would be an new shell (but I think it is worth it), but from PowerShell it would be </p>\n\n<pre><code>[int](get-content counter.txt) + 1 | out-file counter.txt\n</code></pre>\n"
},
{
"answer_id": 40856,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't mind running a Microscoft Windows Based Script then this jscript will work OK. just save it as a .js file and run it from dos with \"wscript c:/script.js\".</p>\n\n<pre><code>var fso, f, fileCount;\nvar ForReading = 1, ForWriting = 2; \nvar filename = \"c:\\\\testfile.txt\";\nfso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\n//create file if its not found\nif (! fso.FileExists(filename))\n{\n f = fso.OpenTextFile(filename, ForWriting, true);\n f.Write(\"0\");\n f.Close();\n}\n\nf = fso.OpenTextFile(filename, ForReading);\nfileCount = parseInt(f.ReadAll());\n\n//make sure the input is a whole number\nif (isNaN(fileCount))\n{\n fileCount = 0; \n}\n\nfileCount = fileCount + 1;\n\nf = fso.OpenTextFile(filename, ForWriting, true);\nf.Write(fileCount);\nf.Close();\n</code></pre>\n"
},
{
"answer_id": 40869,
"author": "crono",
"author_id": 1462,
"author_profile": "https://Stackoverflow.com/users/1462",
"pm_score": 5,
"selected": true,
"text": "<p>You can try a plain old batchfile.</p>\n\n<pre><code>@echo off\nfor /f \" delims==\" %%i in (counter.txt) do set /A temp_counter= %%i+1\necho %temp_counter% > counter.txt\n</code></pre>\n\n<p>assuming the count.bat and counter.txt are located in the same directory.</p>\n"
},
{
"answer_id": 40899,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 2,
"selected": false,
"text": "<p>I'd suggest just appending the current datetime of the build to a log file. </p>\n\n<pre><code>date >> builddates.txt\n</code></pre>\n\n<p>That way you get a build count via the # of lines, and you may also get some interesting statistics if you can be bothered analysing the dates and times later on.</p>\n\n<p>The extra size & time to count the number of lines in the file will be insignificant unless you are doing seriously fast project iterations!</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/914/"
] | I'd like to keep a "compile-counter" for one of my projects. I figured a quick and dirty way to do this would be to keep a text file with a plain number in it, and then simply call upon a small script to increment this each time I compile.
How would I go about doing this using the regular Windows command line?
I don't really feel like installing some extra shell to do this but if you have any other super simple suggestions that would accomplish just this, they're naturally appreciated as well. | You can try a plain old batchfile.
```
@echo off
for /f " delims==" %%i in (counter.txt) do set /A temp_counter= %%i+1
echo %temp_counter% > counter.txt
```
assuming the count.bat and counter.txt are located in the same directory. |
40,814 | <p>I need to execute a large set of SQL statements (creating a bunch of tables, views and stored procedures) from within a C# program.</p>
<p>These statements need to be separated by <code>GO</code> statements, but <code>SqlCommand.ExecuteNonQuery()</code> does not like <code>GO</code> statements. My solution, which I suppose I'll post for reference, was to split the SQL string on <code>GO</code> lines, and execute each batch separately.</p>
<p>Is there an easier/better way?</p>
| [
{
"answer_id": 40824,
"author": "ila",
"author_id": 1178,
"author_profile": "https://Stackoverflow.com/users/1178",
"pm_score": 2,
"selected": false,
"text": "<p>I also faced the same problem, and I could not find any other way but splitting the single SQL operation in separate files, then executing all of them in sequence.</p>\n\n<p>Obviously the problem is not with lists of DML commands, they can be executed without GO in between; different story with DDL (create, alter, drop...)</p>\n"
},
{
"answer_id": 40827,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 5,
"selected": false,
"text": "<p>This is what I knocked together to solve my immediate problem.</p>\n\n<pre><code>private void ExecuteBatchNonQuery(string sql, SqlConnection conn) {\n string sqlBatch = string.Empty;\n SqlCommand cmd = new SqlCommand(string.Empty, conn);\n conn.Open();\n sql += \"\\nGO\"; // make sure last batch is executed.\n try {\n foreach (string line in sql.Split(new string[2] { \"\\n\", \"\\r\" }, StringSplitOptions.RemoveEmptyEntries)) {\n if (line.ToUpperInvariant().Trim() == \"GO\") {\n cmd.CommandText = sqlBatch;\n cmd.ExecuteNonQuery();\n sqlBatch = string.Empty;\n } else {\n sqlBatch += line + \"\\n\";\n }\n } \n } finally {\n conn.Close();\n }\n}\n</code></pre>\n\n<p>It requires GO commands to be on their own line, and will not detect block-comments, so this sort of thing will get split, and cause an error:</p>\n\n<pre><code>ExecuteBatchNonQuery(@\"\n /*\n GO\n */\", conn);\n</code></pre>\n"
},
{
"answer_id": 40830,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 8,
"selected": true,
"text": "<p>Use SQL Server Management Objects (SMO) which understands GO separators. See my blog post here: <a href=\"http://weblogs.asp.net/jgalloway/archive/2006/11/07/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts-_2D00_-the-easy-way.aspx\" rel=\"noreferrer\">http://weblogs.asp.net/jongalloway/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts-<em>2D00</em>-the-easy-way</a></p>\n\n<p>Sample code:</p>\n\n<pre><code>public static void Main() \n{ \n string scriptDirectory = \"c:\\\\temp\\\\sqltest\\\\\";\n string sqlConnectionString = \"Integrated Security=SSPI;\" +\n \"Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)\";\n DirectoryInfo di = new DirectoryInfo(scriptDirectory);\n FileInfo[] rgFiles = di.GetFiles(\"*.sql\");\n foreach (FileInfo fi in rgFiles)\n {\n FileInfo fileInfo = new FileInfo(fi.FullName);\n string script = fileInfo.OpenText().ReadToEnd();\n using (SqlConnection connection = new SqlConnection(sqlConnectionString))\n {\n Server server = new Server(new ServerConnection(connection));\n server.ConnectionContext.ExecuteNonQuery(script);\n }\n }\n}\n</code></pre>\n\n<p>If that won't work for you, see Phil Haack's library which handles that: <a href=\"http://haacked.com/archive/2007/11/04/a-library-for-executing-sql-scripts-with-go-separators-and.aspx\" rel=\"noreferrer\">http://haacked.com/archive/2007/11/04/a-library-for-executing-sql-scripts-with-go-separators-and.aspx</a></p>\n"
},
{
"answer_id": 40839,
"author": "tbreffni",
"author_id": 637,
"author_profile": "https://Stackoverflow.com/users/637",
"pm_score": 4,
"selected": false,
"text": "<p>You can use <a href=\"http://msdn.microsoft.com/en-us/library/ms162557.aspx\" rel=\"nofollow noreferrer\">SQL Management Objects</a> to perform this. These are the same objects that Management Studio uses to execute queries. I believe <code>Server.ConnectionContext.ExecuteNonQuery()</code> will perform what you need.</p>\n"
},
{
"answer_id": 40850,
"author": "John Hubert",
"author_id": 4286,
"author_profile": "https://Stackoverflow.com/users/4286",
"pm_score": 3,
"selected": false,
"text": "<p>The \"GO\" batch separator keyword is actually used by SQL Management Studio itself, so that it knows where to terminate the batches it is sending to the server, and it is not passed to SQL server. You can even change the keyword in Management Studio, should you so desire.</p>\n"
},
{
"answer_id": 40861,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't want to go the SMO route you can search and replace \"GO\" for \";\" and the query as you would. Note that soly the the last result set will be returned.</p>\n"
},
{
"answer_id": 9892659,
"author": "Natalya",
"author_id": 1278118,
"author_profile": "https://Stackoverflow.com/users/1278118",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't want to install SMO objects you can use gplex tool (see <a href=\"https://stackoverflow.com/a/9892349/1278118\">this answer</a>)</p>\n"
},
{
"answer_id": 10734775,
"author": "grv",
"author_id": 1414633,
"author_profile": "https://Stackoverflow.com/users/1414633",
"pm_score": -1,
"selected": false,
"text": "<p>Too difficult :)</p>\n\n<p>Create array of strings str[] replacing GO with \",@\" :</p>\n\n<pre><code> string[] str ={\n @\"\nUSE master;\n\",@\"\n\n\nCREATE DATABASE \" +con_str_initdir+ @\";\n\",@\"\n-- Verify the database files and sizes\n--SELECT name, size, size*1.0/128 AS [Size in MBs] \n--SELECT name \n--FROM sys.master_files\n--WHERE name = N'\" + con_str_initdir + @\"';\n--GO\n\nUSE \" + con_str_initdir + @\";\n\",@\"\n\nSET ANSI_NULLS ON\n\",@\"\nSET QUOTED_IDENTIFIER ON\n\",@\"\n\nIF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Customers]') AND type in (N'U'))\nBEGIN\nCREATE TABLE [dbo].[Customers](\n [CustomerID] [int] IDENTITY(1,1) NOT NULL,\n [CustomerName] [nvarchar](50) NULL,\n CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED \n(\n [CustomerID] ASC\n)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]\n) ON [PRIMARY]\nEND\n\",@\"\n\n\n\nSET ANSI_NULLS ON\n\",@\"\nSET QUOTED_IDENTIFIER ON\n\",@\"\nIF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GOODS]') AND type in (N'U'))\nBEGIN\nCREATE TABLE [dbo].[GOODS](\n [GoodsID] [int] IDENTITY(1,1) NOT NULL,\n [GoodsName] [nvarchar](50) NOT NULL,\n [GoodsPrice] [float] NOT NULL,\n CONSTRAINT [PK_GOODS] PRIMARY KEY CLUSTERED \n(\n [GoodsID] ASC\n)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]\n) ON [PRIMARY]\nEND\n\",@\"\nSET ANSI_NULLS ON\n\",@\"\nSET QUOTED_IDENTIFIER ON\n\",@\"\nIF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Orders]') AND type in (N'U'))\nBEGIN\nCREATE TABLE [dbo].[Orders](\n [OrderID] [int] IDENTITY(1,1) NOT NULL,\n [CustomerID] [int] NOT NULL,\n [Date] [smalldatetime] NOT NULL,\n CONSTRAINT [PK_Orders] PRIMARY KEY CLUSTERED \n(\n [OrderID] ASC\n)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]\n) ON [PRIMARY]\nEND\n\",@\"\nSET ANSI_NULLS ON\n\",@\"\nSET QUOTED_IDENTIFIER ON\n\",@\"\nIF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OrderDetails]') AND type in (N'U'))\nBEGIN\nCREATE TABLE [dbo].[OrderDetails](\n [OrderID] [int] NOT NULL,\n [GoodsID] [int] NOT NULL,\n [Qty] [int] NOT NULL,\n [Price] [float] NOT NULL,\n CONSTRAINT [PK_OrderDetails] PRIMARY KEY CLUSTERED \n(\n [OrderID] ASC,\n [GoodsID] ASC\n)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]\n) ON [PRIMARY]\nEND\n\",@\"\n\nSET ANSI_NULLS ON\n\",@\"\nSET QUOTED_IDENTIFIER ON\n\",@\"\nIF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[InsertCustomers]') AND type in (N'P', N'PC'))\nBEGIN\nEXEC dbo.sp_executesql @statement = N'-- =============================================\n-- Author: <Author,,Name>\n-- Create date: <Create Date,,>\n-- Description: <Description,,>\n-- =============================================\ncreate PROCEDURE [dbo].[InsertCustomers]\n @CustomerName nvarchar(50),\n @Identity int OUT\nAS\nINSERT INTO Customers (CustomerName) VALUES(@CustomerName)\nSET @Identity = SCOPE_IDENTITY()\n\n' \nEND\n\",@\"\nIF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Orders_Customers]') AND parent_object_id = OBJECT_ID(N'[dbo].[Orders]'))\nALTER TABLE [dbo].[Orders] WITH CHECK ADD CONSTRAINT [FK_Orders_Customers] FOREIGN KEY([CustomerID])\nREFERENCES [dbo].[Customers] ([CustomerID])\nON UPDATE CASCADE\n\",@\"\nALTER TABLE [dbo].[Orders] CHECK CONSTRAINT [FK_Orders_Customers]\n\",@\"\nIF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_OrderDetails_GOODS]') AND parent_object_id = OBJECT_ID(N'[dbo].[OrderDetails]'))\nALTER TABLE [dbo].[OrderDetails] WITH CHECK ADD CONSTRAINT [FK_OrderDetails_GOODS] FOREIGN KEY([GoodsID])\nREFERENCES [dbo].[GOODS] ([GoodsID])\nON UPDATE CASCADE\n\",@\"\nALTER TABLE [dbo].[OrderDetails] CHECK CONSTRAINT [FK_OrderDetails_GOODS]\n\",@\"\nIF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_OrderDetails_Orders]') AND parent_object_id = OBJECT_ID(N'[dbo].[OrderDetails]'))\nALTER TABLE [dbo].[OrderDetails] WITH CHECK ADD CONSTRAINT [FK_OrderDetails_Orders] FOREIGN KEY([OrderID])\nREFERENCES [dbo].[Orders] ([OrderID])\nON UPDATE CASCADE\nON DELETE CASCADE\n\",@\"\nALTER TABLE [dbo].[OrderDetails] CHECK CONSTRAINT [FK_OrderDetails_Orders]\n\n\n \"};\n\n\n for(int i =0; i<str.Length;i++) \n {\n myCommand.CommandText=str[i];\n try\n {\n myCommand.ExecuteNonQuery();\n }\n catch (SystemException ee)\n {\n MessageBox.Show(\"Error \"+ee.ToString());\n }\n\n }\n</code></pre>\n\n<p>That's all, enjoy.</p>\n"
},
{
"answer_id": 13570258,
"author": "Andy Dove",
"author_id": 1854197,
"author_profile": "https://Stackoverflow.com/users/1854197",
"pm_score": 2,
"selected": false,
"text": "<p>I accomplished this today by loading my SQL from a text file into one string. I then used the string Split function to separate the string into individual commands which were then sent to the server individually. Simples :)</p>\n\n<p>Just realised that you need to split on \\nGO just in case the letters GO appear in any of your table names etc. Guess I was lucky there!</p>\n"
},
{
"answer_id": 23898655,
"author": "Ryan Penfold",
"author_id": 1111806,
"author_profile": "https://Stackoverflow.com/users/1111806",
"pm_score": 2,
"selected": false,
"text": "<p>Based on Blorgbeard's solution.</p>\n\n<pre><code>foreach (var sqlBatch in commandText.Split(new[] { \"GO\" }, StringSplitOptions.RemoveEmptyEntries))\n{\n sqlCommand.CommandText = sqlBatch;\n sqlCommand.ExecuteNonQuery();\n}\n</code></pre>\n"
},
{
"answer_id": 24179458,
"author": "jbrunodomingues",
"author_id": 3644735,
"author_profile": "https://Stackoverflow.com/users/3644735",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem in java and I solved it with a bit of logic and regex. I believe the same logic can be applied.First I read from the slq file into memory. Then I apply the following logic. It's pretty much what has been said before however I believe that using regex word bound is safer than expecting a new line char.</p>\n\n<pre><code>String pattern = \"\\\\bGO\\\\b|\\\\bgo\\\\b\";\n\nString[] splitedSql = sql.split(pattern);\nfor (String chunk : splitedSql) {\n getJdbcTemplate().update(chunk);\n}\n</code></pre>\n\n<p>This basically splits the sql string into an array of sql strings. The regex is basically to detect full 'go' words either lower case or upper case. Then you execute the different querys sequentially.</p>\n"
},
{
"answer_id": 25601409,
"author": "Bigjim",
"author_id": 1773646,
"author_profile": "https://Stackoverflow.com/users/1773646",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't want to use SMO (which is better than the solution below, but i want to give an alternative...) you can split your query with this function.</p>\n\n<p>It is:</p>\n\n<ul>\n<li>Comment proof (example --GO or /* GO */)</li>\n<li>Only works on a new line, just as in SSMS (example /* test /* GO works and select 1 as go not</li>\n<li><p>String proof (example print 'no go ')</p>\n\n<pre><code>private List<string> SplitScriptGo(string script)\n{\n var result = new List<string>();\n int pos1 = 0;\n int pos2 = 0;\n bool whiteSpace = true;\n bool emptyLine = true;\n bool inStr = false;\n bool inComment1 = false;\n bool inComment2 = false;\n\n while (true)\n {\n while (pos2 < script.Length && Char.IsWhiteSpace(script[pos2]))\n {\n if (script[pos2] == '\\r' || script[pos2] == '\\n')\n {\n emptyLine = true;\n inComment1 = false;\n }\n\n pos2++;\n }\n\n if (pos2 == script.Length)\n break;\n\n bool min2 = (pos2 + 1) < script.Length;\n bool min3 = (pos2 + 2) < script.Length;\n\n if (!inStr && !inComment2 && min2 && script.Substring(pos2, 2) == \"--\")\n inComment1 = true;\n\n if (!inStr && !inComment1 && min2 && script.Substring(pos2, 2) == \"/*\")\n inComment2 = true;\n\n if (!inComment1 && !inComment2 && script[pos2] == '\\'')\n inStr = !inStr;\n\n if (!inStr && !inComment1 && !inComment2 && emptyLine\n && (min2 && script.Substring(pos2, 2).ToLower() == \"go\")\n && (!min3 || char.IsWhiteSpace(script[pos2 + 2]) || script.Substring(pos2 + 2, 2) == \"--\" || script.Substring(pos2 + 2, 2) == \"/*\"))\n {\n if (!whiteSpace)\n result.Add(script.Substring(pos1, pos2 - pos1));\n\n whiteSpace = true;\n emptyLine = false;\n pos2 += 2;\n pos1 = pos2;\n }\n else\n {\n pos2++;\n whiteSpace = false;\n\n if (!inComment2)\n emptyLine = false;\n }\n\n if (!inStr && inComment2 && pos2 > 1 && script.Substring(pos2 - 2, 2) == \"*/\")\n inComment2 = false;\n }\n\n if (!whiteSpace)\n result.Add(script.Substring(pos1));\n\n return result;\n}\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 25992625,
"author": "Stefan Steiger",
"author_id": 155077,
"author_profile": "https://Stackoverflow.com/users/155077",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't want to use SMO, for example because you need to be cross-platform, you can also use the ScriptSplitter class from SubText.</p>\n\n<p><a href=\"https://github.com/ststeiger/ScriptSplitter\" rel=\"nofollow noreferrer\">Here's</a> the implementation in C# & VB.NET </p>\n\n<p>Usage:</p>\n\n<pre><code> string strSQL = @\"\nSELECT * FROM INFORMATION_SCHEMA.columns\nGO\nSELECT * FROM INFORMATION_SCHEMA.views\n\";\n\n foreach(string Script in new Subtext.Scripting.ScriptSplitter(strSQL ))\n {\n Console.WriteLine(Script);\n }\n</code></pre>\n\n<p>If you have problems with multiline c-style comments, remove the comments with regex:</p>\n\n<pre><code>static string RemoveCstyleComments(string strInput)\n{\n string strPattern = @\"/[*][\\w\\d\\s]+[*]/\";\n //strPattern = @\"/\\*.*?\\*/\"; // Doesn't work\n //strPattern = \"/\\\\*.*?\\\\*/\"; // Doesn't work\n //strPattern = @\"/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/ \"; // Doesn't work\n //strPattern = @\"/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/ \"; // Doesn't work\n\n // http://stackoverflow.com/questions/462843/improving-fixing-a-regex-for-c-style-block-comments\n strPattern = @\"/\\*(?>(?:(?>[^*]+)|\\*(?!/))*)\\*/\"; // Works !\n\n string strOutput = System.Text.RegularExpressions.Regex.Replace(strInput, strPattern, string.Empty, System.Text.RegularExpressions.RegexOptions.Multiline);\n Console.WriteLine(strOutput);\n return strOutput;\n} // End Function RemoveCstyleComments\n</code></pre>\n\n<p>Removing single-line comments is here:</p>\n\n<pre><code>https://stackoverflow.com/questions/9842991/regex-to-remove-single-line-sql-comments\n</code></pre>\n"
},
{
"answer_id": 28557032,
"author": "Sriwantha Attanayake",
"author_id": 215336,
"author_profile": "https://Stackoverflow.com/users/215336",
"pm_score": 1,
"selected": false,
"text": "<p>use the following method to split the string and execute batch by batch</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Text.RegularExpressions;\nnamespace RegExTrial\n{\n class Program\n {\n static void Main(string[] args)\n {\n string sql = String.Empty;\n string path=@\"D:\\temp\\sample.sql\";\n using (StreamReader reader = new StreamReader(path)) {\n sql = reader.ReadToEnd();\n } \n //Select any GO (ignore case) that starts with at least \n //one white space such as tab, space,new line, verticle tab etc\n string pattern=\"[\\\\s](?i)GO(?-i)\";\n\n Regex matcher = new Regex(pattern, RegexOptions.Compiled);\n int start = 0;\n int end = 0;\n Match batch=matcher.Match(sql);\n while (batch.Success) {\n end = batch.Index;\n string batchQuery = sql.Substring(start, end - start).Trim();\n //execute the batch\n ExecuteBatch(batchQuery);\n start = end + batch.Length;\n batch = matcher.Match(sql,start);\n }\n\n }\n\n private static void ExecuteBatch(string command)\n { \n //execute your query here\n }\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 31785091,
"author": "Morvael",
"author_id": 1286358,
"author_profile": "https://Stackoverflow.com/users/1286358",
"pm_score": 0,
"selected": false,
"text": "<p>I hit this same issue and eventually just solved it by a simple string replace, replacing the word GO with a semi-colon (;)</p>\n\n<p>All seems to be working fine while executing scripts with in-line comments, block comments, and GO commands</p>\n\n<pre><code>public static bool ExecuteExternalScript(string filePath)\n{\n using (StreamReader file = new StreamReader(filePath))\n using (SqlConnection conn = new SqlConnection(dbConnStr))\n {\n StringBuilder sql = new StringBuilder();\n\n string line;\n while ((line = file.ReadLine()) != null)\n {\n // replace GO with semi-colon\n if (line == \"GO\")\n sql.Append(\";\");\n // remove inline comments\n else if (line.IndexOf(\"--\") > -1)\n sql.AppendFormat(\" {0} \", line.Split(new string[] { \"--\" }, StringSplitOptions.None)[0]);\n // just the line as it is\n else\n sql.AppendFormat(\" {0} \", line);\n }\n conn.Open();\n\n SqlCommand cmd = new SqlCommand(sql.ToString(), conn);\n cmd.ExecuteNonQuery();\n }\n\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 47066366,
"author": "Yargo",
"author_id": 3748460,
"author_profile": "https://Stackoverflow.com/users/3748460",
"pm_score": 1,
"selected": false,
"text": "<p>To avoid third parties, regexes, memory overheads and fast work with large scripts I created my own stream-based parser. It</p>\n\n<ul>\n<li>checks syntax before</li>\n<li><p>can recognize comments with -- or /**/</p>\n\n<pre><code>-- some commented text\n /*\ndrop table Users;\nGO\n */\n</code></pre></li>\n<li><p>can recognize string literals with ' or \"</p>\n\n<pre><code>set @s =\n 'create table foo(...);\n GO\n create index ...';\n</code></pre></li>\n<li>preserves LF and CR formatting</li>\n<li>preserves comments block in object bodies (stored procedures, views etc.)</li>\n<li><p>and other constructions such as</p>\n\n<pre><code> gO -- commented text\n</code></pre></li>\n</ul>\n\n<h2>How to use</h2>\n\n<pre><code> try\n {\n using (SqlConnection connection = new SqlConnection(\"Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=DATABASE-NAME;Data Source=SERVER-NAME\"))\n {\n connection.Open();\n\n int rowsAffected = SqlStatementReader.ExecuteSqlFile(\n \"C:\\\\target-sql-script.sql\",\n connection,\n // Don't forget to use the correct file encoding!!!\n Encoding.Default,\n // Indefinitely (sec)\n 0\n );\n }\n }\n // implement your handlers\n catch (SqlStatementReader.SqlBadSyntaxException) { }\n catch (SqlException) { }\n catch (Exception) { }\n</code></pre>\n\n<h2>Stream-based SQL script reader</h2>\n\n<pre><code>class SqlStatementReader\n{\n public class SqlBadSyntaxException : Exception\n {\n public SqlBadSyntaxException(string description) : base(description) { }\n public SqlBadSyntaxException(string description, int line) : base(OnBase(description, line, null)) { }\n public SqlBadSyntaxException(string description, int line, string filePath) : base(OnBase(description, line, filePath)) { }\n private static string OnBase(string description, int line, string filePath)\n {\n if (filePath == null)\n return string.Format(\"Line: {0}. {1}\", line, description);\n else\n return string.Format(\"File: {0}\\r\\nLine: {1}. {2}\", filePath, line, description);\n }\n }\n\n enum SqlScriptChunkTypes\n {\n InstructionOrUnquotedIdentifier = 0,\n BracketIdentifier = 1,\n QuotIdentifierOrLiteral = 2,\n DblQuotIdentifierOrLiteral = 3,\n CommentLine = 4,\n CommentMultiline = 5,\n }\n\n StreamReader _sr = null;\n string _filePath = null;\n int _lineStart = 1;\n int _lineEnd = 1;\n bool _isNextChar = false;\n char _nextChar = '\\0';\n\n public SqlStatementReader(StreamReader sr)\n {\n if (sr == null)\n throw new ArgumentNullException(\"StreamReader can't be null.\");\n\n if (sr.BaseStream is FileStream)\n _filePath = ((FileStream)sr.BaseStream).Name;\n\n _sr = sr;\n }\n\n public SqlStatementReader(StreamReader sr, string filePath)\n {\n if (sr == null)\n throw new ArgumentNullException(\"StreamReader can't be null.\");\n\n _sr = sr;\n _filePath = filePath;\n }\n\n public int LineStart { get { return _lineStart; } }\n public int LineEnd { get { return _lineEnd == 1 ? _lineEnd : _lineEnd - 1; } }\n\n public void LightSyntaxCheck()\n {\n while (ReadStatementInternal(true) != null) ;\n }\n\n public string ReadStatement()\n {\n for (string s = ReadStatementInternal(false); s != null; s = ReadStatementInternal(false))\n {\n // skip empty\n for (int i = 0; i < s.Length; i++)\n {\n switch (s[i])\n {\n case ' ': continue;\n case '\\t': continue;\n case '\\r': continue;\n case '\\n': continue;\n default:\n return s;\n }\n }\n }\n return null;\n }\n\n string ReadStatementInternal(bool syntaxCheck)\n {\n if (_isNextChar == false && _sr.EndOfStream)\n return null;\n\n StringBuilder allLines = new StringBuilder();\n StringBuilder line = new StringBuilder();\n SqlScriptChunkTypes nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;\n SqlScriptChunkTypes currentChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;\n char ch = '\\0';\n int lineCounter = 0;\n int nextLine = 0;\n int currentLine = 0;\n bool nextCharHandled = false;\n bool foundGO;\n int go = 1;\n\n while (ReadChar(out ch))\n {\n if (nextCharHandled == false)\n {\n currentChunk = nextChunk;\n currentLine = nextLine;\n\n switch (currentChunk)\n {\n case SqlScriptChunkTypes.InstructionOrUnquotedIdentifier:\n\n if (ch == '[')\n {\n currentChunk = nextChunk = SqlScriptChunkTypes.BracketIdentifier;\n currentLine = nextLine = lineCounter;\n }\n else if (ch == '\"')\n {\n currentChunk = nextChunk = SqlScriptChunkTypes.DblQuotIdentifierOrLiteral;\n currentLine = nextLine = lineCounter;\n }\n else if (ch == '\\'')\n {\n currentChunk = nextChunk = SqlScriptChunkTypes.QuotIdentifierOrLiteral;\n currentLine = nextLine = lineCounter;\n }\n else if (ch == '-' && (_isNextChar && _nextChar == '-'))\n {\n nextCharHandled = true;\n currentChunk = nextChunk = SqlScriptChunkTypes.CommentLine;\n currentLine = nextLine = lineCounter;\n }\n else if (ch == '/' && (_isNextChar && _nextChar == '*'))\n {\n nextCharHandled = true;\n currentChunk = nextChunk = SqlScriptChunkTypes.CommentMultiline;\n currentLine = nextLine = lineCounter;\n }\n else if (ch == ']')\n {\n throw new SqlBadSyntaxException(\"Incorrect syntax near ']'.\", _lineEnd + lineCounter, _filePath);\n }\n else if (ch == '*' && (_isNextChar && _nextChar == '/'))\n {\n throw new SqlBadSyntaxException(\"Incorrect syntax near '*'.\", _lineEnd + lineCounter, _filePath);\n }\n break;\n\n case SqlScriptChunkTypes.CommentLine:\n\n if (ch == '\\r' && (_isNextChar && _nextChar == '\\n'))\n {\n nextCharHandled = true;\n currentChunk = nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;\n currentLine = nextLine = lineCounter;\n }\n else if (ch == '\\n' || ch == '\\r')\n {\n currentChunk = nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;\n currentLine = nextLine = lineCounter;\n }\n break;\n\n case SqlScriptChunkTypes.CommentMultiline:\n\n if (ch == '*' && (_isNextChar && _nextChar == '/'))\n {\n nextCharHandled = true;\n nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;\n nextLine = lineCounter;\n }\n else if (ch == '/' && (_isNextChar && _nextChar == '*'))\n {\n throw new SqlBadSyntaxException(\"Missing end comment mark '*/'.\", _lineEnd + currentLine, _filePath);\n }\n break;\n\n case SqlScriptChunkTypes.BracketIdentifier:\n\n if (ch == ']')\n {\n nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;\n nextLine = lineCounter;\n }\n break;\n\n case SqlScriptChunkTypes.DblQuotIdentifierOrLiteral:\n\n if (ch == '\"')\n {\n if (_isNextChar && _nextChar == '\"')\n {\n nextCharHandled = true;\n }\n else\n {\n nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;\n nextLine = lineCounter;\n }\n }\n break;\n\n case SqlScriptChunkTypes.QuotIdentifierOrLiteral:\n\n if (ch == '\\'')\n {\n if (_isNextChar && _nextChar == '\\'')\n {\n nextCharHandled = true;\n }\n else\n {\n nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;\n nextLine = lineCounter;\n }\n }\n break;\n }\n }\n else\n nextCharHandled = false;\n\n foundGO = false;\n if (currentChunk == SqlScriptChunkTypes.InstructionOrUnquotedIdentifier || go >= 5 || (go == 4 && currentChunk == SqlScriptChunkTypes.CommentLine))\n {\n // go = 0 - break, 1 - begin of the string, 2 - spaces after begin of the string, 3 - G or g, 4 - O or o, 5 - spaces after GO, 6 - line comment after valid GO\n switch (go)\n {\n case 0:\n if (ch == '\\r' || ch == '\\n')\n go = 1;\n break;\n case 1:\n if (ch == ' ' || ch == '\\t')\n go = 2;\n else if (ch == 'G' || ch == 'g')\n go = 3;\n else if (ch != '\\n' && ch != '\\r')\n go = 0;\n break;\n case 2:\n if (ch == 'G' || ch == 'g')\n go = 3;\n else if (ch == '\\n' || ch == '\\r')\n go = 1;\n else if (ch != ' ' && ch != '\\t')\n go = 0;\n break;\n case 3:\n if (ch == 'O' || ch == 'o')\n go = 4;\n else if (ch == '\\n' || ch == '\\r')\n go = 1;\n else\n go = 0;\n break;\n case 4:\n if (ch == '\\r' && (_isNextChar && _nextChar == '\\n'))\n go = 5;\n else if (ch == '\\n' || ch == '\\r')\n foundGO = true;\n else if (ch == ' ' || ch == '\\t')\n go = 5;\n else if (ch == '-' && (_isNextChar && _nextChar == '-'))\n go = 6;\n else\n go = 0;\n break;\n case 5:\n if (ch == '\\r' && (_isNextChar && _nextChar == '\\n'))\n go = 5;\n else if (ch == '\\n' || ch == '\\r')\n foundGO = true;\n else if (ch == '-' && (_isNextChar && _nextChar == '-'))\n go = 6;\n else if (ch != ' ' && ch != '\\t')\n throw new SqlBadSyntaxException(\"Incorrect syntax was encountered while parsing go.\", _lineEnd + lineCounter, _filePath);\n break;\n case 6:\n if (ch == '\\r' && (_isNextChar && _nextChar == '\\n'))\n go = 6;\n else if (ch == '\\n' || ch == '\\r')\n foundGO = true;\n break;\n default:\n go = 0;\n break;\n }\n }\n else\n go = 0;\n\n if (foundGO)\n {\n if (ch == '\\r' || ch == '\\n')\n {\n ++lineCounter;\n }\n // clear GO\n string s = line.Append(ch).ToString();\n for (int i = 0; i < s.Length; i++)\n {\n switch (s[i])\n {\n case ' ': continue;\n case '\\t': continue;\n case '\\r': continue;\n case '\\n': continue;\n default:\n _lineStart = _lineEnd;\n _lineEnd += lineCounter;\n return allLines.Append(s.Substring(0, i)).ToString();\n }\n }\n return string.Empty;\n }\n\n // accumulate by string\n if (ch == '\\r' && (_isNextChar == false || _nextChar != '\\n'))\n {\n ++lineCounter;\n if (syntaxCheck == false)\n allLines.Append(line.Append('\\r').ToString());\n line.Clear();\n }\n else if (ch == '\\n')\n {\n ++lineCounter;\n if (syntaxCheck == false)\n allLines.Append(line.Append('\\n').ToString());\n line.Clear();\n }\n else\n {\n if (syntaxCheck == false)\n line.Append(ch);\n }\n }\n\n // this is the end of the stream, return it without GO, if GO exists\n switch (currentChunk)\n {\n case SqlScriptChunkTypes.InstructionOrUnquotedIdentifier:\n case SqlScriptChunkTypes.CommentLine:\n break;\n case SqlScriptChunkTypes.CommentMultiline:\n if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)\n throw new SqlBadSyntaxException(\"Missing end comment mark '*/'.\", _lineEnd + currentLine, _filePath);\n break;\n case SqlScriptChunkTypes.BracketIdentifier:\n if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)\n throw new SqlBadSyntaxException(\"Unclosed quotation mark [.\", _lineEnd + currentLine, _filePath);\n break;\n case SqlScriptChunkTypes.DblQuotIdentifierOrLiteral:\n if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)\n throw new SqlBadSyntaxException(\"Unclosed quotation mark \\\".\", _lineEnd + currentLine, _filePath);\n break;\n case SqlScriptChunkTypes.QuotIdentifierOrLiteral:\n if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)\n throw new SqlBadSyntaxException(\"Unclosed quotation mark '.\", _lineEnd + currentLine, _filePath);\n break;\n }\n\n if (go >= 4)\n {\n string s = line.ToString();\n for (int i = 0; i < s.Length; i++)\n {\n switch (s[i])\n {\n case ' ': continue;\n case '\\t': continue;\n case '\\r': continue;\n case '\\n': continue;\n default:\n _lineStart = _lineEnd;\n _lineEnd += lineCounter + 1;\n return allLines.Append(s.Substring(0, i)).ToString();\n }\n }\n }\n\n _lineStart = _lineEnd;\n _lineEnd += lineCounter + 1;\n return allLines.Append(line.ToString()).ToString();\n }\n\n bool ReadChar(out char ch)\n {\n if (_isNextChar)\n {\n ch = _nextChar;\n if (_sr.EndOfStream)\n _isNextChar = false;\n else\n _nextChar = Convert.ToChar(_sr.Read());\n return true;\n }\n else if (_sr.EndOfStream == false)\n {\n ch = Convert.ToChar(_sr.Read());\n if (_sr.EndOfStream == false)\n {\n _isNextChar = true;\n _nextChar = Convert.ToChar(_sr.Read());\n }\n return true;\n }\n else\n {\n ch = '\\0';\n return false;\n }\n }\n\n public static int ExecuteSqlFile(string filePath, SqlConnection connection, Encoding fileEncoding, int commandTimeout)\n {\n int rowsAffected = 0;\n using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))\n {\n // Simple syntax check (you can comment out these two lines below)\n new SqlStatementReader(new StreamReader(fs, fileEncoding)).LightSyntaxCheck();\n fs.Seek(0L, SeekOrigin.Begin);\n\n // Read statements without GO\n SqlStatementReader rd = new SqlStatementReader(new StreamReader(fs, fileEncoding));\n string stmt;\n while ((stmt = rd.ReadStatement()) != null)\n {\n using (SqlCommand cmd = connection.CreateCommand())\n {\n cmd.CommandText = stmt;\n cmd.CommandTimeout = commandTimeout;\n int i = cmd.ExecuteNonQuery();\n if (i > 0)\n rowsAffected += i;\n }\n }\n }\n return rowsAffected;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 52443620,
"author": "Filip Cordas",
"author_id": 6330636,
"author_profile": "https://Stackoverflow.com/users/6330636",
"pm_score": 3,
"selected": false,
"text": "<p>I look at this a few times at the end decided with <a href=\"https://github.com/aspnet/EntityFramework6/blob/6.1.3/src/EntityFramework.SqlServer/SqlServerMigrationSqlGenerator.cs#L1494\" rel=\"noreferrer\">EF implementation</a>\nA bit modified for <code>SqlConnection</code></p>\n\n<pre><code>public static void ExecuteSqlScript(this SqlConnection sqlConnection, string sqlBatch)\n {\n // Handle backslash utility statement (see http://technet.microsoft.com/en-us/library/dd207007.aspx)\n sqlBatch = Regex.Replace(sqlBatch, @\"\\\\(\\r\\n|\\r|\\n)\", string.Empty);\n\n // Handle batch splitting utility statement (see http://technet.microsoft.com/en-us/library/ms188037.aspx)\n var batches = Regex.Split(\n sqlBatch,\n string.Format(CultureInfo.InvariantCulture, @\"^\\s*({0}[ \\t]+[0-9]+|{0})(?:\\s+|$)\", BatchTerminator),\n RegexOptions.IgnoreCase | RegexOptions.Multiline);\n\n for (int i = 0; i < batches.Length; ++i)\n {\n // Skip batches that merely contain the batch terminator\n if (batches[i].StartsWith(BatchTerminator, StringComparison.OrdinalIgnoreCase) ||\n (i == batches.Length - 1 && string.IsNullOrWhiteSpace(batches[i])))\n {\n continue;\n }\n\n // Include batch terminator if the next element is a batch terminator\n if (batches.Length > i + 1 &&\n batches[i + 1].StartsWith(BatchTerminator, StringComparison.OrdinalIgnoreCase))\n {\n int repeatCount = 1;\n\n // Handle count parameter on the batch splitting utility statement\n if (!string.Equals(batches[i + 1], BatchTerminator, StringComparison.OrdinalIgnoreCase))\n {\n repeatCount = int.Parse(Regex.Match(batches[i + 1], @\"([0-9]+)\").Value, CultureInfo.InvariantCulture);\n }\n\n for (int j = 0; j < repeatCount; ++j)\n {\n var command = sqlConnection.CreateCommand();\n command.CommandText = batches[i];\n command.ExecuteNonQuery();\n }\n }\n else\n {\n var command = sqlConnection.CreateCommand();\n command.CommandText = batches[i];\n command.ExecuteNonQuery();\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 55621284,
"author": "Sprot",
"author_id": 2960937,
"author_profile": "https://Stackoverflow.com/users/2960937",
"pm_score": -1,
"selected": false,
"text": "<p>For anyone still having the problem. You could use official Microsoft SMO </p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/overview-smo?view=sql-server-2017\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/overview-smo?view=sql-server-2017</a></p>\n\n<pre><code>using (var connection = new SqlConnection(connectionString))\n{\n var server = new Server(new ServerConnection(connection));\n server.ConnectionContext.ExecuteNonQuery(sql);\n}\n</code></pre>\n"
},
{
"answer_id": 66628734,
"author": "Ahmed Suror",
"author_id": 1655837,
"author_profile": "https://Stackoverflow.com/users/1655837",
"pm_score": 0,
"selected": false,
"text": "<p>You can just use <code>;</code> at the end of each statement as it worked for me.\nReally don't know if there are any drawbacks to it.</p>\n"
},
{
"answer_id": 72480033,
"author": "adamency",
"author_id": 16974218,
"author_profile": "https://Stackoverflow.com/users/16974218",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the most elegant solution I could find.</p>\n<p>Let's say your SQL script containing <code>GO</code> statements is in a file <code>script.sql</code>.</p>\n<p>You can do:</p>\n<pre><code>$query = ((Get-Content -Raw "script.sql") -replace '([\\s\\n]*)GO([\\s\\n]+)','$1$2')\n</code></pre>\n<p>This will remove all GO statements without removing other occurences of the string <code>go</code> anywhere else (according to my tests).</p>\n<p>You can then do:</p>\n<pre><code>$SqlConnection = New-Object System.Data.SqlClient.SqlConnection \n$SqlCmd = New-Object System.Data.SqlClient.SqlCommand\n\n$SqlConnection.ConnectionString = <your_connection_string>\n\n$SqlConnection.Open()\n \n$SqlCmd.Connection = $SqlConnection \n$SqlCmd.CommandText = $query\n$SqlCmd.ExecuteNonQuery()\n</code></pre>\n<p>which should normally work without issues.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
] | I need to execute a large set of SQL statements (creating a bunch of tables, views and stored procedures) from within a C# program.
These statements need to be separated by `GO` statements, but `SqlCommand.ExecuteNonQuery()` does not like `GO` statements. My solution, which I suppose I'll post for reference, was to split the SQL string on `GO` lines, and execute each batch separately.
Is there an easier/better way? | Use SQL Server Management Objects (SMO) which understands GO separators. See my blog post here: [http://weblogs.asp.net/jongalloway/Handling-\_2200\_GO\_2200\_-Separators-in-SQL-Scripts-*2D00*-the-easy-way](http://weblogs.asp.net/jgalloway/archive/2006/11/07/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts-_2D00_-the-easy-way.aspx)
Sample code:
```
public static void Main()
{
string scriptDirectory = "c:\\temp\\sqltest\\";
string sqlConnectionString = "Integrated Security=SSPI;" +
"Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)";
DirectoryInfo di = new DirectoryInfo(scriptDirectory);
FileInfo[] rgFiles = di.GetFiles("*.sql");
foreach (FileInfo fi in rgFiles)
{
FileInfo fileInfo = new FileInfo(fi.FullName);
string script = fileInfo.OpenText().ReadToEnd();
using (SqlConnection connection = new SqlConnection(sqlConnectionString))
{
Server server = new Server(new ServerConnection(connection));
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}
```
If that won't work for you, see Phil Haack's library which handles that: <http://haacked.com/archive/2007/11/04/a-library-for-executing-sql-scripts-with-go-separators-and.aspx> |
40,816 | <p>If I have an HTML helper like so:</p>
<pre><code>Name:<br />
<%=Html.TextBox("txtName",20) %><br />
</code></pre>
<p>How do I apply a CSS class to it? Do I have to wrap it in a span? Or do I need to somehow utilize the HtmlAttributes property of the helper?</p>
| [
{
"answer_id": 40846,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 6,
"selected": true,
"text": "<p>You can pass it into the TextBox call as a parameter.</p>\n\n<pre><code>Name:<br/> \n<%= Html.TextBox(\"txtName\", \"20\", new { @class = \"hello\" }) %>\n</code></pre>\n\n<p>This line will create a text box with the value 20 and assign the class attribute with the value hello. I put the @ character in front of the class, because class is a reserved keyword. If you want to add other attributes, just separate the key/value pairs with commas.</p>\n"
},
{
"answer_id": 40847,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 2,
"selected": false,
"text": "<p>Use the <code>htmlAttributes</code> parameter with an anonymous type, like tihs:</p>\n\n<pre><code><%=Html.TextBox(\"txtName\",\"20\", new { @class = \"test\"}) %>\n</code></pre>\n"
},
{
"answer_id": 40877,
"author": "David Negron",
"author_id": 981,
"author_profile": "https://Stackoverflow.com/users/981",
"pm_score": 2,
"selected": false,
"text": "<p>I did some research and came across this article that seems to have a solution to your question.</p>\n\n<p><strong>Ajax Control Toolkit with ASP.NET MVC#</strong></p>\n\n<p>source: jimzimmerman</p>\n\n<p><strong>ARTICLE LINK</strong></p>\n\n<p><a href=\"http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=330\" rel=\"nofollow noreferrer\">http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=330</a></p>\n\n<p><strong>QUOTE</strong></p>\n\n<blockquote>\n <p>So basically if you put the class name\n TextboxWatermark on any textbox input\n with the title you like to show as the\n watermark like this:</p>\n\n<pre><code><input type=\"text\" class\"TextboxWatermark\" name=\"username\" id=\"username\" title=\"Must be at least 6 chars\" />\n</code></pre>\n \n <p>or</p>\n\n<pre><code><%= Html.TextBox(\"username\", new { @class = \"TextboxWatermark\", @title = \"Must be at least 6 chars\" }) %>\n</code></pre>\n \n <p>What is nice about the second option\n is that you get the added benefit of\n getting the View Engine to fill out\n the value of the textbox if there is\n an item in ViewData of the\n ViewData.Model that has a var named\n 'username'.</p>\n</blockquote>\n"
},
{
"answer_id": 456094,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "\n\n<p></p>\n\n<p>Is it that much more work? </p>\n"
},
{
"answer_id": 13659584,
"author": "JGilmartin",
"author_id": 266552,
"author_profile": "https://Stackoverflow.com/users/266552",
"pm_score": 4,
"selected": false,
"text": "<p>This is how to add a class and a style on the same element...</p>\n\n<p>\"x\" being the model passed to the view with a property of TextBoxID</p>\n\n<pre><code>@Html.TextBoxFor(x => x.TextBoxID, new { @class = \"SearchBarSelect\", style = \"width: 20px; background-color: green;\" })\n</code></pre>\n"
},
{
"answer_id": 52705298,
"author": "Nelson Martins",
"author_id": 6410596,
"author_profile": "https://Stackoverflow.com/users/6410596",
"pm_score": -1,
"selected": false,
"text": "<p>Theres no need to use span, because its not dynamic.</p>\n\n<p>Css:</p>\n\n<pre><code>.testClass {\ncolor: #1600d3;\n}\n</code></pre>\n\n<p>View (Index):</p>\n\n<pre><code>@Html.TextBox(\"expression\", \"Text to show.\", new { @class = \"testClass\" })\n</code></pre>\n\n<p>if you need dynamic options you can use for example:</p>\n\n<p>CSS:</p>\n\n<pre><code>.test class{\nbackground: #ffffff;\n}\n</code></pre>\n\n<p>Controller (Index for test):</p>\n\n<pre><code>[HttpGet]\npublic ActionResult Index()\n{\nViewBag.vbColor = \"#000000\";\nreturn View();\n}\n</code></pre>\n\n<p>View (Index):</p>\n\n<pre><code><div>\n<span>\[email protected](\"expression\", \"Text to show.\", new \n{ @class = \"testClass\", @style=\"color: \" + \[email protected] })\n</span>\n</div>\n</code></pre>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 52768400,
"author": "Hamid Jolany",
"author_id": 555078,
"author_profile": "https://Stackoverflow.com/users/555078",
"pm_score": 0,
"selected": false,
"text": "<p>the helper implementation </p>\n\n<pre><code>public static class LabelExtensioncs\n{\n public static MvcHtmlString Alarm(this HtmlHelper helper, string target, string text)\n {\n return MvcHtmlString.Create(string.Format(\"<p class='alert' style='background-color: #b8f89d;border-radius: 5px;width: 100%;'><b>{0}</b><br /><i>{1}</i></p>\", target, text));\n } \n}\n</code></pre>\n\n<p>the usage in view section</p>\n\n<pre><code>@Html.Alarm(\"Title\", \"please unsure your card no is invisible in your authorized information\")\n</code></pre>\n\n<p>the result\n<a href=\"https://i.stack.imgur.com/Jo8St.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Jo8St.png\" alt=\"enter image description here\"></a></p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] | If I have an HTML helper like so:
```
Name:<br />
<%=Html.TextBox("txtName",20) %><br />
```
How do I apply a CSS class to it? Do I have to wrap it in a span? Or do I need to somehow utilize the HtmlAttributes property of the helper? | You can pass it into the TextBox call as a parameter.
```
Name:<br/>
<%= Html.TextBox("txtName", "20", new { @class = "hello" }) %>
```
This line will create a text box with the value 20 and assign the class attribute with the value hello. I put the @ character in front of the class, because class is a reserved keyword. If you want to add other attributes, just separate the key/value pairs with commas. |
40,840 | <p>I have a custom installer action that updates the PATH environment, and creates an additional environment variable. Appending a directory to the existing path variable is working fine, but for some reason my attempts to create a new environment variable have been unsuccessful. The code I am using is:</p>
<pre><code> using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true))
{
reg.SetValue("MYVAR", "SomeVal", RegistryValueKind.ExpandString);
}
</code></pre>
<p>Edit: The OS is 32-bit XP, and as far as I can tell it is failing silently.</p>
| [
{
"answer_id": 40864,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 1,
"selected": false,
"text": "<p>What OS is this? Is it on a 64-bit system? What is the nature of the failure: silent or is an exception thrown?</p>\n\n<p>You could try running <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow noreferrer\">ProcessMonitor</a> and seeing if it sees the attempt to set the value.</p>\n"
},
{
"answer_id": 40866,
"author": "Peter Hession",
"author_id": 441,
"author_profile": "https://Stackoverflow.com/users/441",
"pm_score": 2,
"selected": true,
"text": "<p>Is there any reason that you have to do it through the registry?</p>\n\n<p>If not, you can use Environment.SetEnvironmentVariable() since .NET 2.0. It allows you to set on a machine, process or user basis.</p>\n"
},
{
"answer_id": 41952,
"author": "Brian Stewart",
"author_id": 3114,
"author_profile": "https://Stackoverflow.com/users/3114",
"pm_score": 0,
"selected": false,
"text": "<p>It turns out there was another problem that was preventing the code in my question from being called. However, I was using the Win32 assembly because the example code I was following was written before the Environment assembly became available. So Thanks Peter for pointing out the Environment API.</p>\n"
},
{
"answer_id": 303019,
"author": "Rob Mensching",
"author_id": 23852,
"author_profile": "https://Stackoverflow.com/users/23852",
"pm_score": 1,
"selected": false,
"text": "<p>Why are you using a CustomAction for this? The Windows Installer supports updating environment variables natively.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114/"
] | I have a custom installer action that updates the PATH environment, and creates an additional environment variable. Appending a directory to the existing path variable is working fine, but for some reason my attempts to create a new environment variable have been unsuccessful. The code I am using is:
```
using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true))
{
reg.SetValue("MYVAR", "SomeVal", RegistryValueKind.ExpandString);
}
```
Edit: The OS is 32-bit XP, and as far as I can tell it is failing silently. | Is there any reason that you have to do it through the registry?
If not, you can use Environment.SetEnvironmentVariable() since .NET 2.0. It allows you to set on a machine, process or user basis. |
40,853 | <p>I have some code like this in a winforms app I was writing to query a user's mail box Storage Quota.</p>
<pre><code>DirectoryEntry mbstore = new DirectoryEntry(
@"LDAP://" + strhome,
m_serviceaccount,
[m_pwd],
AuthenticationTypes.Secure);
</code></pre>
<p>No matter what approach I tried (like <code>SecureString</code>), I am easily able to see the password (<strong>m_pwd</strong>) either using Reflector or using strings tab of Process Explorer for the executable.</p>
<p>I know I could put this code on the server or tighten up the security using mechanisms like delegation and giving only the required privileges to the service account.</p>
<p>Can somebody suggest a reasonably secure way to store the password in the local application without revealing the password to hackers?</p>
<p>Hashing is not possible since I need to know the exact password (not just the hash for matching purpose).
Encryption/Decryption mechanisms are not working since they are machine dependent.</p>
| [
{
"answer_id": 40865,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 2,
"selected": false,
"text": "<p>If you store it as a secure string and save the secure string to a file (possibly using <a href=\"http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.aspx\" rel=\"nofollow noreferrer\">Isolated Storage</a>, the only time you will have a plain text password is when you decrypt it to create your mbstore. Unfortunately, the constructor does not take a SecureString or a Credential object.</p>\n"
},
{
"answer_id": 40867,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 6,
"selected": true,
"text": "<p>The sanctified method is to use CryptoAPI and the Data Protection APIs.</p>\n\n<p>To encrypt, use something like this (C++):</p>\n\n<pre><code>DATA_BLOB blobIn, blobOut;\nblobIn.pbData=(BYTE*)data;\nblobIn.cbData=wcslen(data)*sizeof(WCHAR);\n\nCryptProtectData(&blobIn, description, NULL, NULL, NULL, CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN, &blobOut);\n_encrypted=blobOut.pbData;\n_length=blobOut.cbData;\n</code></pre>\n\n<p>Decryption is the opposite:</p>\n\n<pre><code>DATA_BLOB blobIn, blobOut;\nblobIn.pbData=const_cast<BYTE*>(data);\nblobIn.cbData=length;\n\nCryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &blobOut);\n\nstd::wstring _decrypted;\n_decrypted.assign((LPCWSTR)blobOut.pbData,(LPCWSTR)blobOut.pbData+blobOut.cbData/sizeof(WCHAR));\n</code></pre>\n\n<p>If you don't specify CRYPTPROTECT_LOCAL_MACHINE then the encrypted password can be securely stored in the registry or config file and only you can decrypt it. If you specify LOCAL_MACHINE, then anyone with access to the machine can get it.</p>\n"
},
{
"answer_id": 48762,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "<p>I found this book by keith Brown The .NET Developer's Guide to Windows Security. It has some good samples covering all kinds of security scenarios.\nFree <a href=\"http://alt.pluralsight.com/wiki/default.aspx/Keith.GuideBook.HomePage\" rel=\"nofollow noreferrer\">Online version</a> is also available.</p>\n"
},
{
"answer_id": 155356,
"author": "Michael Petrotta",
"author_id": 23897,
"author_profile": "https://Stackoverflow.com/users/23897",
"pm_score": 4,
"selected": false,
"text": "<p>As mentioned, the Data Protection API is a good way to do this. Note that if you're using .NET 2.0 or greater, you don't need to use P/Invoke to invoke the DPAPI. The framework wraps the calls with the System.Security.Cryptography.ProtectedData class.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4337/"
] | I have some code like this in a winforms app I was writing to query a user's mail box Storage Quota.
```
DirectoryEntry mbstore = new DirectoryEntry(
@"LDAP://" + strhome,
m_serviceaccount,
[m_pwd],
AuthenticationTypes.Secure);
```
No matter what approach I tried (like `SecureString`), I am easily able to see the password (**m\_pwd**) either using Reflector or using strings tab of Process Explorer for the executable.
I know I could put this code on the server or tighten up the security using mechanisms like delegation and giving only the required privileges to the service account.
Can somebody suggest a reasonably secure way to store the password in the local application without revealing the password to hackers?
Hashing is not possible since I need to know the exact password (not just the hash for matching purpose).
Encryption/Decryption mechanisms are not working since they are machine dependent. | The sanctified method is to use CryptoAPI and the Data Protection APIs.
To encrypt, use something like this (C++):
```
DATA_BLOB blobIn, blobOut;
blobIn.pbData=(BYTE*)data;
blobIn.cbData=wcslen(data)*sizeof(WCHAR);
CryptProtectData(&blobIn, description, NULL, NULL, NULL, CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN, &blobOut);
_encrypted=blobOut.pbData;
_length=blobOut.cbData;
```
Decryption is the opposite:
```
DATA_BLOB blobIn, blobOut;
blobIn.pbData=const_cast<BYTE*>(data);
blobIn.cbData=length;
CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &blobOut);
std::wstring _decrypted;
_decrypted.assign((LPCWSTR)blobOut.pbData,(LPCWSTR)blobOut.pbData+blobOut.cbData/sizeof(WCHAR));
```
If you don't specify CRYPTPROTECT\_LOCAL\_MACHINE then the encrypted password can be securely stored in the registry or config file and only you can decrypt it. If you specify LOCAL\_MACHINE, then anyone with access to the machine can get it. |
40,873 | <p>I have a table which is full of arbitrarily formatted phone numbers, like this</p>
<pre><code>027 123 5644
021 393-5593
(07) 123 456
042123456
</code></pre>
<p>I need to search for a phone number in a similarly arbitrary format ( e.g. <code>07123456</code> should find the entry <code>(07) 123 456</code></p>
<p>The way I'd do this in a normal programming language is to strip all the non-digit characters out of the 'needle', then go through each number in the haystack, strip all non-digit characters out of it, then compare against the needle, eg (in ruby)</p>
<pre><code>digits_only = lambda{ |n| n.gsub /[^\d]/, '' }
needle = digits_only[input_phone_number]
haystack.map(&digits_only).include?(needle)
</code></pre>
<p>The catch is, I need to do this in MySQL. It has a host of string functions, none of which really seem to do what I want.</p>
<p>Currently I can think of 2 'solutions'</p>
<ul>
<li>Hack together a franken-query of <code>CONCAT</code> and <code>SUBSTR</code></li>
<li>Insert a <code>%</code> between every character of the needle ( so it's like this: <code>%0%7%1%2%3%4%5%6%</code> )</li>
</ul>
<p>However, neither of these seem like particularly elegant solutions.<br />
Hopefully someone can help or I might be forced to use the %%%%%% solution</p>
<h3>Update: This is operating over a relatively fixed set of data, with maybe a few hundred rows. I just didn't want to do something ridiculously bad that future programmers would cry over.</h3>
<p>If the dataset grows I'll take the 'phoneStripped' approach. Thanks for all the feedback!</p>
<hr />
<blockquote>
<p>could you use a "replace" function to strip out any instances of "(", "-" and " ",</p>
</blockquote>
<p>I'm not concerned about the result being numeric.
The main characters I need to consider are <code>+</code>, <code>-</code>, <code>(</code>, <code>)</code> and <code>space</code>
So would that solution look like this?</p>
<pre><code>SELECT * FROM people
WHERE
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phonenumber, '('),')'),'-'),' '),'+')
LIKE '123456'
</code></pre>
<p>Wouldn't that be terribly slow?</p>
| [
{
"answer_id": 40880,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "<p>An out-of-the-box idea, but could you use a \"replace\" function to strip out any instances of \"(\", \"-\" and \" \", and then use an \"isnumeric\" function to test whether the resulting string is a number?</p>\n\n<p>Then you could do the same to the phone number string you're searching for and compare them as integers.</p>\n\n<p>Of course, this won't work for numbers like 1800-MATT-ROCKS. :)</p>\n"
},
{
"answer_id": 40895,
"author": "crono",
"author_id": 1462,
"author_profile": "https://Stackoverflow.com/users/1462",
"pm_score": 2,
"selected": false,
"text": "<p>This is a problem with MySQL - the regex function can match, but it can't replace. <a href=\"http://forums.mysql.com/read.php?10,137433,137465\" rel=\"nofollow noreferrer\">See this post</a> for a possible solution.</p>\n"
},
{
"answer_id": 40900,
"author": "megabytephreak",
"author_id": 4108,
"author_profile": "https://Stackoverflow.com/users/4108",
"pm_score": 2,
"selected": false,
"text": "<p>Is it possible to run a query to reformat the data to match a desired format and then just run a simple query? That way even if the initial reformatting is slow you it doesn't really matter. </p>\n"
},
{
"answer_id": 40904,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>MySQL can search based on regular expressions.</p>\n</blockquote>\n\n<p>Sure, but given the arbitrary formatting, if my haystack contained <code>\"(027) 123 456\"</code> (bear in mind position of spaces can change, it could just as easily be <code>027 12 3456</code> and I wanted to match it with <code>027123456</code>, would my regex therefore need to be this?</p>\n\n<pre><code>\"^[\\D]+0[\\D]+2[\\D]+7[\\D]+1[\\D]+2[\\D]+3[\\D]+4[\\D]+5[\\D]+6$\"\n</code></pre>\n\n<p>(actually it'd be worse as the mysql manual doesn't seem to indicate it supports <code>\\D</code>)</p>\n\n<p>If that is the case, isn't it more or less the same as my %%%%% idea?</p>\n"
},
{
"answer_id": 40916,
"author": "crucible",
"author_id": 3717,
"author_profile": "https://Stackoverflow.com/users/3717",
"pm_score": 0,
"selected": false,
"text": "<p>Just an idea, but couldn't you use Regex to quickly strip out the characters and then compare against that like @Matt Hamilton suggested?</p>\n\n<p>Maybe even set up a view (not sure of mysql on views) that would hold all phone numbers stripped by regex to a plain phone number?</p>\n"
},
{
"answer_id": 40938,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "<p>Woe is me. I ended up doing this:</p>\n\n<pre><code>mre = mobile_number && ('%' + mobile_number.gsub(/\\D/, '').scan(/./m).join('%'))\n\nfind(:first, :conditions => ['trim(mobile_phone) like ?', mre])\n</code></pre>\n"
},
{
"answer_id": 40980,
"author": "Tanj",
"author_id": 4275,
"author_profile": "https://Stackoverflow.com/users/4275",
"pm_score": 0,
"selected": false,
"text": "<p>if this is something that is going to happen on a regular basis perhaps modifying the data to be all one format and then setup the search form to strip out any non-alphanumeric (if you allow numbers like 310-BELL) would be a good idea. Having data in an easily searched format is half the battle.</p>\n"
},
{
"answer_id": 41016,
"author": "John Dyer",
"author_id": 2862,
"author_profile": "https://Stackoverflow.com/users/2862",
"pm_score": 5,
"selected": true,
"text": "<p>This looks like a problem from the start. Any kind of searching you do will require a table scan and we all know that's bad.</p>\n\n<p>How about adding a column with a hash of the current phone numbers after stripping out all formatting characters. Then you can at least index the hash values and avoid a full blown table scan.</p>\n\n<p>Or is the amount of data small and not expected to grow much?\nThen maybe just sucking all the numbers into the client and running a search there.</p>\n"
},
{
"answer_id": 95661,
"author": "Michael Johnson",
"author_id": 17688,
"author_profile": "https://Stackoverflow.com/users/17688",
"pm_score": 2,
"selected": false,
"text": "<p>My solution would be something along the lines of what John Dyer said. I'd add a second column (e.g. phoneStripped) that gets stripped on insert and update. Index this column and search on it (after stripping your search term, of course).</p>\n\n<p>You could also add a trigger to automatically update the column, although I've not worked with triggers. But like you said, it's really difficult to write the MySQL code to strip the strings, so it's probably easier to just do it in your client code.</p>\n\n<p>(I know this is late, but I just started looking around here :)</p>\n"
},
{
"answer_id": 911592,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>a possible solution can be found at http: //udf-regexp.php-baustelle.de/trac/</p>\n\n<p>additional package need to be installed, then you can play with REGEXP_REPLACE</p>\n"
},
{
"answer_id": 2426729,
"author": "Grbts",
"author_id": 230229,
"author_profile": "https://Stackoverflow.com/users/230229",
"pm_score": 2,
"selected": false,
"text": "<p>See</p>\n\n<p><a href=\"http://www.mfs-erp.org/community/blog/find-phone-number-in-database-format-independent\" rel=\"nofollow noreferrer\">http://www.mfs-erp.org/community/blog/find-phone-number-in-database-format-independent</a></p>\n\n<p>It is not really an issue that the regular expression would become visually appalling, since only mysql \"sees\" it. Note that instead of '+' (cfr. post with [\\D] from the OP) you should use '*' in the regular expression. </p>\n\n<p>Some users are concerned about performance (non-indexed search), but in a table with 100000 customers, this query, when issued from a user interface returns immediately, without noticeable delay. </p>\n"
},
{
"answer_id": 4585143,
"author": "Michael Bagryantcev",
"author_id": 529115,
"author_profile": "https://Stackoverflow.com/users/529115",
"pm_score": 2,
"selected": false,
"text": "<p>i suggest to use php functions, and not mysql patterns, so you will have some code like this:</p>\n\n<pre><code>$tmp_phone = '';\nfor ($i=0; $i < strlen($phone); $i++)\n if (is_numeric($phone[$i]))\n $tmp_phone .= '%'.$phone[$i];\n$tmp_phone .= '%';\n$search_condition .= \" and phone LIKE '\" . $tmp_phone . \"' \";\n</code></pre>\n"
},
{
"answer_id": 18870782,
"author": "Sathish",
"author_id": 1064360,
"author_profile": "https://Stackoverflow.com/users/1064360",
"pm_score": 0,
"selected": false,
"text": "<p>Create a user defined function to dynamically creates Regex.</p>\n\n<pre><code>DELIMITER //\n\nCREATE FUNCTION udfn_GetPhoneRegex\n( \n var_Input VARCHAR(25)\n)\nRETURNS VARCHAR(200)\n\nBEGIN\n DECLARE iterator INT DEFAULT 1;\n DECLARE phoneregex VARCHAR(200) DEFAULT '';\n\n DECLARE output VARCHAR(25) DEFAULT '';\n\n\n WHILE iterator < (LENGTH(var_Input) + 1) DO\n IF SUBSTRING(var_Input, iterator, 1) IN ( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ) THEN\n SET output = CONCAT(output, SUBSTRING(var_Input, iterator, 1));\n END IF;\n SET iterator = iterator + 1;\n END WHILE;\n SET output = RIGHT(output,10);\n SET iterator = 1;\n WHILE iterator < (LENGTH(output) + 1) DO\n SET phoneregex = CONCAT(phoneregex,'[^0-9]*',SUBSTRING(output, iterator, 1));\n SET iterator = iterator + 1;\n END WHILE;\n SET phoneregex = CONCAT(phoneregex,'$');\n RETURN phoneregex;\nEND//\nDELIMITER ;\n</code></pre>\n\n<hr>\n\n<p>Call that User Defined Function in your stored procedure.</p>\n\n<pre><code>DECLARE var_PhoneNumberRegex VARCHAR(200);\nSET var_PhoneNumberRegex = udfn_GetPhoneRegex('+ 123 555 7890');\nSELECT * FROM Customer WHERE phonenumber REGEXP var_PhoneNumberRegex;\n</code></pre>\n"
},
{
"answer_id": 21316683,
"author": "Nihal",
"author_id": 3229181,
"author_profile": "https://Stackoverflow.com/users/3229181",
"pm_score": 3,
"selected": false,
"text": "<p>I know this is ancient history, but I found it while looking for a similar solution.</p>\n\n<p>A simple REGEXP may work:</p>\n\n<pre><code>select * from phone_table where phone1 REGEXP \"07[^0-9]*123[^0-9]*456\"\n</code></pre>\n\n<p>This would match the <code>phonenumber</code> column with or without any separating characters.</p>\n"
},
{
"answer_id": 41933997,
"author": "Heisenberg",
"author_id": 2051133,
"author_profile": "https://Stackoverflow.com/users/2051133",
"pm_score": 0,
"selected": false,
"text": "<p>I would use Google's <a href=\"https://github.com/googlei18n/libphonenumber\" rel=\"nofollow noreferrer\">libPhoneNumber</a> to format a number to E164 format. I would add a second column called \"e164_number\" to store the e164 formatted number and add an index on it. </p>\n"
},
{
"answer_id": 60871662,
"author": "Bréndal Teixeira",
"author_id": 5221538,
"author_profile": "https://Stackoverflow.com/users/5221538",
"pm_score": 2,
"selected": false,
"text": "<p>As John Dyer said, you should consider fixing the data in the DB and store only numbers. However, if you are facing the same situation as mine (I cannot run a update query) the workaround I found was combining 2 queries.</p>\n\n<p>The \"inside\" query will retrieve all the phone numbers and format them removing the non-numeric characters.</p>\n\n<pre><code>SELECT REGEXP_REPLACE(column_name, '[^0-9]', '') phone_formatted FROM table_name\n</code></pre>\n\n<p>The result of it will be all phone numbers without any special character. After that the \"outside\" query just need to get the entry you are looking for.\nThe 2 queries will be:</p>\n\n<pre><code>SELECT phone_formatted FROM (\n SELECT REGEXP_REPLACE(column_name, '[^0-9]', '') phone_formatted FROM table_name\n) AS result WHERE phone_formatted = 9999999999\n</code></pre>\n\n<p>Important: the <strong>AS result</strong> is not used but it should be there to avoid erros.</p>\n"
},
{
"answer_id": 70549733,
"author": "ideaztech",
"author_id": 3131411,
"author_profile": "https://Stackoverflow.com/users/3131411",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a working Solution for PHP users.</p>\n<p>This uses a loop in PHP to build the Regular Expression. Then searches the database in MySQL with the RLIKE operator.</p>\n<pre><code>$phone = '(456) 584-5874' // can be any format\n$phone = preg_replace('/[^0-9]/', '', $phone); // strip non-numeric characters\n$len = strlen($phone); // get length of phone number\nfor ($i = 0; $i < $len - 1; $i++) {\n $regex .= $phone[$i] . "[^[:digit:]]*";\n}\n$regex .= $phone[$len - 1];\n</code></pre>\n<p>This creates a Regular Expression that looks like this: 4[^[:digit:]]*5[^[:digit:]]*6[^[:digit:]]*5[^[:digit:]]*8[^[:digit:]]*4[^[:digit:]]*5[^[:digit:]]*8[^[:digit:]]*7[^[:digit:]]*4</p>\n<p>Now formulate your MySQL something like this:</p>\n<pre><code>$sql = "SELECT Client FROM tb_clients WHERE Phone RLIKE '$regex'"\n</code></pre>\n<p>NOTE: I tried several of the other posted answers but found performance issues. For example, on our large database, it took 16 seconds to run the IsNumeric example. But this solution ran instantly. And this solution is compatible with older MySQL versions.</p>\n"
},
{
"answer_id": 71467126,
"author": "Meloman",
"author_id": 2282880,
"author_profile": "https://Stackoverflow.com/users/2282880",
"pm_score": 0,
"selected": false,
"text": "<p>In my case, I needed to identify Swiss (CH) mobile phone numbers in the <code>phone</code> column and move them in <code>mobile</code> column.</p>\n<p>As all mobile phone numbers starts with 07x or +417x here is the regex to use :</p>\n<pre><code>/^(\\+[0-9][0-9]\\s*|0|)7.*/mgix\n</code></pre>\n<p>It find all numbers like the following :</p>\n<ul>\n<li>+41 79 123 456 78</li>\n<li>+417612345678</li>\n<li>076 123 456 78</li>\n<li>07812345678</li>\n<li>7712345678</li>\n</ul>\n<p>and ignore all others like theese :</p>\n<ul>\n<li>+41 47 123 456 78</li>\n<li>+413212345678</li>\n<li>021 123 456 78</li>\n<li>02212345678</li>\n<li>3412345678</li>\n</ul>\n<p>In MySQL it gives the following code :</p>\n<pre><code>UPDATE `contact` \nSET `mobile` = `phone`,\n `phone` = ''\nWHERE `phone` REGEXP '^(\\\\+[\\D+][0-9]\\\\s*|0|)(7.*)$'\n</code></pre>\n<blockquote>\n<p>You'll need to clean your number from special chars like <code>-/.()</code> before.</p>\n</blockquote>\n<p><a href=\"https://regex101.com/r/AiWFX8/1\" rel=\"nofollow noreferrer\">https://regex101.com/r/AiWFX8/1</a></p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] | I have a table which is full of arbitrarily formatted phone numbers, like this
```
027 123 5644
021 393-5593
(07) 123 456
042123456
```
I need to search for a phone number in a similarly arbitrary format ( e.g. `07123456` should find the entry `(07) 123 456`
The way I'd do this in a normal programming language is to strip all the non-digit characters out of the 'needle', then go through each number in the haystack, strip all non-digit characters out of it, then compare against the needle, eg (in ruby)
```
digits_only = lambda{ |n| n.gsub /[^\d]/, '' }
needle = digits_only[input_phone_number]
haystack.map(&digits_only).include?(needle)
```
The catch is, I need to do this in MySQL. It has a host of string functions, none of which really seem to do what I want.
Currently I can think of 2 'solutions'
* Hack together a franken-query of `CONCAT` and `SUBSTR`
* Insert a `%` between every character of the needle ( so it's like this: `%0%7%1%2%3%4%5%6%` )
However, neither of these seem like particularly elegant solutions.
Hopefully someone can help or I might be forced to use the %%%%%% solution
### Update: This is operating over a relatively fixed set of data, with maybe a few hundred rows. I just didn't want to do something ridiculously bad that future programmers would cry over.
If the dataset grows I'll take the 'phoneStripped' approach. Thanks for all the feedback!
---
>
> could you use a "replace" function to strip out any instances of "(", "-" and " ",
>
>
>
I'm not concerned about the result being numeric.
The main characters I need to consider are `+`, `-`, `(`, `)` and `space`
So would that solution look like this?
```
SELECT * FROM people
WHERE
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phonenumber, '('),')'),'-'),' '),'+')
LIKE '123456'
```
Wouldn't that be terribly slow? | This looks like a problem from the start. Any kind of searching you do will require a table scan and we all know that's bad.
How about adding a column with a hash of the current phone numbers after stripping out all formatting characters. Then you can at least index the hash values and avoid a full blown table scan.
Or is the amount of data small and not expected to grow much?
Then maybe just sucking all the numbers into the client and running a search there. |
40,912 | <p>I'm looking for a way to check within <code>pageLoad()</code> if this method is raised during load event because of a postback/async postback or because of being loaded and access the first time.</p>
<p>This is similar to <code>Page.IsPostback</code> property within code behind page.</p>
<p>TIA,
Ricky</p>
| [
{
"answer_id": 40924,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 2,
"selected": false,
"text": "<p>You could have a hidden input that you set to a known value on the server side if it's a postback/callback - and your javascript could check that value.</p>\n\n<p>That said, I really hope that there's a client-only solution for this.</p>\n\n<p><strong>Edit:</strong> @mmattax - I believe he's looking for a client-side solution - the JavaScript equivalent of that.</p>\n"
},
{
"answer_id": 40925,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>What you can do is wire up to the load event of the <a href=\"http://msdn.microsoft.com/en-us/library/bb310856.aspx\" rel=\"nofollow noreferrer\">Sys.Application</a> class. you can then use the isPartialLoad property of the <a href=\"http://msdn.microsoft.com/en-us/library/bb397457.aspx\" rel=\"nofollow noreferrer\">Sys.ApplicationLoadEventArgs</a> class. I believe that would let you know if you are in a async postback or not.</p>\n\n<p>To know if you are in a post back, you'll have to handle that in server side code and emit that to the client.</p>\n"
},
{
"answer_id": 40955,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 0,
"selected": false,
"text": "<p>You can still use Page.IsPostback during an async call.</p>\n"
},
{
"answer_id": 40981,
"author": "Ricky Supit",
"author_id": 4191,
"author_profile": "https://Stackoverflow.com/users/4191",
"pm_score": 2,
"selected": false,
"text": "<p>@Darren: Thanks for the answer. I had tried to create pageLoad with event argument <a href=\"http://asp.net/AJAX/Documentation/Live/ClientReference/Sys/ApplicationLoadEventArgsClass/ApplicationLoadEventArgsIsPartialLoadProperty.aspx\" rel=\"nofollow noreferrer\">ApplicationLoadEventArgs</a> as parameter (see below). However according to <a href=\"http://msdn.microsoft.com/en-us/library/bb386417.aspx\" rel=\"nofollow noreferrer\">this</a>:</p>\n\n<p><em>The load event is raised for all postbacks to the server, which includes asynchronous postbacks.</em></p>\n\n<p>As you have indicated, the isPartialLoad property does not cover all postback scenarios. It'll be nice if the event argument also contain isPostback property.</p>\n\n<pre><code> function pageLoad(sender, arg) {\n if (!arg.get_isPartialLoad()) {\n //code to be executed only on the first load\n }\n }\n</code></pre>\n\n<p>@mmattax: I'm looking for property that can be called from client-side (javascript).</p>\n"
},
{
"answer_id": 44993,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.asp.net/AJAX/documentation/live/ClientReference/Sys/ApplicationClass/SysApplicationInitEvent.aspx\" rel=\"nofollow noreferrer\">Application.Init</a> is probably a more appropriate event to use, if you only want the code to execute on the first load.</p>\n"
},
{
"answer_id": 45117,
"author": "Ricky Supit",
"author_id": 4191,
"author_profile": "https://Stackoverflow.com/users/4191",
"pm_score": 0,
"selected": false,
"text": "<p>@Dave Ward: This normally would work. However, the code is to attach event on behavior object. Because the creation of behavior object happens during Application.Init, attaching to that event will lead to unpredictable behavior.</p>\n\n<p>It will be nice if there is PostInit event.</p>\n"
},
{
"answer_id": 45189,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 4,
"selected": true,
"text": "<p>One way you could do that is to wire up an Application.Load handler in Application.Init, then have that handler unbind itself after running:</p>\n\n<pre><code>Sys.Application.add_init(AppInit);\n\nfunction AppInit() {\n Sys.Application.add_load(RunOnce);\n}\n\nfunction RunOnce() {\n // This will only happen once per GET request to the page.\n\n Sys.Application.remove_load(RunOnce);\n}\n</code></pre>\n\n<p>That will execute after Application.Init. It should be the last thing before pageLoad is called.</p>\n"
},
{
"answer_id": 46319,
"author": "Ricky Supit",
"author_id": 4191,
"author_profile": "https://Stackoverflow.com/users/4191",
"pm_score": 0,
"selected": false,
"text": "<p>@Dave Ward:\nThe use of RunOnce method works perfectly. This solve my problem without having the workaround to check first if handler already exist before attaching to an event.</p>\n\n<p>I'll mark your answer as an accepted answer. Thanks again.</p>\n"
},
{
"answer_id": 75248,
"author": "Compulsion",
"author_id": 3675,
"author_profile": "https://Stackoverflow.com/users/3675",
"pm_score": 0,
"selected": false,
"text": "<p>Here's our Ajax equivalent to isPostback which we've been using for a while.</p>\n\n<pre><code>public static bool isAjaxRequest(System.Web.HttpRequest request)\n {//Checks to see if the request is an Ajax request\n if (request.ServerVariables[\"HTTP_X_MICROSOFTAJAX\"] != null ||\n request.Form[\"__CALLBACKID\"] != null)\n return true;\n else\n return false;\n }\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4191/"
] | I'm looking for a way to check within `pageLoad()` if this method is raised during load event because of a postback/async postback or because of being loaded and access the first time.
This is similar to `Page.IsPostback` property within code behind page.
TIA,
Ricky | One way you could do that is to wire up an Application.Load handler in Application.Init, then have that handler unbind itself after running:
```
Sys.Application.add_init(AppInit);
function AppInit() {
Sys.Application.add_load(RunOnce);
}
function RunOnce() {
// This will only happen once per GET request to the page.
Sys.Application.remove_load(RunOnce);
}
```
That will execute after Application.Init. It should be the last thing before pageLoad is called. |
40,913 | <p>I am having problems manually looping through xml data that is received via an HTTPService call, the xml looks something like this: </p>
<pre><code><DataTable>
<Row>
<text>foo</text>
</Row>
<Row>
<text>bar</text>
</Row>
</DataTable>
</code></pre>
<p>When the webservice result event is fired I do something like this:</p>
<pre><code>for(var i:int=0;i&lt;event.result.DataTable.Row.length;i++)
{
if(event.result.DataTable.Row[i].text == "foo")
mx.controls.Alert.show('foo found!');
}
</code></pre>
<p>This code works then there is more than 1 "Row" nodes returned. However, it seems that if there is only one "Row" node then the <em>event.DataTable.Row</em> object is not an error and the code subsequently breaks. </p>
<p>What is the proper way to loop through the <em>HTTPService</em> result object? Do I need to convert it to some type of <em>XMLList</em> collection or an <em>ArrayCollection</em>? I have tried setting the resultFormat to <em>e4x</em> and that has yet to fix the problem...</p>
<p>Thanks.</p>
| [
{
"answer_id": 40930,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 2,
"selected": false,
"text": "<p>Row isn't an array unless there are multiple Row elements. It is annoying. You have to do something like this, but I haven't written AS3 in a while so I forget if there's an exists function.</p>\n\n<pre><code>if (exists(event.result.DataTable) && exists(event.result.DataTable.Row)){\n if (exists(event.result.DataTable.Row.length)) {\n for(var i:int=0;i<event.result.DataTable.Row.length;i++)\n {\n if (exists(event.result.DataTable.Row[i].text)\n && \"foo\" == event.result.DataTable.Row[i].text)\n mx.controls.Alert.show('foo found!');\n }\n }\n if (exists(event.result.DataTable.Row.text)\n && \"foo\" == event.result.DataTable.Row.text)\n mx.controls.Alert.show('foo found!');\n}\n</code></pre>\n"
},
{
"answer_id": 40937,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 1,
"selected": false,
"text": "<p>I would store it in an Xml object and then use its methods to search for the node value you need.</p>\n\n<pre><code>var returnedXml:Xml = new Xml(event.result.toString());\n</code></pre>\n"
},
{
"answer_id": 41222,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 3,
"selected": true,
"text": "<p>The problem lies in this statement</p>\n\n<pre><code>event.result.DataTable.Row.length\n</code></pre>\n\n<p><code>length</code> is not a property of <code>XMLList</code>, but a method:</p>\n\n<pre><code>event.result.DataTable.Row.length()\n</code></pre>\n\n<p>it's confusing, but that's the way it is.</p>\n\n<p><em>Addition:</em> actually, the safest thing to do is to always use a <code>for each</code> loop when iterating over <code>XMLList</code>s, that way you never make the mistake, it's less code, and easier to read:</p>\n\n<pre><code>for each ( var node : XML in event.result.DataTable.Row )\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/40913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | I am having problems manually looping through xml data that is received via an HTTPService call, the xml looks something like this:
```
<DataTable>
<Row>
<text>foo</text>
</Row>
<Row>
<text>bar</text>
</Row>
</DataTable>
```
When the webservice result event is fired I do something like this:
```
for(var i:int=0;i<event.result.DataTable.Row.length;i++)
{
if(event.result.DataTable.Row[i].text == "foo")
mx.controls.Alert.show('foo found!');
}
```
This code works then there is more than 1 "Row" nodes returned. However, it seems that if there is only one "Row" node then the *event.DataTable.Row* object is not an error and the code subsequently breaks.
What is the proper way to loop through the *HTTPService* result object? Do I need to convert it to some type of *XMLList* collection or an *ArrayCollection*? I have tried setting the resultFormat to *e4x* and that has yet to fix the problem...
Thanks. | The problem lies in this statement
```
event.result.DataTable.Row.length
```
`length` is not a property of `XMLList`, but a method:
```
event.result.DataTable.Row.length()
```
it's confusing, but that's the way it is.
*Addition:* actually, the safest thing to do is to always use a `for each` loop when iterating over `XMLList`s, that way you never make the mistake, it's less code, and easier to read:
```
for each ( var node : XML in event.result.DataTable.Row )
``` |
40,943 | <p>What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited?</p>
<p>I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software?</p>
| [
{
"answer_id": 40945,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 5,
"selected": false,
"text": "<p>Here is an example of sending back a pdf.</p>\n\n<pre><code>header('Content-type: application/pdf');\nheader('Content-Disposition: attachment; filename=\"' . basename($filename) . '\"');\nheader('Content-Transfer-Encoding: binary');\nreadfile($filename);\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/40943/how-to-automatically-start-a-download-in-php#40947\">@Swish</a> I didn't find application/force-download content type to do anything different (tested in IE and Firefox). Is there a reason for not sending back the actual MIME type?</p>\n\n<p>Also in the PHP manual <a href=\"http://au.php.net/manual/en/function.header.php#71993\" rel=\"noreferrer\">Hayley Watson</a> posted:</p>\n\n<blockquote>\n <p>If you wish to force a file to be downloaded and saved, instead of being rendered, remember that there is no such MIME type as \"application/force-download\". The correct type to use in this situation is \"application/octet-stream\", and using anything else is merely relying on the fact that clients are supposed to ignore unrecognised MIME types and use \"application/octet-stream\" instead (reference: Sections 4.1.4 and 4.5.1 of RFC 2046).</p>\n</blockquote>\n\n<p>Also according <a href=\"http://www.iana.org/assignments/media-types/application/\" rel=\"noreferrer\">IANA</a> there is no registered application/force-download type.</p>\n"
},
{
"answer_id": 40947,
"author": "Robert Swisher",
"author_id": 1852,
"author_profile": "https://Stackoverflow.com/users/1852",
"pm_score": 7,
"selected": true,
"text": "<p>Send the following headers before outputting the file:</p>\n\n<pre><code>header(\"Content-Disposition: attachment; filename=\\\"\" . basename($File) . \"\\\"\");\nheader(\"Content-Type: application/octet-stream\");\nheader(\"Content-Length: \" . filesize($File));\nheader(\"Connection: close\");\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/users/486/grom\">@grom</a>: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)</p>\n"
},
{
"answer_id": 8349390,
"author": "vdbuilder",
"author_id": 1076318,
"author_profile": "https://Stackoverflow.com/users/1076318",
"pm_score": 4,
"selected": false,
"text": "<p>A clean example.</p>\n\n<pre><code><?php\n header('Content-Type: application/download');\n header('Content-Disposition: attachment; filename=\"example.txt\"');\n header(\"Content-Length: \" . filesize(\"example.txt\"));\n\n $fp = fopen(\"example.txt\", \"r\");\n fpassthru($fp);\n fclose($fp);\n?>\n</code></pre>\n"
},
{
"answer_id": 10014110,
"author": "Omidoo",
"author_id": 879163,
"author_profile": "https://Stackoverflow.com/users/879163",
"pm_score": 0,
"selected": false,
"text": "<p>my code works for txt,doc,docx,pdf,ppt,pptx,jpg,png,zip extensions and I think its better to use the actual MIME types explicitly.</p>\n\n<pre><code>$file_name = \"a.txt\";\n\n// extracting the extension:\n$ext = substr($file_name, strpos($file_name,'.')+1);\n\nheader('Content-disposition: attachment; filename='.$file_name);\n\nif(strtolower($ext) == \"txt\")\n{\n header('Content-type: text/plain'); // works for txt only\n}\nelse\n{\n header('Content-type: application/'.$ext); // works for all extensions except txt\n}\nreadfile($decrypted_file_path);\n</code></pre>\n"
},
{
"answer_id": 68258678,
"author": "gtamborero",
"author_id": 3577257,
"author_profile": "https://Stackoverflow.com/users/3577257",
"pm_score": 1,
"selected": false,
"text": "<p>None of above worked for me!</p>\n<p>Working on 2021 for WordPress and PHP:</p>\n<pre><code><?php\n$file = ABSPATH . 'pdf.pdf'; // Where ABSPATH is the absolute server path, not url\n//echo $file; //Be sure you are echoing the absolute path and file name\n$filename = 'Custom file name for the.pdf'; /* Note: Always use .pdf at the end. */\n\nheader('Content-type: application/pdf');\nheader('Content-Disposition: inline; filename="' . $filename . '"');\nheader('Content-Transfer-Encoding: binary');\nheader('Content-Length: ' . filesize($file));\nheader('Accept-Ranges: bytes');\n@readfile($file);\n</code></pre>\n<p>Thanks to: <a href=\"https://qastack.mx/programming/4679756/show-a-pdf-files-in-users-browser-via-php-perl\" rel=\"nofollow noreferrer\">https://qastack.mx/programming/4679756/show-a-pdf-files-in-users-browser-via-php-perl</a></p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/40943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] | What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited?
I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software? | Send the following headers before outputting the file:
```
header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");
```
[@grom](https://stackoverflow.com/users/486/grom): Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :) |
40,966 | <p>I have a javascript function that manipulates the DOM when it is called (adds CSS classes, etc). This is invoked when the user changes some values in a form. When the document is first loading, I want to invoke this function to prepare the initial state (which is simpler in this case than setting up the DOM from the server side to the correct initial state).</p>
<p>Is it better to use window.onload to do this functionality or have a script block after the DOM elements I need to modify? For either case, why is it better?</p>
<p>For example:</p>
<pre><code>function updateDOM(id) {
// updates the id element based on form state
}
</code></pre>
<p>should I invoke it via:</p>
<pre><code>window.onload = function() { updateDOM("myElement"); };
</code></pre>
<p>or:</p>
<pre><code><div id="myElement">...</div>
<script language="javascript">
updateDOM("myElement");
</script>
</code></pre>
<p>The former seems to be the standard way to do it, but the latter seems to be just as good, perhaps better since it will update the element as soon as the script is hit, and as long as it is placed after the element, I don't see a problem with it.</p>
<p>Any thoughts? Is one version really better than the other?</p>
| [
{
"answer_id": 40972,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": true,
"text": "<p>Definitely use <code>onload</code>. Keep your scripts separate from your page, or you'll go mad trying to disentangle them later.</p>\n"
},
{
"answer_id": 40977,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 0,
"selected": false,
"text": "<p>My take is the former becauase you can only have 1 window.onload function, while inline script blocks you have an <em>n</em> number.</p>\n"
},
{
"answer_id": 40996,
"author": "DancesWithBamboo",
"author_id": 1334,
"author_profile": "https://Stackoverflow.com/users/1334",
"pm_score": 0,
"selected": false,
"text": "<p>onLoad because it is far easier to tell what code runs when the page loads up than having to read down through scads of html looking for script tags that might execute.</p>\n"
},
{
"answer_id": 41005,
"author": "The How-To Geek",
"author_id": 291,
"author_profile": "https://Stackoverflow.com/users/291",
"pm_score": 1,
"selected": false,
"text": "<p>While I agree with the others about using window.onload if possible for clean code, I'm pretty sure that window.onload will be called again when a user hits the back button in IE, but doesn't get called again in Firefox. (Unless they changed it recently). </p>\n\n<p>Edit: I could have that backwards.</p>\n\n<p>In some cases, it's necessary to use inline script when you want your script to be evaluated when the user hits the back button from another page, back to your page.</p>\n\n<p>Any corrections or additions to this answer are welcome... I'm not a javascript expert.</p>\n"
},
{
"answer_id": 41008,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "<p>@The Geek</p>\n\n<blockquote>\n <p>I'm pretty sure that window.onload will be called again when a user hits the back button in IE, but doesn't get called again in Firefox. (Unless they changed it recently).</p>\n</blockquote>\n\n<p>In Firefox, <code>onload</code> is called when the DOM has finished loading regardless of how you navigated to a page.</p>\n"
},
{
"answer_id": 41011,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 2,
"selected": false,
"text": "<p>Some JavaScript frameworks, such as <a href=\"http://docs.mootools.net/Utilities/DomReady\" rel=\"nofollow noreferrer\">mootools</a>, give you access to a special event named \"domready\":</p>\n\n<blockquote>\n <p>Contains the window Event 'domready', which will execute when the DOM has loaded. To ensure that DOM elements exist when the code attempting to access them is executed, they should be placed within the 'domready' event.</p>\n\n<pre><code>window.addEvent('domready', function() {\n alert(\"The DOM is ready.\");\n});\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 41013,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 4,
"selected": false,
"text": "<p>The onload event is considered the proper way to do it, but if you don't mind using a javascript library, jQuery's $(document).ready() is even better.</p>\n\n<pre><code>$(document).ready(function(){\n // manipulate the DOM all you want here\n});\n</code></pre>\n\n<p>The advantages are:</p>\n\n<ol>\n<li>Call $(document).ready() as many times as you want to register additional code to run - you can only set window.onload once.</li>\n<li>$(document).ready() actions happen as soon as the DOM is complete - window.onload has to wait for images and such.</li>\n</ol>\n\n<p>I hope I'm not becoming The Guy Who Suggests jQuery On Every JavaScript Question, but it really is great.</p>\n"
},
{
"answer_id": 41019,
"author": "TonyLa",
"author_id": 1295,
"author_profile": "https://Stackoverflow.com/users/1295",
"pm_score": 2,
"selected": false,
"text": "<p>window.onload on IE waits for the binary information to load also. It isn't a strict definition of \"when the DOM is loaded\". So there can be significant lag between when the page is perceived to be loaded and when your script gets fired. Because of this I would recommend looking into one of the plentiful JS frameworks (prototype/jQuery) to handle the heavy lifting for you.</p>\n"
},
{
"answer_id": 41049,
"author": "Ryan Doherty",
"author_id": 956,
"author_profile": "https://Stackoverflow.com/users/956",
"pm_score": 3,
"selected": false,
"text": "<p>I've written lots of Javascript and window.onload is a <strong>terrible</strong> way to do it. It is brittle and waits until <strong>every</strong> asset of the page has loaded. So if one image takes forever or a resource doesn't timeout until 30 seconds, your code will not run before the user can see/manipulate the page.</p>\n\n<p>Also, if another piece of Javascript decides to use window.onload = function() {}, your code will be blown away.</p>\n\n<p>The proper way to run your code when the page is ready is wait for the element you need to change is ready/available. Many JS libraries have this as built-in functionality. </p>\n\n<p>Check out:</p>\n\n<ul>\n<li><a href=\"http://docs.jquery.com/Events/ready#fn\" rel=\"noreferrer\">http://docs.jquery.com/Events/ready#fn</a></li>\n<li><a href=\"http://developer.yahoo.com/yui/event/#onavailable\" rel=\"noreferrer\">http://developer.yahoo.com/yui/event/#onavailable</a></li>\n</ul>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/40966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | I have a javascript function that manipulates the DOM when it is called (adds CSS classes, etc). This is invoked when the user changes some values in a form. When the document is first loading, I want to invoke this function to prepare the initial state (which is simpler in this case than setting up the DOM from the server side to the correct initial state).
Is it better to use window.onload to do this functionality or have a script block after the DOM elements I need to modify? For either case, why is it better?
For example:
```
function updateDOM(id) {
// updates the id element based on form state
}
```
should I invoke it via:
```
window.onload = function() { updateDOM("myElement"); };
```
or:
```
<div id="myElement">...</div>
<script language="javascript">
updateDOM("myElement");
</script>
```
The former seems to be the standard way to do it, but the latter seems to be just as good, perhaps better since it will update the element as soon as the script is hit, and as long as it is placed after the element, I don't see a problem with it.
Any thoughts? Is one version really better than the other? | Definitely use `onload`. Keep your scripts separate from your page, or you'll go mad trying to disentangle them later. |
40,999 | <p>Here's a quick question I've been banging my head against today.</p>
<p>I'm trying to convert a .Net dataset into an XML stream, transform it with an xsl file in memory, then output the result to a new XML file. </p>
<p>Here's the current solution:</p>
<pre><code> string transformXML = @"pathToXslDocument";
XmlDocument originalXml = new XmlDocument();
XmlDocument transformedXml = new XmlDocument();
XslCompiledTransform transformer = new XslCompiledTransform();
DataSet ds = new DataSet();
string filepath;
originalXml.LoadXml(ds.GetXml()); //data loaded prior
StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb);
transformer.Load(transformXML);
transformer.Transform(originalXml, writer); //no need to select the node
transformedXml.LoadXml(sb.ToString());
transformedXml.Save(filepath);
writer.Close();
</code></pre>
<p>Here's the original code:</p>
<pre><code>BufferedStream stream = new BufferedStream(new MemoryStream());
DataSet ds = new DataSet();
da.Fill(ds);
ds.WriteXml(stream);
StreamReader sr = new StreamReader(stream, true);
stream.Position = 0; //I'm not certain if this is necessary, but for the StreamReader to read the text the position must be reset.
XmlReader reader = XmlReader.Create(sr, null); //Problem is created here, the XmlReader is created with none of the data from the StreamReader
XslCompiledTransform transformer = new XslCompiledTransform();
transformer.Load(@"<path to xsl file>");
transformer.Transform(reader, null, writer); //Exception is thrown here, though the problem originates from the XmlReader.Create(sr, null)
</code></pre>
<p>For some reason in the transformer.Transform method, the reader has no root node, in fact the reader isn't reading anything from the StreamReader.</p>
<p>My questions is what is wrong with this code? Secondarily, is there a better way to convert/transform/store a dataset into XML?</p>
<p>Edit: Both answers were helpful and technically aku's was closer. However I am leaning towards a solution that more closely resembles Longhorn's after trying both solutions.</p>
| [
{
"answer_id": 41012,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 4,
"selected": true,
"text": "<p>I'm not sure but it seems that you didn't reset position in stream before passing it to XmlReader. Try to seek at the beginning of your stream before trying to read from it. Also it may be necessary to close\\flush stream after you wrote some data to it.</p>\n\n<p><strong>EDIT</strong>:</p>\n\n<p>Just tried following code and it worked perfectly:</p>\n\n<pre><code> BufferedStream stream = new BufferedStream(new MemoryStream());\n stream.Write(Encoding.ASCII.GetBytes(\"<xml>foo</xml>\"), 0, \"<xml>foo</xml>\".Length);\n stream.Seek(0, SeekOrigin.Begin);\n StreamReader sr = new StreamReader(stream);\n XmlReader reader = XmlReader.Create(sr);\n while (reader.Read())\n {\n Console.WriteLine(reader.Value);\n }\n stream.Close();\n</code></pre>\n"
},
{
"answer_id": 41020,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 2,
"selected": false,
"text": "<p>You must select the root node. This doesn't use Datasets, but I use this function everyday and it works great.</p>\n\n<pre><code>System.Xml.XmlDocument orgDoc = new System.Xml.XmlDocument();\norgDoc.LoadXml(orgXML);\n\n// MUST SELECT THE ROOT NODE\nXmlNode transNode = orgDoc.SelectSingleNode(\"/\");\nSystem.Text.StringBuilder sb = new System.Text.StringBuilder();\nXmlWriter writer = XmlWriter.Create(sb);\n\nSystem.IO.StringReader stream = new System.IO.StringReader(transformXML);\nXmlReader reader = XmlReader.Create(stream);\n\nSystem.Xml.Xsl.XslCompiledTransform trans = new System.Xml.Xsl.XslCompiledTransform();\ntrans.Load(reader);\ntrans.Transform(transNode, writer);\n\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(sb.ToString());\n\nreturn doc;\n</code></pre>\n"
},
{
"answer_id": 28757385,
"author": "user1453680",
"author_id": 1453680,
"author_profile": "https://Stackoverflow.com/users/1453680",
"pm_score": 0,
"selected": false,
"text": "<p>please look it and use..</p>\n\n<pre><code>using (MemoryStream memStream = new MemoryStream())\n {\n memStream.Write(Encoding.UTF8.GetBytes(xmlBody), 0, xmlBody.Length);\n memStream.Seek(0, SeekOrigin.Begin);\n\n using (StreamReader reader = new StreamReader(memStream))\n {\n // xml reader setting.\n XmlReaderSettings xmlReaderSettings = new XmlReaderSettings()\n {\n IgnoreComments = true,\n IgnoreWhitespace = true,\n\n };\n\n // xml reader create.\n using (XmlReader xmlReader = XmlReader.Create(reader, xmlReaderSettings))\n { \n XmlSerializer xmlSerializer = new XmlSerializer(typeof(LoginInfo));\n myObject = (LoginInfo)xmlSerializer.Deserialize(xmlReader);\n\n }\n\n } \n }\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/40999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2916/"
] | Here's a quick question I've been banging my head against today.
I'm trying to convert a .Net dataset into an XML stream, transform it with an xsl file in memory, then output the result to a new XML file.
Here's the current solution:
```
string transformXML = @"pathToXslDocument";
XmlDocument originalXml = new XmlDocument();
XmlDocument transformedXml = new XmlDocument();
XslCompiledTransform transformer = new XslCompiledTransform();
DataSet ds = new DataSet();
string filepath;
originalXml.LoadXml(ds.GetXml()); //data loaded prior
StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb);
transformer.Load(transformXML);
transformer.Transform(originalXml, writer); //no need to select the node
transformedXml.LoadXml(sb.ToString());
transformedXml.Save(filepath);
writer.Close();
```
Here's the original code:
```
BufferedStream stream = new BufferedStream(new MemoryStream());
DataSet ds = new DataSet();
da.Fill(ds);
ds.WriteXml(stream);
StreamReader sr = new StreamReader(stream, true);
stream.Position = 0; //I'm not certain if this is necessary, but for the StreamReader to read the text the position must be reset.
XmlReader reader = XmlReader.Create(sr, null); //Problem is created here, the XmlReader is created with none of the data from the StreamReader
XslCompiledTransform transformer = new XslCompiledTransform();
transformer.Load(@"<path to xsl file>");
transformer.Transform(reader, null, writer); //Exception is thrown here, though the problem originates from the XmlReader.Create(sr, null)
```
For some reason in the transformer.Transform method, the reader has no root node, in fact the reader isn't reading anything from the StreamReader.
My questions is what is wrong with this code? Secondarily, is there a better way to convert/transform/store a dataset into XML?
Edit: Both answers were helpful and technically aku's was closer. However I am leaning towards a solution that more closely resembles Longhorn's after trying both solutions. | I'm not sure but it seems that you didn't reset position in stream before passing it to XmlReader. Try to seek at the beginning of your stream before trying to read from it. Also it may be necessary to close\flush stream after you wrote some data to it.
**EDIT**:
Just tried following code and it worked perfectly:
```
BufferedStream stream = new BufferedStream(new MemoryStream());
stream.Write(Encoding.ASCII.GetBytes("<xml>foo</xml>"), 0, "<xml>foo</xml>".Length);
stream.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(stream);
XmlReader reader = XmlReader.Create(sr);
while (reader.Read())
{
Console.WriteLine(reader.Value);
}
stream.Close();
``` |
41,045 | <p>As a general rule, I prefer using value rather than pointer semantics in C++ (ie using <code>vector<Class></code> instead of <code>vector<Class*></code>). Usually the slight loss in performance is more than made up for by not having to remember to delete dynamically allocated objects.</p>
<p>Unfortunately, value collections don't work when you want to store a variety of object types that all derive from a common base. See the example below.</p>
<pre><code>#include <iostream>
using namespace std;
class Parent
{
public:
Parent() : parent_mem(1) {}
virtual void write() { cout << "Parent: " << parent_mem << endl; }
int parent_mem;
};
class Child : public Parent
{
public:
Child() : child_mem(2) { parent_mem = 2; }
void write() { cout << "Child: " << parent_mem << ", " << child_mem << endl; }
int child_mem;
};
int main(int, char**)
{
// I can have a polymorphic container with pointer semantics
vector<Parent*> pointerVec;
pointerVec.push_back(new Parent());
pointerVec.push_back(new Child());
pointerVec[0]->write();
pointerVec[1]->write();
// Output:
//
// Parent: 1
// Child: 2, 2
// But I can't do it with value semantics
vector<Parent> valueVec;
valueVec.push_back(Parent());
valueVec.push_back(Child()); // gets turned into a Parent object :(
valueVec[0].write();
valueVec[1].write();
// Output:
//
// Parent: 1
// Parent: 2
}
</code></pre>
<p>My question is: Can I have have my cake (value semantics) and eat it too (polymorphic containers)? Or do I have to use pointers?</p>
| [
{
"answer_id": 41059,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 6,
"selected": true,
"text": "<p>Since the objects of different classes will have different sizes, you would end up running into the slicing problem if you store them as values.</p>\n\n<p>One reasonable solution is to store container safe smart pointers. I normally use boost::shared_ptr which is safe to store in a container. Note that std::auto_ptr is not.</p>\n\n<pre><code>vector<shared_ptr<Parent>> vec;\nvec.push_back(shared_ptr<Parent>(new Child()));\n</code></pre>\n\n<p>shared_ptr uses reference counting so it will not delete the underlying instance until all references are removed.</p>\n"
},
{
"answer_id": 41074,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Take a look at <em>static_cast</em> and <em>reinterpret_cast</em><br>\n In C++ Programming Language, 3rd ed, Bjarne Stroustrup describes it on page 130. There's a whole section on this in Chapter 6.<br>\n You can recast your Parent class to Child class. This requires you to know when each one is which. In the book, Dr. Stroustrup talks about different techniques to avoid this situation.</p>\n</blockquote>\n\n<p>Do not do this. This negates the polymorphism that you're trying to achieve in the first place!</p>\n"
},
{
"answer_id": 41103,
"author": "Adam Hollidge",
"author_id": 4069,
"author_profile": "https://Stackoverflow.com/users/4069",
"pm_score": 3,
"selected": false,
"text": "<p>You might also consider <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/any.html\" rel=\"noreferrer\">boost::any</a>. I've used it for heterogeneous containers. When reading the value back, you need to perform an any_cast. It will throw a bad_any_cast if it fails. If that happens, you can catch and move on to the next type.</p>\n\n<p>I <em>believe</em> it will throw a bad_any_cast if you try to any_cast a derived class to its base. I tried it:</p>\n\n<blockquote>\n<pre><code> // But you sort of can do it with boost::any.\n\n vector<any> valueVec;\n\n valueVec.push_back(any(Parent()));\n valueVec.push_back(any(Child())); // remains a Child, wrapped in an Any.\n\n Parent p = any_cast<Parent>(valueVec[0]);\n Child c = any_cast<Child>(valueVec[1]);\n p.write();\n c.write();\n\n // Output:\n //\n // Parent: 1\n // Child: 2, 2\n\n // Now try casting the child as a parent.\n try {\n Parent p2 = any_cast<Parent>(valueVec[1]);\n p2.write();\n }\n catch (const boost::bad_any_cast &e)\n {\n cout << e.what() << endl;\n }\n\n // Output:\n // boost::bad_any_cast: failed conversion using boost::any_cast\n</code></pre>\n</blockquote>\n\n<p>All that being said, I would also go the shared_ptr route first! Just thought this might be of some interest.</p>\n"
},
{
"answer_id": 41106,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Most container types want to abstract the particular storage strategy, be it linked list, vector, tree-based or what have you. For this reason, you're going to have trouble with both possessing and consuming the aforementioned cake (i.e., the cake is lie (NB: someone had to make this joke)).</p>\n\n<p>So what to do? Well there are a few cute options, but most will reduce to variants on one of a few themes or combinations of them: picking or inventing a suitable smart pointer, playing with templates or template templates in some clever way, using a common interface for containees that provides a hook for implementing per-containee double-dispatch.</p>\n\n<p>There's basic tension between your two stated goals, so you should decide what you want, then try to design something that gets you basically what you want. It <em>is</em> possible to do some nice and unexpected tricks to get pointers to look like values with clever enough reference counting and clever enough implementations of a factory. The basic idea is to use reference counting and copy-on-demand and constness and (for the factor) a combination of the preprocessor, templates, and C++'s static initialization rules to get something that is as smart as possible about automating pointer conversions.</p>\n\n<p>I have, in the past, spent some time trying to envision how to use Virtual Proxy / Envelope-Letter / that cute trick with reference counted pointers to accomplish something like a basis for value semantic programming in C++.</p>\n\n<p>And I think it could be done, but you'd have to provide a fairly closed, C#-managed-code-like world within C++ (though one from which you could break through to underlying C++ when needed). So I have a lot of sympathy for your line of thought.</p>\n"
},
{
"answer_id": 41287,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": 2,
"selected": false,
"text": "<p>Just to add one thing to all <a href=\"https://stackoverflow.com/questions/41045/can-i-have-polymorphic-containers-with-value-semantics-in-c#41059\">1800 INFORMATION</a> already said.</p>\n\n<p>You might want to take a look at <a href=\"https://rads.stackoverflow.com/amzn/click/com/020163371X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">\"More Effective C++\"</a> by Scott Mayers \"Item 3: Never treat arrays polymorphically\" in order to better understand this issue.</p>\n"
},
{
"answer_id": 44855,
"author": "ben",
"author_id": 4607,
"author_profile": "https://Stackoverflow.com/users/4607",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, you can.</p>\n\n<p>The boost.ptr_container library provides polymorphic value semantic versions of the standard containers. You only have to pass in a pointer to a heap-allocated object, and the container will take ownership and all further operations will provide value semantics , except for reclaiming ownership, which gives you almost all the benefits of value semantics by using a smart pointer.</p>\n"
},
{
"answer_id": 71264,
"author": "0124816",
"author_id": 11521,
"author_profile": "https://Stackoverflow.com/users/11521",
"pm_score": 4,
"selected": false,
"text": "<p>I just wanted to point out that vector<Foo> is usually more efficient than vector<Foo*>. In a vector<Foo>, all the Foos will be adjacent to each other in memory. Assuming a cold TLB and cache, the first read will add the page to the TLB and pull a chunk of the vector into the L# caches; subsequent reads will use the warm cache and loaded TLB, with occasional cache misses and less frequent TLB faults.</p>\n\n<p>Contrast this with a vector<Foo*>: As you fill the vector, you obtain Foo*'s from your memory allocator. Assuming your allocator is not extremely smart, (tcmalloc?) or you fill the vector slowly over time, the location of each Foo is likely to be far apart from the other Foos: maybe just by hundreds of bytes, maybe megabytes apart.</p>\n\n<p>In the worst case, as you scan through a vector<Foo*> and dereferencing each pointer you will incur a TLB fault and cache miss -- this will end up being a <em>lot</em> slower than if you had a vector<Foo>. (Well, in the really worst case, each Foo has been paged out to disk, and every read incurs a disk seek() and read() to move the page back into RAM.)</p>\n\n<p>So, keep on using vector<Foo> whenever appropriate. :-)</p>\n"
},
{
"answer_id": 71355,
"author": "Johann Gerell",
"author_id": 6345,
"author_profile": "https://Stackoverflow.com/users/6345",
"pm_score": 1,
"selected": false,
"text": "<p>I'm using my own templated collection class with exposed value type semantics, but internally it stores pointers. It's using a custom iterator class that when dereferenced gets a value reference instead of a pointer. Copying the collection makes deep item copies, instead of duplicated pointers, and this is where most overhead lies (a really minor issue, considered what I get instead).</p>\n\n<p>That's an idea that could suit your needs.</p>\n"
},
{
"answer_id": 49720854,
"author": "dragly",
"author_id": 632150,
"author_profile": "https://Stackoverflow.com/users/632150",
"pm_score": 3,
"selected": false,
"text": "<p>While searching for an answer to this problem, I came across both this and <a href=\"https://stackoverflow.com/questions/18856824/ad-hoc-polymorphism-and-heterogeneous-containers-with-value-semantics\">a similar question</a>. In the answers to the other question you will find two suggested solutions:</p>\n\n<ol>\n<li>Use std::optional or boost::optional and a visitor pattern. This solution makes it hard to add new types, but easy to add new functionality. </li>\n<li>Use a wrapper class similar to what <a href=\"https://www.youtube.com/watch?v=QGcVXgEVMJg\" rel=\"noreferrer\">Sean Parent presents in his talk</a>. This solution makes it hard to add new functionality, but easy to add new types.</li>\n</ol>\n\n<p>The wrapper defines the interface you need for your classes and holds a pointer to one such object. The implementation of the interface is done with free functions.</p>\n\n<p>Here is an example implementation of this pattern:</p>\n\n<pre><code>class Shape\n{\npublic:\n template<typename T>\n Shape(T t)\n : container(std::make_shared<Model<T>>(std::move(t)))\n {}\n\n friend void draw(const Shape &shape)\n {\n shape.container->drawImpl();\n }\n // add more functions similar to draw() here if you wish\n // remember also to add a wrapper in the Concept and Model below\n\nprivate:\n struct Concept\n {\n virtual ~Concept() = default;\n virtual void drawImpl() const = 0;\n };\n\n template<typename T>\n struct Model : public Concept\n {\n Model(T x) : m_data(move(x)) { }\n void drawImpl() const override\n {\n draw(m_data);\n }\n T m_data;\n };\n\n std::shared_ptr<const Concept> container;\n};\n</code></pre>\n\n<p>Different shapes are then implemented as regular structs/classes. You are free to choose if you want to use member functions or free functions (but you will have to update the above implementation to use member functions). I prefer free functions:</p>\n\n<pre><code>struct Circle\n{\n const double radius = 4.0;\n};\n\nstruct Rectangle\n{\n const double width = 2.0;\n const double height = 3.0;\n};\n\nvoid draw(const Circle &circle)\n{\n cout << \"Drew circle with radius \" << circle.radius << endl;\n}\n\nvoid draw(const Rectangle &rectangle)\n{\n cout << \"Drew rectangle with width \" << rectangle.width << endl;\n}\n</code></pre>\n\n<p>You can now add both <code>Circle</code> and <code>Rectangle</code> objects to the same <code>std::vector<Shape></code>:</p>\n\n<pre><code>int main() {\n std::vector<Shape> shapes;\n shapes.emplace_back(Circle());\n shapes.emplace_back(Rectangle());\n for (const auto &shape : shapes) {\n draw(shape);\n }\n return 0;\n}\n</code></pre>\n\n<p>The downside of this pattern is that it requires a large amount of boilerplate in the interface, since each function needs to be defined three times.\nThe upside is that you get copy-semantics:</p>\n\n<pre><code>int main() {\n Shape a = Circle();\n Shape b = Rectangle();\n b = a;\n draw(a);\n draw(b);\n return 0;\n}\n</code></pre>\n\n<p>This produces:</p>\n\n<pre><code>Drew rectangle with width 2\nDrew rectangle with width 2\n</code></pre>\n\n<p>If you are concerned about the <code>shared_ptr</code>, you can replace it with a <code>unique_ptr</code>.\nHowever, it will no longer be copyable and you will have to either move all objects or implement copying manually.\nSean Parent discusses this in detail in his talk and an implementation is shown in the above mentioned answer.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2994/"
] | As a general rule, I prefer using value rather than pointer semantics in C++ (ie using `vector<Class>` instead of `vector<Class*>`). Usually the slight loss in performance is more than made up for by not having to remember to delete dynamically allocated objects.
Unfortunately, value collections don't work when you want to store a variety of object types that all derive from a common base. See the example below.
```
#include <iostream>
using namespace std;
class Parent
{
public:
Parent() : parent_mem(1) {}
virtual void write() { cout << "Parent: " << parent_mem << endl; }
int parent_mem;
};
class Child : public Parent
{
public:
Child() : child_mem(2) { parent_mem = 2; }
void write() { cout << "Child: " << parent_mem << ", " << child_mem << endl; }
int child_mem;
};
int main(int, char**)
{
// I can have a polymorphic container with pointer semantics
vector<Parent*> pointerVec;
pointerVec.push_back(new Parent());
pointerVec.push_back(new Child());
pointerVec[0]->write();
pointerVec[1]->write();
// Output:
//
// Parent: 1
// Child: 2, 2
// But I can't do it with value semantics
vector<Parent> valueVec;
valueVec.push_back(Parent());
valueVec.push_back(Child()); // gets turned into a Parent object :(
valueVec[0].write();
valueVec[1].write();
// Output:
//
// Parent: 1
// Parent: 2
}
```
My question is: Can I have have my cake (value semantics) and eat it too (polymorphic containers)? Or do I have to use pointers? | Since the objects of different classes will have different sizes, you would end up running into the slicing problem if you store them as values.
One reasonable solution is to store container safe smart pointers. I normally use boost::shared\_ptr which is safe to store in a container. Note that std::auto\_ptr is not.
```
vector<shared_ptr<Parent>> vec;
vec.push_back(shared_ptr<Parent>(new Child()));
```
shared\_ptr uses reference counting so it will not delete the underlying instance until all references are removed. |
41,089 | <p>I have a vb6 form with an ocx control on it. The ocx control has a button on it that I want to press from code. How do I do this?</p>
<p>I have:</p>
<pre><code>Dim b As CommandButton
Set b = ocx.GetButton("btnPrint")
SendMessage ocx.hwnd, WM_COMMAND, GetWindowLong(b.hwnd, GWL_ID), b.hwnd
</code></pre>
<p>but it doesn't seem to work.</p>
| [
{
"answer_id": 41123,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 1,
"selected": false,
"text": "<p>If you have access to the OCX code, you could expose the associated event handler and invoke it directly.<br>\nDon't know if an equivalent of .Net Button's Click() method existed back in VB6 days</p>\n"
},
{
"answer_id": 41521,
"author": "DAC",
"author_id": 1111,
"author_profile": "https://Stackoverflow.com/users/1111",
"pm_score": 3,
"selected": true,
"text": "<p>I believe the following will work:</p>\n\n<pre><code>Dim b As CommandButton\nSet b = ocx.GetButton(\"btnPrint\")\nb = True\n</code></pre>\n\n<p><code>CommandButton</code>s actually have two functions. One is the usual click button and the other is a toggle button that acts similar to a <code>CheckBox</code>. The default property of the <code>CommandButton</code> is actually the <code>Value</code> property that indicates whether a button is toggled. By setting the property, the <code>Click</code> event is generated. This is done even if the button is not styled as a <code>ToggleButton</code> and therefore doesn't change its state.</p>\n"
},
{
"answer_id": 41543,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have access to the OCX code? You shouldn't really be directly invoking the click of a button. You should refactor the code so that the OCX button click code calls a function, e.g.</p>\n\n<pre><code>CMyWindow::OnLButtonDown()\n{\n this->FooBar();\n}\n</code></pre>\n\n<p>Then from your VB6 app, directly call the FooBar method. If you can't directly call functions from VB6 you can wrap the FooBar() method with a windows message proc function, e.g.</p>\n\n<pre><code>#define WM_FOOBAR WM_APP + 1\n</code></pre>\n\n<p>Then use <code>SendMessage</code> in the VB6, like <code>SendMessage(WM_FOOBAR, ...)</code></p>\n"
},
{
"answer_id": 42802,
"author": "dan gibson",
"author_id": 4495,
"author_profile": "https://Stackoverflow.com/users/4495",
"pm_score": 0,
"selected": false,
"text": "<p>This:</p>\n\n<pre><code>Dim b As CommandButton\nSet b = ocx.GetButton(\"btnPrint\")\nb = True\n</code></pre>\n\n<p>does work. Completely unintuitive. I'd expect it to throw an error since a bool is not a valid CommandButton, but it is because of the default property thing.</p>\n\n<p><code>WM_LBUTTONDOWN</code> would be a mouse click, what I want is a button click (button as in a hwnd button, not a mouse button).</p>\n\n<p>I don't have access to the source of the ocx (it's a 3rd party control). If I did, I would expose the function that I wanted to call (the original writer of the ocx should have exposed it).</p>\n"
},
{
"answer_id": 156328,
"author": "sharvell",
"author_id": 23095,
"author_profile": "https://Stackoverflow.com/users/23095",
"pm_score": 0,
"selected": false,
"text": "<p>For keypress you can also use sendmessage sending both keydown and keyup:</p>\n\n<pre><code>Private Declare Function SendMessage Lib \"user32\" Alias \"SendMessageA\" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long\nConst WM_KEYDOWN As Integer = &H100\nConst WM_KEYUP As Integer = &H101\nConst VK_SPACE = &H20\n\nPrivate Sub cmdCommand1_Click()\n Dim b As CommandButton\n Set b = ocx.GetButton(\"btnPrint\")\n SendMessage b.hWnd, WM_KEYDOWN, VK_SPACE, 0&\n SendMessage b.hWnd, WM_KEYUP, VK_SPACE, 0&\nEnd Sub\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4495/"
] | I have a vb6 form with an ocx control on it. The ocx control has a button on it that I want to press from code. How do I do this?
I have:
```
Dim b As CommandButton
Set b = ocx.GetButton("btnPrint")
SendMessage ocx.hwnd, WM_COMMAND, GetWindowLong(b.hwnd, GWL_ID), b.hwnd
```
but it doesn't seem to work. | I believe the following will work:
```
Dim b As CommandButton
Set b = ocx.GetButton("btnPrint")
b = True
```
`CommandButton`s actually have two functions. One is the usual click button and the other is a toggle button that acts similar to a `CheckBox`. The default property of the `CommandButton` is actually the `Value` property that indicates whether a button is toggled. By setting the property, the `Click` event is generated. This is done even if the button is not styled as a `ToggleButton` and therefore doesn't change its state. |
41,097 | <p>The question sort of says it all.</p>
<p>Whether it's for code testing purposes, or you're modeling a real-world process, or you're trying to impress a loved one, what are some algorithms that folks use to generate interesting time series data? Are there any good resources out there with a consolidated list? No constraints on values (except plus or minus infinity) or dimensions, but I'm looking for examples that people have found useful or exciting in practice. </p>
<p>Bonus points for parsimonious and readable code samples. </p>
| [
{
"answer_id": 41123,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 1,
"selected": false,
"text": "<p>If you have access to the OCX code, you could expose the associated event handler and invoke it directly.<br>\nDon't know if an equivalent of .Net Button's Click() method existed back in VB6 days</p>\n"
},
{
"answer_id": 41521,
"author": "DAC",
"author_id": 1111,
"author_profile": "https://Stackoverflow.com/users/1111",
"pm_score": 3,
"selected": true,
"text": "<p>I believe the following will work:</p>\n\n<pre><code>Dim b As CommandButton\nSet b = ocx.GetButton(\"btnPrint\")\nb = True\n</code></pre>\n\n<p><code>CommandButton</code>s actually have two functions. One is the usual click button and the other is a toggle button that acts similar to a <code>CheckBox</code>. The default property of the <code>CommandButton</code> is actually the <code>Value</code> property that indicates whether a button is toggled. By setting the property, the <code>Click</code> event is generated. This is done even if the button is not styled as a <code>ToggleButton</code> and therefore doesn't change its state.</p>\n"
},
{
"answer_id": 41543,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have access to the OCX code? You shouldn't really be directly invoking the click of a button. You should refactor the code so that the OCX button click code calls a function, e.g.</p>\n\n<pre><code>CMyWindow::OnLButtonDown()\n{\n this->FooBar();\n}\n</code></pre>\n\n<p>Then from your VB6 app, directly call the FooBar method. If you can't directly call functions from VB6 you can wrap the FooBar() method with a windows message proc function, e.g.</p>\n\n<pre><code>#define WM_FOOBAR WM_APP + 1\n</code></pre>\n\n<p>Then use <code>SendMessage</code> in the VB6, like <code>SendMessage(WM_FOOBAR, ...)</code></p>\n"
},
{
"answer_id": 42802,
"author": "dan gibson",
"author_id": 4495,
"author_profile": "https://Stackoverflow.com/users/4495",
"pm_score": 0,
"selected": false,
"text": "<p>This:</p>\n\n<pre><code>Dim b As CommandButton\nSet b = ocx.GetButton(\"btnPrint\")\nb = True\n</code></pre>\n\n<p>does work. Completely unintuitive. I'd expect it to throw an error since a bool is not a valid CommandButton, but it is because of the default property thing.</p>\n\n<p><code>WM_LBUTTONDOWN</code> would be a mouse click, what I want is a button click (button as in a hwnd button, not a mouse button).</p>\n\n<p>I don't have access to the source of the ocx (it's a 3rd party control). If I did, I would expose the function that I wanted to call (the original writer of the ocx should have exposed it).</p>\n"
},
{
"answer_id": 156328,
"author": "sharvell",
"author_id": 23095,
"author_profile": "https://Stackoverflow.com/users/23095",
"pm_score": 0,
"selected": false,
"text": "<p>For keypress you can also use sendmessage sending both keydown and keyup:</p>\n\n<pre><code>Private Declare Function SendMessage Lib \"user32\" Alias \"SendMessageA\" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long\nConst WM_KEYDOWN As Integer = &H100\nConst WM_KEYUP As Integer = &H101\nConst VK_SPACE = &H20\n\nPrivate Sub cmdCommand1_Click()\n Dim b As CommandButton\n Set b = ocx.GetButton(\"btnPrint\")\n SendMessage b.hWnd, WM_KEYDOWN, VK_SPACE, 0&\n SendMessage b.hWnd, WM_KEYUP, VK_SPACE, 0&\nEnd Sub\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4069/"
] | The question sort of says it all.
Whether it's for code testing purposes, or you're modeling a real-world process, or you're trying to impress a loved one, what are some algorithms that folks use to generate interesting time series data? Are there any good resources out there with a consolidated list? No constraints on values (except plus or minus infinity) or dimensions, but I'm looking for examples that people have found useful or exciting in practice.
Bonus points for parsimonious and readable code samples. | I believe the following will work:
```
Dim b As CommandButton
Set b = ocx.GetButton("btnPrint")
b = True
```
`CommandButton`s actually have two functions. One is the usual click button and the other is a toggle button that acts similar to a `CheckBox`. The default property of the `CommandButton` is actually the `Value` property that indicates whether a button is toggled. By setting the property, the `Click` event is generated. This is done even if the button is not styled as a `ToggleButton` and therefore doesn't change its state. |
41,107 | <p>I've been looking for a <em>simple</em> Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would "likely" be unique over <code>500K+</code> generation (my needs don't really require anything much more sophisticated). </p>
<p>Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like <code>"AEYGF7K0DM1X"</code>. </p>
| [
{
"answer_id": 41156,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 12,
"selected": true,
"text": "<h2>Algorithm</h2>\n<p>To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length.</p>\n<h2>Implementation</h2>\n<p>Here's some fairly simple and very flexible code for generating random identifiers. <em>Read the information that follows</em> for important application notes.</p>\n<pre><code>public class RandomString {\n\n /**\n * Generate a random string.\n */\n public String nextString() {\n for (int idx = 0; idx < buf.length; ++idx)\n buf[idx] = symbols[random.nextInt(symbols.length)];\n return new String(buf);\n }\n\n public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n\n public static final String lower = upper.toLowerCase(Locale.ROOT);\n\n public static final String digits = "0123456789";\n\n public static final String alphanum = upper + lower + digits;\n\n private final Random random;\n\n private final char[] symbols;\n\n private final char[] buf;\n\n public RandomString(int length, Random random, String symbols) {\n if (length < 1) throw new IllegalArgumentException();\n if (symbols.length() < 2) throw new IllegalArgumentException();\n this.random = Objects.requireNonNull(random);\n this.symbols = symbols.toCharArray();\n this.buf = new char[length];\n }\n\n /**\n * Create an alphanumeric string generator.\n */\n public RandomString(int length, Random random) {\n this(length, random, alphanum);\n }\n\n /**\n * Create an alphanumeric strings from a secure generator.\n */\n public RandomString(int length) {\n this(length, new SecureRandom());\n }\n\n /**\n * Create session identifiers.\n */\n public RandomString() {\n this(21);\n }\n\n}\n</code></pre>\n<h2>Usage examples</h2>\n<p>Create an insecure generator for 8-character identifiers:</p>\n<pre><code>RandomString gen = new RandomString(8, ThreadLocalRandom.current());\n</code></pre>\n<p>Create a secure generator for session identifiers:</p>\n<pre><code>RandomString session = new RandomString();\n</code></pre>\n<p>Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols:</p>\n<pre><code>String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";\nRandomString tickets = new RandomString(23, new SecureRandom(), easy);\n</code></pre>\n<h2>Use as session identifiers</h2>\n<p>Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used.</p>\n<p>There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand.</p>\n<p>The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible.</p>\n<h2>Use as object identifiers</h2>\n<p>Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big.</p>\n<p>Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission.</p>\n<p>Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." <a href=\"https://en.wikipedia.org/wiki/Birthday_problem#Square_approximation\" rel=\"noreferrer\">The probability of a collision,</a> <em>p</em>, is approximately n<sup>2</sup>/(2q<sup>x</sup>), where <em>n</em> is the number of identifiers actually generated, <em>q</em> is the number of distinct symbols in the alphabet, and <em>x</em> is the length of the identifiers. This should be a very small number, like 2<sup>‑50</sup> or less.</p>\n<p>Working this out shows that the chance of collision among 500k 15-character identifiers is about 2<sup>‑52</sup>, which is probably less likely than undetected errors from cosmic rays, etc.</p>\n<h2>Comparison with UUIDs</h2>\n<p>According to their specification, <a href=\"https://www.rfc-editor.org/rfc/rfc4122#section-6\" rel=\"noreferrer\">UUIDs</a> are not designed to be unpredictable, and <em>should not</em> be used as session identifiers.</p>\n<p>UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters.</p>\n<p>UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.</p>\n"
},
{
"answer_id": 41177,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 5,
"selected": false,
"text": "<p>Here it is in Java:</p>\n\n<pre><code>import static java.lang.Math.round;\nimport static java.lang.Math.random;\nimport static java.lang.Math.pow;\nimport static java.lang.Math.abs;\nimport static java.lang.Math.min;\nimport static org.apache.commons.lang.StringUtils.leftPad\n\npublic class RandomAlphaNum {\n public static String gen(int length) {\n StringBuffer sb = new StringBuffer();\n for (int i = length; i > 0; i -= 12) {\n int n = min(12, abs(i));\n sb.append(leftPad(Long.toString(round(random() * pow(36, n)), 36), n, '0'));\n }\n return sb.toString();\n }\n}\n</code></pre>\n\n<p>Here's a sample run:</p>\n\n<pre><code>scala> RandomAlphaNum.gen(42)\nres3: java.lang.String = uja6snx21bswf9t89s00bxssu8g6qlu16ffzqaxxoy\n</code></pre>\n"
},
{
"answer_id": 41762,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 10,
"selected": false,
"text": "<p>Java supplies a way of doing this directly. If you don't want the dashes, they are easy to strip out. Just use <code>uuid.replace("-", "")</code></p>\n<pre><code>import java.util.UUID;\n\npublic class randomStringGenerator {\n public static void main(String[] args) {\n System.out.println(generateString());\n }\n\n public static String generateString() {\n String uuid = UUID.randomUUID().toString();\n return "uuid = " + uuid;\n }\n}\n</code></pre>\n<h3>Output</h3>\n<pre class=\"lang-none prettyprint-override\"><code>uuid = 2d7428a6-b58c-4008-8575-f05549f16316\n</code></pre>\n"
},
{
"answer_id": 41772,
"author": "Todd",
"author_id": 3803,
"author_profile": "https://Stackoverflow.com/users/3803",
"pm_score": 3,
"selected": false,
"text": "<p>I found this solution that generates a random hex encoded string. The provided unit test seems to hold up to my primary use case. Although, it is slightly more complex than some of the other answers provided.</p>\n\n<pre><code>/**\n * Generate a random hex encoded string token of the specified length\n * \n * @param length\n * @return random hex string\n */\npublic static synchronized String generateUniqueToken(Integer length){ \n byte random[] = new byte[length];\n Random randomGenerator = new Random();\n StringBuffer buffer = new StringBuffer();\n\n randomGenerator.nextBytes(random);\n\n for (int j = 0; j < random.length; j++) {\n byte b1 = (byte) ((random[j] & 0xf0) >> 4);\n byte b2 = (byte) (random[j] & 0x0f);\n if (b1 < 10)\n buffer.append((char) ('0' + b1));\n else\n buffer.append((char) ('A' + (b1 - 10)));\n if (b2 < 10)\n buffer.append((char) ('0' + b2));\n else\n buffer.append((char) ('A' + (b2 - 10)));\n }\n return (buffer.toString());\n}\n\n@Test\npublic void testGenerateUniqueToken(){\n Set set = new HashSet();\n String token = null;\n int size = 16;\n\n /* Seems like we should be able to generate 500K tokens \n * without a duplicate \n */\n for (int i=0; i<500000; i++){\n token = Utility.generateUniqueToken(size);\n\n if (token.length() != size * 2){\n fail(\"Incorrect length\");\n } else if (set.contains(token)) {\n fail(\"Duplicate token generated\");\n } else{\n set.add(token);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 43496,
"author": "cmsherratt",
"author_id": 3512,
"author_profile": "https://Stackoverflow.com/users/3512",
"pm_score": 9,
"selected": false,
"text": "<p>If you're happy to use Apache classes, you could use <a href=\"https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/RandomStringGenerator.html\" rel=\"noreferrer\"><code>org.apache.commons.text.RandomStringGenerator</code></a> (<a href=\"https://en.wikipedia.org/wiki/Apache_Commons#Commons_Proper\" rel=\"noreferrer\">Apache Commons Text</a>).</p>\n<p>Example:</p>\n<pre><code>RandomStringGenerator randomStringGenerator =\n new RandomStringGenerator.Builder()\n .withinRange('0', 'z')\n .filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)\n .build();\nrandomStringGenerator.generate(12); // toUpperCase() if you want\n</code></pre>\n<p>Since <a href=\"https://en.wikipedia.org/wiki/Apache_Commons#Commons_Proper\" rel=\"noreferrer\">Apache Commons Lang</a> 3.6, <code>RandomStringUtils</code> is deprecated.</p>\n"
},
{
"answer_id": 157202,
"author": "maxp",
"author_id": 21152,
"author_profile": "https://Stackoverflow.com/users/21152",
"pm_score": 9,
"selected": false,
"text": "<pre><code>static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";\nstatic SecureRandom rnd = new SecureRandom();\n\nString randomString(int len){\n StringBuilder sb = new StringBuilder(len);\n for(int i = 0; i < len; i++)\n sb.append(AB.charAt(rnd.nextInt(AB.length())));\n return sb.toString();\n}\n</code></pre>\n"
},
{
"answer_id": 1016930,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I have developed an application to develop an autogenerated alphanumberic string for my project. In this string, the first three characters are alphabetical and the next seven are integers.</p>\n<pre><code>public class AlphaNumericGenerator {\n\n public static void main(String[] args) {\n java.util.Random r = new java.util.Random();\n int i = 1, n = 0;\n char c;\n String str = "";\n for (int t = 0; t < 3; t++) {\n while (true) {\n i = r.nextInt(10);\n if (i > 5 && i < 10) {\n\n if (i == 9) {\n i = 90;\n n = 90;\n break;\n }\n if (i != 90) {\n n = i * 10 + r.nextInt(10);\n while (n < 65) {\n n = i * 10 + r.nextInt(10);\n }\n }\n break;\n }\n }\n c = (char)n;\n\n str = String.valueOf(c) + str;\n }\n\n while(true){\n i = r.nextInt(10000000);\n if(i > 999999)\n break;\n }\n str = str + i;\n System.out.println(str);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1439556,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<p>In one line:</p>\n<pre><code>Long.toHexString(Double.doubleToLongBits(Math.random()));\n</code></pre>\n<p>Source: <em><a href=\"http://mynotes.wordpress.com/2009/07/23/java-generating-random-string/\" rel=\"noreferrer\">Java - generating a random string</a></em></p>\n"
},
{
"answer_id": 2178588,
"author": "dfa",
"author_id": 89266,
"author_profile": "https://Stackoverflow.com/users/89266",
"pm_score": 5,
"selected": false,
"text": "<p>Using <a href=\"https://bitbucket.org/adamldavis/dollar/\" rel=\"nofollow noreferrer\">Dollar</a> should be as simple as:</p>\n<pre><code>// "0123456789" + "ABCDE...Z"\nString validCharacters = $('0', '9').join() + $('A', 'Z').join();\n\nString randomString(int length) {\n return $(validCharacters).shuffle().slice(length).toString();\n}\n\n@Test\npublic void buildFiveRandomStrings() {\n for (int i : $(5)) {\n System.out.println(randomString(12));\n }\n}\n</code></pre>\n<p>It outputs something like this:</p>\n<pre class=\"lang-none prettyprint-override\"><code>DKL1SBH9UJWC\nJH7P0IT21EA5\n5DTI72EO6SFU\nHQUMJTEBNF7Y\n1HCR6SKYWGT7\n</code></pre>\n"
},
{
"answer_id": 6530353,
"author": "Suganya",
"author_id": 822390,
"author_profile": "https://Stackoverflow.com/users/822390",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import java.util.*;\nimport javax.swing.*;\n\npublic class alphanumeric {\n public static void main(String args[]) {\n String nval, lenval;\n int n, len;\n\n nval = JOptionPane.showInputDialog("Enter number of codes you require: ");\n n = Integer.parseInt(nval);\n\n lenval = JOptionPane.showInputDialog("Enter code length you require: ");\n len = Integer.parseInt(lenval);\n\n find(n, len);\n }\n\n public static void find(int n, int length) {\n String str1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n StringBuilder sb = new StringBuilder(length);\n Random r = new Random();\n\n System.out.println("\\n\\t Unique codes are \\n\\n");\n for(int i=0; i<n; i++) {\n for(int j=0; j<length; j++) {\n sb.append(str1.charAt(r.nextInt(str1.length())));\n }\n System.out.println(" " + sb.toString());\n sb.delete(0, length);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 7367588,
"author": "michaelok",
"author_id": 443633,
"author_profile": "https://Stackoverflow.com/users/443633",
"pm_score": 3,
"selected": false,
"text": "<p>You mention \"simple\", but just in case anyone else is looking for something that meets more stringent security requirements, you might want to take a look at <a href=\"https://github.com/zhelev/jpwgen\" rel=\"nofollow noreferrer\">jpwgen</a>. jpwgen is modeled after <a href=\"http://sourceforge.net/projects/pwgen/\" rel=\"nofollow noreferrer\">pwgen</a> in Unix, and is very configurable.</p>\n"
},
{
"answer_id": 7816591,
"author": "Jameskittu",
"author_id": 367407,
"author_profile": "https://Stackoverflow.com/users/367407",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import java.util.Date;\nimport java.util.Random;\n\npublic class RandomGenerator {\n\n private static Random random = new Random((new Date()).getTime());\n\n public static String generateRandomString(int length) {\n char[] values = {'a','b','c','d','e','f','g','h','i','j',\n 'k','l','m','n','o','p','q','r','s','t',\n 'u','v','w','x','y','z','0','1','2','3',\n '4','5','6','7','8','9'};\n\n String out = \"\";\n\n for (int i=0;i<length;i++) {\n int idx=random.nextInt(values.length);\n out += values[idx];\n }\n return out;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10177396,
"author": "cmpbah",
"author_id": 1336707,
"author_profile": "https://Stackoverflow.com/users/1336707",
"pm_score": 4,
"selected": false,
"text": "<pre><code>import java.util.Random;\n\npublic class passGen{\n // Version 1.0\n private static final String dCase = "abcdefghijklmnopqrstuvwxyz";\n private static final String uCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n private static final String sChar = "!@#$%^&*";\n private static final String intChar = "0123456789";\n private static Random r = new Random();\n private static StringBuilder pass = new StringBuilder();\n\n public static void main (String[] args) {\n System.out.println ("Generating pass...");\n while (pass.length () != 16){\n int rPick = r.nextInt(4);\n if (rPick == 0){\n int spot = r.nextInt(26);\n pass.append(dCase.charAt(spot));\n } else if (rPick == 1) {\n int spot = r.nextInt(26);\n pass.append(uCase.charAt(spot));\n } else if (rPick == 2) {\n int spot = r.nextInt(8);\n pass.append(sChar.charAt(spot));\n } else {\n int spot = r.nextInt(10);\n pass.append(intChar.charAt(spot));\n }\n }\n System.out.println ("Generated Pass: " + pass.toString());\n }\n}\n</code></pre>\n<p>This just adds the password into the string and... yeah, it works well. Check it out... It is very simple; I wrote it.</p>\n"
},
{
"answer_id": 10189194,
"author": "user unknown",
"author_id": 312172,
"author_profile": "https://Stackoverflow.com/users/312172",
"pm_score": 5,
"selected": false,
"text": "<p>A short and easy solution, but it uses only lowercase and numerics:</p>\n<pre><code>Random r = new java.util.Random ();\nString s = Long.toString (r.nextLong () & Long.MAX_VALUE, 36);\n</code></pre>\n<p>The size is about 12 digits to base 36 and can't be improved further, that way. Of course you can append multiple instances.</p>\n"
},
{
"answer_id": 10361524,
"author": "Bhavik Ambani",
"author_id": 1145285,
"author_profile": "https://Stackoverflow.com/users/1145285",
"pm_score": 1,
"selected": false,
"text": "<p>Best Random String Generator Method</p>\n\n<pre><code>public class RandomStringGenerator{\n\n private static int randomStringLength = 25 ;\n private static boolean allowSpecialCharacters = true ;\n private static String specialCharacters = \"!@$%*-_+:\";\n private static boolean allowDuplicates = false ;\n\n private static boolean isAlphanum = false;\n private static boolean isNumeric = false;\n private static boolean isAlpha = false;\n private static final String alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n private static boolean mixCase = false;\n private static final String capAlpha = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n private static final String num = \"0123456789\";\n\n public static String getRandomString() {\n String returnVal = \"\";\n int specialCharactersCount = 0;\n int maxspecialCharacters = randomStringLength/4;\n\n try {\n StringBuffer values = buildList();\n for (int inx = 0; inx < randomStringLength; inx++) {\n int selChar = (int) (Math.random() * (values.length() - 1));\n if (allowSpecialCharacters)\n {\n if (specialCharacters.indexOf(\"\" + values.charAt(selChar)) > -1)\n {\n specialCharactersCount ++;\n if (specialCharactersCount > maxspecialCharacters)\n {\n while (specialCharacters.indexOf(\"\" + values.charAt(selChar)) != -1)\n {\n selChar = (int) (Math.random() * (values.length() - 1));\n }\n }\n }\n }\n returnVal += values.charAt(selChar);\n if (!allowDuplicates) {\n values.deleteCharAt(selChar);\n }\n }\n } catch (Exception e) {\n returnVal = \"Error While Processing Values\";\n }\n return returnVal;\n }\n\n private static StringBuffer buildList() {\n StringBuffer list = new StringBuffer(0);\n if (isNumeric || isAlphanum) {\n list.append(num);\n }\n if (isAlpha || isAlphanum) {\n list.append(alphabet);\n if (mixCase) {\n list.append(capAlpha);\n }\n }\n if (allowSpecialCharacters)\n {\n list.append(specialCharacters);\n }\n int currLen = list.length();\n String returnVal = \"\";\n for (int inx = 0; inx < currLen; inx++) {\n int selChar = (int) (Math.random() * (list.length() - 1));\n returnVal += list.charAt(selChar);\n list.deleteCharAt(selChar);\n }\n list = new StringBuffer(returnVal);\n return list;\n } \n\n}\n</code></pre>\n"
},
{
"answer_id": 11577455,
"author": "Manish Singh",
"author_id": 518493,
"author_profile": "https://Stackoverflow.com/users/518493",
"pm_score": 7,
"selected": false,
"text": "<p>You can use an <a href=\"https://en.wikipedia.org/wiki/Apache_Commons\" rel=\"noreferrer\">Apache Commons</a> library for this, <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/RandomStringUtils.html\" rel=\"noreferrer\">RandomStringUtils</a>:</p>\n<pre><code>RandomStringUtils.randomAlphanumeric(20).toUpperCase();\n</code></pre>\n"
},
{
"answer_id": 11629612,
"author": "Ugo Matrangolo",
"author_id": 1548481,
"author_profile": "https://Stackoverflow.com/users/1548481",
"pm_score": 2,
"selected": false,
"text": "<p>Here it is a Scala solution:</p>\n\n<pre><code>(for (i <- 0 until rnd.nextInt(64)) yield { \n ('0' + rnd.nextInt(64)).asInstanceOf[Char] \n}) mkString(\"\")\n</code></pre>\n"
},
{
"answer_id": 12792917,
"author": "rina",
"author_id": 1730605,
"author_profile": "https://Stackoverflow.com/users/1730605",
"pm_score": 4,
"selected": false,
"text": "<pre><code>public static String generateSessionKey(int length){\n String alphabet =\n new String("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); // 9\n\n int n = alphabet.length(); // 10\n\n String result = new String();\n Random r = new Random(); // 11\n\n for (int i=0; i<length; i++) // 12\n result = result + alphabet.charAt(r.nextInt(n)); //13\n\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 12891357,
"author": "hridayesh",
"author_id": 1169187,
"author_profile": "https://Stackoverflow.com/users/1169187",
"pm_score": 2,
"selected": false,
"text": "<p>Using an <a href=\"https://en.wikipedia.org/wiki/Apache_Commons\" rel=\"nofollow noreferrer\">Apache Commons</a> library, it can be done in one line:</p>\n<pre><code>import org.apache.commons.lang.RandomStringUtils;\nRandomStringUtils.randomAlphanumeric(64);\n</code></pre>\n<p><a href=\"http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/RandomStringUtils.html\" rel=\"nofollow noreferrer\">Documentation</a></p>\n"
},
{
"answer_id": 13072330,
"author": "Michael Allen",
"author_id": 308474,
"author_profile": "https://Stackoverflow.com/users/308474",
"pm_score": 5,
"selected": false,
"text": "<p>Surprising, no one here has suggested it, but:</p>\n<pre><code>import java.util.UUID\n\nUUID.randomUUID().toString();\n</code></pre>\n<p>Easy.</p>\n<p>The benefit of this is UUIDs are nice, long, and guaranteed to be almost impossible to collide.</p>\n<p>Wikipedia has <a href=\"http://en.wikipedia.org/wiki/Universally_unique_identifier#Random_UUID_probability_of_duplicates\" rel=\"nofollow noreferrer\">a good explanation</a> of it:</p>\n<blockquote>\n<p>" ...only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%."</p>\n</blockquote>\n<p>The first four bits are the version type and two for the variant, so you get 122 bits of random. So if you <em>want</em> to, you can truncate from the end to reduce the size of the UUID. It's not recommended, but you still have loads of randomness, enough for your 500k records easy.</p>\n"
},
{
"answer_id": 13171599,
"author": "Prasobh.Kollattu",
"author_id": 1037363,
"author_profile": "https://Stackoverflow.com/users/1037363",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the following code, if your password mandatory contains numbers and alphabetic special characters:</p>\n<pre><code>private static final String NUMBERS = "0123456789";\nprivate static final String UPPER_ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\nprivate static final String LOWER_ALPHABETS = "abcdefghijklmnopqrstuvwxyz";\nprivate static final String SPECIALCHARACTERS = "@#$%&*";\nprivate static final int MINLENGTHOFPASSWORD = 8;\n\npublic static String getRandomPassword() {\n StringBuilder password = new StringBuilder();\n int j = 0;\n for (int i = 0; i < MINLENGTHOFPASSWORD; i++) {\n password.append(getRandomPasswordCharacters(j));\n j++;\n if (j == 3) {\n j = 0;\n }\n }\n return password.toString();\n}\n\nprivate static String getRandomPasswordCharacters(int pos) {\n Random randomNum = new Random();\n StringBuilder randomChar = new StringBuilder();\n switch (pos) {\n case 0:\n randomChar.append(NUMBERS.charAt(randomNum.nextInt(NUMBERS.length() - 1)));\n break;\n case 1:\n randomChar.append(UPPER_ALPHABETS.charAt(randomNum.nextInt(UPPER_ALPHABETS.length() - 1)));\n break;\n case 2:\n randomChar.append(SPECIALCHARACTERS.charAt(randomNum.nextInt(SPECIALCHARACTERS.length() - 1)));\n break;\n case 3:\n randomChar.append(LOWER_ALPHABETS.charAt(randomNum.nextInt(LOWER_ALPHABETS.length() - 1)));\n break;\n }\n return randomChar.toString();\n}\n</code></pre>\n"
},
{
"answer_id": 13678355,
"author": "Vin",
"author_id": 1621446,
"author_profile": "https://Stackoverflow.com/users/1621446",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public static String getRandomString(int length)\n{\n String randomStr = UUID.randomUUID().toString();\n while(randomStr.length() < length) {\n randomStr += UUID.randomUUID().toString();\n }\n return randomStr.substring(0, length);\n}\n</code></pre>\n"
},
{
"answer_id": 13686133,
"author": "Jamie",
"author_id": 1385083,
"author_profile": "https://Stackoverflow.com/users/1385083",
"pm_score": 1,
"selected": false,
"text": "<p>There are lots of use of StringBuilder in previous answers. I guess it's easy, but it requires a function call per character, growing an array, etc...</p>\n<p>If using the stringbuilder, a suggestion is to specify the required capacity of the string, i.e.,</p>\n<pre><code>new StringBuilder(int capacity);\n</code></pre>\n<p>Here's a version that doesn't use a StringBuilder or String appending, and no dictionary.</p>\n<pre><code>public static String randomString(int length)\n{\n SecureRandom random = new SecureRandom();\n char[] chars = new char[length];\n for(int i=0; i<chars.length; i++)\n {\n int v = random.nextInt(10 + 26 + 26);\n char c;\n if (v < 10)\n {\n c = (char)('0' + v);\n }\n else if (v < 36)\n {\n c = (char)('a' - 10 + v);\n }\n else\n {\n c = (char)('A' - 36 + v);\n }\n chars[i] = c;\n }\n return new String(chars);\n}\n</code></pre>\n"
},
{
"answer_id": 14021567,
"author": "duggu",
"author_id": 1722818,
"author_profile": "https://Stackoverflow.com/users/1722818",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public static String randomSeriesForThreeCharacter() {\n Random r = new Random();\n String value = "";\n char random_Char ;\n for(int i=0; i<10; i++)\n {\n random_Char = (char) (48 + r.nextInt(74));\n value = value + random_char;\n }\n return value;\n}\n</code></pre>\n"
},
{
"answer_id": 14241303,
"author": "Burak T",
"author_id": 1962854,
"author_profile": "https://Stackoverflow.com/users/1962854",
"pm_score": 1,
"selected": false,
"text": "<p>You can create a character array which includes all the letters and numbers, and then you can randomly select from this character array and create your own string password.</p>\n<pre><code>char[] chars = new char[62]; // Sum of letters and numbers\n\nint i = 0;\n\nfor(char c = 'a'; c <= 'z'; c++) { // For letters\n chars[i++] = c;\n}\n\nfor(char c = '0'; c <= '9';c++) { // For numbers\n chars[i++] = c;\n}\n\nfor(char c = 'A'; c <= 'Z';c++) { // For capital letters\n chars[i++] = c;\n}\n\nint numberOfCodes = 0;\nString code = "";\nwhile (numberOfCodes < 1) { // Enter how much you want to generate at one time\n int numChars = 8; // Enter how many digits you want in your password\n\n for(i = 0; i < numChars; i++) {\n char c = chars[(int)(Math.random() * chars.length)];\n code = code + c;\n }\n System.out.println("Code is:" + code);\n}\n</code></pre>\n"
},
{
"answer_id": 17926222,
"author": "neuhaus",
"author_id": 2630572,
"author_profile": "https://Stackoverflow.com/users/2630572",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the UUID class with its getLeastSignificantBits() message to get 64 bit of <em>random</em> data, and then convert it to a radix 36 number (i.e. a string consisting of 0-9,A-Z):</p>\n<pre><code>Long.toString(Math.abs( UUID.randomUUID().getLeastSignificantBits(), 36));\n</code></pre>\n<p>This yields a <em>string</em> up to 13 characters long. We use Math.abs() to make sure there isn't a minus sign sneaking in.</p>\n"
},
{
"answer_id": 21604071,
"author": "deepakmodak",
"author_id": 1424605,
"author_profile": "https://Stackoverflow.com/users/1424605",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li><p>Change <em>String</em> characters as per as your requirements.</p>\n</li>\n<li><p>String is immutable. Here <code>StringBuilder.append</code> is more efficient than string concatenation.</p>\n</li>\n</ol>\n<br/>\n<pre><code>public static String getRandomString(int length) {\n final String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+";\n StringBuilder result = new StringBuilder();\n\n while(length > 0) {\n Random rand = new Random();\n result.append(characters.charAt(rand.nextInt(characters.length())));\n length--;\n }\n return result.toString();\n}\n</code></pre>\n"
},
{
"answer_id": 27120868,
"author": "Howard Lovatt",
"author_id": 1481689,
"author_profile": "https://Stackoverflow.com/users/1481689",
"pm_score": 4,
"selected": false,
"text": "<p>An alternative in Java 8 is:</p>\n\n<pre><code>static final Random random = new Random(); // Or SecureRandom\nstatic final int startChar = (int) '!';\nstatic final int endChar = (int) '~';\n\nstatic String randomString(final int maxLength) {\n final int length = random.nextInt(maxLength + 1);\n return random.ints(length, startChar, endChar + 1)\n .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)\n .toString();\n}\n</code></pre>\n"
},
{
"answer_id": 27350150,
"author": "Steven L",
"author_id": 681122,
"author_profile": "https://Stackoverflow.com/users/681122",
"pm_score": -1,
"selected": false,
"text": "<p>Yet another solution...</p>\n<pre><code>public static String generatePassword(int passwordLength) {\n int asciiFirst = 33;\n int asciiLast = 126;\n Integer[] exceptions = { 34, 39, 96 };\n\n List<Integer> exceptionsList = Arrays.asList(exceptions);\n SecureRandom random = new SecureRandom();\n StringBuilder builder = new StringBuilder();\n for (int i=0; i<passwordLength; i++) {\n int charIndex;\n\n do {\n charIndex = random.nextInt(asciiLast - asciiFirst + 1) + asciiFirst;\n }\n while (exceptionsList.contains(charIndex));\n\n builder.append((char) charIndex);\n }\n return builder.toString();\n}\n</code></pre>\n"
},
{
"answer_id": 31214709,
"author": "Kristian Kraljic",
"author_id": 1338417,
"author_profile": "https://Stackoverflow.com/users/1338417",
"pm_score": 4,
"selected": false,
"text": "<p>Using UUIDs is insecure, because parts of the UUID aren't random at all. The <a href=\"https://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string/41156#41156\">procedure of erickson</a> is very neat, but it does not create strings of the same length. The following snippet should be sufficient:</p>\n<pre><code>/*\n * The random generator used by this class to create random keys.\n * In a holder class to defer initialization until needed.\n */\nprivate static class RandomHolder {\n static final Random random = new SecureRandom();\n public static String randomKey(int length) {\n return String.format("%"+length+"s", new BigInteger(length*5/*base 32,2^5*/, random)\n .toString(32)).replace('\\u0020', '0');\n }\n}\n</code></pre>\n<p>Why choose <code>length*5</code>? Let's assume the simple case of a random string of length 1, so one random character. To get a random character containing all digits 0-9 and characters a-z, we would need a random number between 0 and 35 to get one of each character.</p>\n<p><code>BigInteger</code> provides a constructor to generate a random number, uniformly distributed over the range <code>0 to (2^numBits - 1)</code>. Unfortunately 35 is not a number which can be received by 2^numBits - 1.</p>\n<p>So we have two options: Either go with <code>2^5-1=31</code> or <code>2^6-1=63</code>. If we would choose <code>2^6</code> we would get a lot of "unnecessary" / "longer" numbers. Therefore <code>2^5</code> is the better option, even if we lose four characters (w-z). To now generate a string of a certain length, we can simply use a <code>2^(length*numBits)-1</code> number. The last problem, if we want a string with a certain length, random could generate a small number, so the length is not met, so we have to pad the string to its required length prepending zeros.</p>\n"
},
{
"answer_id": 38776878,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe this is helpful</p>\n\n<pre><code>package password.generater;\n\nimport java.util.Random;\n\n/**\n *\n * @author dell\n */\npublic class PasswordGenerater {\n\n /**\n * @param args the command line arguments\n */\n public static void main(String[] args) {\n int length= 11;\n System.out.println(generatePswd(length));\n\n // TODO code application logic here\n }\n static char[] generatePswd(int len){\n System.out.println(\"Your Password \");\n String charsCaps=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; \n String Chars=\"abcdefghijklmnopqrstuvwxyz\";\n String nums=\"0123456789\";\n String symbols=\"!@#$%^&*()_+-=.,/';:?><~*/-+\";\n String passSymbols=charsCaps + Chars + nums +symbols;\n Random rnd=new Random();\n char[] password=new char[len];\n\n for(int i=0; i<len;i++){\n password[i]=passSymbols.charAt(rnd.nextInt(passSymbols.length()));\n }\n return password;\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 40852832,
"author": "user_3380739",
"author_id": 3380739,
"author_profile": "https://Stackoverflow.com/users/3380739",
"pm_score": 3,
"selected": false,
"text": "<p>Here is the one-liner by <a href=\"https://github.com/landawn/AbacusUtil\" rel=\"nofollow noreferrer\">AbacusUtil</a>:</p>\n<pre><code>String.valueOf(CharStream.random('0', 'z').filter(c -> N.isLetterOrDigit(c)).limit(12).toArray())\n</code></pre>\n<p>Random doesn't mean it must be unique. To get unique strings, use:</p>\n<pre><code>N.uuid() // E.g.: "e812e749-cf4c-4959-8ee1-57829a69a80f". length is 36.\nN.guid() // E.g.: "0678ce04e18945559ba82ddeccaabfcd". length is 32 without '-'\n</code></pre>\n"
},
{
"answer_id": 44227131,
"author": "Patrick",
"author_id": 774398,
"author_profile": "https://Stackoverflow.com/users/774398",
"pm_score": 6,
"selected": false,
"text": "<p>This is easily achievable without any external libraries.</p>\n<h1>1. Cryptographic Pseudo Random Data Generation (PRNG)</h1>\n<p>First you need a cryptographic PRNG. Java has <a href=\"https://docs.oracle.com/javase/8/docs/api/java/security/SecureRandom.html\" rel=\"noreferrer\"><code>SecureRandom</code></a> for that and typically uses the best entropy source on the machine (e.g. <code>/dev/random</code>). <a href=\"https://tersesystems.com/2015/12/17/the-right-way-to-use-securerandom/\" rel=\"noreferrer\">Read more here</a>.</p>\n<pre><code>SecureRandom rnd = new SecureRandom();\nbyte[] token = new byte[byteLength];\nrnd.nextBytes(token);\n</code></pre>\n<p><em><strong>Note:</strong></em> <code>SecureRandom</code> is the slowest, but most secure way in Java of generating random bytes. I do however recommend <em>not</em> considering performance here since it usually has no real impact on your application unless you have to generate millions of tokens per second.</p>\n<h1>2. Required Space of Possible Values</h1>\n<p>Next you have to decide "how unique" your token needs to be. The whole and only point of considering entropy is to make sure that the system can resist brute force attacks: the space of possible values must be so large that any attacker could only try a negligible proportion of the values in non-ludicrous time<sup><a href=\"https://security.stackexchange.com/a/102163/60108\">1</a></sup>.</p>\n<p>Unique identifiers such as random <a href=\"https://en.wikipedia.org/wiki/Universally_unique_identifier\" rel=\"noreferrer\"><code>UUID</code></a> have 122 bit of entropy (i.e., 2^122 = 5.3x10^36) - the chance of collision is "*(...) for there to be a one in a billion chance of duplication, 103 trillion version 4 UUIDs must be generated<sup><a href=\"https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions\" rel=\"noreferrer\">2</a></sup>". <strong>We will choose 128 bits since it fits exactly into 16 bytes</strong> and is seen as <a href=\"https://security.stackexchange.com/questions/6141/amount-of-simple-operations-that-is-safely-out-of-reach-for-all-humanity/6149#6149\">highly sufficient</a> for being unique for basically every, but the most extreme, use cases and you don't have to think about duplicates. Here is a simple comparison table of entropy including simple analysis of the <a href=\"https://en.wikipedia.org/wiki/Birthday_problem\" rel=\"noreferrer\">birthday problem</a>.</p>\n<p><a href=\"https://i.stack.imgur.com/LoLpJ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/LoLpJ.png\" alt=\"Comparison of token sizes\" /></a></p>\n<p><sup>For simple requirements, 8 or 12 byte length might suffice, but with 16 bytes you are on the "safe side".</sup></p>\n<p>And that's basically it. The last thing is to think about encoding so it can be represented as a printable text (read, a <code>String</code>).</p>\n<h1>3. Binary to Text Encoding</h1>\n<p>Typical encodings include:</p>\n<ul>\n<li><p><a href=\"https://en.wikipedia.org/wiki/Base64\" rel=\"noreferrer\"><code>Base64</code></a> every character encodes 6 bit, creating a 33% overhead. Fortunately there are standard implementations in <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html\" rel=\"noreferrer\">Java 8+</a> and <a href=\"https://developer.android.com/reference/android/util/Base64.html\" rel=\"noreferrer\">Android</a>. With older Java you can use any of the <a href=\"https://stackoverflow.com/questions/13109588/base64-encoding-in-java\">numerous third-party libraries</a>. If you want your tokens to be URL safe use the <a href=\"https://en.wikipedia.org/wiki/Base64#URL_applications\" rel=\"noreferrer\">URL-safe</a> version of RFC4648 (which usually is supported by most implementations). Example encoding 16 bytes with padding: <code>XfJhfv3C0P6ag7y9VQxSbw==</code></p>\n</li>\n<li><p><a href=\"https://en.wikipedia.org/wiki/Base32\" rel=\"noreferrer\"><code>Base32</code></a> every character encodes 5 bit, creating a 40% overhead. This will use <code>A-Z</code> and <code>2-7</code>, making it reasonably space efficient while being case-insensitive alpha-numeric. There isn't any <a href=\"https://stackoverflow.com/questions/21515479/encode-string-to-base32-string-in-java\">standard implementation in the JDK</a>. Example encoding 16 bytes without padding: <code>WUPIL5DQTZGMF4D3NX5L7LNFOY</code></p>\n</li>\n<li><p><a href=\"https://en.wikipedia.org/wiki/Hexadecimal\" rel=\"noreferrer\"><code>Base16</code></a> (hexadecimal) every character encodes four bit, requiring two characters per byte (i.e., 16 bytes create a string of length 32). Therefore hexadecimal is less space efficient than <code>Base32</code>, but it is safe to use in most cases (URL) since it only uses <code>0-9</code> and <code>A</code> to <code>F</code>. Example encoding 16 bytes: <code>4fa3dd0f57cb3bf331441ed285b27735</code>. <a href=\"https://stackoverflow.com/a/58118078/774398\">See a Stack Overflow discussion about converting to hexadecimal here</a>.</p>\n</li>\n</ul>\n<p>Additional encodings like <a href=\"https://en.wikipedia.org/wiki/Ascii85#RFC_1924_version\" rel=\"noreferrer\">Base85</a> and the exotic <a href=\"http://blog.kevinalbs.com/base122\" rel=\"noreferrer\">Base122</a> exist with better/worse space efficiency. You can create your own encoding (which basically most answers in this thread do), but I would advise against it, if you don't have very specific requirements. See <a href=\"https://en.wikipedia.org/wiki/Binary-to-text_encoding\" rel=\"noreferrer\">more encoding schemes in the Wikipedia article</a>.</p>\n<h1>4. Summary and Example</h1>\n<ul>\n<li>Use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/security/SecureRandom.html\" rel=\"noreferrer\"><code>SecureRandom</code></a></li>\n<li>Use at least 16 bytes (2^128) of possible values</li>\n<li>Encode according to your requirements (usually <code>hex</code> or <code>base32</code> if you need it to be alpha-numeric)</li>\n</ul>\n<p><strong>Don't</strong></p>\n<ul>\n<li>... use your home brew encoding: <em>better maintainable and readable for others if they see what standard encoding you use instead of weird <em>for</em> loops creating characters at a time.</em></li>\n<li>... use UUID: <em>it has no guarantees on randomness; you are wasting 6 bits of entropy and have a verbose string representation</em></li>\n</ul>\n<h2>Example: Hexadecimal Token Generator</h2>\n<pre><code>public static String generateRandomHexToken(int byteLength) {\n SecureRandom secureRandom = new SecureRandom();\n byte[] token = new byte[byteLength];\n secureRandom.nextBytes(token);\n return new BigInteger(1, token).toString(16); // Hexadecimal encoding\n}\n\n//generateRandomHexToken(16) -> 2189df7475e96aa3982dbeab266497cd\n</code></pre>\n<h2>Example: Base64 Token Generator (URL Safe)</h2>\n<pre><code>public static String generateRandomBase64Token(int byteLength) {\n SecureRandom secureRandom = new SecureRandom();\n byte[] token = new byte[byteLength];\n secureRandom.nextBytes(token);\n return Base64.getUrlEncoder().withoutPadding().encodeToString(token); //base64 encoding\n}\n\n//generateRandomBase64Token(16) -> EEcCCAYuUcQk7IuzdaPzrg\n</code></pre>\n<h2>Example: Java CLI Tool</h2>\n<p>If you want a ready-to-use CLI tool you may use <a href=\"https://github.com/patrickfav/dice\" rel=\"noreferrer\">dice</a>:</p>\n<h2>Example: Related issue - Protect Your Current Ids</h2>\n<p>If you already have an id you can use (e.g., a synthetic <code>long</code> in your entity), but <a href=\"https://medium.com/@patrickfav/a-better-way-to-protect-your-database-ids-a33fa9867552\" rel=\"noreferrer\">don't want to publish the internal value</a>, you can use this library to encrypt it and obfuscate it: <a href=\"https://github.com/patrickfav/id-mask\" rel=\"noreferrer\">https://github.com/patrickfav/id-mask</a></p>\n<pre><code>IdMask<Long> idMask = IdMasks.forLongIds(Config.builder(key).build());\nString maskedId = idMask.mask(id);\n// Example: NPSBolhMyabUBdTyanrbqT8\nlong originalId = idMask.unmask(maskedId);\n</code></pre>\n"
},
{
"answer_id": 44866347,
"author": "kyxap",
"author_id": 975638,
"author_profile": "https://Stackoverflow.com/users/975638",
"pm_score": -1,
"selected": false,
"text": "<p>Also, you can generate any lowercase or uppercase letters or even special characters through data from the ASCII table. For example, generate upper case letters from A (DEC 65) to Z (DEC 90):</p>\n<pre><code>String generateRandomStr(int min, int max, int size) {\n String result = "";\n for (int i = 0; i < size; i++) {\n result += String.valueOf((char)(new Random().nextInt((max - min) + 1) + min));\n }\n return result;\n}\n</code></pre>\n<p>Generated output for <code>generateRandomStr(65, 90, 100));</code>:</p>\n<pre><code>TVLPFQJCYFXQDCQSLKUKKILKKHAUFYEXLUQFHDWNMRBIRRRWNXNNZQTINZPCTKLHGHVYWRKEOYNSOFPZBGEECFMCOKWHLHCEWLDZ\n</code></pre>\n"
},
{
"answer_id": 48909646,
"author": "Patrik Bego",
"author_id": 2306839,
"author_profile": "https://Stackoverflow.com/users/2306839",
"pm_score": 3,
"selected": false,
"text": "<p>I don't really like any of these answers regarding a "simple" solution :S</p>\n<p>I would go for a simple ;), pure Java, one liner (entropy is based on random string length and the given character set):</p>\n<pre><code>public String randomString(int length, String characterSet) {\n return IntStream.range(0, length).map(i -> new SecureRandom().nextInt(characterSet.length())).mapToObj(randomInt -> characterSet.substring(randomInt, randomInt + 1)).collect(Collectors.joining());\n}\n\n@Test\npublic void buildFiveRandomStrings() {\n for (int q = 0; q < 5; q++) {\n System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); // The character set can basically be anything\n }\n}\n</code></pre>\n<p>Or (a bit more readable old way)</p>\n<pre><code>public String randomString(int length, String characterSet) {\n StringBuilder sb = new StringBuilder(); // Consider using StringBuffer if needed\n for (int i = 0; i < length; i++) {\n int randomInt = new SecureRandom().nextInt(characterSet.length());\n sb.append(characterSet.substring(randomInt, randomInt + 1));\n }\n return sb.toString();\n}\n\n@Test\npublic void buildFiveRandomStrings() {\n for (int q = 0; q < 5; q++) {\n System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); // The character set can basically be anything\n }\n}\n</code></pre>\n<p>But on the other hand you could also go with <a href=\"https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions\" rel=\"nofollow noreferrer\">UUID</a> which has a pretty good entropy:</p>\n<pre><code>UUID.randomUUID().toString().replace("-", "")\n</code></pre>\n"
},
{
"answer_id": 49056893,
"author": "aaronvargas",
"author_id": 114549,
"author_profile": "https://Stackoverflow.com/users/114549",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a simple one-liner using UUIDs as the character base and being able to specify (almost) any length. (Yes, I know that using a UUID has been suggested before.)</p>\n<pre><code>public static String randString(int length) {\n return UUID.randomUUID().toString().replace("-", "").substring(0, Math.min(length, 32)) + (length > 32 ? randString(length - 32) : "");\n}\n</code></pre>\n"
},
{
"answer_id": 51896107,
"author": "Prasad Parab",
"author_id": 6359611,
"author_profile": "https://Stackoverflow.com/users/6359611",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public static String getRandomString(int length) {\n char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST".toCharArray();\n\n StringBuilder sb = new StringBuilder();\n Random random = new Random();\n for (int i = 0; i < length; i++) {\n char c = chars[random.nextInt(chars.length)];\n sb.append(c);\n }\n String randomStr = sb.toString();\n\n return randomStr;\n}\n</code></pre>\n"
},
{
"answer_id": 53487039,
"author": "FileInputStream",
"author_id": 9139738,
"author_profile": "https://Stackoverflow.com/users/9139738",
"pm_score": 2,
"selected": false,
"text": "<p>I think this is the smallest solution here, or nearly one of the smallest:</p>\n<pre><code> public String generateRandomString(int length) {\n String randomString = "";\n\n final char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890".toCharArray();\n final Random random = new Random();\n for (int i = 0; i < length; i++) {\n randomString = randomString + chars[random.nextInt(chars.length)];\n }\n\n return randomString;\n}\n</code></pre>\n<p>The code works just fine. If you are using this method, I recommend you to use more than 10 characters. A collision happens at 5 characters / 30362 iterations. This took 9 seconds.</p>\n"
},
{
"answer_id": 54907024,
"author": "mike",
"author_id": 1809463,
"author_profile": "https://Stackoverflow.com/users/1809463",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a Java 8 solution based on streams.</p>\n\n<pre><code> public String generateString(String alphabet, int length) {\n return generateString(alphabet, length, new SecureRandom()::nextInt);\n }\n\n // nextInt = bound -> n in [0, bound)\n public String generateString(String source, int length, IntFunction<Integer> nextInt) {\n StringBuilder sb = new StringBuilder();\n IntStream.generate(source::length)\n .boxed()\n .limit(length)\n .map(nextInt::apply)\n .map(source::charAt)\n .forEach(sb::append);\n\n return sb.toString();\n }\n</code></pre>\n\n<p>Use it like </p>\n\n<pre><code>String alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\nint length = 12;\nString generated = generateString(alphabet, length);\nSystem.out.println(generated);\n</code></pre>\n\n<p>The function <code>nextInt</code> should accept an int <code>bound</code> and return a random number between <code>0</code> and <code>bound - 1</code>.</p>\n"
},
{
"answer_id": 55376955,
"author": "SoBeRich",
"author_id": 8305572,
"author_profile": "https://Stackoverflow.com/users/8305572",
"pm_score": -1,
"selected": false,
"text": "<p>Efficient and short.</p>\n<pre><code>/**\n * Utility class for generating random Strings.\n */\npublic interface RandomUtil {\n\n int DEF_COUNT = 20;\n Random RANDOM = new SecureRandom();\n\n /**\n * Generate a password.\n *\n * @return the generated password\n */\n static String generatePassword() {\n return generate(true, true);\n }\n\n /**\n * Generate an activation key.\n *\n * @return the generated activation key\n */\n static String generateActivationKey() {\n return generate(false, true);\n }\n\n /**\n * Generate a reset key.\n *\n * @return the generated reset key\n */\n static String generateResetKey() {\n return generate(false, true);\n }\n\n static String generate(boolean letters, boolean numbers) {\n int\n start = ' ',\n end = 'z' + 1,\n count = DEF_COUNT,\n gap = end - start;\n StringBuilder builder = new StringBuilder(count);\n\n while (count-- != 0) {\n int codePoint = RANDOM.nextInt(gap) + start;\n\n switch (getType(codePoint)) {\n case UNASSIGNED:\n case PRIVATE_USE:\n case SURROGATE:\n count++;\n continue;\n }\n\n int numberOfChars = charCount(codePoint);\n\n if (count == 0 && numberOfChars > 1) {\n count++;\n continue;\n }\n\n if (letters && isLetter(codePoint)\n || numbers && isDigit(codePoint)\n || !letters && !numbers) {\n\n builder.appendCodePoint(codePoint);\n if (numberOfChars == 2)\n count--;\n }\n else\n count++;\n }\n return builder.toString();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 59223550,
"author": "Riley Jones",
"author_id": 12491840,
"author_profile": "https://Stackoverflow.com/users/12491840",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public static String RandomAlphanum(int length)\n{\n String charstring = "abcdefghijklmnopqrstuvwxyz0123456789";\n String randalphanum = "";\n double randroll;\n String randchar;\n for (double i = 0; i < length; i++)\n {\n randroll = Math.random();\n randchar = "";\n for (int j = 1; j <= 35; j++)\n {\n if (randroll <= (1.0 / 36.0 * j))\n {\n randchar = Character.toString(charstring.charAt(j - 1));\n break;\n }\n }\n randalphanum += randchar;\n }\n return randalphanum;\n}\n</code></pre>\n<p>I used a very primitive algorithm using Math.random(). To increase randomness, you can directly implement the <code>util.Date</code> class. Nevertheless, it works.</p>\n"
},
{
"answer_id": 61152198,
"author": "Chuong Tran",
"author_id": 8568835,
"author_profile": "https://Stackoverflow.com/users/8568835",
"pm_score": 3,
"selected": false,
"text": "<p>I'm using a library from <a href=\"https://en.wikipedia.org/wiki/Apache_Commons\" rel=\"nofollow noreferrer\">Apache Commons</a> to generate an alphanumeric string:</p>\n<pre><code>import org.apache.commons.lang3.RandomStringUtils;\n\nString keyLength = 20;\nRandomStringUtils.randomAlphanumeric(keylength);\n</code></pre>\n<p>It's fast and simple!</p>\n"
},
{
"answer_id": 67010786,
"author": "Mayank",
"author_id": 9297984,
"author_profile": "https://Stackoverflow.com/users/9297984",
"pm_score": -1,
"selected": false,
"text": "<p>I am using a very simple solution using Java 8. Just customize it according to your needs.</p>\n<pre><code>...\nimport java.security.SecureRandom;\n...\n\n//Generate a random String of length between 10 to 20.\n//Length is also randomly generated here.\nSecureRandom random = new SecureRandom();\n\nString sampleSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";\n\nint stringLength = random.ints(1, 10, 21).mapToObj(x -> x).reduce((a, b) -> a).get();\n\nString randomString = random.ints(stringLength, 0, sampleSet.length() - 1)\n .mapToObj(x -> sampleSet.charAt(x))\n .collect(Collector\n .of(StringBuilder::new, StringBuilder::append,\n StringBuilder::append, StringBuilder::toString));\n</code></pre>\n<hr />\n<p>We can use this to generate an alphanumeric random String like this (the returned String will mandatorily have some non-numeric characters as well as some numeric characters):</p>\n<pre><code>public String generateRandomString() {\n \n String sampleSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_";\n String sampleSetNumeric = "0123456789";\n \n String randomString = getRandomString(sampleSet, 10, 21);\n String randomStringNumeric = getRandomString(sampleSetNumeric, 10, 21);\n \n randomString = randomString + randomStringNumeric;\n \n //Convert String to List<Character>\n List<Character> list = randomString.chars()\n .mapToObj(x -> (char)x)\n .collect(Collectors.toList());\n \n Collections.shuffle(list);\n \n //This is needed to force a non-numeric character as the first String\n //Skip this for() if you don't need this logic\n\n for(;;) {\n if(Character.isDigit(list.get(0))) Collections.shuffle(list);\n else break;\n }\n \n //Convert List<Character> to String\n randomString = list.stream()\n .map(String::valueOf)\n .collect(Collectors.joining());\n \n return randomString;\n \n}\n\n//Generate a random number between the lower bound (inclusive) and upper bound (exclusive)\nprivate int getRandomLength(int min, int max) {\n SecureRandom random = new SecureRandom();\n return random.ints(1, min, max).mapToObj(x -> x).reduce((a, b) -> a).get();\n}\n\n//Generate a random String from the given sample string, having a random length between the lower bound (inclusive) and upper bound (exclusive)\nprivate String getRandomString(String sampleSet, int min, int max) {\n SecureRandom random = new SecureRandom();\n return random.ints(getRandomLength(min, max), 0, sampleSet.length() - 1)\n .mapToObj(x -> sampleSet.charAt(x))\n .collect(Collector\n .of(StringBuilder::new, StringBuilder::append,\n StringBuilder::append, StringBuilder::toString));\n}\n</code></pre>\n"
},
{
"answer_id": 67020131,
"author": "Muxammed Gafarov",
"author_id": 13589507,
"author_profile": "https://Stackoverflow.com/users/13589507",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public class Utils {\n private final Random RANDOM = new SecureRandom();\n private final String ALPHABET = "0123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";\n\n private String generateRandomString(int length) {\n StringBuffer buffer = new StringBuffer(length);\n for (int i = 0; i < length; i++) {\n buffer.append(ALPHABET.charAt(RANDOM.nextInt(ALPHABET.length())));\n }\n return new String(buffer);\n } \n}\n</code></pre>\n"
},
{
"answer_id": 74024384,
"author": "cwtuan",
"author_id": 2822680,
"author_profile": "https://Stackoverflow.com/users/2822680",
"pm_score": 0,
"selected": false,
"text": "<p>Given the some characters (<code>AllCharacters</code>), you could pickup a character in the string randomly. Then use-for loop to get random charcter repeatedly.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class MyProgram {\n static String getRandomString(int size) {\n String AllCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";\n StringBuilder sb = new StringBuilder(size);\n int length = AllCharacters.length();\n for (int i = 0; i < size; i++) {\n sb.append(AllCharacters.charAt((int)(length * Math.random())));\n }\n return sb.toString();\n }\n\n public static void main(String[] args) {\n System.out.println(MyProgram.getRandomString(30));\n }\n}\n</code></pre>\n<ul>\n<li>Try it on the <a href=\"https://codehs.com/sandbox/id/java-main-4NaSkG\" rel=\"nofollow noreferrer\">sandbox</a></li>\n<li>Also see other languages implement <a href=\"https://fe-tool.com/en-us/random-password\" rel=\"nofollow noreferrer\">random string generator</a></li>\n</ul>\n"
},
{
"answer_id": 74402390,
"author": "F_SO_K",
"author_id": 4985580,
"author_profile": "https://Stackoverflow.com/users/4985580",
"pm_score": 0,
"selected": false,
"text": "<p>You can do this in one line with no external libraries.</p>\n<pre><code>int length = 12;\nString randomString = new Random().ints(48, 122).filter(i -> (i < 58 || i > 64) && (i < 91 || i > 96)).limit(length).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();\nSystem.out.print(randomString);\n</code></pre>\n<p>I have separated out the length into a parameter, and added a line to print the result.</p>\n<p>This code creates a stream of random integers bounded to the alphanumeric ascii range. It then filters out some symbols, because the alphanumeric range is not continuous. It then limits the length and collects the result into a string.</p>\n<p>Because this approach discards something like 20% of the numbers/characters it generates (as they are symbols), there is a small performance impact.</p>\n<p>I don't find it particularly readable, but I don't think anyone else has suggested a native Java solution in one line.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803/"
] | I've been looking for a *simple* Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would "likely" be unique over `500K+` generation (my needs don't really require anything much more sophisticated).
Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like `"AEYGF7K0DM1X"`. | Algorithm
---------
To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length.
Implementation
--------------
Here's some fairly simple and very flexible code for generating random identifiers. *Read the information that follows* for important application notes.
```
public class RandomString {
/**
* Generate a random string.
*/
public String nextString() {
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols[random.nextInt(symbols.length)];
return new String(buf);
}
public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String lower = upper.toLowerCase(Locale.ROOT);
public static final String digits = "0123456789";
public static final String alphanum = upper + lower + digits;
private final Random random;
private final char[] symbols;
private final char[] buf;
public RandomString(int length, Random random, String symbols) {
if (length < 1) throw new IllegalArgumentException();
if (symbols.length() < 2) throw new IllegalArgumentException();
this.random = Objects.requireNonNull(random);
this.symbols = symbols.toCharArray();
this.buf = new char[length];
}
/**
* Create an alphanumeric string generator.
*/
public RandomString(int length, Random random) {
this(length, random, alphanum);
}
/**
* Create an alphanumeric strings from a secure generator.
*/
public RandomString(int length) {
this(length, new SecureRandom());
}
/**
* Create session identifiers.
*/
public RandomString() {
this(21);
}
}
```
Usage examples
--------------
Create an insecure generator for 8-character identifiers:
```
RandomString gen = new RandomString(8, ThreadLocalRandom.current());
```
Create a secure generator for session identifiers:
```
RandomString session = new RandomString();
```
Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols:
```
String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";
RandomString tickets = new RandomString(23, new SecureRandom(), easy);
```
Use as session identifiers
--------------------------
Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used.
There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand.
The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible.
Use as object identifiers
-------------------------
Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big.
Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission.
Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." [The probability of a collision,](https://en.wikipedia.org/wiki/Birthday_problem#Square_approximation) *p*, is approximately n2/(2qx), where *n* is the number of identifiers actually generated, *q* is the number of distinct symbols in the alphabet, and *x* is the length of the identifiers. This should be a very small number, like 2‑50 or less.
Working this out shows that the chance of collision among 500k 15-character identifiers is about 2‑52, which is probably less likely than undetected errors from cosmic rays, etc.
Comparison with UUIDs
---------------------
According to their specification, [UUIDs](https://www.rfc-editor.org/rfc/rfc4122#section-6) are not designed to be unpredictable, and *should not* be used as session identifiers.
UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters.
UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient. |
41,155 | <p>In the process of developing my first WCF service and when I try to use it I get "Method not Allowed" with no other explanation. </p>
<p>I've got my interface set up with the ServiceContract and OperationContract:</p>
<pre><code> [OperationContract]
void FileUpload(UploadedFile file);
</code></pre>
<p>Along with the actual method:</p>
<pre><code> public void FileUpload(UploadedFile file) {};
</code></pre>
<p>To access the Service I enter <a href="http://localhost/project/myService.svc/FileUpload" rel="noreferrer">http://localhost/project/myService.svc/FileUpload</a>
but I get the "Method not Allowed" error</p>
<p>Am I missing something?</p>
| [
{
"answer_id": 41205,
"author": "Jeremy McGee",
"author_id": 3546,
"author_profile": "https://Stackoverflow.com/users/3546",
"pm_score": 2,
"selected": false,
"text": "<p>The basic intrinsic types (e.g. <code>byte</code>, <code>int</code>, <code>string</code>, and arrays) will be serialized automatically by WCF. Custom classes, like your UploadedFile, won't be. </p>\n\n<p>So, a silly question (but I have to ask it...): is UploadedFile marked as a <code>[DataContract]</code>? If not, you'll need to make sure that it is, and that each of the members in the class that you want to send are marked with [DataMember]. </p>\n\n<p>Unlike remoting, where marking a class with [XmlSerializable] allowed you to serialize the whole class without bothering to mark the members that you wanted serialized, WCF needs you to mark up each member. (I believe this is changing in .NET 3.5 SP1...)</p>\n\n<p>A tremendous resource for WCF development is what we know in our shop as \"the fish book\": <a href=\"http://www.amazon.co.uk/Programming-WCF-Services-Juval-Lowy/dp/0596526997/ref=sr_1_4?ie=UTF8&s=books&qid=1220419338&sr=8-4\" rel=\"nofollow noreferrer\">Programming WCF Services</a> by Juval Lowy. Unlike some of the other WCF books around, which are a bit dry and academic, this one takes a practical approach to building WCF services and is actually useful. Thoroughly recommended.</p>\n"
},
{
"answer_id": 41301,
"author": "Ubiguchi",
"author_id": 2562,
"author_profile": "https://Stackoverflow.com/users/2562",
"pm_score": 1,
"selected": false,
"text": "<p>It sounds like you're using an incorrect address:</p>\n\n<blockquote>\n <p>To access the Service I enter <a href=\"http://localhost/project/myService.svc/FileUpload\" rel=\"nofollow noreferrer\">http://localhost/project/myService.svc/FileUpload</a></p>\n</blockquote>\n\n<p>Assuming you mean this is the address you give your client code then I suspect it should actually be:</p>\n\n<pre><code>http://localhost/project/myService.svc\n</code></pre>\n"
},
{
"answer_id": 545754,
"author": "Ries",
"author_id": 64565,
"author_profile": "https://Stackoverflow.com/users/64565",
"pm_score": 7,
"selected": true,
"text": "<p>Your browser is sending an HTTP GET request: Make sure you have the WebGet attribute on the operation in the contract:</p>\n\n<pre><code>[ServiceContract]\npublic interface IUploadService\n{\n [WebGet()]\n [OperationContract]\n string TestGetMethod(); // This method takes no arguments, returns a string. Perfect for testing quickly with a browser.\n\n [OperationContract]\n void UploadFile(UploadedFile file); // This probably involves an HTTP POST request. Not so easy for a quick browser test.\n }\n</code></pre>\n"
},
{
"answer_id": 2018327,
"author": "darthjit",
"author_id": 121397,
"author_profile": "https://Stackoverflow.com/users/121397",
"pm_score": 6,
"selected": false,
"text": "<p>If you are using the <code>[WebInvoke(Method=\"GET\")]</code> attribute on the service method, make sure that you spell the method name as \"GET\" and not \"Get\" or \"get\" since it is case sensitive! I had the same error and it took me an hour to figure that one out. </p>\n"
},
{
"answer_id": 4752095,
"author": "Sameh",
"author_id": 583561,
"author_profile": "https://Stackoverflow.com/users/583561",
"pm_score": 0,
"selected": false,
"text": "<p>Only methods with WebGet can be accessed from browser IE ; you can access other http verbs by just typing address</p>\n\n<p>You can either try Restful service startup kit of codeples or use fiddler to test your other http verbs</p>\n"
},
{
"answer_id": 12079267,
"author": "sandeep",
"author_id": 1617832,
"author_profile": "https://Stackoverflow.com/users/1617832",
"pm_score": 0,
"selected": false,
"text": "<p>you need to add in web.config </p>\n\n<pre><code><endpoint address=\"customBinding\" binding=\"customBinding\" bindingConfiguration=\"basicConfig\" contract=\"WcfRest.IService1\"/> \n\n<bindings> \n <customBinding> \n <binding name=\"basicConfig\"> \n <binaryMessageEncoding/> \n <httpTransport transferMode=\"Streamed\" maxReceivedMessageSize=\"67108864\"/> \n </binding> \n </customBinding> \n</code></pre>\n"
},
{
"answer_id": 27261464,
"author": "flobadob",
"author_id": 339348,
"author_profile": "https://Stackoverflow.com/users/339348",
"pm_score": 1,
"selected": false,
"text": "<p>I've been having this same problem for over a day now - finally figured it out. Thanks to @Sameh for the hint.</p>\n\n<p>Your service is probably working just fine. Testing POST messages using the address bar of a browser won't work. You need to use Fiddler to test a POST message.</p>\n\n<p>Fiddler instructions...\n<a href=\"http://www.ehow.com/how_8788176_do-post-using-fiddler.html\" rel=\"nofollow\">http://www.ehow.com/how_8788176_do-post-using-fiddler.html</a></p>\n"
},
{
"answer_id": 30732917,
"author": "dudeNumber4",
"author_id": 74000,
"author_profile": "https://Stackoverflow.com/users/74000",
"pm_score": 0,
"selected": false,
"text": "<p>My case: configuring the service on new server. ASP.NET 4.0 was not installed/registered properly; svc extension was not recognized.</p>\n"
},
{
"answer_id": 62238509,
"author": "Stuart Smith",
"author_id": 4089404,
"author_profile": "https://Stackoverflow.com/users/4089404",
"pm_score": 2,
"selected": false,
"text": "<p>I ran into this exact same issue today. I had installed IIS, but did not have the activate WCF Services Enabled under .net framework 4.6.</p>\n\n<p><a href=\"https://i.stack.imgur.com/mEoWS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mEoWS.png\" alt=\"enter image description here\"></a></p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/831/"
] | In the process of developing my first WCF service and when I try to use it I get "Method not Allowed" with no other explanation.
I've got my interface set up with the ServiceContract and OperationContract:
```
[OperationContract]
void FileUpload(UploadedFile file);
```
Along with the actual method:
```
public void FileUpload(UploadedFile file) {};
```
To access the Service I enter <http://localhost/project/myService.svc/FileUpload>
but I get the "Method not Allowed" error
Am I missing something? | Your browser is sending an HTTP GET request: Make sure you have the WebGet attribute on the operation in the contract:
```
[ServiceContract]
public interface IUploadService
{
[WebGet()]
[OperationContract]
string TestGetMethod(); // This method takes no arguments, returns a string. Perfect for testing quickly with a browser.
[OperationContract]
void UploadFile(UploadedFile file); // This probably involves an HTTP POST request. Not so easy for a quick browser test.
}
``` |
41,159 | <p>Given the following:</p>
<pre><code>List<List<Option>> optionLists;
</code></pre>
<p>what would be a quick way to determine the subset of Option objects that appear in all N lists? Equality is determined through some string property such as option1.Value == option2.Value.</p>
<p>So we should end up with <code>List<Option></code> where each item appears only once.</p>
| [
{
"answer_id": 41175,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, this will find the list of Option objects that have a Value appearing in <em>every</em> list.</p>\n\n<pre><code>var x = from list in optionLists\n from option in list\n where optionLists.All(l => l.Any(o => o.Value == option.Value))\n orderby option.Value\n select option;\n</code></pre>\n\n<p>It doesn't do a \"distinct\" select so it'll return multiple Option objects, some of them with the same Value.</p>\n"
},
{
"answer_id": 41286,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>Sort, then do something akin to a merge-sort.</p>\n\n<p>Basically you would do this:</p>\n\n<ol>\n<li>Retrieve the first item from each list</li>\n<li>Compare the items, if equal, output</li>\n<li>If any of the items are before the others, sort-wise, retrieve a new item from the corresponding list to replace it, otherwise, retrieve new items to replace them all, from all the list</li>\n<li>As long as you still got items, go back to 2.</li>\n</ol>\n"
},
{
"answer_id": 41318,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 1,
"selected": false,
"text": "<p>what about using a <em><a href=\"http://msdn.microsoft.com/en-us/library/bb359438.aspx\" rel=\"nofollow noreferrer\">hashSet</a></em>? that way you can do what you want in O(n) where n is the number of items in all the lists combined, and I think that's the fastest way to do it.</p>\n\n<p>you just have to iterate over every list and insert the values you find into the hashset\nWhen you insert a key that already exists you will receive <em>false</em> as the return value of the <a href=\"http://msdn.microsoft.com/en-us/library/bb353005.aspx\" rel=\"nofollow noreferrer\">.add method,</a> otherwise <em>true</em> is returned</p>\n"
},
{
"answer_id": 41327,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a much more efficent implementation:</p>\n\n<pre><code>static SortedDictionary<T,bool>.KeyCollection FindCommon<T> (List<List<T>> items)\n{\n SortedDictionary<T, bool>\n current_common = new SortedDictionary<T, bool> (),\n common = new SortedDictionary<T, bool> ();\n\n foreach (List<T> list in items)\n {\n if (current_common.Count == 0)\n {\n foreach (T item in list)\n {\n common [item] = true;\n }\n }\n else\n {\n foreach (T item in list)\n {\n if (current_common.ContainsKey(item))\n common[item] = true;\n else\n common[item] = false;\n }\n }\n\n if (common.Count == 0)\n {\n current_common.Clear ();\n break;\n }\n\n SortedDictionary<T, bool>\n swap = current_common;\n\n current_common = common;\n common = swap;\n common.Clear ();\n }\n\n return current_common.Keys;\n} \n</code></pre>\n\n<p>It works by creating a set of all items common to all lists processed so far and comparing each list with this set, creating a temporary set of the items common to the current list and the list of common items so far. Effectively an O(n.m) where n is the number of lists and m the number of items in the lists.</p>\n\n<p>An example of using it:</p>\n\n<pre><code>static void Main (string [] args)\n{\n Random\n random = new Random();\n\n List<List<int>>\n items = new List<List<int>>();\n\n for (int i = 0 ; i < 10 ; ++i)\n {\n List<int>\n list = new List<int> ();\n\n items.Add (list);\n\n for (int j = 0 ; j < 100 ; ++j)\n {\n list.Add (random.Next (70));\n }\n }\n\n SortedDictionary<int, bool>.KeyCollection\n common = FindCommon (items);\n\n foreach (List<int> list in items)\n {\n list.Sort ();\n }\n\n for (int i = 0 ; i < 100 ; ++i)\n {\n for (int j = 0 ; j < 10 ; ++j)\n {\n System.Diagnostics.Trace.Write (String.Format (\"{0,-4:D} \", items [j] [i]));\n }\n\n System.Diagnostics.Trace.WriteLine (\"\");\n }\n\n foreach (int item in common)\n {\n System.Diagnostics.Trace.WriteLine (String.Format (\"{0,-4:D} \", item));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 42288,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 0,
"selected": false,
"text": "<p>I don't have the performance stats, but if you don't want to roll your own method, various collections libraries have a 'Set' or 'Set(T)' object that offer the usual set procedures. (listed in the order I would use them).</p>\n\n<ol>\n<li><a href=\"http://www.codeproject.com/KB/recipes/GenericISet.aspx\" rel=\"nofollow noreferrer\">IESI Collections</a> (literally just Set classes)</li>\n<li><a href=\"http://www.codeplex.com/PowerCollections\" rel=\"nofollow noreferrer\">PowerCollections</a> (not updated in a while)</li>\n<li><a href=\"http://www.itu.dk/research/c5/\" rel=\"nofollow noreferrer\">C5</a> (never personally used)</li>\n</ol>\n"
},
{
"answer_id": 42941,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 2,
"selected": false,
"text": "<p>Building on <a href=\"https://stackoverflow.com/questions/41159/fastest-way-to-find-common-items-across-multiple-lists-in-c#41175\">Matt's answer</a>, since we are only interested in options that all lists have in common, we can simply check for any options in the first list that the others share:</p>\n\n<pre><code>var sharedOptions =\n from option in optionLists.First( ).Distinct( )\n where optionLists.Skip( 1 ).All( l => l.Contains( option ) )\n select option;\n</code></pre>\n\n<p>If an option list cannot contain duplicate entires, the <code>Distinct</code> call is unnecessary. If the lists vary greatly in size, it would be better to iterate over the options in the shortest list, rather than whatever list happens to be <code>First</code>. Sorted or hashed collections could be used to improve the lookup time of the <code>Contains</code> call, though it should not make much difference for a moderate number of items.</p>\n"
},
{
"answer_id": 18097168,
"author": "logicnp",
"author_id": 51919,
"author_profile": "https://Stackoverflow.com/users/51919",
"pm_score": 0,
"selected": false,
"text": "<p>You can do this by counting occurrences of all items in all lists - those items whose occurrence count is equal to the number of lists, are common to all lists:</p>\n\n<pre><code> static List<T> FindCommon<T>(IEnumerable<List<T>> lists)\n {\n Dictionary<T, int> map = new Dictionary<T, int>();\n int listCount = 0; // number of lists\n\n foreach (IEnumerable<T> list in lists)\n {\n listCount++;\n foreach (T item in list)\n {\n // Item encountered, increment count\n int currCount;\n if (!map.TryGetValue(item, out currCount))\n currCount = 0;\n\n currCount++;\n map[item] = currCount;\n }\n }\n\n List<T> result= new List<T>();\n foreach (KeyValuePair<T,int> kvp in map)\n {\n // Items whose occurrence count is equal to the number of lists are common to all the lists\n if (kvp.Value == listCount)\n result.Add(kvp.Key);\n }\n\n return result;\n }\n</code></pre>\n"
},
{
"answer_id": 45240713,
"author": "user2102327",
"author_id": 2102327,
"author_profile": "https://Stackoverflow.com/users/2102327",
"pm_score": 0,
"selected": false,
"text": "<pre><code>/// <summary>\n /// The method FindCommonItems, returns a list of all the COMMON ITEMS in the lists contained in the listOfLists.\n /// The method expects lists containing NO DUPLICATE ITEMS.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"allSets\"></param>\n /// <returns></returns>\n public static List<T> FindCommonItems<T>(IEnumerable<List<T>> allSets)\n {\n Dictionary<T, int> map = new Dictionary<T, int>();\n int listCount = 0; // Number of lists.\n foreach (IEnumerable<T> currentSet in allSets)\n {\n int itemsCount = currentSet.ToList().Count;\n HashSet<T> uniqueItems = new HashSet<T>();\n bool duplicateItemEncountered = false;\n listCount++;\n foreach (T item in currentSet)\n {\n if (!uniqueItems.Add(item))\n {\n duplicateItemEncountered = true;\n } \n if (map.ContainsKey(item))\n {\n map[item]++;\n } \n else\n {\n map.Add(item, 1);\n }\n }\n if (duplicateItemEncountered)\n {\n uniqueItems.Clear();\n List<T> duplicateItems = new List<T>();\n StringBuilder currentSetItems = new StringBuilder();\n List<T> currentSetAsList = new List<T>(currentSet);\n for (int i = 0; i < itemsCount; i++)\n {\n T currentItem = currentSetAsList[i];\n if (!uniqueItems.Add(currentItem))\n {\n duplicateItems.Add(currentItem);\n }\n currentSetItems.Append(currentItem);\n if (i < itemsCount - 1)\n {\n currentSetItems.Append(\", \");\n }\n }\n StringBuilder duplicateItemsNamesEnumeration = new StringBuilder();\n int j = 0;\n foreach (T item in duplicateItems)\n {\n duplicateItemsNamesEnumeration.Append(item.ToString());\n if (j < uniqueItems.Count - 1)\n {\n duplicateItemsNamesEnumeration.Append(\", \");\n }\n }\n throw new Exception(\"The list \" + currentSetItems.ToString() + \" contains the following duplicate items: \" + duplicateItemsNamesEnumeration.ToString());\n }\n }\n List<T> result= new List<T>();\n foreach (KeyValuePair<T, int> itemAndItsCount in map)\n {\n if (itemAndItsCount.Value == listCount) // Items whose occurrence count is equal to the number of lists are common to all the lists.\n {\n result.Add(itemAndItsCount.Key);\n }\n }\n\n return result;\n }\n</code></pre>\n"
},
{
"answer_id": 45251772,
"author": "user2102327",
"author_id": 2102327,
"author_profile": "https://Stackoverflow.com/users/2102327",
"pm_score": 0,
"selected": false,
"text": "<p>@Skizz The method is not correct. It returns also items that are not common to all the lists in items.\nHere is the corrected method:</p>\n\n<pre><code>/// <summary>.\n /// The method FindAllCommonItemsInAllTheLists, returns a HashSet that contains all the common items in the lists contained in the listOfLists,\n /// regardless of the order of the items in the various lists.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"listOfLists\"></param>\n /// <returns></returns>\n public static HashSet<T> FindAllCommonItemsInAllTheLists<T>(List<List<T>> listOfLists)\n {\n if (listOfLists == null || listOfLists.Count == 0)\n {\n return null;\n }\n HashSet<T> currentCommon = new HashSet<T>();\n HashSet<T> common = new HashSet<T>();\n\n foreach (List<T> currentList in listOfLists)\n {\n if (currentCommon.Count == 0)\n {\n foreach (T item in currentList)\n {\n common.Add(item);\n }\n }\n else\n {\n foreach (T item in currentList)\n {\n if (currentCommon.Contains(item))\n {\n common.Add(item);\n }\n }\n }\n if (common.Count == 0)\n {\n currentCommon.Clear();\n break;\n }\n currentCommon.Clear(); // Empty currentCommon for a new iteration.\n foreach (T item in common) /* Copy all the items contained in common to currentCommon. \n * currentCommon = common; \n * does not work because thus currentCommon and common would point at the same object and \n * the next statement: \n * common.Clear();\n * will also clear currentCommon.\n */\n {\n if (!currentCommon.Contains(item))\n {\n currentCommon.Add(item);\n }\n }\n common.Clear();\n }\n\n return currentCommon;\n }\n</code></pre>\n"
},
{
"answer_id": 46712990,
"author": "birdus",
"author_id": 220899,
"author_profile": "https://Stackoverflow.com/users/220899",
"pm_score": 0,
"selected": false,
"text": "<p>After searching the 'net and not really coming up with something I liked (or that worked), I slept on it and came up with this. My <code>SearchResult</code> is similar to your <code>Option</code>. It has an <code>EmployeeId</code> in it and that's the thing I need to be common across lists. I return all records that have an <code>EmployeeId</code> in every list. It's not fancy, but it's simple and easy to understand, just what I like. For small lists (my case) it should perform just fine—and anyone can understand it!</p>\n\n<pre><code>private List<SearchResult> GetFinalSearchResults(IEnumerable<IEnumerable<SearchResult>> lists)\n{\n Dictionary<int, SearchResult> oldList = new Dictionary<int, SearchResult>();\n Dictionary<int, SearchResult> newList = new Dictionary<int, SearchResult>();\n\n oldList = lists.First().ToDictionary(x => x.EmployeeId, x => x);\n\n foreach (List<SearchResult> list in lists.Skip(1))\n {\n foreach (SearchResult emp in list)\n {\n if (oldList.Keys.Contains(emp.EmployeeId))\n {\n newList.Add(emp.EmployeeId, emp);\n }\n }\n\n oldList = new Dictionary<int, SearchResult>(newList);\n newList.Clear();\n }\n\n return oldList.Values.ToList();\n}\n</code></pre>\n"
},
{
"answer_id": 57379638,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 2,
"selected": false,
"text": "<p>Fastest to write :)</p>\n\n<pre><code>var subset = optionLists.Aggregate((x, y) => x.Intersect(y))\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3615/"
] | Given the following:
```
List<List<Option>> optionLists;
```
what would be a quick way to determine the subset of Option objects that appear in all N lists? Equality is determined through some string property such as option1.Value == option2.Value.
So we should end up with `List<Option>` where each item appears only once. | Ok, this will find the list of Option objects that have a Value appearing in *every* list.
```
var x = from list in optionLists
from option in list
where optionLists.All(l => l.Any(o => o.Value == option.Value))
orderby option.Value
select option;
```
It doesn't do a "distinct" select so it'll return multiple Option objects, some of them with the same Value. |
41,185 | <p>I'm doing a fair bit of work in Ruby recently, and using</p>
<pre><code> ruby script/console
</code></pre>
<p>Is absolutely critical. However, I'm really disappointed with the default Windows console in Vista, especially in that there's a really annoying bug where moving the cursor back when at the bottom of the screen irregularly causes it to jump back. Anyone have a decent console app they use in Windows?</p>
| [
{
"answer_id": 41190,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx\" rel=\"nofollow noreferrer\">Powershell</a></p>\n\n<blockquote>\n <p>Windows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework. PowerShell provides full access to COM and WMI, enabling administrators to perform administrative tasks on both local and remote Windows systems.</p>\n</blockquote>\n"
},
{
"answer_id": 41202,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 4,
"selected": true,
"text": "<p>I use <a href=\"http://sourceforge.net/projects/console/\" rel=\"nofollow noreferrer\">Console2</a>.</p>\n\n<p>I like the tabbed interface and that copy works properly if text breaks at the end of a line.</p>\n"
},
{
"answer_id": 41243,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 2,
"selected": false,
"text": "<p>I have had some pleasant experiences with rxvt (comes with cygwin, does not need an x server running). Putty is also often mentioned as a good alternative.</p>\n\n<p>You could also try to get xterm working :)</p>\n"
},
{
"answer_id": 41311,
"author": "Dominik Grabiec",
"author_id": 3719,
"author_profile": "https://Stackoverflow.com/users/3719",
"pm_score": 2,
"selected": false,
"text": "<p>Are you resizing the console window? I've found that the ruby scripts (irb, etc) that use the readline library don't work correctly with resized console windows (in XP or Vista).</p>\n\n<p>Effectively I believe that the readline library expects the console window to be 80 characters wide, anything else and it goes bezerk. So far I haven't found a way to fix it on windows without giving up other nice features.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
] | I'm doing a fair bit of work in Ruby recently, and using
```
ruby script/console
```
Is absolutely critical. However, I'm really disappointed with the default Windows console in Vista, especially in that there's a really annoying bug where moving the cursor back when at the bottom of the screen irregularly causes it to jump back. Anyone have a decent console app they use in Windows? | I use [Console2](http://sourceforge.net/projects/console/).
I like the tabbed interface and that copy works properly if text breaks at the end of a line. |
41,198 | <p>How can I get an image to stretch the height of a <code>DIV</code> class?</p>
<p>Currently it looks like this:</p>
<p><img src="https://i.stack.imgur.com/DcrXC.png" width="650" /></p>
<p>However, I would like the <code>DIV</code> to be stretched so the <code>image</code> fits properly, but I do not want to resize the `image.</p>
<p>Here is the CSS for the <code>DIV</code> (the grey box):</p>
<pre class="lang-css prettyprint-override"><code>.product1 {
width: 100%;
padding: 5px;
margin: 0px 0px 15px -5px;
background: #ADA19A;
color: #000000;
min-height: 100px;
}
</code></pre>
<p>The CSS being applied on the image:</p>
<pre class="lang-css prettyprint-override"><code>.product{
display: inline;
float: left;
}
</code></pre>
<p>So, how can I fix this?</p>
| [
{
"answer_id": 41201,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 1,
"selected": false,
"text": "<pre><code>display:inline \nfloat:left \n</code></pre>\n\n<p>is your problem</p>\n\n<p>Floating makes the parents width not be stretched by the child, try placing the image without the float. If you take the float off, it should give you the desired effect.<br>\nAnother approach would be to make sure you are clearing your floats at the end of the parent element so that they don't scope creep.</p>\n\n<p><strong>Update:</strong> After viewing your link Your height issue as displayed, is because the floats are not being cleared.</p>\n"
},
{
"answer_id": 41203,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p>In the markup after the image, insert something like <code><div style=\"clear:left\"/></code>. A bit messy, but it's the easiest way I've found.</p>\n\n<p>And while you're at it, put a bit of margin on that image so the text doesn't butt up against it.</p>\n"
},
{
"answer_id": 41232,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming @John Millikin is correct, the code</p>\n\n<pre><code>.product + * { clear: left; }\n</code></pre>\n\n<p>would suffice to do the same thing without forcing you to manually adjust the code after the div.</p>\n"
},
{
"answer_id": 41235,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 6,
"selected": true,
"text": "<p>Add <code>overflow:auto;</code> to <code>.product1</code></p>\n"
},
{
"answer_id": 42090,
"author": "Jeremy",
"author_id": 2076253,
"author_profile": "https://Stackoverflow.com/users/2076253",
"pm_score": 2,
"selected": false,
"text": "<p>One trick you can use is to set the <code><div></code>'s overflow property to hidden. This forces browsers to calculate the physical size of the box, and fixes the weird overlap problem with the floated image. It will save you from adding in any extra HTML markup.</p>\n\n<p>Here's how the class should look:</p>\n\n<pre><code>.product1 {\n width: 100%;\n padding: 5px;\n margin: 0px 0px 15px -5px;\n background: #ADA19A;\n color: #000000;\n min-height: 100px;\n overflow: hidden;\n}\n</code></pre>\n"
},
{
"answer_id": 47810,
"author": "David Heggie",
"author_id": 4309,
"author_profile": "https://Stackoverflow.com/users/4309",
"pm_score": 2,
"selected": false,
"text": "<p>This looks like a job for <a href=\"http://www.positioniseverything.net/easyclearing.html\" rel=\"nofollow noreferrer\">clearfix</a> to me ...</p>\n"
},
{
"answer_id": 8324360,
"author": "Palanikumar",
"author_id": 1019435,
"author_profile": "https://Stackoverflow.com/users/1019435",
"pm_score": 2,
"selected": false,
"text": "<p>Try the following:</p>\n\n<pre><code>.Strech\n{\n background:url(image.jpg);\n background-size:100% 100%;\n background-repeat:no-repeat;\n\n width:500px;\n height:500px;\n}\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] | How can I get an image to stretch the height of a `DIV` class?
Currently it looks like this:

However, I would like the `DIV` to be stretched so the `image` fits properly, but I do not want to resize the `image.
Here is the CSS for the `DIV` (the grey box):
```css
.product1 {
width: 100%;
padding: 5px;
margin: 0px 0px 15px -5px;
background: #ADA19A;
color: #000000;
min-height: 100px;
}
```
The CSS being applied on the image:
```css
.product{
display: inline;
float: left;
}
```
So, how can I fix this? | Add `overflow:auto;` to `.product1` |
41,204 | <p>Is there a fast and clean way of returning a JSON hash back from any node in a Ruby on Rails' acts_as_nested_set without using recursion?</p>
<p>Here's the recursive solution for reference:</p>
<pre><code>class Node < ActiveRecord::Base
has_many :products
def json_hash
if children.size > 0
children.collect { |node| { node.name => node.json_hash }.to_json
else
{ node.name => node.products.find(:all).collect(&:name) }.to_json
end
end
end
</code></pre>
| [
{
"answer_id": 41275,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>There is a <a href=\"http://en.wikipedia.org/wiki/Tree_traversal\" rel=\"nofollow noreferrer\">wikipedia article</a> on tree traversal which shows different alternatives to the recursive solution you are using. It may be tricky to use them in your specific case, but it should be possible.</p>\n\n<p>However, my question to you is, is there a specific reason you want to use iteration instead of recursion? I don't think any of the iterative solutions will be nearly as clean. Are your trees so big that you are running out of stack space (they would have to be pretty big)? Otherwise, I'm not so sure an iterative solution will really be faster.</p>\n\n<p>I see one potential for improvement though, if you are seeing performance issues... but I don't know rails, so I'm not sure if it is accurate:</p>\n\n<p>Does the find method return a new array? If so, you probably want to invoke .collect! instead of .collect, because if find creates an array, you are just creating an array and then throwing it away to the call to collect (which also creates an array), which surely is not going to be very efficient and may slow you down a lot if you have a big tree there.</p>\n\n<p>So </p>\n\n<pre><code>{ node.name => node.products.find(:all).collect(&:name) }.to_json\n</code></pre>\n\n<p>might become</p>\n\n<pre><code>{ node.name => node.products.find(:all).collect!(&:name) }.to_json\n</code></pre>\n\n<p>EDIT: Also, it may be more efficient to create your hash of hashes, and then convert the whole thing to json in 1 fell swoop, rather than converting it piecemail like you are doing.</p>\n\n<p>So</p>\n\n<pre><code>class Node < ActiveRecord::Base\n has_many :products\n def json_hash\n if children.size > 0\n children.collect { |node| { node.name => node.json_hash }.to_json\n else\n { node.name => node.products.find(:all).collect!(&:name) }.to_json\n end\n end\nend\n</code></pre>\n\n<p>might become</p>\n\n<pre><code>class Node < ActiveRecord::Base\n has_many :products\n def json_hash\n to_hash.to_json\n end\n\n def to_hash\n if children.size > 0\n children.collect { |node| { node.name => node.to_hash }\n else\n { node.name => node.products.find(:all).collect!(&:name) }\n end\n end\nend\n</code></pre>\n\n<p>Whether this works and is more efficient I leave as an exercise for you ;-)</p>\n"
},
{
"answer_id": 3587874,
"author": "standup75",
"author_id": 433333,
"author_profile": "https://Stackoverflow.com/users/433333",
"pm_score": 1,
"selected": false,
"text": "<p>JSONifier!</p>\n\n<pre><code>node.to_json(:include=>{:products=>{:include=>:product_parts}})\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3499/"
] | Is there a fast and clean way of returning a JSON hash back from any node in a Ruby on Rails' acts\_as\_nested\_set without using recursion?
Here's the recursive solution for reference:
```
class Node < ActiveRecord::Base
has_many :products
def json_hash
if children.size > 0
children.collect { |node| { node.name => node.json_hash }.to_json
else
{ node.name => node.products.find(:all).collect(&:name) }.to_json
end
end
end
``` | There is a [wikipedia article](http://en.wikipedia.org/wiki/Tree_traversal) on tree traversal which shows different alternatives to the recursive solution you are using. It may be tricky to use them in your specific case, but it should be possible.
However, my question to you is, is there a specific reason you want to use iteration instead of recursion? I don't think any of the iterative solutions will be nearly as clean. Are your trees so big that you are running out of stack space (they would have to be pretty big)? Otherwise, I'm not so sure an iterative solution will really be faster.
I see one potential for improvement though, if you are seeing performance issues... but I don't know rails, so I'm not sure if it is accurate:
Does the find method return a new array? If so, you probably want to invoke .collect! instead of .collect, because if find creates an array, you are just creating an array and then throwing it away to the call to collect (which also creates an array), which surely is not going to be very efficient and may slow you down a lot if you have a big tree there.
So
```
{ node.name => node.products.find(:all).collect(&:name) }.to_json
```
might become
```
{ node.name => node.products.find(:all).collect!(&:name) }.to_json
```
EDIT: Also, it may be more efficient to create your hash of hashes, and then convert the whole thing to json in 1 fell swoop, rather than converting it piecemail like you are doing.
So
```
class Node < ActiveRecord::Base
has_many :products
def json_hash
if children.size > 0
children.collect { |node| { node.name => node.json_hash }.to_json
else
{ node.name => node.products.find(:all).collect!(&:name) }.to_json
end
end
end
```
might become
```
class Node < ActiveRecord::Base
has_many :products
def json_hash
to_hash.to_json
end
def to_hash
if children.size > 0
children.collect { |node| { node.name => node.to_hash }
else
{ node.name => node.products.find(:all).collect!(&:name) }
end
end
end
```
Whether this works and is more efficient I leave as an exercise for you ;-) |
41,218 | <p>I am running MAMP locally on my laptop, and I like to test as much as I can locally. Unfortunately, since I work on e-commerce stuff (PHP), I normally force ssl in most of the checkout forms and it just fails on my laptop. Is there any easy configuration that I might be missing to allow "https" to run under MAMP? Please note, I know that I <strong>could</strong> configure Apache by hand, re-compile PHP, etc. but I'm just wondering if there's an easier way for a lazy programmer.</p>
<p>Thanks</p>
| [
{
"answer_id": 41272,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 2,
"selected": false,
"text": "<p>There doesn't seem to be an easier way, <a href=\"http://www.rocketwerx.com/blog/8-apple/34-getting-ssl-to-work-with-mamp-pro\" rel=\"nofollow noreferrer\">unless you're willing to buy MAMP Pro</a>.</p>\n\n<p>As far as I know, the only way to use SSL with MAMP is to <a href=\"http://www.macosxhints.com/article.php?story=20041129143420344\" rel=\"nofollow noreferrer\">configure mod_ssl for Apache</a>. mod_ssl is bundled with MAMP, and I found configuration to be pretty straightforward. Note that you'll probably have to start Apache from the command line to use it:</p>\n\n<pre><code>/Applications/MAMP/bin/apache2/bin$ ./apachectl stop\n/Applications/MAMP/bin/apache2/bin$ sudo ./apachectl startssl\n</code></pre>\n"
},
{
"answer_id": 43384,
"author": "Rodney Amato",
"author_id": 4342,
"author_profile": "https://Stackoverflow.com/users/4342",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p><strong>NOTE: startssl is no longer supported after version 2+ of MAMP. You\n have to update the config files (httpd.conf) to enable ssl.</strong></p>\n</blockquote>\n\n<p>You can modify the free version of MAMP to enable ssl by default very easily. Once you have setup all the SSL parts of apache and have it working so that calling apachectl startssl works, just edit the file </p>\n\n<pre><code>/Applications/MAMP/startApache.sh\n</code></pre>\n\n<p>in your favorite text editor and change the <strong>start</strong> argument to <strong>startssl</strong> and you will have the MAMP launcher starting apache in ssl mode for you.</p>\n"
},
{
"answer_id": 1795144,
"author": "Riley",
"author_id": 218358,
"author_profile": "https://Stackoverflow.com/users/218358",
"pm_score": 5,
"selected": false,
"text": "<p>First, make a duplicate of /Applications/MAMP.</p>\n\n<p>Open /Applications/MAMP/conf/apache/httpd.conf<br>\nBelow the line<br>\n<code># LoadModule foo_module modules/mod_foo.so</code><br>\nyou add<br>\n<code>LoadModule ssl_module modules/mod_ssl.so</code><br>\nRemove all lines <code><IfDefine SSL></code> as well as <code></IfDefine SSL></code>.<br></p>\n\n<p>Open /Applications/MAMP/conf/apache/ssl.conf<br>\nRemove all lines <code><IfDefine SSL></code> as well as <code></IfDefine SSL></code>.<br>\nFind the line defining <code>SSLCertificateFile</code> and <code>SSLCertificateKeyFile</code>, set it to<br>\n<code>SSLCertificateFile /Applications/MAMP/conf/apache/ssl/server.crt</code>\n<code>SSLCertificateKeyFile /Applications/MAMP/conf/apache/ssl/server.key</code></p>\n\n<p>Create a new folder /Applications/MAMP/conf/apache/ssl<br>\nDrop into the terminal an navigate to the new folder<br>\n<code>cd /Applications/MAMP/conf/apache/ssl</code><br>\nCreate a private key, giving a password<br>\n<code>openssl genrsa -des3 -out server.key 1024</code><br>\nRemove the password<br>\n<code>cp server.key server-pw.key</code><br>\n<code>openssl rsa -in server-pw.key -out server.key</code><br>\nCreate a certificate signing request, pressing return for default values<br>\n<code>openssl req -new -key server.key -out server.csr</code><br>\nCreate a certificate<br>\n<code>openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt</code></p>\n\n<p>Restart your server. If you encounter any problems check the system log file. The first time you visit <code>https://localhost/</code> you will be asked to accept the certificate.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4247/"
] | I am running MAMP locally on my laptop, and I like to test as much as I can locally. Unfortunately, since I work on e-commerce stuff (PHP), I normally force ssl in most of the checkout forms and it just fails on my laptop. Is there any easy configuration that I might be missing to allow "https" to run under MAMP? Please note, I know that I **could** configure Apache by hand, re-compile PHP, etc. but I'm just wondering if there's an easier way for a lazy programmer.
Thanks | >
> **NOTE: startssl is no longer supported after version 2+ of MAMP. You
> have to update the config files (httpd.conf) to enable ssl.**
>
>
>
You can modify the free version of MAMP to enable ssl by default very easily. Once you have setup all the SSL parts of apache and have it working so that calling apachectl startssl works, just edit the file
```
/Applications/MAMP/startApache.sh
```
in your favorite text editor and change the **start** argument to **startssl** and you will have the MAMP launcher starting apache in ssl mode for you. |
41,239 | <p>I am pretty sure that the settings that I am using are correct, so all possible things can be wrong which I should check out so that I can make authentication with our Active Directory work.</p>
| [
{
"answer_id": 41247,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 1,
"selected": false,
"text": "<p>Try test if PHP can connect to active directory</p>\n\n<pre><code><?php\n$ds = ldap_connect('host.ad.lan', 389);\nldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);\nldap_set_option($ds, LDAP_OPT_REFERRALS, 0);\nldap_bind($ds, '[email protected]', 'xxx');\n$sr = ldap_search($ds, 'CN=Cameron Zemek,OU=Users,OU=BRC,DC=ad,DC=lan', '(objectclass=*)', array('cn'));\n$entryID = ldap_first_entry($ds, $sr);\n$data = ldap_get_attributes($ds, $entryID);\nprint_r($data);\nldap_close($ds);\n</code></pre>\n\n<p>What do you have has your $config['ldap_user'] and $config['ldap_uid'] ? You want to set $config['ldap_uid'] to sAMAccountName</p>\n"
},
{
"answer_id": 43470,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 0,
"selected": false,
"text": "<p>@grom... thanks but, yes PHP is working just fine. I have a WordPress and a MediaWiki installation on the same server, and they are both authenticating against the same active directory just fine.</p>\n"
},
{
"answer_id": 6303827,
"author": "Andrey Regentov",
"author_id": 772853,
"author_profile": "https://Stackoverflow.com/users/772853",
"pm_score": 1,
"selected": false,
"text": "<p>There is a trick to do activeDirectory auth with phpbb3. You should:</p>\n\n<ul>\n<li>make an account in phpBB with a name identical to some AD-name</li>\n<li>give this account admin/founder rights in phpBB</li>\n<li>login with this account</li>\n<li>set up auth parameters from within this account</li>\n</ul>\n\n<p>By the way, what error messages do you get from phpBB?</p>\n"
},
{
"answer_id": 45745926,
"author": "incrementor",
"author_id": 1203340,
"author_profile": "https://Stackoverflow.com/users/1203340",
"pm_score": 0,
"selected": false,
"text": "<p>phpBB3 does not offer much info about how to enable LDAPS, so I hope this helps someone...</p>\n\n<p>Note that you may need to actually clear all phpBB3 cookies immediately after the base installation. This will allow the admin user to see the ACP. Once you are able to consistently log into phpBB3 as an admin, and want to enable LDAPS authentication, do the following (tested with AD and Debian stretch): </p>\n\n<ul>\n<li><p>Obtain the root TLS certificate from your AD/LDAP Administrator, or get it yourself with something like:</p>\n\n<p><code># openssl s_client -showcerts -connect google.com:443</code></p></li>\n</ul>\n\n<p>See the MediaWiki documentation, as phpBB3 docs are quite sparse:\n<a href=\"https://www.mediawiki.org/wiki/Extension:LDAP_Authentication/Requirements\" rel=\"nofollow noreferrer\">https://www.mediawiki.org/wiki/Extension:LDAP_Authentication/Requirements</a></p>\n\n<ul>\n<li><p>Install the PEM formatted certificate with a .crt name into your OS certificate store. For Debian based systems, that would be <code>/usr/local/share/ca-certificates</code> then run <code># dpkg-reconfigure ca-certificates</code></p></li>\n<li><p>Configure <code>/etc/ldap/ldap.conf</code> to your local settings. Note that port 3268 may not have in-built limits like 686 with AD. YMMV.</p></li>\n<li><p>Create a special AD user for binding. Give it permissions to lookup, but not to change, attributes. Confirm that the credentials work with ldapsearch. eg: <code>ldapsearch -x -LLL -h ad.mydomain.com -D binduser -W -z 30 -b \"dc=mydomain,dc=com\" searchString</code></p></li>\n<li><p>Create a phpBB3 user with the same username as the above AD bind user. As the phpBB3 admin, grant the AD bind user Founder permissions.</p></li>\n<li><p>Using a different browser, log into phpBB3 as the binduser, then set up the LDAP Authentication as that user. (As noted in the above post).</p></li>\n<li><p>Test it! Logout of phpBB3 and then login again using the LDAP/AD credentials.</p></li>\n</ul>\n\n<p>If that does not work, the PHP dev documentation is quite good, and offers many comments with examples and example code to try. </p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
] | I am pretty sure that the settings that I am using are correct, so all possible things can be wrong which I should check out so that I can make authentication with our Active Directory work. | Try test if PHP can connect to active directory
```
<?php
$ds = ldap_connect('host.ad.lan', 389);
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
ldap_bind($ds, '[email protected]', 'xxx');
$sr = ldap_search($ds, 'CN=Cameron Zemek,OU=Users,OU=BRC,DC=ad,DC=lan', '(objectclass=*)', array('cn'));
$entryID = ldap_first_entry($ds, $sr);
$data = ldap_get_attributes($ds, $entryID);
print_r($data);
ldap_close($ds);
```
What do you have has your $config['ldap\_user'] and $config['ldap\_uid'] ? You want to set $config['ldap\_uid'] to sAMAccountName |
41,244 | <p>I found an example in the <a href="http://msdn2.microsoft.com/en-us/bb330936.aspx" rel="noreferrer">VS2008 Examples</a> for Dynamic LINQ that allows you to use a SQL-like string (e.g. <code>OrderBy("Name, Age DESC"))</code> for ordering. Unfortunately, the method included only works on <code>IQueryable<T></code>. Is there any way to get this functionality on <code>IEnumerable<T></code>?</p>
| [
{
"answer_id": 41262,
"author": "Kjetil Watnedal",
"author_id": 4116,
"author_profile": "https://Stackoverflow.com/users/4116",
"pm_score": 6,
"selected": false,
"text": "<p>I guess it would work to use reflection to get whatever property you want to sort on:</p>\n\n<pre><code>IEnumerable<T> myEnumerables\nvar query=from enumerable in myenumerables\n where some criteria\n orderby GetPropertyValue(enumerable,\"SomeProperty\")\n select enumerable\n\nprivate static object GetPropertyValue(object obj, string property)\n{\n System.Reflection.PropertyInfo propertyInfo=obj.GetType().GetProperty(property);\n return propertyInfo.GetValue(obj, null);\n}\n</code></pre>\n\n<p>Note that using reflection is considerably slower than accessing the property directly, so the performance would have to be investigated.</p>\n"
},
{
"answer_id": 41427,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<p>You could add it:</p>\n\n<pre><code>public static IEnumerable<T> OrderBy( this IEnumerable<T> input, string queryString) {\n //parse the string into property names\n //Use reflection to get and sort by properties\n //something like\n\n foreach( string propname in queryString.Split(','))\n input.OrderBy( x => GetPropertyValue( x, propname ) );\n\n // I used Kjetil Watnedal's reflection example\n}\n</code></pre>\n\n<p>The <code>GetPropertyValue</code> function is from <a href=\"https://stackoverflow.com/questions/41244/dynamic-linq-orderby#41262\">Kjetil Watnedal's answer</a></p>\n\n<p>The issue would be why? Any such sort would throw exceptions at run-time, rather than compile time (like D2VIANT's answer).</p>\n\n<p>If you're dealing with Linq to Sql and the orderby is an expression tree it will be converted into SQL for execution anyway.</p>\n"
},
{
"answer_id": 233505,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 11,
"selected": true,
"text": "<p>Just stumbled into this oldie...</p>\n\n<p>To do this without the dynamic LINQ library, you just need the code as below. This covers most common scenarios including nested properties.</p>\n\n<p>To get it working with <code>IEnumerable<T></code> you could add some wrapper methods that go via <code>AsQueryable</code> - but the code below is the core <code>Expression</code> logic needed.</p>\n\n<pre><code>public static IOrderedQueryable<T> OrderBy<T>(\n this IQueryable<T> source, \n string property)\n{\n return ApplyOrder<T>(source, property, \"OrderBy\");\n}\n\npublic static IOrderedQueryable<T> OrderByDescending<T>(\n this IQueryable<T> source, \n string property)\n{\n return ApplyOrder<T>(source, property, \"OrderByDescending\");\n}\n\npublic static IOrderedQueryable<T> ThenBy<T>(\n this IOrderedQueryable<T> source, \n string property)\n{\n return ApplyOrder<T>(source, property, \"ThenBy\");\n}\n\npublic static IOrderedQueryable<T> ThenByDescending<T>(\n this IOrderedQueryable<T> source, \n string property)\n{\n return ApplyOrder<T>(source, property, \"ThenByDescending\");\n}\n\nstatic IOrderedQueryable<T> ApplyOrder<T>(\n IQueryable<T> source, \n string property, \n string methodName) \n{\n string[] props = property.Split('.');\n Type type = typeof(T);\n ParameterExpression arg = Expression.Parameter(type, \"x\");\n Expression expr = arg;\n foreach(string prop in props) {\n // use reflection (not ComponentModel) to mirror LINQ\n PropertyInfo pi = type.GetProperty(prop);\n expr = Expression.Property(expr, pi);\n type = pi.PropertyType;\n }\n Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);\n LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);\n\n object result = typeof(Queryable).GetMethods().Single(\n method => method.Name == methodName\n && method.IsGenericMethodDefinition\n && method.GetGenericArguments().Length == 2\n && method.GetParameters().Length == 2)\n .MakeGenericMethod(typeof(T), type)\n .Invoke(null, new object[] {source, lambda});\n return (IOrderedQueryable<T>)result;\n}\n</code></pre>\n\n<hr>\n\n<p>Edit: it gets more fun if you want to mix that with <code>dynamic</code> - although note that <code>dynamic</code> only applies to LINQ-to-Objects (expression-trees for ORMs etc can't really represent <code>dynamic</code> queries - <code>MemberExpression</code> doesn't support it). But here's a way to do it with LINQ-to-Objects. Note that the choice of <code>Hashtable</code> is due to favorable locking semantics:</p>\n\n<pre><code>using Microsoft.CSharp.RuntimeBinder;\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Dynamic;\nusing System.Linq;\nusing System.Runtime.CompilerServices;\nstatic class Program\n{\n private static class AccessorCache\n {\n private static readonly Hashtable accessors = new Hashtable();\n\n private static readonly Hashtable callSites = new Hashtable();\n\n private static CallSite<Func<CallSite, object, object>> GetCallSiteLocked(\n string name) \n {\n var callSite = (CallSite<Func<CallSite, object, object>>)callSites[name];\n if(callSite == null)\n {\n callSites[name] = callSite = CallSite<Func<CallSite, object, object>>\n .Create(Binder.GetMember(\n CSharpBinderFlags.None, \n name, \n typeof(AccessorCache),\n new CSharpArgumentInfo[] { \n CSharpArgumentInfo.Create(\n CSharpArgumentInfoFlags.None, \n null) \n }));\n }\n return callSite;\n }\n\n internal static Func<dynamic,object> GetAccessor(string name)\n {\n Func<dynamic, object> accessor = (Func<dynamic, object>)accessors[name];\n if (accessor == null)\n {\n lock (accessors )\n {\n accessor = (Func<dynamic, object>)accessors[name];\n if (accessor == null)\n {\n if(name.IndexOf('.') >= 0) {\n string[] props = name.Split('.');\n CallSite<Func<CallSite, object, object>>[] arr \n = Array.ConvertAll(props, GetCallSiteLocked);\n accessor = target =>\n {\n object val = (object)target;\n for (int i = 0; i < arr.Length; i++)\n {\n var cs = arr[i];\n val = cs.Target(cs, val);\n }\n return val;\n };\n } else {\n var callSite = GetCallSiteLocked(name);\n accessor = target =>\n {\n return callSite.Target(callSite, (object)target);\n };\n }\n accessors[name] = accessor;\n }\n }\n }\n return accessor;\n }\n }\n\n public static IOrderedEnumerable<dynamic> OrderBy(\n this IEnumerable<dynamic> source, \n string property)\n {\n return Enumerable.OrderBy<dynamic, object>(\n source, \n AccessorCache.GetAccessor(property), \n Comparer<object>.Default);\n }\n\n public static IOrderedEnumerable<dynamic> OrderByDescending(\n this IEnumerable<dynamic> source, \n string property)\n {\n return Enumerable.OrderByDescending<dynamic, object>(\n source, \n AccessorCache.GetAccessor(property), \n Comparer<object>.Default);\n }\n\n public static IOrderedEnumerable<dynamic> ThenBy(\n this IOrderedEnumerable<dynamic> source, \n string property)\n {\n return Enumerable.ThenBy<dynamic, object>(\n source, \n AccessorCache.GetAccessor(property), \n Comparer<object>.Default);\n }\n\n public static IOrderedEnumerable<dynamic> ThenByDescending(\n this IOrderedEnumerable<dynamic> source, \n string property)\n {\n return Enumerable.ThenByDescending<dynamic, object>(\n source, \n AccessorCache.GetAccessor(property), \n Comparer<object>.Default);\n }\n\n static void Main()\n {\n dynamic a = new ExpandoObject(), \n b = new ExpandoObject(), \n c = new ExpandoObject();\n a.X = \"abc\";\n b.X = \"ghi\";\n c.X = \"def\";\n dynamic[] data = new[] { \n new { Y = a },\n new { Y = b }, \n new { Y = c } \n };\n\n var ordered = data.OrderByDescending(\"Y.X\").ToArray();\n foreach (var obj in ordered)\n {\n Console.WriteLine(obj.Y.X);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 370126,
"author": "InfoStatus",
"author_id": 41385,
"author_profile": "https://Stackoverflow.com/users/41385",
"pm_score": 3,
"selected": false,
"text": "<p>I've stumble this question looking for Linq multiple orderby clauses\nand maybe this was what the author was looking for</p>\n\n<p>Here's how to do that:</p>\n\n<pre><code>var query = pets.OrderBy(pet => pet.Name).ThenByDescending(pet => pet.Age); \n</code></pre>\n"
},
{
"answer_id": 649026,
"author": "Mike Christiansen",
"author_id": 29249,
"author_profile": "https://Stackoverflow.com/users/29249",
"pm_score": 2,
"selected": false,
"text": "<p>An alternate solution uses the following class/interface. It's not truly dynamic, but it works.</p>\n\n<pre><code>public interface IID\n{\n int ID\n {\n get; set;\n }\n}\n\npublic static class Utils\n{\n public static int GetID<T>(ObjectQuery<T> items) where T:EntityObject, IID\n {\n if (items.Count() == 0) return 1;\n return items.OrderByDescending(u => u.ID).FirstOrDefault().ID + 1;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 704341,
"author": "vdhant",
"author_id": 30572,
"author_profile": "https://Stackoverflow.com/users/30572",
"pm_score": 5,
"selected": false,
"text": "<p>Just building on what others have said. I found that the following works quite well.</p>\n\n<pre><code>public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> input, string queryString)\n{\n if (string.IsNullOrEmpty(queryString))\n return input;\n\n int i = 0;\n foreach (string propname in queryString.Split(','))\n {\n var subContent = propname.Split('|');\n if (Convert.ToInt32(subContent[1].Trim()) == 0)\n {\n if (i == 0)\n input = input.OrderBy(x => GetPropertyValue(x, subContent[0].Trim()));\n else\n input = ((IOrderedEnumerable<T>)input).ThenBy(x => GetPropertyValue(x, subContent[0].Trim()));\n }\n else\n {\n if (i == 0)\n input = input.OrderByDescending(x => GetPropertyValue(x, subContent[0].Trim()));\n else\n input = ((IOrderedEnumerable<T>)input).ThenByDescending(x => GetPropertyValue(x, subContent[0].Trim()));\n }\n i++;\n }\n\n return input;\n}\n</code></pre>\n"
},
{
"answer_id": 1642942,
"author": "James McCormack",
"author_id": 71906,
"author_profile": "https://Stackoverflow.com/users/71906",
"pm_score": 4,
"selected": false,
"text": "<p>I was trying to do this but having problems with <a href=\"https://stackoverflow.com/questions/41244/dynamic-linq-orderby#41262\">Kjetil Watnedal's solution</a> because I don't use the inline linq syntax - I prefer method-style syntax. My specific problem was in trying to do dynamic sorting using a custom <code>IComparer</code>.</p>\n\n<p>My solution ended up like this:</p>\n\n<p>Given an IQueryable query like so:</p>\n\n<pre><code>List<DATA__Security__Team> teams = TeamManager.GetTeams();\nvar query = teams.Where(team => team.ID < 10).AsQueryable();\n</code></pre>\n\n<p>And given a run-time sort field argument:</p>\n\n<pre><code>string SortField; // Set at run-time to \"Name\"\n</code></pre>\n\n<p>The dynamic OrderBy looks like so:</p>\n\n<pre><code>query = query.OrderBy(item => item.GetReflectedPropertyValue(SortField));\n</code></pre>\n\n<p>And that's using a little helper method called GetReflectedPropertyValue():</p>\n\n<pre><code>public static string GetReflectedPropertyValue(this object subject, string field)\n{\n object reflectedValue = subject.GetType().GetProperty(field).GetValue(subject, null);\n return reflectedValue != null ? reflectedValue.ToString() : \"\";\n}\n</code></pre>\n\n<hr>\n\n<p>One last thing - I mentioned that I wanted the <code>OrderBy</code> to use custom <code>IComparer</code> - because I wanted to do <a href=\"https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/\" rel=\"noreferrer\">Natural sorting</a>.</p>\n\n<p>To do that, I just alter the <code>OrderBy</code> to:</p>\n\n<pre><code>query = query.OrderBy(item => item.GetReflectedPropertyValue(SortField), new NaturalSortComparer<string>());\n</code></pre>\n\n<p>See <a href=\"http://zootfroot.blogspot.com/2009/09/natural-sort-compare-with-linq-orderby.html\" rel=\"noreferrer\">this post</a> for the code for <code>NaturalSortComparer()</code>.</p>\n"
},
{
"answer_id": 2058305,
"author": "Sameer Alibhai",
"author_id": 2343,
"author_profile": "https://Stackoverflow.com/users/2343",
"pm_score": 2,
"selected": false,
"text": "<p>Here's something else I found interesting.\nIf your source is a DataTable, you can use dynamic sorting without using Dynamic Linq</p>\n\n<pre><code>DataTable orders = dataSet.Tables[\"SalesOrderHeader\"];\nEnumerableRowCollection<DataRow> query = from order in orders.AsEnumerable()\n orderby order.Field<DateTime>(\"OrderDate\")\n select order;\nDataView view = query.AsDataView();\nbindingSource1.DataSource = view;\n</code></pre>\n\n<p>reference: <a href=\"http://msdn.microsoft.com/en-us/library/bb669083.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb669083.aspx</a> (Using DataSetExtensions)</p>\n\n<p>Here is one more way to do it by converting it to a DataView:</p>\n\n<pre><code>DataTable contacts = dataSet.Tables[\"Contact\"]; \nDataView view = contacts.AsDataView(); \nview.Sort = \"LastName desc, FirstName asc\"; \nbindingSource1.DataSource = view;\ndataGridView1.AutoResizeColumns();\n</code></pre>\n"
},
{
"answer_id": 3508411,
"author": "Adam Anderson",
"author_id": 302998,
"author_profile": "https://Stackoverflow.com/users/302998",
"pm_score": 6,
"selected": false,
"text": "<p>Just stumbled across this question.</p>\n\n<p>Using Marc's ApplyOrder implementation from above, I slapped together an Extension method that handles SQL-like strings like:</p>\n\n<pre><code>list.OrderBy(\"MyProperty DESC, MyOtherProperty ASC\");\n</code></pre>\n\n<p>Details can be found here: <a href=\"http://aonnull.blogspot.com/2010/08/dynamic-sql-like-linq-orderby-extension.html\" rel=\"noreferrer\">http://aonnull.blogspot.com/2010/08/dynamic-sql-like-linq-orderby-extension.html</a></p>\n"
},
{
"answer_id": 8660293,
"author": "Alaa Osta",
"author_id": 456156,
"author_profile": "https://Stackoverflow.com/users/456156",
"pm_score": 8,
"selected": false,
"text": "<p>Too easy without any complication:</p>\n<ol>\n<li>Add <code>using System.Linq.Dynamic;</code> at the top.</li>\n<li>Use <code>vehicles = vehicles.AsQueryable().OrderBy("Make ASC, Year DESC").ToList();</code></li>\n</ol>\n<p><strong>Edit</strong>: to save some time, the <strong>System.Linq.Dynamic.Core</strong> (System.Linq.Dynamic is deprecated) assembly is not part of the framework, but can be installed from nuget: <a href=\"https://www.nuget.org/packages/System.Linq.Dynamic.Core/\" rel=\"noreferrer\">System.Linq.Dynamic.Core</a></p>\n"
},
{
"answer_id": 12920204,
"author": "joaopintocruz",
"author_id": 1139347,
"author_profile": "https://Stackoverflow.com/users/1139347",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks to Maarten (<a href=\"https://stackoverflow.com/questions/11431546/query-a-collection-using-propertyinfo-object-in-linq\">Query a collection using PropertyInfo object in LINQ</a>) I got this solution:</p>\n\n<pre><code>myList.OrderByDescending(x => myPropertyInfo.GetValue(x, null)).ToList();\n</code></pre>\n\n<p>In my case I was working on a \"ColumnHeaderMouseClick\" (WindowsForm) so just found the specific Column pressed and its correspondent PropertyInfo:</p>\n\n<pre><code>foreach (PropertyInfo column in (new Process()).GetType().GetProperties())\n{\n if (column.Name == dgvProcessList.Columns[e.ColumnIndex].Name)\n {}\n}\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>PropertyInfo column = (new Process()).GetType().GetProperties().Where(x => x.Name == dgvProcessList.Columns[e.ColumnIndex].Name).First();\n</code></pre>\n\n<p>(be sure to have your column Names matching the object Properties)</p>\n\n<p>Cheers</p>\n"
},
{
"answer_id": 16046948,
"author": "Sanchitos",
"author_id": 317832,
"author_profile": "https://Stackoverflow.com/users/317832",
"pm_score": 3,
"selected": false,
"text": "<p>After a lot of searching this worked for me:</p>\n\n<pre><code>public static IEnumerable<TEntity> OrderBy<TEntity>(this IEnumerable<TEntity> source, \n string orderByProperty, bool desc)\n{\n string command = desc ? \"OrderByDescending\" : \"OrderBy\";\n var type = typeof(TEntity);\n var property = type.GetProperty(orderByProperty);\n var parameter = Expression.Parameter(type, \"p\");\n var propertyAccess = Expression.MakeMemberAccess(parameter, property);\n var orderByExpression = Expression.Lambda(propertyAccess, parameter);\n var resultExpression = Expression.Call(typeof(Queryable), command, \n new[] { type, property.PropertyType },\n source.AsQueryable().Expression, \n Expression.Quote(orderByExpression));\n return source.AsQueryable().Provider.CreateQuery<TEntity>(resultExpression);\n}\n</code></pre>\n"
},
{
"answer_id": 18062130,
"author": "user145610",
"author_id": 145610,
"author_profile": "https://Stackoverflow.com/users/145610",
"pm_score": 0,
"selected": false,
"text": "<p>Convert List to IEnumerable or Iquerable, add using System.LINQ.Dynamic namespace, then u can mention the property names in comma seperated string to OrderBy Method which comes by default from System.LINQ.Dynamic.</p>\n"
},
{
"answer_id": 25034533,
"author": "Richard YS",
"author_id": 1659637,
"author_profile": "https://Stackoverflow.com/users/1659637",
"pm_score": 2,
"selected": false,
"text": "<p>You can convert the IEnumerable to IQueryable.</p>\n\n<pre><code>items = items.AsQueryable().OrderBy(\"Name ASC\");\n</code></pre>\n"
},
{
"answer_id": 37251268,
"author": "Arindam",
"author_id": 6198269,
"author_profile": "https://Stackoverflow.com/users/6198269",
"pm_score": -1,
"selected": false,
"text": "<pre><code>var result1 = lst.OrderBy(a=>a.Name);// for ascending order. \n var result1 = lst.OrderByDescending(a=>a.Name);// for desc order. \n</code></pre>\n"
},
{
"answer_id": 47462935,
"author": "M.Hassan",
"author_id": 3142139,
"author_profile": "https://Stackoverflow.com/users/3142139",
"pm_score": 2,
"selected": false,
"text": "<p>This answer is a response to the comments that need an example for the solution provided by <a href=\"https://stackoverflow.com/a/74735/3142139\">@John Sheehan - Runscope</a></p>\n<blockquote>\n<p>Please provide an example for the rest of us.</p>\n</blockquote>\n<p>in DAL (Data Access Layer),</p>\n<p><strong>The IEnumerable version:</strong></p>\n<pre><code>public IEnumerable<Order> GetOrders()\n{\n // i use Dapper to return IEnumerable<T> using Query<T>\n //.. do stuff\n\n return orders // IEnumerable<Order>\n}\n</code></pre>\n<p><strong>The IQueryable version</strong></p>\n<pre><code>public IQueryable<Order> GetOrdersAsQuerable()\n{\n IEnumerable<Order> qry= GetOrders();\n\n // use the built-in extension method AsQueryable in System.Linq namespace\n return qry.AsQueryable(); \n}\n</code></pre>\n<p>Now you can use the IQueryable version to bind, for example GridView in Asp.net and benefit for sorting (you can't sort using IEnumerable version)</p>\n<p>I used Dapper as ORM and build IQueryable version and utilized sorting in GridView in asp.net so easy.</p>\n"
},
{
"answer_id": 49212617,
"author": "Aminur Rahman",
"author_id": 5644299,
"author_profile": "https://Stackoverflow.com/users/5644299",
"pm_score": 3,
"selected": false,
"text": "<p>First Install Dynamic \n<strong>Tools --> NuGet Package Manager --> Package Manager Console</strong></p>\n\n<pre><code>install-package System.Linq.Dynamic\n</code></pre>\n\n<p>Add <strong>Namespace</strong> <code>using System.Linq.Dynamic;</code></p>\n\n<p>Now you can use <code>OrderBy(\"Name, Age DESC\")</code></p>\n"
},
{
"answer_id": 53921180,
"author": "Masoud Darvishian",
"author_id": 1402749,
"author_profile": "https://Stackoverflow.com/users/1402749",
"pm_score": 3,
"selected": false,
"text": "<p>Use dynamic <code>linq</code></p>\n\n<p>just add <code>using System.Linq.Dynamic;</code></p>\n\n<p>And use it like this to order all your columns:</p>\n\n<pre><code>string sortTypeStr = \"ASC\"; // or DESC\nstring SortColumnName = \"Age\"; // Your column name\nquery = query.OrderBy($\"{SortColumnName} {sortTypeStr}\");\n</code></pre>\n"
},
{
"answer_id": 60711480,
"author": "k1developer",
"author_id": 3607574,
"author_profile": "https://Stackoverflow.com/users/3607574",
"pm_score": 2,
"selected": false,
"text": "<p>You can use this:</p>\n\n<pre><code> public List<Book> Books(string orderField, bool desc, int skip, int take)\n{\n var propertyInfo = typeof(Book).GetProperty(orderField);\n\n return _context.Books\n .Where(...)\n .OrderBy(p => !desc ? propertyInfo.GetValue(p, null) : 0)\n .ThenByDescending(p => desc ? propertyInfo.GetValue(p, null) : 0)\n .Skip(skip)\n .Take(take)\n .ToList();\n}\n</code></pre>\n"
},
{
"answer_id": 64088037,
"author": "Francis Shaw",
"author_id": 9614021,
"author_profile": "https://Stackoverflow.com/users/9614021",
"pm_score": 1,
"selected": false,
"text": "<p>you can do it like this for multiple order by</p>\n<pre><code>IOrderedEnumerable<JToken> sort;\n\nif (query.OrderBys[0].IsDESC)\n{\n sort = jarry.OrderByDescending(r => (string)r[query.OrderBys[0].Key]);\n}\nelse\n{\n sort = jarry.OrderBy(r =>\n (string) r[query.OrderBys[0].Key]); \n}\n\nforeach (var item in query.OrderBys.Skip(1))\n{\n if (item.IsDESC)\n {\n sort = sort.ThenByDescending(r => (string)r[item.Key]);\n }\n else\n {\n sort = sort.ThenBy(r => (string)r[item.Key]);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 70193394,
"author": "BenW",
"author_id": 1833408,
"author_profile": "https://Stackoverflow.com/users/1833408",
"pm_score": -1,
"selected": false,
"text": "<p>I am able to do this with the code below. No need write long and complex code.</p>\n<pre><code> protected void sort_array(string field_name, string asc_desc)\n {\n\n objArrayList= Sort(objArrayList, field_name, asc_desc);\n }\n\n protected List<ArrayType> Sort(List<ArrayType> input, string property, string asc_desc)\n {\n if (asc_desc == "ASC")\n {\n\n return input.OrderBy(p => p.GetType()\n .GetProperty(property)\n .GetValue(p, null)).ToList();\n }\n else\n {\n return input.OrderByDescending(p => p.GetType()\n .GetProperty(property)\n .GetValue(p, null)).ToList();\n }\n }\n</code></pre>\n"
},
{
"answer_id": 70411214,
"author": "Sajed",
"author_id": 10336618,
"author_profile": "https://Stackoverflow.com/users/10336618",
"pm_score": 2,
"selected": false,
"text": "<p>You can define a dictionary from string to Func<> like this :</p>\n<pre><code>Dictionary<string, Func<Item, object>> SortParameters = new Dictionary<string, Func<Item, object>>()\n{\n {"Rank", x => x.Rank}\n};\n</code></pre>\n<p>And use it like this :</p>\n<pre><code>yourList.OrderBy(SortParameters["Rank"]);\n</code></pre>\n<p>In this case you can dynamically sort by string.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1786/"
] | I found an example in the [VS2008 Examples](http://msdn2.microsoft.com/en-us/bb330936.aspx) for Dynamic LINQ that allows you to use a SQL-like string (e.g. `OrderBy("Name, Age DESC"))` for ordering. Unfortunately, the method included only works on `IQueryable<T>`. Is there any way to get this functionality on `IEnumerable<T>`? | Just stumbled into this oldie...
To do this without the dynamic LINQ library, you just need the code as below. This covers most common scenarios including nested properties.
To get it working with `IEnumerable<T>` you could add some wrapper methods that go via `AsQueryable` - but the code below is the core `Expression` logic needed.
```
public static IOrderedQueryable<T> OrderBy<T>(
this IQueryable<T> source,
string property)
{
return ApplyOrder<T>(source, property, "OrderBy");
}
public static IOrderedQueryable<T> OrderByDescending<T>(
this IQueryable<T> source,
string property)
{
return ApplyOrder<T>(source, property, "OrderByDescending");
}
public static IOrderedQueryable<T> ThenBy<T>(
this IOrderedQueryable<T> source,
string property)
{
return ApplyOrder<T>(source, property, "ThenBy");
}
public static IOrderedQueryable<T> ThenByDescending<T>(
this IOrderedQueryable<T> source,
string property)
{
return ApplyOrder<T>(source, property, "ThenByDescending");
}
static IOrderedQueryable<T> ApplyOrder<T>(
IQueryable<T> source,
string property,
string methodName)
{
string[] props = property.Split('.');
Type type = typeof(T);
ParameterExpression arg = Expression.Parameter(type, "x");
Expression expr = arg;
foreach(string prop in props) {
// use reflection (not ComponentModel) to mirror LINQ
PropertyInfo pi = type.GetProperty(prop);
expr = Expression.Property(expr, pi);
type = pi.PropertyType;
}
Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);
object result = typeof(Queryable).GetMethods().Single(
method => method.Name == methodName
&& method.IsGenericMethodDefinition
&& method.GetGenericArguments().Length == 2
&& method.GetParameters().Length == 2)
.MakeGenericMethod(typeof(T), type)
.Invoke(null, new object[] {source, lambda});
return (IOrderedQueryable<T>)result;
}
```
---
Edit: it gets more fun if you want to mix that with `dynamic` - although note that `dynamic` only applies to LINQ-to-Objects (expression-trees for ORMs etc can't really represent `dynamic` queries - `MemberExpression` doesn't support it). But here's a way to do it with LINQ-to-Objects. Note that the choice of `Hashtable` is due to favorable locking semantics:
```
using Microsoft.CSharp.RuntimeBinder;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Runtime.CompilerServices;
static class Program
{
private static class AccessorCache
{
private static readonly Hashtable accessors = new Hashtable();
private static readonly Hashtable callSites = new Hashtable();
private static CallSite<Func<CallSite, object, object>> GetCallSiteLocked(
string name)
{
var callSite = (CallSite<Func<CallSite, object, object>>)callSites[name];
if(callSite == null)
{
callSites[name] = callSite = CallSite<Func<CallSite, object, object>>
.Create(Binder.GetMember(
CSharpBinderFlags.None,
name,
typeof(AccessorCache),
new CSharpArgumentInfo[] {
CSharpArgumentInfo.Create(
CSharpArgumentInfoFlags.None,
null)
}));
}
return callSite;
}
internal static Func<dynamic,object> GetAccessor(string name)
{
Func<dynamic, object> accessor = (Func<dynamic, object>)accessors[name];
if (accessor == null)
{
lock (accessors )
{
accessor = (Func<dynamic, object>)accessors[name];
if (accessor == null)
{
if(name.IndexOf('.') >= 0) {
string[] props = name.Split('.');
CallSite<Func<CallSite, object, object>>[] arr
= Array.ConvertAll(props, GetCallSiteLocked);
accessor = target =>
{
object val = (object)target;
for (int i = 0; i < arr.Length; i++)
{
var cs = arr[i];
val = cs.Target(cs, val);
}
return val;
};
} else {
var callSite = GetCallSiteLocked(name);
accessor = target =>
{
return callSite.Target(callSite, (object)target);
};
}
accessors[name] = accessor;
}
}
}
return accessor;
}
}
public static IOrderedEnumerable<dynamic> OrderBy(
this IEnumerable<dynamic> source,
string property)
{
return Enumerable.OrderBy<dynamic, object>(
source,
AccessorCache.GetAccessor(property),
Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> OrderByDescending(
this IEnumerable<dynamic> source,
string property)
{
return Enumerable.OrderByDescending<dynamic, object>(
source,
AccessorCache.GetAccessor(property),
Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> ThenBy(
this IOrderedEnumerable<dynamic> source,
string property)
{
return Enumerable.ThenBy<dynamic, object>(
source,
AccessorCache.GetAccessor(property),
Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> ThenByDescending(
this IOrderedEnumerable<dynamic> source,
string property)
{
return Enumerable.ThenByDescending<dynamic, object>(
source,
AccessorCache.GetAccessor(property),
Comparer<object>.Default);
}
static void Main()
{
dynamic a = new ExpandoObject(),
b = new ExpandoObject(),
c = new ExpandoObject();
a.X = "abc";
b.X = "ghi";
c.X = "def";
dynamic[] data = new[] {
new { Y = a },
new { Y = b },
new { Y = c }
};
var ordered = data.OrderByDescending("Y.X").ToArray();
foreach (var obj in ordered)
{
Console.WriteLine(obj.Y.X);
}
}
}
``` |
41,279 | <p>I've got bunches of auxiliary files that are generated by code and LaTeX documents that I dearly wish <em>would not</em> be suggested by SpotLight as potential search candidates. I'm not looking for <code>example.log</code>, I'm looking for <code>example.tex</code>!</p>
<p>So can Spotlight be configured to ignore, say, all <code>.log</code> files?</p>
<p>(I know, I know; I should just use QuickSilver instead…)</p>
<hr>
<p>@<a href="https://stackoverflow.com/questions/41279/can-mac-os-xs-spotlight-be-configured-to-ignore-certain-file-types#41295">diciu</a> That's an interesting answer. The problem in my case is this:</p>
<blockquote>
<p>Figure out which importer handles your type of file</p>
</blockquote>
<p>I'm not sure if my type of file is handled by any single importer? Since they've all got weird extensions (.aux, .glo, .out, whatever) I think it's improbable that there's an importer that's <em>trying</em> to index them. But because they're plain text they're being picked up as generic files. (Admittedly, I don't know much about Spotlight's indexing, so I might be completely wrong on this.)</p>
<hr>
<p>@<a href="https://stackoverflow.com/questions/41279/can-mac-os-xs-spotlight-be-configured-to-ignore-certain-file-types#41342">diciu</a> again: <code>TextImporterDontImportList</code> sounds very promising; I'll head off and see if anything comes of it.</p>
<p>Like you say, it does seem like the whole UTI system doesn't really allow <em>not</em> searching for something.</p>
<hr>
<p>@<a href="https://stackoverflow.com/questions/41279/can-mac-os-xs-spotlight-be-configured-to-ignore-certain-file-types#41377">Raynet</a> Making the files invisible is a good idea actually, albeit relatively tedious for me to set up in the general sense. If worst comes to worst, I might give that a shot (but probably after exhausting other options such as QuickSilver). (Oh, and SetFile requires the Developer Tools, but I'm guessing everyone here has them installed anyway <code>:)</code> )</p>
| [
{
"answer_id": 41283,
"author": "D2VIANT",
"author_id": 4365,
"author_profile": "https://Stackoverflow.com/users/4365",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure how to do it on a file type level, but you can do it on a folder level:</p>\n\n<p>Source: <a href=\"http://lists.apple.com/archives/spotlight-dev/2008/Jul/msg00007.html\" rel=\"nofollow noreferrer\">http://lists.apple.com/archives/spotlight-dev/2008/Jul/msg00007.html</a></p>\n\n<p><strong>Make spotlight ignore a folder</strong></p>\n\n<p>If you absolutely can't rename the folder because other software depends on it another technique is to go ahead and rename the directory to end in \".noindex\", but then create a symlink in the same location pointing to the real location using the original name.</p>\n\n<p>Most software is happy to use the symlink with the original name, but Spotlight ignores symlinks and will note the \"real\" name ends in *.noindex and will ignore that location.</p>\n\n<p>Perhaps something like:</p>\n\n<blockquote>\n <p>mv OriginalName OriginalName.noindex\n ln -s OriginalName.noindex<br>\n OriginalName</p>\n \n <p>ls -l</p>\n \n <p>lrwxr-xr-x 1 andy admin 24 Jan 9 2008\n OriginalName -> OriginalName.noindex\n drwxr-xr-x 11 andy admin 374 Jul 11\n 07:03 Original.noindex</p>\n</blockquote>\n"
},
{
"answer_id": 41295,
"author": "diciu",
"author_id": 2811,
"author_profile": "https://Stackoverflow.com/users/2811",
"pm_score": 2,
"selected": false,
"text": "<p>Here's how it <i>might</i> work.</p>\n\n<p><b>Note</b>: this is not a very good solution as a system update <i>will</i> overwrite changes you will perform.</p>\n\n<p>Get a list of all importers</p>\n\n<pre>\ncristi:~ diciu$ mdimport -L\n2008-09-03 10:42:27.144 mdimport[727:10b] Paths: id(501) (\n \"/System/Library/Spotlight/Audio.mdimporter\",\n \"/System/Library/Spotlight/Chat.mdimporter\",\n \"/Developer/Applications/Xcode.app/Contents/Library/Spotlight/SourceCode.mdimporter\",\n</pre>\n\n<p>Figure out which importer handles your type of file (example for the Audio importer):</p>\n\n<pre>\ncristi:~ diciu$ cat /System/Library/Spotlight/Audio.mdimporter/Contents/Info.plist \n\n\n\n\n[..]\n CFBundleTypeRole\n MDImporter\n LSItemContentTypes\n \n public.mp3\n public.aifc-audio\n public.aiff-audio\n\n</pre>\n\n<p>Alter the importer's plist to delete the type you want to ignore.</p>\n\n<p>Reimport the importer's types so the system picks up the change:</p>\n\n<pre>\nmdimport -r /System/Library/Spotlight/Chat.mdimporter\n</pre>\n"
},
{
"answer_id": 41342,
"author": "diciu",
"author_id": 2811,
"author_profile": "https://Stackoverflow.com/users/2811",
"pm_score": 3,
"selected": true,
"text": "<p>@Will - these things that define types are called <a href=\"http://developer.apple.com/macosx/uniformtypeidentifiers.html\" rel=\"nofollow noreferrer\">uniform type identifiers</a>.</p>\n\n<p>The problem is they are a combination of extensions (like .txt) and generic types (i.e. public.plain-text matches a txt file without the txt extension based purely on content) so it's not as simple as looking for an extension.</p>\n\n<p>RichText.mdimporter is <i>probably</i> the importer that imports your text file.\nThis should be easily verified by running mdimport in debug mode on one of the files you don't want indexed:</p>\n\n<pre>\ncristi:~ diciu$ echo \"All work and no play makes Jack a dull boy\" > ~/input.txt\ncristi:~ diciu$ mdimport -d 4 -n ~/input.txt 2>&1 | grep Imported\n kMD2008-09-03 12:05:06.342 mdimport[1230:10b] Imported '/Users/diciu/input.txt' of type 'public.plain-text' with plugIn /System/Library/Spotlight/RichText.mdimporter.\n\n</pre>\n\n<p>The type that matches in my example is public.plain-text.</p>\n\n<p>I've no idea how you actually write an extension-based exception for an UTI (like public.plain-text except anything ending in .log).</p>\n\n<p>Later edit: I've also looked though the RichText mdimporter binary and found a promising string but I can't figure out if it's actually being used (as a preference name or whatever):</p>\n\n<pre>\ncristi:FoodBrowser diciu$ strings /System/Library/Spotlight/RichText.mdimporter/Contents/MacOS/RichText |grep Text\n\nTextImporterDontImportList\n\n</pre>\n"
},
{
"answer_id": 41377,
"author": "Raynet",
"author_id": 4294,
"author_profile": "https://Stackoverflow.com/users/4294",
"pm_score": 1,
"selected": false,
"text": "<p>The only option probably is to have them not indexed by spotlight as from some reason you cannot do negative searches. You can search for files with specifix file extension, but you cannot not search for ones that don't match.</p>\n\n<p>You could try making those files invisible for Finder, Spotlight won't index invisible files. Command for setting the kIsInvisible flag on files is:</p>\n\n<p>SetFile -a v [filename(s)]</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4161/"
] | I've got bunches of auxiliary files that are generated by code and LaTeX documents that I dearly wish *would not* be suggested by SpotLight as potential search candidates. I'm not looking for `example.log`, I'm looking for `example.tex`!
So can Spotlight be configured to ignore, say, all `.log` files?
(I know, I know; I should just use QuickSilver instead…)
---
@[diciu](https://stackoverflow.com/questions/41279/can-mac-os-xs-spotlight-be-configured-to-ignore-certain-file-types#41295) That's an interesting answer. The problem in my case is this:
>
> Figure out which importer handles your type of file
>
>
>
I'm not sure if my type of file is handled by any single importer? Since they've all got weird extensions (.aux, .glo, .out, whatever) I think it's improbable that there's an importer that's *trying* to index them. But because they're plain text they're being picked up as generic files. (Admittedly, I don't know much about Spotlight's indexing, so I might be completely wrong on this.)
---
@[diciu](https://stackoverflow.com/questions/41279/can-mac-os-xs-spotlight-be-configured-to-ignore-certain-file-types#41342) again: `TextImporterDontImportList` sounds very promising; I'll head off and see if anything comes of it.
Like you say, it does seem like the whole UTI system doesn't really allow *not* searching for something.
---
@[Raynet](https://stackoverflow.com/questions/41279/can-mac-os-xs-spotlight-be-configured-to-ignore-certain-file-types#41377) Making the files invisible is a good idea actually, albeit relatively tedious for me to set up in the general sense. If worst comes to worst, I might give that a shot (but probably after exhausting other options such as QuickSilver). (Oh, and SetFile requires the Developer Tools, but I'm guessing everyone here has them installed anyway `:)` ) | @Will - these things that define types are called [uniform type identifiers](http://developer.apple.com/macosx/uniformtypeidentifiers.html).
The problem is they are a combination of extensions (like .txt) and generic types (i.e. public.plain-text matches a txt file without the txt extension based purely on content) so it's not as simple as looking for an extension.
RichText.mdimporter is *probably* the importer that imports your text file.
This should be easily verified by running mdimport in debug mode on one of the files you don't want indexed:
```
cristi:~ diciu$ echo "All work and no play makes Jack a dull boy" > ~/input.txt
cristi:~ diciu$ mdimport -d 4 -n ~/input.txt 2>&1 | grep Imported
kMD2008-09-03 12:05:06.342 mdimport[1230:10b] Imported '/Users/diciu/input.txt' of type 'public.plain-text' with plugIn /System/Library/Spotlight/RichText.mdimporter.
```
The type that matches in my example is public.plain-text.
I've no idea how you actually write an extension-based exception for an UTI (like public.plain-text except anything ending in .log).
Later edit: I've also looked though the RichText mdimporter binary and found a promising string but I can't figure out if it's actually being used (as a preference name or whatever):
```
cristi:FoodBrowser diciu$ strings /System/Library/Spotlight/RichText.mdimporter/Contents/MacOS/RichText |grep Text
TextImporterDontImportList
``` |
41,290 | <p>I have a file which is an XML representation of some data that is taken from a Web service and cached locally within a Web Application. The idea being is that this data is <em>very</em> static, but just <em>might</em> change. So I have set it up to cache to a file, and stuck a monitor against it to check if it has been deleted. Once deleted, the file will be refreshed from its source and rebuilt.</p>
<p>I am now running in to problems though, because obviously in a multi-threaded environment it falls over as it is trying to access the data when it is still reading/writing the file.</p>
<p>This is confusing me, because I added a object to lock against, and this is always locked during read/write. It was my understanding that attempted access from other threads would be told to "wait" until the lock was released?</p>
<p>Just to let you know, I am real new to multi-threaded development, so I am totally willing to accept this is a screw up on my part :)</p>
<ul>
<li><strong>Am I missing something?</strong></li>
<li><strong>What is the best file access strategy in a multi-threaded environment?</strong>
<hr></li>
</ul>
<h3>Edit</h3>
<p>Sorry - I should have said this is using <strong>ASP.NET 2.0</strong> :)</p>
| [
{
"answer_id": 41312,
"author": "Ubiguchi",
"author_id": 2562,
"author_profile": "https://Stackoverflow.com/users/2562",
"pm_score": 1,
"selected": false,
"text": "<p>If you're locking on a object stored as a <em>static</em> then the lock should work for all threads in the same Application Domain, but perhaps you need to upload a code sample so we can have a look at the offending lines.</p>\n\n<p>That said, one thought would be to check if IIS is configured to run in <a href=\"http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/57fd3d02-9b05-4b3f-8c3a-f326ff895ab8.mspx?mfr=true\" rel=\"nofollow noreferrer\">Web Garden</a> mode (i.e. more than 1 process executing your application) which would break your locking logic. While you could fix such a situation with a mutex it'd be easier to reconfigure your application to execute in a single process, although you'd be wise to check the performance before and after messing with the web garden settings as it can potentially affect performance.</p>\n"
},
{
"answer_id": 41351,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You could maybe create the file with a temporary name (\"data.xml_TMP\"), and when it's ready change the name to what it is supposed to be. That way, no other process will be accessing it before it is ready.</p>\n"
},
{
"answer_id": 41559,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 4,
"selected": true,
"text": "<p>Here is the code that I use to make sure a file is not locked by another process. It's not 100% foolproof, but it gets the job done most of the time:</p>\n\n<pre><code> /// <summary>\n /// Blocks until the file is not locked any more.\n /// </summary>\n /// <param name=\"fullPath\"></param>\n bool WaitForFile(string fullPath)\n {\n int numTries = 0;\n while (true)\n {\n ++numTries;\n try\n {\n // Attempt to open the file exclusively.\n using (FileStream fs = new FileStream(fullPath,\n FileMode.Open, FileAccess.ReadWrite, \n FileShare.None, 100))\n {\n fs.ReadByte();\n\n // If we got this far the file is ready\n break;\n }\n }\n catch (Exception ex)\n {\n Log.LogWarning(\n \"WaitForFile {0} failed to get an exclusive lock: {1}\", \n fullPath, ex.ToString());\n\n if (numTries > 10)\n {\n Log.LogWarning(\n \"WaitForFile {0} giving up after 10 tries\", \n fullPath);\n return false;\n }\n\n // Wait for the lock to be released\n System.Threading.Thread.Sleep(500);\n }\n }\n\n Log.LogTrace(\"WaitForFile {0} returning true after {1} tries\",\n fullPath, numTries);\n return true;\n }\n</code></pre>\n\n<p>Obviously you can tweak the timeouts and retries to suit your application. I use this to process huge FTP files that take a while to be written.</p>\n"
},
{
"answer_id": 113659,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "<p>OK, I have been working on this and ended up creating a stress-test module to basically hammer the crap out of my code from several threads (<a href=\"https://stackoverflow.com/questions/41568/whats-the-best-way-to-unit-test-from-multiple-threads\">See Related Question</a>).</p>\n\n<p>It was much easier from this point on to find holes in my code. It turns out that my code wasn't actually far off, but there was a certain logic path that it could enter in to which basically caused read/write operations to stack up, meaning if they didn't get cleared in time, it would go boom!</p>\n\n<p>Once I took that out, ran my stress test again, all worked fine!</p>\n\n<p><strong>So, I didn't really do anything <em>special</em> in my file access code, just ensured I used <a href=\"http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.85).aspx\" rel=\"nofollow noreferrer\"><code>lock</code></a> statements where appropriate (i.e. when reading or writing).</strong></p>\n"
},
{
"answer_id": 32701350,
"author": "gmail user",
"author_id": 344394,
"author_profile": "https://Stackoverflow.com/users/344394",
"pm_score": 0,
"selected": false,
"text": "<p>How about using <code>AutoResetEvent</code> to communicate between threads? I created a console app which creates roughly 8 GB file in <code>createfile</code> method and then copy that file in <code>main</code> method</p>\n\n<pre><code> static AutoResetEvent waitHandle = new AutoResetEvent(false);\n static string filePath=@\"C:\\Temp\\test.txt\";\n static string fileCopyPath=@\"C:\\Temp\\test-copy.txt\";\n static void Main(string[] args)\n {\n Console.WriteLine(\"in main method\");\n Console.WriteLine();\n Thread thread = new Thread(createFile);\n thread.Start();\n\n Console.WriteLine(\"waiting for file to be processed \");\n Console.WriteLine();\n waitHandle.WaitOne();\n Console.WriteLine();\n\n File.Copy(filePath, fileCopyPath);\n Console.WriteLine(\"file copied \");\n\n }\n\n\n static void createFile()\n {\n\n FileStream fs= File.Create(filePath); \n Console.WriteLine(\"start processing a file \"+DateTime.Now);\n Console.WriteLine();\n using (StreamWriter sw = new StreamWriter(fs))\n {\n for (long i = 0; i < 300000000; i++)\n {\n sw.WriteLine(\"The value of i is \" + i);\n\n }\n }\n Console.WriteLine(\"file processed \" + DateTime.Now);\n Console.WriteLine();\n\n waitHandle.Set();\n }\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | I have a file which is an XML representation of some data that is taken from a Web service and cached locally within a Web Application. The idea being is that this data is *very* static, but just *might* change. So I have set it up to cache to a file, and stuck a monitor against it to check if it has been deleted. Once deleted, the file will be refreshed from its source and rebuilt.
I am now running in to problems though, because obviously in a multi-threaded environment it falls over as it is trying to access the data when it is still reading/writing the file.
This is confusing me, because I added a object to lock against, and this is always locked during read/write. It was my understanding that attempted access from other threads would be told to "wait" until the lock was released?
Just to let you know, I am real new to multi-threaded development, so I am totally willing to accept this is a screw up on my part :)
* **Am I missing something?**
* **What is the best file access strategy in a multi-threaded environment?**
---
### Edit
Sorry - I should have said this is using **ASP.NET 2.0** :) | Here is the code that I use to make sure a file is not locked by another process. It's not 100% foolproof, but it gets the job done most of the time:
```
/// <summary>
/// Blocks until the file is not locked any more.
/// </summary>
/// <param name="fullPath"></param>
bool WaitForFile(string fullPath)
{
int numTries = 0;
while (true)
{
++numTries;
try
{
// Attempt to open the file exclusively.
using (FileStream fs = new FileStream(fullPath,
FileMode.Open, FileAccess.ReadWrite,
FileShare.None, 100))
{
fs.ReadByte();
// If we got this far the file is ready
break;
}
}
catch (Exception ex)
{
Log.LogWarning(
"WaitForFile {0} failed to get an exclusive lock: {1}",
fullPath, ex.ToString());
if (numTries > 10)
{
Log.LogWarning(
"WaitForFile {0} giving up after 10 tries",
fullPath);
return false;
}
// Wait for the lock to be released
System.Threading.Thread.Sleep(500);
}
}
Log.LogTrace("WaitForFile {0} returning true after {1} tries",
fullPath, numTries);
return true;
}
```
Obviously you can tweak the timeouts and retries to suit your application. I use this to process huge FTP files that take a while to be written. |
41,304 | <p>I know in ASP.NET I can get an item from a DropDownList by using</p>
<pre><code>DropDownList1.Items.FindByText
</code></pre>
<p>Is there a similar method I can use in WPF for a ComboBox?</p>
<p>Here's the scenario.</p>
<p>I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values.</p>
<p>In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record.</p>
<hr>
<p>Here's the scenario.</p>
<p>I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values.</p>
<p>In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record.</p>
<p>Does this make sense?</p>
| [
{
"answer_id": 41305,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>In WPF you can use FindName method.</p>\n\n<p>XAML:</p>\n\n<pre><code> <ComboBox Name=\"combo\">\n <ComboBoxItem Name=\"item1\" >1</ComboBoxItem>\n <ComboBoxItem Name=\"item2\">2</ComboBoxItem>\n <ComboBoxItem Name=\"item3\">3</ComboBoxItem>\n </ComboBox>\n</code></pre>\n\n<p>Code-behind file</p>\n\n<pre><code> item1.Content = \"New content\"; // Reference combo box item by name\n ComboBoxItem item = (ComboBoxItem)this.combo.FindName(\"item1\"); // Using FindName method\n</code></pre>\n\n<p>To find item by its content you can use <a href=\"http://msdn.microsoft.com/en-us/library/ms747327.aspx\" rel=\"nofollow noreferrer\">UI automation</a>.</p>\n"
},
{
"answer_id": 99549,
"author": "SmartyP",
"author_id": 18005,
"author_profile": "https://Stackoverflow.com/users/18005",
"pm_score": 1,
"selected": false,
"text": "<p>instead of trying to bind the SelectedIndex why don't you just bind the SelectedItem in the ComboBox to the value in the record?</p>\n\n<p>in other words, set the DataContext of the ComboBox (or its parent) to the selected 'record' and bind the SelectedItem on the ComboBox to an exposed property on the 'record'.. </p>\n\n<p>it may help if you could provide some code snippets, or extra details so that responses can be more specific and refer to the variables and types you are using in both the source record and the ComboBox which you have populated.</p>\n"
},
{
"answer_id": 662946,
"author": "Rich",
"author_id": 53501,
"author_profile": "https://Stackoverflow.com/users/53501",
"pm_score": 5,
"selected": true,
"text": "<p>Can you use ItemContainerGenerator?</p>\n\n<p>ItemContainerGenerator contains a ContainerFromItem method that takes an object parameter. If you have a reference to the full object that your comboBox contains (or a way to reconstruct it), you can use the following:</p>\n\n<pre><code>ComboBoxItem item = \n (ComboBoxItem)myComboBox.ItemContainerGenerator.ContainerFromItem(myObject);\n</code></pre>\n"
},
{
"answer_id": 662950,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 0,
"selected": false,
"text": "<p>You can retrieve combobox items in two ways:</p>\n\n<p>By item:</p>\n\n<pre><code>ComboBoxItem item = (ComboBoxItem) control.ItemContainerGenerator.ContainerFromItem(control.SelectedItem);\n</code></pre>\n\n<p>By index:</p>\n\n<pre><code>ComboBoxItem item = (ComboBoxItem) control.ItemContainerGenerator.ContainerFromIndex(1);\n</code></pre>\n"
},
{
"answer_id": 662969,
"author": "Denis Troller",
"author_id": 29336,
"author_profile": "https://Stackoverflow.com/users/29336",
"pm_score": 0,
"selected": false,
"text": "<p>Can you give some context as to what exactly you are trying to do?</p>\n\n<p>What objects do you put in your Combobox, and using which method? (Are you setting or binding the ItemsSource property?)\nWhy do you need to lookup an item by its \"text\"? The most usual usage in WPF is to bind the SelectedItem property to something else so you can retrieve/set the selected entry using your representation. Is there a specific requirement for which you need to find a specific item in the list?</p>\n\n<p>Worst case, you can perform the search on the collection to which you bind your ComboBox using Linq To Objects.</p>\n\n<p>Do not mistake the ComboBoxItem (that is, the element generated for you behind the scenes by WPF when you bind ItemsSource) with the SelectedItem, which is the actual object in the collection you bind to. That usually is the source of most problems whith WPF when you are not used to it. There are precious few cases when you need to find the actual ComboBoxItem.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71/"
] | I know in ASP.NET I can get an item from a DropDownList by using
```
DropDownList1.Items.FindByText
```
Is there a similar method I can use in WPF for a ComboBox?
Here's the scenario.
I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values.
In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record.
---
Here's the scenario.
I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values.
In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record.
Does this make sense? | Can you use ItemContainerGenerator?
ItemContainerGenerator contains a ContainerFromItem method that takes an object parameter. If you have a reference to the full object that your comboBox contains (or a way to reconstruct it), you can use the following:
```
ComboBoxItem item =
(ComboBoxItem)myComboBox.ItemContainerGenerator.ContainerFromItem(myObject);
``` |
41,319 | <p>What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type <code>IEnumerable<T></code> and doesn't have a Count property.</p>
<p>Right now I'm tossing up between this:</p>
<pre><code>if (myList.Count() == 0) { ... }
</code></pre>
<p>and this:</p>
<pre><code>if (!myList.Any()) { ... }
</code></pre>
<p>My guess is that the second option is faster, since it'll come back with a result as soon as it sees the first item, whereas the second option (for an IEnumerable) will need to visit every item to return the count.</p>
<p>That being said, does the second option look as readable to you? Which would you prefer? Or can you think of a better way to test for an empty list?</p>
<p><strong>Edit</strong> @lassevk's response seems to be the most logical, coupled with a bit of runtime checking to use a cached count if possible, like this:</p>
<pre><code>public static bool IsEmpty<T>(this IEnumerable<T> list)
{
if (list is ICollection<T>) return ((ICollection<T>)list).Count == 0;
return !list.Any();
}
</code></pre>
| [
{
"answer_id": 41324,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 8,
"selected": true,
"text": "<p>You could do this:</p>\n\n<pre><code>public static Boolean IsEmpty<T>(this IEnumerable<T> source)\n{\n if (source == null)\n return true; // or throw an exception\n return !source.Any();\n}\n</code></pre>\n\n<p><strong>Edit</strong>: Note that simply using the .Count method will be fast if the underlying source actually has a fast Count property. A valid optimization above would be to detect a few base types and simply use the .Count property of those, instead of the .Any() approach, but then fall back to .Any() if no guarantee can be made.</p>\n"
},
{
"answer_id": 41325,
"author": "crucible",
"author_id": 3717,
"author_profile": "https://Stackoverflow.com/users/3717",
"pm_score": 3,
"selected": false,
"text": "<p>I just wrote up a quick test, try this:</p>\n\n<pre><code> IEnumerable<Object> myList = new List<Object>();\n\n Stopwatch watch = new Stopwatch();\n\n int x;\n\n watch.Start();\n for (var i = 0; i <= 1000000; i++)\n {\n if (myList.Count() == 0) x = i; \n }\n watch.Stop();\n\n Stopwatch watch2 = new Stopwatch();\n\n watch2.Start();\n for (var i = 0; i <= 1000000; i++)\n {\n if (!myList.Any()) x = i;\n }\n watch2.Stop();\n\n Console.WriteLine(\"myList.Count() = \" + watch.ElapsedMilliseconds.ToString());\n Console.WriteLine(\"myList.Any() = \" + watch2.ElapsedMilliseconds.ToString());\n Console.ReadLine();\n</code></pre>\n\n<p>The second is almost three times slower :)</p>\n\n<p>Trying the stopwatch test again with a Stack or array or other scenarios it really depends on the type of list it seems - because they prove Count to be slower.</p>\n\n<p>So I guess it depends on the type of list you're using!</p>\n\n<p>(Just to point out, I put 2000+ objects in the List and count was still faster, opposite with other types)</p>\n"
},
{
"answer_id": 41339,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "<p>The second option is much quicker if you have multiple items.</p>\n\n<ul>\n<li><code>Any()</code> returns as soon as 1 item is found.</li>\n<li><code>Count()</code> has to keep going through the entire list.</li>\n</ul>\n\n<p>For instance suppose the enumeration had 1000 items.</p>\n\n<ul>\n<li><code>Any()</code> would check the first one, then return true.</li>\n<li><code>Count()</code> would return 1000 after traversing the entire enumeration.</li>\n</ul>\n\n<p>This is potentially worse if you use one of the predicate overrides - Count() still has to check every single item, even it there is only one match.</p>\n\n<p>You get used to using the Any one - it does make sense and is readable.</p>\n\n<p>One caveat - if you have a List, rather than just an IEnumerable then use that list's Count property.</p>\n"
},
{
"answer_id": 41357,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>LINQ itself must be doing some serious optimization around the Count() method somehow.</p>\n</blockquote>\n\n<p>Does this surprise you? I imagine that for <code>IList</code> implementations, <code>Count</code> simply reads the number of elements directly while <code>Any</code> has to query the <code>IEnumerable.GetEnumerator</code> method, create an instance and call <code>MoveNext</code> at least once.</p>\n\n<p>/EDIT @Matt:</p>\n\n<blockquote>\n <p>I can only assume that the Count() extension method for IEnumerable is doing something like this:</p>\n</blockquote>\n\n<p>Yes, of course it does. This is what I meant. Actually, it uses <code>ICollection</code> instead of <code>IList</code> but the result is the same.</p>\n"
},
{
"answer_id": 41365,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "<p>@Konrad what surprises me is that in my tests, I'm passing the list into a method that accepts <code>IEnumerable<T></code>, so the runtime can't optimize it by calling the Count() extension method for <code>IList<T></code>.</p>\n\n<p>I can only assume that the Count() extension method for IEnumerable is doing something like this:</p>\n\n<pre><code>public static int Count<T>(this IEnumerable<T> list)\n{\n if (list is IList<T>) return ((IList<T>)list).Count;\n\n int i = 0;\n foreach (var t in list) i++;\n return i;\n}\n</code></pre>\n\n<p>... in other words, a bit of runtime optimization for the special case of <code>IList<T></code>.</p>\n\n<p>/EDIT @Konrad +1 mate - you're right about it more likely being on <code>ICollection<T></code>.</p>\n"
},
{
"answer_id": 1620712,
"author": "Jonny Dee",
"author_id": 196164,
"author_profile": "https://Stackoverflow.com/users/196164",
"pm_score": -1,
"selected": false,
"text": "<p>This extension method works for me:</p>\n\n<pre><code>public static bool IsEmpty<T>(this IEnumerable<T> enumerable)\n{\n try\n {\n enumerable.First();\n return false;\n }\n catch (InvalidOperationException)\n {\n return true;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1623097,
"author": "Jonny Dee",
"author_id": 196432,
"author_profile": "https://Stackoverflow.com/users/196432",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, so what about this one?</p>\n\n<pre><code>public static bool IsEmpty<T>(this IEnumerable<T> enumerable)\n{\n return !enumerable.GetEnumerator().MoveNext();\n}\n</code></pre>\n\n<p>EDIT: I've just realized that someone has sketched this solution already. It was mentioned that the Any() method will do this, but why not do it yourself? Regards</p>\n"
},
{
"answer_id": 1938747,
"author": "ChulioMartinez",
"author_id": 63865,
"author_profile": "https://Stackoverflow.com/users/63865",
"pm_score": 1,
"selected": false,
"text": "<p>Another idea:</p>\n\n<pre><code>if(enumerable.FirstOrDefault() != null)\n</code></pre>\n\n<p>However I like the Any() approach more.</p>\n"
},
{
"answer_id": 3495249,
"author": "Dasmowenator",
"author_id": 367544,
"author_profile": "https://Stackoverflow.com/users/367544",
"pm_score": 3,
"selected": false,
"text": "<p><code>List.Count</code> is O(1) according to Microsoft's documentation:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/27b47ht3.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/27b47ht3.aspx</a> </p>\n\n<p>so just use <code>List.Count == 0</code> it's much faster than a query</p>\n\n<p>This is because it has a data member called Count which is updated any time something is added or removed from the list, so when you call <code>List.Count</code> it doesn't have to iterate through every element to get it, it just returns the data member.</p>\n"
},
{
"answer_id": 3576549,
"author": "Dan Tao",
"author_id": 105570,
"author_profile": "https://Stackoverflow.com/users/105570",
"pm_score": 4,
"selected": false,
"text": "<p>I would make one small addition to the code you seem to have settled on: check also for <code>ICollection</code>, as this is implemented even by some non-obsolete generic classes as well (i.e., <code>Queue<T></code> and <code>Stack<T></code>). I would also use <code>as</code> instead of <code>is</code> as it's more idiomatic and <a href=\"http://www.codeproject.com/KB/cs/csharpcasts.aspx\" rel=\"noreferrer\">has been shown to be faster</a>.</p>\n\n<pre><code>public static bool IsEmpty<T>(this IEnumerable<T> list)\n{\n if (list == null)\n {\n throw new ArgumentNullException(\"list\");\n }\n\n var genericCollection = list as ICollection<T>;\n if (genericCollection != null)\n {\n return genericCollection.Count == 0;\n }\n\n var nonGenericCollection = list as ICollection;\n if (nonGenericCollection != null)\n {\n return nonGenericCollection.Count == 0;\n }\n\n return !list.Any();\n}\n</code></pre>\n"
},
{
"answer_id": 6958074,
"author": "gandarez",
"author_id": 833531,
"author_profile": "https://Stackoverflow.com/users/833531",
"pm_score": 0,
"selected": false,
"text": "<p>If I check with Count() Linq executes a \"SELECT COUNT(*)..\" in the database, but I need to check if the results contains data, I resolved to introducing FirstOrDefault() instead of Count();</p>\n\n<p>Before</p>\n\n<pre><code>var cfop = from tabelaCFOPs in ERPDAOManager.GetTable<TabelaCFOPs>()\n\nif (cfop.Count() > 0)\n{\n var itemCfop = cfop.First();\n //....\n}\n</code></pre>\n\n<p>After</p>\n\n<pre><code>var cfop = from tabelaCFOPs in ERPDAOManager.GetTable<TabelaCFOPs>()\n\nvar itemCfop = cfop.FirstOrDefault();\n\nif (itemCfop != null)\n{\n //....\n}\n</code></pre>\n"
},
{
"answer_id": 8527081,
"author": "Holt Mansfield",
"author_id": 522598,
"author_profile": "https://Stackoverflow.com/users/522598",
"pm_score": 1,
"selected": false,
"text": "<p>This was critical to get this to work with Entity Framework:</p>\n\n<pre><code>var genericCollection = list as ICollection<T>;\n\nif (genericCollection != null)\n{\n //your code \n}\n</code></pre>\n"
},
{
"answer_id": 9770656,
"author": "suneelsarraf",
"author_id": 1124234,
"author_profile": "https://Stackoverflow.com/users/1124234",
"pm_score": 0,
"selected": false,
"text": "<pre><code>private bool NullTest<T>(T[] list, string attribute)\n\n {\n bool status = false;\n if (list != null)\n {\n int flag = 0;\n var property = GetProperty(list.FirstOrDefault(), attribute);\n foreach (T obj in list)\n {\n if (property.GetValue(obj, null) == null)\n flag++;\n }\n status = flag == 0 ? true : false;\n }\n return status;\n }\n\n\npublic PropertyInfo GetProperty<T>(T obj, string str)\n\n {\n Expression<Func<T, string, PropertyInfo>> GetProperty = (TypeObj, Column) => TypeObj.GetType().GetProperty(TypeObj\n .GetType().GetProperties().ToList()\n .Find(property => property.Name\n .ToLower() == Column\n .ToLower()).Name.ToString());\n return GetProperty.Compile()(obj, str);\n }\n</code></pre>\n"
},
{
"answer_id": 10409651,
"author": "Milad Sadeghi",
"author_id": 1369436,
"author_profile": "https://Stackoverflow.com/users/1369436",
"pm_score": -1,
"selected": false,
"text": "<pre><code>List<T> li = new List<T>();\n(li.First().DefaultValue.HasValue) ? string.Format(\"{0:yyyy/MM/dd}\", sender.First().DefaultValue.Value) : string.Empty;\n</code></pre>\n"
},
{
"answer_id": 12237400,
"author": "devuxer",
"author_id": 129164,
"author_profile": "https://Stackoverflow.com/users/129164",
"pm_score": 0,
"selected": false,
"text": "<p>Here's my implementation of Dan Tao's answer, allowing for a predicate:</p>\n\n<pre><code>public static bool IsEmpty<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)\n{\n if (source == null) throw new ArgumentNullException();\n if (IsCollectionAndEmpty(source)) return true;\n return !source.Any(predicate);\n}\n\npublic static bool IsEmpty<TSource>(this IEnumerable<TSource> source)\n{\n if (source == null) throw new ArgumentNullException();\n if (IsCollectionAndEmpty(source)) return true;\n return !source.Any();\n}\n\nprivate static bool IsCollectionAndEmpty<TSource>(IEnumerable<TSource> source)\n{\n var genericCollection = source as ICollection<TSource>;\n if (genericCollection != null) return genericCollection.Count == 0;\n var nonGenericCollection = source as ICollection;\n if (nonGenericCollection != null) return nonGenericCollection.Count == 0;\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 30056312,
"author": "user3149517",
"author_id": 3149517,
"author_profile": "https://Stackoverflow.com/users/3149517",
"pm_score": -1,
"selected": false,
"text": "<p><code>myList.ToList().Count == 0</code>. That's all</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615/"
] | What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type `IEnumerable<T>` and doesn't have a Count property.
Right now I'm tossing up between this:
```
if (myList.Count() == 0) { ... }
```
and this:
```
if (!myList.Any()) { ... }
```
My guess is that the second option is faster, since it'll come back with a result as soon as it sees the first item, whereas the second option (for an IEnumerable) will need to visit every item to return the count.
That being said, does the second option look as readable to you? Which would you prefer? Or can you think of a better way to test for an empty list?
**Edit** @lassevk's response seems to be the most logical, coupled with a bit of runtime checking to use a cached count if possible, like this:
```
public static bool IsEmpty<T>(this IEnumerable<T> list)
{
if (list is ICollection<T>) return ((ICollection<T>)list).Count == 0;
return !list.Any();
}
``` | You could do this:
```
public static Boolean IsEmpty<T>(this IEnumerable<T> source)
{
if (source == null)
return true; // or throw an exception
return !source.Any();
}
```
**Edit**: Note that simply using the .Count method will be fast if the underlying source actually has a fast Count property. A valid optimization above would be to detect a few base types and simply use the .Count property of those, instead of the .Any() approach, but then fall back to .Any() if no guarantee can be made. |
41,330 | <p>How do I detect if the system has a default recording device installed?
I bet this can be done through some calls to the Win32 API, anyone has any experience with this?</p>
<p>I'm talking about doing this through code, not by opening the control panel and taking a look under sound options.</p>
| [
{
"answer_id": 41346,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>There is an Open Source Audio API called <a href=\"http://www.portaudio.com/\" rel=\"nofollow noreferrer\">PortAudio</a> that has a method you could use. I think the method is called Pa_GetDeviceInfo() or something.</p>\n"
},
{
"answer_id": 41385,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 2,
"selected": true,
"text": "<p>Using the <a href=\"https://www.microsoft.com/en-in/download/details.aspx?id=6812\" rel=\"nofollow noreferrer\">DirectX SDK</a>, you can call DirectSoundCaptureEnumerate, which will call your DSEnumCallback function for each DirectSoundCapture device on the system. The first parameter passed to your DSEnumCallback is an LPGUID, which is the \"Address of the GUID that identifies the device being enumerated, or NULL for the primary device\".</p>\n\n<p>If all you need to do is find out if a recording device is present (I don't think this is good enough if you really need to know the default device), you can use waveInGetNumDevs:</p>\n\n<pre><code>#include <tchar.h>\n#include <windows.h>\n#include \"mmsystem.h\"\n\nint _tmain( int argc, wchar_t *argv[] )\n{\n UINT deviceCount = waveInGetNumDevs();\n\n if ( deviceCount > 0 )\n {\n for ( int i = 0; i < deviceCount; i++ )\n {\n WAVEINCAPSW waveInCaps;\n\n waveInGetDevCapsW( i, &waveInCaps, sizeof( WAVEINCAPS ) );\n\n // do some stuff with waveInCaps...\n }\n }\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 47702,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 0,
"selected": false,
"text": "<p>The win32 api has a function called <a href=\"http://msdn.microsoft.com/en-us/library/ms713732(VS.85).aspx\" rel=\"nofollow noreferrer\">waveInGetNumDevs</a> for it.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1509946/"
] | How do I detect if the system has a default recording device installed?
I bet this can be done through some calls to the Win32 API, anyone has any experience with this?
I'm talking about doing this through code, not by opening the control panel and taking a look under sound options. | Using the [DirectX SDK](https://www.microsoft.com/en-in/download/details.aspx?id=6812), you can call DirectSoundCaptureEnumerate, which will call your DSEnumCallback function for each DirectSoundCapture device on the system. The first parameter passed to your DSEnumCallback is an LPGUID, which is the "Address of the GUID that identifies the device being enumerated, or NULL for the primary device".
If all you need to do is find out if a recording device is present (I don't think this is good enough if you really need to know the default device), you can use waveInGetNumDevs:
```
#include <tchar.h>
#include <windows.h>
#include "mmsystem.h"
int _tmain( int argc, wchar_t *argv[] )
{
UINT deviceCount = waveInGetNumDevs();
if ( deviceCount > 0 )
{
for ( int i = 0; i < deviceCount; i++ )
{
WAVEINCAPSW waveInCaps;
waveInGetDevCapsW( i, &waveInCaps, sizeof( WAVEINCAPS ) );
// do some stuff with waveInCaps...
}
}
return 0;
}
``` |
41,397 | <p>Right, I know I am totally going to look an idiot with this one, but my brain is just <em>not</em> kicking in to gear this morning.</p>
<p>I want to have a method where I can say "if it goes bad, come back with this type of Exception", right?</p>
<p>For example, something like (<strong>and this doesn't work</strong>):</p>
<pre><code> static ExType TestException<ExType>(string message) where ExType:Exception
{
Exception ex1 = new Exception();
ExType ex = new Exception(message);
return ex;
}
</code></pre>
<p>Now whats confusing me is that we <em>KNOW</em> that the generic type is going to be of an Exception type due to the <em>where</em> clause. However, the code fails because we cannot implicitly cast <em>Exception</em> to <em>ExType</em>. We cannot explicitly convert it either, such as:</p>
<pre><code> static ExType TestException<ExType>(string message) where ExType:Exception
{
Exception ex1 = new Exception();
ExType ex = (ExType)(new Exception(message));
return ex;
}
</code></pre>
<p>As that fails too.. So <strong>is this kind of thing possible?</strong> I have a strong feeling its going to be real simple, but I am having a tough day with the old noggin, so cut me some slack :P</p>
<hr />
<h2>Update</h2>
<p>Thanks for the responses guys, looks like it wasn't me being a <em>complete</em> idiot! ;)</p>
<p>OK, so <a href="https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41398">Vegard</a> and <a href="https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41404">Sam</a> got me on to the point where I could instantiate the correct type, but then obviously got stuck because the <em>message</em> param is read-only following instantiation.</p>
<p><a href="https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41408">Matt</a> hit the nail right on the head with his response, I have tested this and all works fine. Here is the example code:</p>
<pre><code> static ExType TestException<ExType>(string message) where ExType:Exception, new ()
{
ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message);
return ex;
}
</code></pre>
<p>Sweet! :)</p>
<p>Thanks guys!</p>
| [
{
"answer_id": 41402,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried, instead:</p>\n\n<pre><code>static T TestException<Exception>(string message)\n{}\n</code></pre>\n\n<p>because I have a feeling that putting in the generic constraint is not necessary as all throwable exceptions <em>must</em> inherit from System.Exception anyway.</p>\n\n<p>Remember that generics do accept inherited types.</p>\n"
},
{
"answer_id": 41404,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": -1,
"selected": false,
"text": "<p>I think seeing as all exceptions should have a parameterless constructor, and have the <code>Message</code> property, so the following should work:</p>\n\n<pre><code>static ExType TestException<ExType>(string message) where ExType:Exception\n{\n ExType ex = new ExType();\n ex.Message = message;\n return ex;\n}\n</code></pre>\n\n<p>Edit: OK, Message is read only, so you'll have to hope the class implements the Exception(string) constructor instead.</p>\n\n<pre><code>static ExType TestException<ExType>(string message) where ExType:Exception\n{\n return new ExType(message);\n}\n</code></pre>\n"
},
{
"answer_id": 41408,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": true,
"text": "<p>You can almost do it like this:</p>\n\n<pre><code>static void TestException<E>(string message) where E : Exception, new()\n{\n var e = new E();\n e.Message = message;\n throw e;\n}\n</code></pre>\n\n<p>However, that doesn't compile because Exception.Message is read only. It can only be assigned by passing it to the constructor, and there's no way to constrain a generic type with something other than a default constructor.</p>\n\n<p>I think you'd have to use reflection (Activator.CreateInstance) to \"new up\" the custom exception type with the message parameter, like this:</p>\n\n<pre><code>static void TestException<E>(string message) where E : Exception\n{\n throw Activator.CreateInstance(typeof(E), message) as E;\n}\n</code></pre>\n\n<p><strong>Edit</strong> Oops just realised you're wanting to <em>return</em> the exception, not throw it. The same principle applies, so I'll leave my answer as-is with the throw statements.</p>\n"
},
{
"answer_id": 41450,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 4,
"selected": false,
"text": "<p>The only issue with the solution is that it is possible to create a subclass of Exception which does not implement a constructor with a single string parameter, so the MethodMissingException might be thrown.</p>\n\n<pre><code>static void TestException<E>(string message) where E : Exception, new()\n{\n try \n {\n return Activator.CreateInstance(typeof(E), message) as E;\n } \n catch(MissingMethodException ex) \n {\n return new E();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 9113952,
"author": "MiloNC",
"author_id": 1185299,
"author_profile": "https://Stackoverflow.com/users/1185299",
"pm_score": 1,
"selected": false,
"text": "<p>I have been instantiating inline the type of exception I want to throw, like this:</p>\n\n<pre><code>if (ItemNameIsValid(ItemName, out errorMessage))\n throw new KeyNotFoundException(\"Invalid name '\" + ItemName + \"': \" + errorMessage);\nif (null == MyArgument)\n throw new ArgumentNullException(\"MyArgument is null\");\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | Right, I know I am totally going to look an idiot with this one, but my brain is just *not* kicking in to gear this morning.
I want to have a method where I can say "if it goes bad, come back with this type of Exception", right?
For example, something like (**and this doesn't work**):
```
static ExType TestException<ExType>(string message) where ExType:Exception
{
Exception ex1 = new Exception();
ExType ex = new Exception(message);
return ex;
}
```
Now whats confusing me is that we *KNOW* that the generic type is going to be of an Exception type due to the *where* clause. However, the code fails because we cannot implicitly cast *Exception* to *ExType*. We cannot explicitly convert it either, such as:
```
static ExType TestException<ExType>(string message) where ExType:Exception
{
Exception ex1 = new Exception();
ExType ex = (ExType)(new Exception(message));
return ex;
}
```
As that fails too.. So **is this kind of thing possible?** I have a strong feeling its going to be real simple, but I am having a tough day with the old noggin, so cut me some slack :P
---
Update
------
Thanks for the responses guys, looks like it wasn't me being a *complete* idiot! ;)
OK, so [Vegard](https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41398) and [Sam](https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41404) got me on to the point where I could instantiate the correct type, but then obviously got stuck because the *message* param is read-only following instantiation.
[Matt](https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41408) hit the nail right on the head with his response, I have tested this and all works fine. Here is the example code:
```
static ExType TestException<ExType>(string message) where ExType:Exception, new ()
{
ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message);
return ex;
}
```
Sweet! :)
Thanks guys! | You can almost do it like this:
```
static void TestException<E>(string message) where E : Exception, new()
{
var e = new E();
e.Message = message;
throw e;
}
```
However, that doesn't compile because Exception.Message is read only. It can only be assigned by passing it to the constructor, and there's no way to constrain a generic type with something other than a default constructor.
I think you'd have to use reflection (Activator.CreateInstance) to "new up" the custom exception type with the message parameter, like this:
```
static void TestException<E>(string message) where E : Exception
{
throw Activator.CreateInstance(typeof(E), message) as E;
}
```
**Edit** Oops just realised you're wanting to *return* the exception, not throw it. The same principle applies, so I'll leave my answer as-is with the throw statements. |
41,400 | <p>I am looking to do this in C/C++. I came across <a href="http://www.swig.org/Doc1.3/Varargs.html" rel="nofollow noreferrer"><strong>Variable Length Arguments</strong></a>, but this suggests a solution with Python and C using <a href="http://sourceware.org/libffi/" rel="nofollow noreferrer">libffi</a>.</p>
<p>Now, if I want to wrap the <code>printf</code> function with <code>myprintf</code>.</p>
<p>I do it like below:</p>
<pre><code>void myprintf(char* fmt, ...)
{
va_list args;
va_start(args, fmt);
printf(fmt, args);
va_end(args);
}
int _tmain(int argc, _TCHAR* argv[])
{
int a = 9;
int b = 10;
char v = 'C';
myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b);
return 0;
}
</code></pre>
<p>But the results are not as expected!</p>
<pre class="lang-none prettyprint-override"><code>This is a number: 1244780 and
this is a character: h and
another number: 29953463
</code></pre>
<p>What did I miss?</p>
| [
{
"answer_id": 41413,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 0,
"selected": false,
"text": "<p>How do you mean a pure C/C++ solution?</p>\n<p>The rest parameter (...) is supported cross platform in the C runtime.</p>\n<p><em><a href=\"https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/va-arg-va-copy-va-end-va-start\" rel=\"nofollow noreferrer\">va_arg, va_copy, va_end, va_start</a></em></p>\n"
},
{
"answer_id": 41414,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "<p>Are you using C or C++? The next C++ version, C++0x, will support <a href=\"http://en.wikipedia.org/wiki/Varargs#Variadic_functions_in_C.2C_Objective-C_and_C.2B.2B\" rel=\"nofollow noreferrer\">variadic templates</a> which provide a solution to that problem.</p>\n\n<p>Another workaround can be achieved by clever operator overloading to achieve a syntax like this:</p>\n\n<pre><code>void f(varargs va) {\n BOOST_FOREACH(varargs::iterator i, va)\n cout << *i << \" \";\n}\n\nf(args = 1, 2, 3, \"Hello\");\n</code></pre>\n\n<p>In order to get this to work, the class <code>varargs</code> has to be implemented to override <code>operator =</code> that returns a proxy object which, in turn, overrides <code>operator ,</code>. However, making this variant type safe in current C++ isn't possible as far as I know since it would have to work by type erasure.</p>\n"
},
{
"answer_id": 41422,
"author": "David Sykes",
"author_id": 259,
"author_profile": "https://Stackoverflow.com/users/259",
"pm_score": 3,
"selected": false,
"text": "<p>I am also unsure what you mean by pure.</p>\n<p>In C++ we use:</p>\n<pre><code>#include <cstdarg>\n#include <cstdio>\n\nclass Foo\n{ \n void Write(const char* pMsg, ...);\n};\n\nvoid Foo::Write( const char* pMsg, ...)\n{\n char buffer[4096];\n std::va_list arg;\n va_start(arg, pMsg);\n std::vsnprintf(buffer, 4096, pMsg, arg);\n va_end(arg);\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 41794,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 7,
"selected": true,
"text": "<p>The problem is that you cannot use 'printf' with <em>va_args</em>. You must use <strong>vprintf</strong> if you are using variable argument lists. <em>vprint</em>, <em>vsprintf</em>, <em>vfprintf</em>, etc. (there are also 'safe' versions in Microsoft's C runtime that will prevent buffer overruns, etc.)</p>\n<p>You sample works as follows:</p>\n<pre><code>void myprintf(char* fmt, ...)\n{\n va_list args;\n va_start(args, fmt);\n vprintf(fmt, args);\n va_end(args);\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n int a = 9;\n int b = 10;\n char v = 'C';\n myprintf("This is a number: %d and \\nthis is a character: %c and \\n another number: %d\\n", a, v, b);\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 10380279,
"author": "john",
"author_id": 1053621,
"author_profile": "https://Stackoverflow.com/users/1053621",
"pm_score": 0,
"selected": false,
"text": "<pre><code>void myprintf(char* fmt, ...)\n{\n va_ list args;\n va_ start(args, fmt);\n printf(fmt, args); // This is the fault. "vprintf(fmt, args);"\n // should have been used.\n va_ end(args);\n}\n</code></pre>\n<p>If you're just trying to call <em>printf</em>,\nthere's a <em>printf</em> variant called <em>vprintf</em> that takes\nthe <em>va_list</em> directly: <em>vprintf(fmt, args);</em></p>\n"
},
{
"answer_id": 17837382,
"author": "Shafik Yaghmour",
"author_id": 1708801,
"author_profile": "https://Stackoverflow.com/users/1708801",
"pm_score": 4,
"selected": false,
"text": "<p>In <a href=\"https://en.wikipedia.org/wiki/C%2B%2B11\" rel=\"nofollow noreferrer\">C++11</a>, this is one possible solution using <a href=\"http://en.cppreference.com/w/cpp/language/parameter_pack\" rel=\"nofollow noreferrer\">variadic templates</a>:</p>\n<pre><code>template<typename... Args>\nvoid myprintf(const char* fmt, Args... args)\n{\n std::printf(fmt, args...);\n}\n</code></pre>\n<p>As <a href=\"https://stackoverflow.com/questions/41400/how-can-i-wrap-a-function-with-variable-length-arguments#comment26036756_41400\">rubenvb points out</a>, there are trade-offs to consider. For example, you will be generating code for each instance which will lead to code bloat.</p>\n"
},
{
"answer_id": 22048209,
"author": "basin",
"author_id": 447503,
"author_profile": "https://Stackoverflow.com/users/447503",
"pm_score": 3,
"selected": false,
"text": "<p>Actually, there's a way to call a function that doesn’t have a <code>va_list</code> version from a wrapper. The idea is to use assembler, do not touch arguments on the stack, and temporarily replace the function return address.</p>\n<p>An example for Visual C x86. <code>call addr_printf</code> calls <code>printf()</code>:</p>\n<pre><code>__declspec( thread ) static void* _tls_ret;\n\nstatic void __stdcall saveret(void *retaddr) {\n _tls_ret = retaddr;\n}\n\nstatic void* __stdcall _getret() {\n return _tls_ret;\n}\n\n__declspec(naked)\nstatic void __stdcall restret_and_return_int(int retval) {\n __asm {\n call _getret\n mov [esp], eax ; /* replace current retaddr with saved */\n mov eax, [esp+4] ; /* retval */\n ret 4\n }\n}\n\nstatic void __stdcall _dbg_printf_beg(const char *fmt, va_list args) {\n printf("calling printf(\\"%s\\")\\n", fmt);\n}\n\nstatic void __stdcall _dbg_printf_end(int ret) {\n printf("printf() returned %d\\n", ret);\n}\n\n__declspec(naked)\nint dbg_printf(const char *fmt, ...)\n{\n static const void *addr_printf = printf;\n /* prolog */\n __asm {\n push ebp\n mov ebp, esp\n sub esp, __LOCAL_SIZE\n nop\n }\n {\n va_list args;\n va_start(args, fmt);\n _dbg_printf_beg(fmt, args);\n va_end(args);\n }\n /* epilog */\n __asm {\n mov esp, ebp\n pop ebp\n }\n __asm {\n call saveret\n call addr_printf\n push eax\n push eax\n call _dbg_printf_end\n call restret_and_return_int\n }\n}\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123/"
] | I am looking to do this in C/C++. I came across [**Variable Length Arguments**](http://www.swig.org/Doc1.3/Varargs.html), but this suggests a solution with Python and C using [libffi](http://sourceware.org/libffi/).
Now, if I want to wrap the `printf` function with `myprintf`.
I do it like below:
```
void myprintf(char* fmt, ...)
{
va_list args;
va_start(args, fmt);
printf(fmt, args);
va_end(args);
}
int _tmain(int argc, _TCHAR* argv[])
{
int a = 9;
int b = 10;
char v = 'C';
myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b);
return 0;
}
```
But the results are not as expected!
```none
This is a number: 1244780 and
this is a character: h and
another number: 29953463
```
What did I miss? | The problem is that you cannot use 'printf' with *va\_args*. You must use **vprintf** if you are using variable argument lists. *vprint*, *vsprintf*, *vfprintf*, etc. (there are also 'safe' versions in Microsoft's C runtime that will prevent buffer overruns, etc.)
You sample works as follows:
```
void myprintf(char* fmt, ...)
{
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
}
int _tmain(int argc, _TCHAR* argv[])
{
int a = 9;
int b = 10;
char v = 'C';
myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b);
return 0;
}
``` |
41,407 | <p>I'm currently working on a parser for our internal log files (generated by log4php, log4net and log4j). So far I have a nice regular expression to parse the logs, except for one annoying bit: Some log messages span multiple lines, which I can't get to match properly. The regex I have now is this:</p>
<pre><code>(?<date>\d{2}/\d{2}/\d{2})\s(?<time>\d{2}):\d{2}:\d{2}),\d{3})\s(?<message>.+)
</code></pre>
<p>The log format (which I use for testing the parser) is this:</p>
<pre><code>07/23/08 14:17:31,321 log
message
spanning
multiple
lines
07/23/08 14:17:31,321 log message on one line
</code></pre>
<p>When I run the parser right now, I get only the line the log starts on. If I change it to span multiple lines, I get only one result (the whole log file).</p>
<hr>
<p>@samjudson:</p>
<p><em>You need to pass the RegexOptions.Singleline flag in to the regular expression, so that "." matches all characters, not just all characters except new lines (which is the default).</em></p>
<p>I tried that, but then it matches the whole file. I also tried to set the message-group to .+? (non-greedy), but then it matches a single character (which isn't what I'm looking for either).</p>
<p>The problem is that the pattern for the message matches on the date-group as well, so when it doesn't break on a new-line it just goes on and on and on.</p>
<hr>
<p>I use this regex for the message group now. It works, unless there's a pattern IN the log message which is the same as the start of the log message.</p>
<pre><code>(?<message>(.(?!\d{2}/\d{2}/\d{2}\s\d{2}:\d{2}:\d{2},\d{3}\s\[\d{4}\]))+)
</code></pre>
| [
{
"answer_id": 41412,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 0,
"selected": false,
"text": "<p>You need to pass the <code>RegexOptions</code>. Singleline flag in to the regular expression, so that \".\" matches all characters, not just all characters except new lines (which is the default).</p>\n"
},
{
"answer_id": 41423,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 1,
"selected": false,
"text": "<p>The problem you have is that you need to terminate the RegEx pattern so it knows when one message ends and then next starts.</p>\n\n<p>When you were running in default mode the newline was working as an implicit terminator.</p>\n\n<p>The problem is if you go into multiline mode there's no terminator so the pattern will gobble up the whole file. Non-greedy matches a few characters as possible which will be just one.</p>\n\n<p>Now, if use the date for the next message as the terminator I think your parser will only get every other line.</p>\n\n<p>Is there something else in the file you could to terminate the pattern?</p>\n"
},
{
"answer_id": 41425,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 2,
"selected": false,
"text": "<p>You obviously need that \"messages lines\" can be distinguished from \"log lines\"; if you allow the message part to start with date/time after a new line, then there is simply no way to determine what is part of a message and what not. So, instead of using the dot, you need an expression that allows anything that does not include a newline followed by a date and time.</p>\n\n<p>Personally, however, I would not use a regular expression to parse the whole log entry. I prefer using my own loop to iterate over each line and use one simple regular expression to determine whether a line is the start of a new entry or not. Also from the point of readability this would have my preference.</p>\n"
},
{
"answer_id": 41428,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 3,
"selected": true,
"text": "<p>This will only work if the log message doesn't contain a date at the beginning of the line, but you could try adding a negative look-ahead assertion for a date in the \"message\" group:</p>\n\n<pre><code>(?<date>\\d{2}/\\d{2}/\\d{2})\\s(?<time>\\d{2}:\\d{2}:\\d{2},\\d{3})\\s(?<message>(.(?!^\\d{2}/\\d{2}/\n\\d{2}))+)\n</code></pre>\n\n<p>Note that this requires the use of the RegexOptions.MultiLine flag.</p>\n"
},
{
"answer_id": 41551,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 0,
"selected": false,
"text": "<p>You might find it a lot easier to parse the file with a proper parser generator - ANTLR can generate one in C#... Context Free parsers only seem hard until you \"get\" them - after that, they are much simpler and friendlier to use than Regular Expressions...</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/909/"
] | I'm currently working on a parser for our internal log files (generated by log4php, log4net and log4j). So far I have a nice regular expression to parse the logs, except for one annoying bit: Some log messages span multiple lines, which I can't get to match properly. The regex I have now is this:
```
(?<date>\d{2}/\d{2}/\d{2})\s(?<time>\d{2}):\d{2}:\d{2}),\d{3})\s(?<message>.+)
```
The log format (which I use for testing the parser) is this:
```
07/23/08 14:17:31,321 log
message
spanning
multiple
lines
07/23/08 14:17:31,321 log message on one line
```
When I run the parser right now, I get only the line the log starts on. If I change it to span multiple lines, I get only one result (the whole log file).
---
@samjudson:
*You need to pass the RegexOptions.Singleline flag in to the regular expression, so that "." matches all characters, not just all characters except new lines (which is the default).*
I tried that, but then it matches the whole file. I also tried to set the message-group to .+? (non-greedy), but then it matches a single character (which isn't what I'm looking for either).
The problem is that the pattern for the message matches on the date-group as well, so when it doesn't break on a new-line it just goes on and on and on.
---
I use this regex for the message group now. It works, unless there's a pattern IN the log message which is the same as the start of the log message.
```
(?<message>(.(?!\d{2}/\d{2}/\d{2}\s\d{2}:\d{2}:\d{2},\d{3}\s\[\d{4}\]))+)
``` | This will only work if the log message doesn't contain a date at the beginning of the line, but you could try adding a negative look-ahead assertion for a date in the "message" group:
```
(?<date>\d{2}/\d{2}/\d{2})\s(?<time>\d{2}:\d{2}:\d{2},\d{3})\s(?<message>(.(?!^\d{2}/\d{2}/
\d{2}))+)
```
Note that this requires the use of the RegexOptions.MultiLine flag. |
41,479 | <p>After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?</p>
<p>For example I rather lazily used var in questionable circumstances, e.g.:-</p>
<pre><code>foreach(var item in someList) { // ... } // Type of 'item' not clear.
var something = someObject.SomeProperty; // Type of 'something' not clear.
var something = someMethod(); // Type of 'something' not clear.
</code></pre>
<p>More legitimate uses of var are as follows:-</p>
<pre><code>var l = new List<string>(); // Obvious what l will be.
var s = new SomeClass(); // Obvious what s will be.
</code></pre>
<p>Interestingly LINQ seems to be a bit of a grey area, e.g.:-</p>
<pre><code>var results = from r in dataContext.SomeTable
select r; // Not *entirely clear* what results will be here.
</code></pre>
<p>It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.</p>
<p>It's even worse when it comes to LINQ to objects, e.g.:-</p>
<pre><code>var results = from item in someList
where item != 3
select item;
</code></pre>
<p>This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.</p>
<p>There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable<int> and IEnumerable<double> the caller might inadvertently pass in the wrong type.</p>
<p><code>var</code> <em>does</em> maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.</p>
| [
{
"answer_id": 41486,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": false,
"text": "<p>I think the use of var should be coupled with wisely-chosen variable names.</p>\n\n<p>I have no problem using var in a foreach statement, provided it's not like this:</p>\n\n<pre><code>foreach (var c in list) { ... }\n</code></pre>\n\n<p>If it were more like this:</p>\n\n<pre><code>foreach (var customer in list) { ... }\n</code></pre>\n\n<p>... then someone reading the code would be much more likely to understand what \"list\" is. If you have control over the name of the list variable itself, that's even better.</p>\n\n<p>The same can apply to other situations. This is pretty useless:</p>\n\n<pre><code>var x = SaveFoo(foo);\n</code></pre>\n\n<p>... but this makes sense:</p>\n\n<pre><code>var saveSucceeded = SaveFoo(foo);\n</code></pre>\n\n<p>Each to his own, I guess. I've found myself doing this, which is just insane:</p>\n\n<pre><code>var f = (float)3;\n</code></pre>\n\n<p>I need some sort of 12-step var program. My name is Matt, and I (ab)use var.</p>\n"
},
{
"answer_id": 41487,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 1,
"selected": false,
"text": "<p>In our office, our CTO has categorically banned the use of the var keyword, for the same reasons that you have stated.</p>\n\n<p>Personally I find the use of var only valid in new object declarations, since the type of the object is obvious in the statement itself.</p>\n\n<p>For LINQ queries, you can resolve results to:</p>\n\n<pre><code>IEnumerable<TypeReturnedBySelectObject>\n</code></pre>\n"
},
{
"answer_id": 41488,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same concern when I started to use <em>var</em> keyword.<br>\nHowever I got used to it over time and not going to go back to explicit variable types. \nVisual Studio's compiler\\intellisense are doing a very good job on making work with implicitly typed variables much easier. </p>\n\n<p>I think that following proper naming conventions can help you to understand code much better then explicit typing.</p>\n\n<p>It seems to be same sort of questions like \"shoud I use prefixes in variable names?\".<br>\nStick with good variable names and let the compiler think on variable types.</p>\n"
},
{
"answer_id": 41496,
"author": "erlando",
"author_id": 4192,
"author_profile": "https://Stackoverflow.com/users/4192",
"pm_score": 2,
"selected": false,
"text": "<p>Someone doesn't like criticism of var.. All answers downmodded.. oh well..</p>\n\n<p>@Jon Limjap:\nI know. :) What I meant was that the readability is degraded like it is in VB6. I don't like to rely on Intellisense to figure out what type a given variable is. I want to be able to figure it out using the source alone.</p>\n\n<p>Naming conventions doesn't help either - I already use good names. Are we going back to prefixing?</p>\n"
},
{
"answer_id": 41501,
"author": "Murph",
"author_id": 1070,
"author_profile": "https://Stackoverflow.com/users/1070",
"pm_score": 3,
"selected": false,
"text": "<p>I think the key thing with VAR is to only use it where appropriate i.e. when doing things in Linq that it facilitates (and probably in other cases). </p>\n\n<p>If you've <em>got</em> a type for something in the then you should use it - not to do so is simple laziness (as opposed to creative laziness which is generally to be encouraged - good programmers oft work very hard to be lazy and could be considered the source of the thing in the first place).</p>\n\n<p>A blanket ban is as bad as abusing the construct in the first place but there does need to be a sensible coding standard.</p>\n\n<p>The other thing to remember is that its not a VB type var in that it can't change types - it <strong>is</strong> a strongly typed variable its just that the type is inferred (which is why there are people that will argue that its not unreasonable to use it in, say, a foreach but I'd disagree for reasons of both readability and maintainability).</p>\n\n<p>I suspect this one is going to run and run (-:</p>\n\n<p>Murph</p>\n"
},
{
"answer_id": 41503,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 4,
"selected": false,
"text": "<p>One specific case where var is difficult: offline code reviews, especially the ones done on paper.</p>\n\n<p>You can't rely on mouse-overs for that.</p>\n"
},
{
"answer_id": 41505,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 9,
"selected": true,
"text": "<p>I still think <code>var</code> can make code more readable in some cases. If I have a Customer class with an Orders property, and I want to assign that to a variable, I will just do this:</p>\n\n<pre><code>var orders = cust.Orders;\n</code></pre>\n\n<p>I don't care if Customer.Orders is <code>IEnumerable<Order></code>, <code>ObservableCollection<Order></code> or <code>BindingList<Order></code> - all I want is to keep that list in memory to iterate over it or get its count or something later on.</p>\n\n<p>Contrast the above declaration with:</p>\n\n<pre><code>ObservableCollection<Order> orders = cust.Orders;\n</code></pre>\n\n<p>To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from <code>ObservableCollection<Order></code> to <code>IList<Order></code>) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.</p>\n"
},
{
"answer_id": 41507,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>@erlando, out of curiosity, why do you need to know the variable's type looking at the source code? </p>\n\n<p>In my practice I found that variable type is matter for me only at the time I'm using it in the code. </p>\n\n<p>If I'm trying to do some inappropriate operation on <em>someVar</em> compiler gladly gives me an error\\warning.</p>\n\n<p>I really don't care what type <em>someVar</em> has if I understand <em>why</em> it's being used it the given context.</p>\n"
},
{
"answer_id": 41514,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": false,
"text": "<p>I use <code>var</code> extensively. There has been criticism that this diminishes the readability of the code, but no argument to support that claim.</p>\n\n<p>Admittedly, it may mean that it's not clear what type we are dealing with. So what? This is actually the point of a decoupled design. When dealing with interfaces, you are emphatically <em>not</em> interested in the type a variable has. <code>var</code> takes this much further, true, but I think that the argument remains the same from a readability point of view: The programmer shouldn't actually be interested in the type of the variable but rather in what a variable <em>does</em>. This is why Microsoft also calls type inference “duck typing.”</p>\n\n<p>So, what does a variable do when I declare it using <code>var</code>? Easy, it does whatever IntelliSense tells me it does. Any reasoning about C# that ignores the IDE falls short of reality. In practice, every C# code is programmed in an IDE that supports IntelliSense.</p>\n\n<p>If I am using a <code>var</code> declared variable and get confused what the variable is there for, there's something fundamentally wrong with my code. <code>var</code> is not the cause, it only makes the symptoms visible. Don't blame the messenger.</p>\n\n<p>Now, the C# team has released a coding guideline stating that <code>var</code> should <em>only</em> be used to capture the result of a LINQ statement that creates an anonymous type (because here, we have no real alternative to <code>var</code>). Well, screw that. As long as the C# team doesn't give me a sound argument for this guideline, I am going to ignore it because in my professional and personal opinion, it's pure baloney. (Sorry; I've got no link to the guideline in question.)</p>\n\n<p>Actually, there are some (superficially) <a href=\"http://www.devx.com/codemag/Article/37010/0/page/2\" rel=\"noreferrer\">good explanations</a> on why you shouldn't use <code>var</code> but I still believe they are largely wrong. Take the example of “searchabililty”: the author claims that <code>var</code> makes it hard to search for places where <code>MyType</code> is used. Right. So do interfaces. Actually, why would I want to know where the class is used? I might be more interested in where it is instantiated and this will still be searchable because somewhere its constructor has to be invoked (even if this is done indirectly, the type name has to be mentioned somewhere).</p>\n"
},
{
"answer_id": 41516,
"author": "erlando",
"author_id": 4192,
"author_profile": "https://Stackoverflow.com/users/4192",
"pm_score": 3,
"selected": false,
"text": "<p>@aku: One example is code reviews. Another example is refactoring scenarios.</p>\n\n<p>Basically I don't want to go type-hunting with my mouse. It might not be available.</p>\n"
},
{
"answer_id": 41519,
"author": "Frep D-Oronge",
"author_id": 3024,
"author_profile": "https://Stackoverflow.com/users/3024",
"pm_score": 4,
"selected": false,
"text": "<p>I don't see what the big deal is..</p>\n\n<pre><code>var something = someMethod(); // Type of 'something' not clear <-- not to the compiler!\n</code></pre>\n\n<p>You still have full intellisense on 'something', and for any ambiguous case you have your unit tests, right? ( do you? )</p>\n\n<p>It's not varchar, it's not dim, and it's certainly not dynamic or weak typing. It is stopping maddnes like this:</p>\n\n<pre><code>List<somethinglongtypename> v = new List<somethinglongtypename>();\n</code></pre>\n\n<p>and reducing that total mindclutter to:</p>\n\n<pre><code>var v = new List<somethinglongtypename>();\n</code></pre>\n\n<p>Nice, not quite as nice as:</p>\n\n<pre><code>v = List<somethinglongtypename>();\n</code></pre>\n\n<p>But then that's what <a href=\"http://www.google.co.uk/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fboo.codehaus.org%2F&ei=XH2-SMO4B4iO1wbX1-Vf&usg=AFQjCNGs4DK8A1ZnEgL7s8pcGjlMMmDOFg&sig2=X0tf_m1xNuEdJ_UetIC19A\" rel=\"nofollow noreferrer\">Boo</a> is for.</p>\n"
},
{
"answer_id": 41520,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>@erlando,</p>\n\n<p>Talking about refactoring it seems to be much easier to change variable type by assigning instance of new type to one variable rather then changing it in multiple places, isn't it ?</p>\n\n<p>As for code review I see no big issues with <em>var</em> keyword. During code review I prefer to check code logic rather variable types. Of course there might be scenarios where developer can use inappropriate type but I think that number of such cases is so small it wouldn't be a reason for my to stop using <em>var</em> keyword.</p>\n\n<p>So I repeat my question. <em>Why</em> does variable type matter to you?</p>\n"
},
{
"answer_id": 41523,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 3,
"selected": false,
"text": "<p>It's a matter of taste. All this fussing about the <em>type</em> of a variable disappears when you get used to dynamically typed languages. That is, <em>if</em> you ever start to like them (I'm not sure if everybody can, but I do).</p>\n\n<p>C#'s <code>var</code> is pretty cool in that it <em>looks</em> like dynamic typing, but actually is <strong>static</strong> typing - the compiler enforces correct usage.</p>\n\n<p>The type of your variable is not really that important (this has been said before). It should be relatively clear from the context (its interactions with other variables and methods) and its name - don't expect <em>customerList</em> to contain an <code>int</code>...</p>\n\n<p>I am still waiting to see what my boss thinks of this matter - I got a blanket \"go ahead\" to use any new constructs in 3.5, but what will we do about maintenance?</p>\n"
},
{
"answer_id": 41531,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<p>In your comparison between <code>IEnumerable<int></code> and <code>IEnumerable<double></code> you don't need to worry - if you pass the wrong type your code won't compile anyway.</p>\n\n<p>There's no concern about type-safety, as <code>var</code> is <strong>not</strong> dynamic. It's just compiler magic and any type unsafe calls you make will get caught. </p>\n\n<p><code>Var</code> is absolutely needed for Linq:</p>\n\n<pre><code>var anonEnumeration =\n from post in AllPosts()\n where post.Date > oldDate\n let author = GetAuthor( post.AuthorId )\n select new { \n PostName = post.Name, \n post.Date, \n AuthorName = author.Name\n };\n</code></pre>\n\n<p>Now look at <em>anonEnumeration</em> in intellisense and it will appear something like <code>IEnumerable<'a></code></p>\n\n<pre><code>foreach( var item in anonEnumeration ) \n{\n //VS knows the type\n item.PostName; //you'll get intellisense here\n\n //you still have type safety\n item.ItemId; //will throw a compiler exception\n}\n</code></pre>\n\n<p>The C# compiler is pretty clever - anon types generated separately will have the same generated type if their properties match.</p>\n\n<p>Outside of that, as long as you have intellisense it makes good sense to use <code>var</code> anywhere the context is clear.</p>\n\n<pre><code>//less typing, this is good\nvar myList = new List<UnreasonablyLongClassName>();\n\n//also good - I can't be mistaken on type\nvar anotherList = GetAllOfSomeItem();\n\n//but not here - probably best to leave single value types declared\nvar decimalNum = 123.456m;\n</code></pre>\n"
},
{
"answer_id": 41532,
"author": "robi-y",
"author_id": 4388,
"author_profile": "https://Stackoverflow.com/users/4388",
"pm_score": 3,
"selected": false,
"text": "<p>I split var all over the places, the only questionable places for me are internal short types, e.g. I prefer <code>int i = 3;</code> over <code>var i = 3;</code></p>\n"
},
{
"answer_id": 41634,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 0,
"selected": false,
"text": "<p>@Keith - </p>\n\n<blockquote>\n <p>In your comparison between\n IEnumerable<int> and\n IEnumerable<double> you don't need to\n worry - if you pass the wrong type\n your code won't compile anyway.</p>\n</blockquote>\n\n<p>That isn't quite true - if a method is overloaded to both IEnumerable<int> and IEnumerable<double> then it may silently pass the unexpected inferred type (due to some other change in the program) to the wrong overload hence causing incorrect behaviour.</p>\n\n<p>I suppose the question is how likely it is that this sort of situation will come up!</p>\n\n<p>I guess part of the problem is how much confusion var adds to a given declaration - if it's not clear what type something is (despite being strongly typed and the compiler understanding entirely what type it is) someone might gloss over a type safety error, or at least take longer to understand a piece of code.</p>\n"
},
{
"answer_id": 41689,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 1,
"selected": false,
"text": "<p>I use var in the following situations:</p>\n\n<ol>\n<li>When I have to (result is anonymous)</li>\n<li><p>When the type is on the same line as the code, e.g.</p>\n\n<p>var emp = new Employee();</p></li>\n</ol>\n\n<p>Its obvious we want an Employee (because we're creating a new Employee object), so how is </p>\n\n<pre><code>Employee emp = new Employee() any more obvious?\n</code></pre>\n\n<p>I do NOT use var when the type cannot be inferred, e.g.</p>\n\n<pre><code>var emp = GetEmployee();\n</code></pre>\n\n<p>Because the return type is not immediately obvious (is at an Employee, an IEmployee, something that has nothing to do with an Employee object at all, etc?).</p>\n"
},
{
"answer_id": 41695,
"author": "Pat",
"author_id": 36,
"author_profile": "https://Stackoverflow.com/users/36",
"pm_score": 2,
"selected": false,
"text": "<p>After just converting over to the 3.0 and 3.5 frameworks I learned about this keyword and decided to give it a whirl. Before committing any code I had the realization that it seemed backwards, as in going back toward an ASP syntax. So I decided to poke the higher ups to see what they thought. </p>\n\n<p>They said go ahead so I use it.</p>\n\n<p>With that said I avoid using it where the type requires some investigation, like this:</p>\n\n<p>var a = company.GetRecords();</p>\n\n<p>Now it could just be a personal thing but I immediately cant look at that and determine if its a collection of Record objects or a string array representing the name of records. Whichever the case I believe explicit declaration is useful in such an instance.</p>\n"
},
{
"answer_id": 41981,
"author": "Kevin Berridge",
"author_id": 4407,
"author_profile": "https://Stackoverflow.com/users/4407",
"pm_score": 1,
"selected": false,
"text": "<p>I have to agree with <a href=\"https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c#41486\">Matt Hamilton</a>.</p>\n\n<p>Var can make your code much more readable and understandable when used with good variable names. But var can also make your code as impossible to read and understand as Perl when used badly. </p>\n\n<p>A list of good and bad uses of var isn't really going to help much either. This is a case for common sense. The larger question is one of readability vs. write-ability. Lots of devs don't care if their code is readable. They just don't want to type as much. Personally I'm a read > write guy.</p>\n"
},
{
"answer_id": 43621,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 1,
"selected": false,
"text": "<p>kronoz - in that case (overloads for both) would it matter? If you have two overloads that took the different types you would essentially be saying that either can be passed and do the same thing.</p>\n\n<p>You shouldn't have two overloads that do completely different actions depending on the types passed.</p>\n\n<p>While you might get some confusion in that instance it would still be entirely type safe, you'd just have someone calling the wrong method.</p>\n"
},
{
"answer_id": 51785,
"author": "Tundey",
"author_id": 1453,
"author_profile": "https://Stackoverflow.com/users/1453",
"pm_score": 1,
"selected": false,
"text": "<p>I don't understand why people start debates like this. It really serves no purpose than to start flame wars at then end of which nothing is gained. Now if the C# team was trying to phase out one style in favor of the other, I can see the reason to argue over the merits of each style. But since both are going to remain in the language, why not use the one <em>you</em> prefer and let everybody do the same. It's like the use of everybody's favorite ternary operator: some like it and some don't. At the end of the day, it makes no difference to the compiler.</p>\n\n<p>This is like arguing with your siblings over which is your favorite parent: it doesn't matter unless they are divorcing!</p>\n"
},
{
"answer_id": 55642,
"author": "nedruod",
"author_id": 5504,
"author_profile": "https://Stackoverflow.com/users/5504",
"pm_score": 2,
"selected": false,
"text": "<p>Static typing is about contracts, not source code. The idea there is a need to have the static information on a single line of what \"should\" be a small method. Common guidelines recommend rarely exceeding 25 lines per method.</p>\n\n<p>If a method is large enough that you can't keep track of a single variable within that method, you are doing something else wrong that would make any criticism of var pale in comparison.</p>\n\n<p>Actually, one of the great arguments for var is that it can make refactoring simpler because you no longer have to worry that you made your declaration overly restrictive (i.e. you used List<> when you should have used IList<>, or IEnumerable<>). You still want to think about the new methods signature, but at least you won't have to go back and change your declarations to match.</p>\n"
},
{
"answer_id": 67083,
"author": "AlanR",
"author_id": 7311,
"author_profile": "https://Stackoverflow.com/users/7311",
"pm_score": 1,
"selected": false,
"text": "<p>I find that using the var keyword actually makes the code more readable because you just get used to skipping the 'var' keyword. You don't need to keep scrolling right to figure out what the code is doing when you really don't care about what the specific type is. If I really need to know what type 'item' is below, I just hover my mouse over it and Visual Studio will tell me. In other words, I would much rather read</p>\n\n<pre><code>foreach( var item in list ) { DoWork( item ); }\n</code></pre>\n\n<p>over and over than</p>\n\n<pre><code>foreach( KeyValuePair<string, double> entry in list ) { DoWork( Item ); }\n</code></pre>\n\n<p>when I am trying to digest the code. I think it boils down to personal preference to some extent. I would rely on common sense on this one -- save enforcing standards for the important stuff (security, database use, logging, etc.)</p>\n\n<p>-Alan.</p>\n"
},
{
"answer_id": 78833,
"author": "Dexter",
"author_id": 10717,
"author_profile": "https://Stackoverflow.com/users/10717",
"pm_score": 5,
"selected": false,
"text": "<p>We've adopted the ethos \"Code for people, not machines\", based on the assumption that you spend multiple times longer in maintenance mode than on new development.</p>\n\n<p>For me, that rules out the argument that the compiler \"knows\" what type the variable is - sure, you can't write invalid code the first time because the compiler stops your code from compiling, but when the next developer is reading the code in 6 months time they need to be able to deduce what the variable is doing correctly or incorrectly and quickly identify the cause of issues.</p>\n\n<p>Thus,</p>\n\n<pre><code>var something = SomeMethod();\n</code></pre>\n\n<p>is outlawed by our coding standards, but the following is encouraged in our team because it increases readability:</p>\n\n<pre><code>var list = new List<KeyValuePair<string, double>>();\nFillList( list );\nforeach( var item in list ) {\n DoWork( item ); \n}\n</code></pre>\n"
},
{
"answer_id": 96490,
"author": "Dustman",
"author_id": 16398,
"author_profile": "https://Stackoverflow.com/users/16398",
"pm_score": 6,
"selected": false,
"text": "<p>From Eric Lippert, a Senior Software Design Engineer on the C# team:</p>\n\n<p>Why was the <code>var</code> keyword introduced?</p>\n\n<blockquote>\n <p>There are two reasons, one which\n exists today, one which will crop up\n in 3.0.</p>\n \n <p>The first reason is that this code is\n incredibly ugly because of all the\n redundancy:</p>\n \n <p><code>Dictionary<string, List<int>> mylists = new Dictionary<string, List<int>>();</code></p>\n \n <p>And that's a simple example – I've\n written worse. Any time you're forced\n to type exactly the same thing twice,\n that's a redundancy that we can\n remove. Much nicer to write</p>\n \n <p><code>var mylists = new Dictionary<string,List<int>>();</code></p>\n \n <p>and let the compiler figure out what\n the type is based on the assignment.</p>\n \n <p>Second, C# 3.0 introduces anonymous\n types. Since anonymous types by\n definition have no names, you <strong>need</strong> to\n be able to infer the type of the\n variable from the initializing\n expression if its type is anonymous.</p>\n</blockquote>\n\n<p>Emphasis mine. The whole article, <a href=\"http://blogs.msdn.com/ericlippert/archive/2005/09/27/c-3-0-is-still-statically-typed-honest.aspx\" rel=\"noreferrer\">C# 3.0 is still statically typed, honest!</a>, and the ensuing <a href=\"http://blogs.msdn.com/ericlippert/archive/tags/Type+Inference/default.aspx\" rel=\"noreferrer\">series</a> are pretty good.</p>\n\n<p>This is what <code>var</code> is for. Other uses probably will not work so well. Any comparison to JScript, VBScript, or dynamic typing is total bunk. Note again, <code>var</code> is <strong>required</strong> in order to have certain other features work in .NET.</p>\n"
},
{
"answer_id": 105485,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 3,
"selected": false,
"text": "<p>To me, the antipathy towards <code>var</code> illustrates why bilingualism in .NET is important. To those C# programmers who have also done VB .NET, the advantages of <code>var</code> are intuitively obvious. The standard C# declaration of:</p>\n\n<pre><code>List<string> whatever = new List<string>();\n</code></pre>\n\n<p>is the equivalent, in VB .NET, of typing this:</p>\n\n<pre><code>Dim whatever As List(Of String) = New List(Of String)\n</code></pre>\n\n<p>Nobody does that in VB .NET, though. It would be silly to, because since the first version of .NET you've been able to do this...</p>\n\n<pre><code>Dim whatever As New List(Of String)\n</code></pre>\n\n<p>...which creates the variable and initializes it all in one reasonably compact line. Ah, but what if you want an <code>IList<string></code>, not a <code>List<string></code>? Well, in VB .NET that means you have to do this:</p>\n\n<pre><code>Dim whatever As IList(Of String) = New List(Of String)\n</code></pre>\n\n<p>Just like you'd have to do in C#, and obviously couldn't use <code>var</code> for:</p>\n\n<pre><code>IList<string> whatever = new List<string>();\n</code></pre>\n\n<p>If you <em>need</em> the type to be something different, it can be. But one of the basic principles of good programming is reducing redundancy, and that's exactly what var does.</p>\n"
},
{
"answer_id": 133732,
"author": "Neil Hewitt",
"author_id": 22178,
"author_profile": "https://Stackoverflow.com/users/22178",
"pm_score": 3,
"selected": false,
"text": "<p>Use it for anonymous types - that's what it's there for. Anything else is a use too far. Like many people who grew up on C, I'm used to looking at the left of the declaration for the type. I don't look at the right side unless I have to. Using <code>var</code> for any old declaration makes me do that all the time, which I personally find uncomfortable.</p>\n\n<p>Those saying 'it doesn't matter, use what you're happy with' are not seeing the whole picture. Everyone will pick up other people's code at one point or another and have to deal with whatever decisions they made at the time they wrote it. It's bad enough having to deal with radically different naming conventions, or - the classic gripe - bracing styles, without adding the whole '<code>var</code> or not' thing into the mix. The worst case will be where one programmer didn't use <code>var</code> and then along comes a maintainer who loves it, and extends the code using it. So now you have an unholy mess. </p>\n\n<p>Standards are a good thing precisely because they mean you're that much more likely to be able to pick up random code and be able to grok it quickly. The more things that are different, the harder that gets. And moving to the 'var everywhere' style makes a <strong>big</strong> difference.</p>\n\n<p>I don't mind dynamic typing, and I don't mind implict typing - in languages that are designed for them. I quite like Python. But C# was designed as a statically explicitly-typed language and that's how it should stay. Breaking the rules for anonymous types was bad enough; letting people take that still further and break the idioms of the language even more is something I'm not happy with. Now that the genie is out of the bottle, it'll never go back in. C# will become balkanised into camps. Not good.</p>\n"
},
{
"answer_id": 213704,
"author": "TimothyP",
"author_id": 28149,
"author_profile": "https://Stackoverflow.com/users/28149",
"pm_score": 1,
"selected": false,
"text": "<p>I think people do not understand the var keyword.\nThey confuse it with the Visual Basic / JavaScript keyword,\nwhich is a different beast all toghether.</p>\n\n<p>Many people think the var keyword implies\nweak typing (or dynamic typing), while in fact c# is and remains strongly typed.</p>\n\n<p>If you consider this in javascript:</p>\n\n<pre><code>var something = 5;\n</code></pre>\n\n<p>you are allowed to:</p>\n\n<pre><code>something = \"hello\";\n</code></pre>\n\n<p>In the case of c#, the compiler would infer the type from the first statement,\ncausing something to be of type \"int\", so the second statement would result\nin an exception.</p>\n\n<p>People simply need to understand that using the var keyword does not imply\ndynamic typing and then decide how far they want to take the use of the var keyword,\nknowing it will have absolutely no difference as to what will be compiled.</p>\n\n<p>Sure the var keyword was introduced to support anonymous types,\nbut if you look at this:</p>\n\n<pre><code>LedDeviceController controller = new LedDeviceController(\"172.17.0.1\");\n</code></pre>\n\n<p>It's very very verbose, and I'm sure this is just as readable, if not more:</p>\n\n<pre><code>var controller = new LedDeviceController(\"172.17.0.1\");\n</code></pre>\n\n<p>The result is exactly the same, so yes I use it throughout my code</p>\n\n<p>UPDATE:</p>\n\n<p>Maybe, just maybe... they should have used another keyword,\nthen we would not be having this discussion... perhaps the \"infered\" keyword instead of \"var\"</p>\n"
},
{
"answer_id": 321277,
"author": "Richard Ev",
"author_id": 39709,
"author_profile": "https://Stackoverflow.com/users/39709",
"pm_score": 0,
"selected": false,
"text": "<p><code>var</code> is essential for anonymous types (as pointed out in one of the previous responses to this question).</p>\n\n<p>I would categorise all other discussion of its pros and cons as \"religious war\". By that I mean that a comparison and discussion of the relative merits of...</p>\n\n<pre><code>var i = 5;\nint j = 5;\n\nSomeType someType = new SomeType();\nvar someType = new SomeType();\n</code></pre>\n\n<p>...is entirely subjective.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb384061.aspx\" rel=\"nofollow noreferrer\">Implicit typing</a> means that there is no runtime penalty for any variable being declared using the <code>var</code> keyword, so it comes down to being a debate about what makes the developers happy. </p>\n"
},
{
"answer_id": 391590,
"author": "Rostov",
"author_id": 2108310,
"author_profile": "https://Stackoverflow.com/users/2108310",
"pm_score": 3,
"selected": false,
"text": "<p>Stolen from the <a href=\"http://www.codinghorror.com/blog/archives/001136.html\" rel=\"nofollow noreferrer\">post on this issue at CodingHorror</a>:</p>\n\n<hr>\n\n<p><em>Unfortunately, you and everyone else pretty much got it wrong. While I agree with you that redundancy is not a good thing, the better way to solve this issue would have been to do something like the following:</p>\n\n<p>MyObject m = new();</p>\n\n<p>Or if you are passing parameters:</p>\n\n<p>Person p = new(\"FirstName\", \"LastName);</p>\n\n<p>Where in the creation of a new object, the compiler infers the type from the left-hand side, and not the right. This has other advantages over \"var\", in that it could be used in field declarations as well (there are also some other areas that it could be useful as well, but I won't get into it here).</p>\n\n<p>In the end, it just wasn't intended to reduce redundancy. Don't get me wrong, \"var\" is VERY important in C# for anonymous types/projections, but the use here is just WAY off (and I've been saying this for a long, long time) as you obfuscate the type that is being used. Having to type it twice is too often, but declaring it zero times is too few.</p>\n\n<p>Nicholas Paldino .NET/C# MVP on June 20, 2008 08:00 AM</em></p>\n\n<hr>\n\n<p>I guess if your main concern is to have to type less -- then there isn't any argument that's going to sway you from using it.</p>\n\n<p>If you are only going to <strong>ever</strong> be the person who looks at your code, then who cares? Otherwise, in a case like this:</p>\n\n<pre><code>var people = Managers.People\n</code></pre>\n\n<p>it's fine, but in a case like this:</p>\n\n<pre><code>var fc = Factory.Run();\n</code></pre>\n\n<p>it short circuits any immediate type deductions my brain could begin forming from the 'English' of the code.</p>\n\n<p>Otherwise, just use your best judgment and programming 'courtesy' towards others who might have to work on your project.</p>\n"
},
{
"answer_id": 488436,
"author": "Christian Klauser",
"author_id": 55208,
"author_profile": "https://Stackoverflow.com/users/55208",
"pm_score": 2,
"selected": false,
"text": "<p>I use <code>var</code> whenever possible. </p>\n\n<p>The actual type of the local variable <em>shouldn't matter</em> if your code is well written (i.e., good variable names, comments, clear structure etc.)</p>\n"
},
{
"answer_id": 498706,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 0,
"selected": false,
"text": "<p>I don't use var as it goes against the roots of C# - C/C++/Java. Even though it's a compiler trick it makes the language feel like it's less strongly typed. Maybe 20+ years of C have engrained it all into our (the anti-var people's) heads that we should have the type on both the left and right side of the equals.</p>\n\n<p>Having said that I can see its merits for long generic collection definitions and long class names like the codinghorror.com example, but elsewhere such as string/int/bool I really can't see the point. Particularly</p>\n\n<pre><code>foreach (var s in stringArray)\n{\n\n}\n</code></pre>\n\n<p>a saving of 3 characters!</p>\n\n<p>The main annoyance for me is not being able to see the type that the var represents for method calls, unless you hover over the method or F12 it.</p>\n"
},
{
"answer_id": 537411,
"author": "user37468",
"author_id": 37468,
"author_profile": "https://Stackoverflow.com/users/37468",
"pm_score": 0,
"selected": false,
"text": "<p>VS2008 w/resharper 4.1 has correct typing in the tooltip when you hover over \"var\" so I think it should be able to find this when you look for all usages of a class.</p>\n\n<p>Haven't yet tested that it does that yet though.</p>\n"
},
{
"answer_id": 792765,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 1,
"selected": false,
"text": "<p>Arriving a bit late at this discussion, but I'd just like to add a thought.</p>\n\n<p>To all those who are against type inference (because that's what we're really talking about here), what about lambda expressions? If you insist on always declaring types explicitly (except for anonymous types), what do you do with lambdas? How does the \"Don't make me use mouseover\" argument apply to var but not to lambdas?</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I've just thought of one argument against 'var' which I don't think anyone has mentioned yet, which is that it 'breaks' \"Find all references\", which could mean (for example) that if you were checking out usage of a class before refactoring, you would miss all the place where the class was used via <code>var</code>.</p>\n"
},
{
"answer_id": 971916,
"author": "Colin",
"author_id": 119660,
"author_profile": "https://Stackoverflow.com/users/119660",
"pm_score": 0,
"selected": false,
"text": "<p>Depends, somehow it makes the code look 'cleaner', but agree it makes it more unreadable to...</p>\n"
},
{
"answer_id": 971919,
"author": "mqp",
"author_id": 55943,
"author_profile": "https://Stackoverflow.com/users/55943",
"pm_score": 3,
"selected": false,
"text": "<p>I guess it depends on your perspective. I personally have never had any difficulty understanding a piece of code because of <code>var</code> \"misuse\", and my coworkers and I use it quite a lot all over. (I agree that Intellisense is a huge aid in this regard.) I welcome it as a way to remove repetitive cruft.</p>\n\n<p>After all, if statements like</p>\n\n<pre><code>var index = 5; // this is supposed to be bad\n\nvar firstEligibleObject = FetchSomething(); // oh no what type is it\n // i am going to die if i don't know\n</code></pre>\n\n<p>were really that impossible to deal with, nobody would use dynamically typed languages.</p>\n"
},
{
"answer_id": 971930,
"author": "SLaks",
"author_id": 34397,
"author_profile": "https://Stackoverflow.com/users/34397",
"pm_score": 0,
"selected": false,
"text": "<p>It can make code simpler and shorter, especially with complicated generic types and delegates.</p>\n\n<p>Also, it makes variable types easier to change.</p>\n"
},
{
"answer_id": 971934,
"author": "Colin Desmond",
"author_id": 93399,
"author_profile": "https://Stackoverflow.com/users/93399",
"pm_score": 4,
"selected": false,
"text": "<p>Given how powerful Intellisense is now, I am not sure var is any harder to read than having member variables in a class, or local variables in a method which are defined off the visible screen area. </p>\n\n<p>If you have a line of code such as </p>\n\n<pre><code>IDictionary<BigClassName, SomeOtherBigClassName> nameDictionary = new Dictionary<BigClassName, SomeOtherBigClassName>();\n</code></pre>\n\n<p>Is is much easier or harder to read than:</p>\n\n<pre><code>var nameDictionary = new Dictionary<BigClassName, SomeOtherBigClassName>();\n</code></pre>\n"
},
{
"answer_id": 971943,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 0,
"selected": false,
"text": "<p><code>var</code> is great when you don't want to repeat yourself. For example, I needed a data structure yesterday that was similar to this. Which representation do you prefer?</p>\n\n<pre><code>Dictionary<string, Dictionary<string, List<MyNewType>>> collection = new Dictionary<string, Dictionary<string, List<MyNewType>>>();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var collection = new Dictionary<string, Dictionary<string, List<MyNewType>>>();\n</code></pre>\n\n<p>Note that there is little ambiguity introduced by using <code>var</code> in this example. However, there are times when it wouldn't be such a good idea. For example, if I used <code>var</code> as in the following,</p>\n\n<pre><code>var value= 5;\n</code></pre>\n\n<p>when I could just write the real type and remove any ambiguity in how <code>5</code> should be represented.</p>\n\n<pre><code>double value = 5;\n</code></pre>\n"
},
{
"answer_id": 971949,
"author": "Richard",
"author_id": 67392,
"author_profile": "https://Stackoverflow.com/users/67392",
"pm_score": 3,
"selected": false,
"text": "<p>It can certainly make things simpler, from code I wrote yesterday:</p>\n\n<pre><code>var content = new Queue<Pair<Regex, Func<string, bool>>>();\n...\nforeach (var entry in content) { ... }\n</code></pre>\n\n<p>This would have be extremely verbose without <code>var</code>.</p>\n\n<p>Addendum: A little time spent with a language with <em>real</em> type inference (e.g. F#) will show just how good compilers are at getting the type of expressions right. It certainly has meant I tend to use <code>var</code> as much as I can, and using an explicit type now indicates that the variable is not of the initialising expression's type.</p>\n"
},
{
"answer_id": 971967,
"author": "BFree",
"author_id": 15861,
"author_profile": "https://Stackoverflow.com/users/15861",
"pm_score": 3,
"selected": false,
"text": "<p>Many time during testing, I find myself having code like this:</p>\n\n<pre><code>var something = myObject.SomeProperty.SomeOtherThing.CallMethod();\nConsole.WriteLine(something);\n</code></pre>\n\n<p>Now, sometimes, I'll want to see what the SomeOtherThing itself contains, SomeOtherThing is not the same type that CallMethod() returns. Since I'm using var though, I just change this:</p>\n\n<pre><code>var something = myObject.SomeProperty.SomeOtherThing.CallMethod();\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>var something = myObject.SomeProperty.SomeOtherThing;\n</code></pre>\n\n<p>Without var, I'd have to keep changing the declared type on the left hand side as well. I know it's minor, but it's extremely convenient.</p>\n"
},
{
"answer_id": 971997,
"author": "Serapth",
"author_id": 101767,
"author_profile": "https://Stackoverflow.com/users/101767",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think var per say is a terrible language feature, as I use it daily with code like what Jeff Yates described. Actually, almost everytime I use var is because generics can make for some extremely wordy code. I live verbose code but generics take it a step too far.</p>\n\n<p>That said, I (obviously... ) think var is ripe for abuse. If code gets to 20+ lines in a method with vars littered through out, you will quickly make maintenance a nightmare. Additionally, var in a tutorial is incredibly counter intuitive and generally is a giant no-no in my books.</p>\n\n<p>On the flipside, var is an \"easy\" feature that new programmers are going to latch onto and love. Then, within a few minutes/hours/days hit a massive roadblock when they start hitting the limits. \"Why can't I return var from functions?\" That kind of question. Also, adding a pseudo dynamic type to a strongly typed language is something that can easily trip up a new developer. In the long run, I think the var keyword will actually make c# harder to learn for new programmers.</p>\n\n<p>That said, as an experienced programmer I do use var, mostly when dealing with generics ( and obviously anonymous types ). I do hold by my quote, I do believe var will be one of the worst abused c# features.</p>\n"
},
{
"answer_id": 972071,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 2,
"selected": false,
"text": "<p>There is bound to be disagreement near the edge cases, but I can tell you my personal guidelines.</p>\n\n<p>I look at these the criteria when I decide to use <code>var</code>:</p>\n\n<ul>\n<li>The type of the variable is <em>obvious</em> [to a human] from the context</li>\n<li>The exact type of the variable is <em>not particularly relevant</em> [to a human]<br>\n<em>[e.g. you can figure out what the algorithm is doing without caring about what kind of container you are using]</em></li>\n<li>The type name is very long and interrupts the readability of the code (<em>hint: usually a generic</em>)</li>\n</ul>\n\n<p>Conversely, these situations would push me to not use <code>var</code>:</p>\n\n<ul>\n<li>The type name is relatively short and easy to read (<em>hint: usually not a generic</em>)</li>\n<li>The type is <em>not obvious</em> from the initializer's name</li>\n<li>The exact type is very important to understand the code/algorithm</li>\n<li>On class hierarchies, when a human can't easily tell which level of the hierarchy is being used</li>\n</ul>\n\n<p>Finally, I would never use <code>var</code> for native value types or corresponding <code>nullable<></code> types (<code>int</code>, <code>decimal</code>, <code>string</code>, <code>decimal?</code>, ...). There is an implicit assumption that if you use <code>var</code>, there must be \"a reason\".</p>\n\n<p>These are all guidelines. You should also think also about the experience and skills of your coworkers, the complexity of the algorithm, the longevity/scope of the variable, etc, etc.</p>\n\n<p>Most of the time, there is no perfect right answer. Or, it doesn't really matter.</p>\n\n<p><em>[Edit: removed a duplicate bullet]</em></p>\n"
},
{
"answer_id": 1031291,
"author": "Jamie Eisenhart",
"author_id": 19533,
"author_profile": "https://Stackoverflow.com/users/19533",
"pm_score": 0,
"selected": false,
"text": "<p>From <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321564162\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Essential LINQ</a>:</p>\n\n<p>It is best not to explicitly declare the type of a range variable unless absolutely necessary. For instance, the following code compiles cleanly, but the type could have been inferred by the compiler without a formal declaration:</p>\n\n<pre><code>List<string> list = new List<string> { \"LINQ\", \"query\", \"adventure\" };\nvar query = from string word in list\n where word.Contains(\"r\")\n orderby word ascending\n select word;\n</code></pre>\n\n<p>Explicitly declaring the type of a range variable forces a behind-the-scenes call to the LINQ Cast operator. This call may have unintended consequences and may hurt performance. If you encounter performance problems with a LINQ query, a cast like the one shown here is one possible place to begin looking for the culprit. (The one exception to this rule is when you are working with a nongeneric Enumerable, in which case you should use the cast.)</p>\n"
},
{
"answer_id": 1298234,
"author": "Ignas R",
"author_id": 153569,
"author_profile": "https://Stackoverflow.com/users/153569",
"pm_score": 3,
"selected": false,
"text": "<p>None, except that you don't have to write the type name twice. <a href=\"http://msdn.microsoft.com/en-us/library/bb383973.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb383973.aspx</a></p>\n"
},
{
"answer_id": 1298236,
"author": "Rune FS",
"author_id": 112407,
"author_profile": "https://Stackoverflow.com/users/112407",
"pm_score": 2,
"selected": false,
"text": "<p>It's purely a convinience. The compiler will inferre the type (based on the type of the expression on the right hand side)</p>\n"
},
{
"answer_id": 1298237,
"author": "ShdNx",
"author_id": 128240,
"author_profile": "https://Stackoverflow.com/users/128240",
"pm_score": 3,
"selected": false,
"text": "<p>In most cases, it's just simpler to type it - imagine</p>\n\n<pre><code>var sb = new StringBuilder();\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\n</code></pre>\n\n<p>Sometimes it's required, for example: anonymous types, like.</p>\n\n<pre><code>var stuff = new { Name = \"Me\", Age = 20 };\n</code></pre>\n\n<p>I personally like using it, in spite of the fact that it makes the code less readable and maintainable.</p>\n"
},
{
"answer_id": 1298256,
"author": "GONeale",
"author_id": 41211,
"author_profile": "https://Stackoverflow.com/users/41211",
"pm_score": 0,
"selected": false,
"text": "<p>You don't have to write out the type name and no this is not less performant as the type is resolved at compile time.</p>\n"
},
{
"answer_id": 1298268,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": false,
"text": "<p>The most likely time you'll need this is for anonymous types (where it is 100% required); but it also avoids repetition for the trivial cases, and IMO makes the line clearer. I don't need to see the type twice for a simple initialization.</p>\n\n<p>For example:</p>\n\n<pre><code>Dictionary<string, List<SomeComplexType<int>>> data = new Dictionary<string, List<SomeComplexType<int>>>();\n</code></pre>\n\n<p>(please don't edit the hscroll in the above - it kinda proves the point!!!)</p>\n\n<p>vs:</p>\n\n<pre><code>var data = new Dictionary<string, List<SomeComplexType<int>>>();\n</code></pre>\n\n<p>There are, however, occasions when this is misleading, and can potentially cause bugs. Be careful using <code>var</code> if the original variable and initialized type weren't identical. For example:</p>\n\n<pre><code>static void DoSomething(IFoo foo) {Console.WriteLine(\"working happily\") }\nstatic void DoSomething(Foo foo) {Console.WriteLine(\"formatting hard disk...\");}\n\n// this working code...\nIFoo oldCode = new Foo();\nDoSomething(oldCode);\n// ...is **very** different to this code\nvar newCode = new Foo();\nDoSomething(newCode);\n</code></pre>\n"
},
{
"answer_id": 1298283,
"author": "MartinStettner",
"author_id": 81424,
"author_profile": "https://Stackoverflow.com/users/81424",
"pm_score": 3,
"selected": false,
"text": "<p>Using <code>var</code> instead of explicit type makes refactorings much easier (therefore I must contradict the previous posters who meant it made no difference or it was purely \"syntactic sugar\").</p>\n\n<p>You can change the return type of your methods without changing every file where this method is called. Imagine</p>\n\n<pre><code>...\nList<MyClass> SomeMethod() { ... }\n...\n</code></pre>\n\n<p>which is used like</p>\n\n<pre><code>...\nIList<MyClass> list = obj.SomeMethod();\nforeach (MyClass c in list)\n System.Console.WriteLine(c.ToString());\n...\n</code></pre>\n\n<p>If you wanted to refactor <code>SomeMethod()</code> to return an <code>IEnumerable<MySecondClass></code>, you would have to change the variable declaration (also inside the <code>foreach</code>) in every place you used the method.</p>\n\n<p>If you write</p>\n\n<pre><code>...\nvar list = obj.SomeMethod();\nforeach (var element in list)\n System.Console.WriteLine(element.ToString());\n...\n</code></pre>\n\n<p>instead, you don't have to change it.</p>\n"
},
{
"answer_id": 1298297,
"author": "Ira Baxter",
"author_id": 120163,
"author_profile": "https://Stackoverflow.com/users/120163",
"pm_score": 1,
"selected": false,
"text": "<p>You can let the compiler (and the fellow who maintains the code next) infer the type from the right hand side of the initializer assignment. If this inference is possible, the compiler can do it so it saves some typing on your part. </p>\n\n<p>If the inference is easy for that poor fellow, then you haven't hurt anything. If the inference is hard, you've made the code harder to maintain and so as a general rule\nI wouldn't do it.</p>\n\n<p>Lastly, if you intended the type to be something particular, and your initializer expression actually has a different type, using var means it will be harder for you to find the induced bug. By explicitly telling the compiler what you intend the type to be, when the type isn't that, you would get an immediate diagnostic. By sluffing on the type declaration and using \"var\", you won't get an error on the initialization; instead, you'll get a type error in some expression that uses the identifier assigned by the var expression, and it will be harder to understand why.</p>\n\n<p>So the moral is, use var sparingly; you generally aren't doing yourself or your downstream fellow maintainer a lot of good. And hope he reasons the same way, so you aren't stuck guessing his intentions because <em>he</em> thought using var was easy. Optimizing on how much you type is a mistake when coding a system with a long life.</p>\n"
},
{
"answer_id": 1298706,
"author": "saret",
"author_id": 155438,
"author_profile": "https://Stackoverflow.com/users/155438",
"pm_score": 1,
"selected": false,
"text": "<p>Sometimes the compiler can also infer what is required \"better\" than the developer - at least a developer who does not understand what the api he's using requires.</p>\n\n<p>For example - when using linq:</p>\n\n<p>Example 1</p>\n\n<pre><code>Func<Person, bool> predicate = (i) => i.Id < 10;\nIEnumerable<Person> result = table.Where(predicate);\n</code></pre>\n\n<p>Example 2</p>\n\n<pre><code>var predicate = (Person i) => i.Id < 10;\nvar result = table.Where(predicate);\n</code></pre>\n\n<p>In the above code - assuming one is using Linq to Nhibernate or Linq to SQL, Example 1 will\nbring the entire resultset for Person objects back and then do filter on the client end.\nExample 2 however will do the query on the server (such as on Sql Server with SQL) as the compiler is smart enough to work out that the Where function should take a Expression> rather than a Func. </p>\n\n<p>The result in Example 1 will also not be further queryable on the server as an IEnumerable is returned, while in Example 2 the compiler can work out if the result should rather be a IQueryable instead of IEnumerable</p>\n"
},
{
"answer_id": 1367659,
"author": "krystan honour",
"author_id": 134848,
"author_profile": "https://Stackoverflow.com/users/134848",
"pm_score": 3,
"selected": false,
"text": "<p>I used to think that the var keyword was a great invention but I put a a limit on it this was</p>\n\n<ul>\n<li>Only use var where it is obvious what the type is immediately (no scrolling or looking at return types)</li>\n</ul>\n\n<p>I came to realise this then gave me no benefit whatsoever and removed all var keywords from my code (unless they were specifically required), for now I think that they make the code less readable, especially to others reading your code.</p>\n\n<p>It hides intent and in at least one instance lead to a runtime bug in some code because of assumption of type.</p>\n"
},
{
"answer_id": 1724070,
"author": "David_001",
"author_id": 209578,
"author_profile": "https://Stackoverflow.com/users/209578",
"pm_score": 2,
"selected": false,
"text": "<p>From the discussion on this topic, the outcome appears to be:</p>\n\n<p>Good: <code>var customers = new List<Customer>();</code></p>\n\n<p>Controversial: <code>var customers = dataAccess.GetCustomers();</code></p>\n\n<p>Ignoring the misguided opinion that \"var\" magically helps with refactoring, the biggest issue for me is people's insistence that they don't care what the return type is, \"so long as they can enumerate the collection\". </p>\n\n<p>Consider: </p>\n\n<pre><code>IList<Customer> customers = dataAccess.GetCustomers();\n\nvar dummyCustomer = new Customer();\ncustomers.Add(dummyCustomer);\n</code></pre>\n\n<p>Now consider:</p>\n\n<pre><code>var customers = dataAccess.GetCustomers();\n\nvar dummyCustomer = new Customer();\ncustomers.Add(dummyCustomer);\n</code></pre>\n\n<p>Now, go and refactor the data access class, so that GetCustomers returns <code>IEnumerable<Customer></code>, and see what happens...</p>\n\n<p>The problem here is that in the first example you're making your expectations of the GetCustomers method explicit - you're saying that you expect it to return something that behaves like a list. In the second example, this expectation is implicit, and not immediately obvious from the code.</p>\n\n<p>It's interesting (to me) that a lot of pro-var arguments say \"i don't care what type it returns\", but go on to say \"i just need to iterate over it...\". (so it needs to implement the IEnumerable interface, implying the type <em>does</em> matter).</p>\n"
},
{
"answer_id": 2427596,
"author": "Wray Smallwood",
"author_id": 291765,
"author_profile": "https://Stackoverflow.com/users/291765",
"pm_score": 3,
"selected": false,
"text": "<p>For the afficionados that think <code>var</code> saves time, it takes less keystrokes to type:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\n</code></pre>\n\n<p>than</p>\n\n<pre><code>var sb = new StringBuilder();\n</code></pre>\n\n<p>Count em if you don't believe me...</p>\n\n<p>19 versus 21</p>\n\n<p>I'll explain if I have to, but just try it... (depending on the current state of your intellisense you may have to type a couple more for each one)</p>\n\n<p>And it's true for every type you can think of!!</p>\n\n<p>My personal feeling is that var should never be used except where the type is not known because it reduces recognition readabiltiy in code. It takes the brain longer to recognize the type than a full line. Old timers who understand machine code and bits know exactly what I am talking about. The brain processes in parallel and when you use var you force it to serialize its input. Why would anyone want to make their brain work harder? That's what computers are for.</p>\n"
},
{
"answer_id": 2746399,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 2,
"selected": false,
"text": "<p>Amazed this hasn't been noted so far, but it is common sense to use <code>var</code> for <code>foreach</code> loop variables.</p>\n\n<p>If you specify a specific type instead, you risk having a runtime cast silently inserted into your program by the compiler!</p>\n\n<pre><code>foreach (Derived d in listOfBase)\n{\n</code></pre>\n\n<p>The above will compile. But the compiler inserts a downcast from <code>Base</code> to <code>Derived</code>. So if anything on the list is not a <code>Derived</code> at runtime, there is an invalid cast exception. Type safety is compromised. Invisible casts are horrible.</p>\n\n<p>The only way to rule this out is to use <code>var</code>, so the compiler determines the type of the loop variable from the static type of the list.</p>\n"
},
{
"answer_id": 2866043,
"author": "Kate Gregory",
"author_id": 203458,
"author_profile": "https://Stackoverflow.com/users/203458",
"pm_score": 5,
"selected": false,
"text": "<p>Var is not like variant at all. The variable is still strongly typed, it's just that you don't press keys to get it that way. You can hover over it in Visual Studio to see the type. If you're reading printed code, it's possible you might have to think a little to work out what the type is. But there is only one line that declares it and many lines that use it, so giving things decent names is still the best way to make your code easier to follow.</p>\n\n<p>Is using Intellisense lazy? It's less typing than the whole name. Or are there things that are less work but don't deserve criticism? I think there are, and var is one of them.</p>\n"
},
{
"answer_id": 2866052,
"author": "Jeff Sternal",
"author_id": 47886,
"author_profile": "https://Stackoverflow.com/users/47886",
"pm_score": 1,
"selected": false,
"text": "<p><em>Deleted for reasons of redundancy.</em></p>\n\n<p><code>vars</code> are still initialized as the correct variable type - the compiler just infers it from the context. As you alluded to, var enables us to store references to anonymous class instances - but it also makes it easier to change your code. For example:</p>\n\n<pre><code>// If you change ItemLibrary to use int, you need to update this call\nbyte totalItemCount = ItemLibrary.GetItemCount();\n\n// If GetItemCount changes, I don't have to update this statement.\nvar totalItemCount = ItemLibrary.GetItemCount();\n</code></pre>\n\n<p>Yes, if it's hard to determine a variable's type from its name and usage, by all means explicitly declare its type.</p>\n"
},
{
"answer_id": 2866054,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>It's not bad, it's more a stylistic thing, which tends to be subjective. It can add inconsistencies, when you do use var and when you don't. </p>\n\n<p>Another case of concern, in the following call you can't tell just by looking at the code the type returned by <code>CallMe</code>:</p>\n\n<pre><code>var variable = CallMe();\n</code></pre>\n\n<p>That's my main complain against var.</p>\n\n<p>I use var when I declare anonymous delegates in methods, somehow var looks cleaner than if I'd use <code>Func</code>. Consider this code:</p>\n\n<pre><code>var callback = new Func<IntPtr, bool>(delegate(IntPtr hWnd) {\n ...\n});\n</code></pre>\n\n<p><strong>EDIT</strong>: Updated the last code sample based on Julian's input</p>\n"
},
{
"answer_id": 2866064,
"author": "Adam Robinson",
"author_id": 82187,
"author_profile": "https://Stackoverflow.com/users/82187",
"pm_score": 7,
"selected": false,
"text": "<p>Neither of those is absolutely true; <code>var</code> can have both positive and negative effects on readability. In my opinion, <code>var</code> should be used when either of the following is true:</p>\n\n<ol>\n<li>The type is anonymous (well, you don't have any choice here, as it <em>must</em> be var in this case)</li>\n<li>The type is obvious based upon the assigned expression (i.e. <code>var foo = new TypeWithAReallyLongNameTheresNoSenseRepeating()</code>)</li>\n</ol>\n\n<p><code>var</code> has no performance impacts, as it's syntactic sugar; the compiler infers the type and defines it once it's compiled into IL; there's nothing <em>actually</em> dynamic about it.</p>\n"
},
{
"answer_id": 2866065,
"author": "andypaxo",
"author_id": 46575,
"author_profile": "https://Stackoverflow.com/users/46575",
"pm_score": 1,
"selected": false,
"text": "<p>In my opinion, there is no problem in using <code>var</code> heavily. It is not a type of its own (you are still using static typing). Instead it's just a time saver, letting the compiler figure out what to do.</p>\n\n<p>Like any other time saver (such as auto properties for example), it <em>is</em> a good idea to understand what it is and how it works before using it everywhere.</p>\n"
},
{
"answer_id": 2866071,
"author": "Martin Harris",
"author_id": 69824,
"author_profile": "https://Stackoverflow.com/users/69824",
"pm_score": 2,
"selected": false,
"text": "<p>I think you <em>may</em> be misunderstanding the usage of var in C#. It <em>is</em> still strong typing, unlike the VB varient type so there is no performance hit from using it or not.</p>\n\n<p>Since there is no effect on the final compiled code it really is a stylist choice. Personally I don't use it since I find the code easier to read with the full types defined, but I can imagine a couple of years down the line that full type declaration will be looked at in the same way as Hungarian notation is now - extra typing for no real benefit over the information that intellisense gives us by default.</p>\n"
},
{
"answer_id": 2866075,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 7,
"selected": false,
"text": "<p>Var, in my opinion, in C# is a <em>good thing</em><sup>tm</sup>. Any variable so typed is still strongly typed, but it gets its type from the right-hand side of the assignment where it is defined. Because the type information is available on the right-hand side, in most cases, it's unnecessary and overly verbose to also have to enter it on the left-hand side. I think this significantly increases readability without decreasing type safety.</p>\n\n<p>From my perspective, using good naming conventions for variables and methods is more important from a readability perspective than explicit type information. If I need the type information, I can always hover over the variable (in VS) and get it. Generally, though, explicit type information shouldn't be necessary to the reader. For the developer, in VS you still get Intellisense, regardless of how the variable is declared. Having said all of that, there may still be cases where it does make sense to explicitly declare the type -- perhaps you have a method that returns a <code>List<T></code>, but you want to treat it as an <code>IEnumerable<T></code> in your method. To ensure that you are using the interface, declaring the variable of the interface type can make this explicit. Or, perhaps, you want to declare a variable without an initial value -- because it immediately gets a value based on some condition. In that case you need the type. If the type information is useful or necessary, go ahead and use it. I feel, though, that typically it isn't necessary and the code is easier to read without it in most cases.</p>\n"
},
{
"answer_id": 2866077,
"author": "Randolpho",
"author_id": 12716,
"author_profile": "https://Stackoverflow.com/users/12716",
"pm_score": 1,
"selected": false,
"text": "<p><code>var</code> is not bad. Remember this. <code>var</code> is not bad. Repeat it. <code>var</code> is not bad. Remember this. <code>var</code> is not bad. Repeat it. </p>\n\n<p>If the compiler is smart enough to figure out the type from the context, then so are you. You don't have to have it written down right there at declaration. And intellisense makes that even less necessary. </p>\n\n<p><code>var</code> is not bad. Remember this. <code>var</code> is not bad. Repeat it. <code>var</code> is not bad. Remember this. <code>var</code> is not bad. Repeat it. </p>\n"
},
{
"answer_id": 2866080,
"author": "Guffa",
"author_id": 69083,
"author_profile": "https://Stackoverflow.com/users/69083",
"pm_score": 4,
"selected": false,
"text": "<p>If someone is using the <code>var</code> keyword because they don't want to \"figure out the type\", that is definitely the wrong reason. The <code>var</code> keyword doesn't create a variable with a dynamic type, the compiler still has to know the type. As the variable always has a specific type, the type should also be evident in the code if possible.</p>\n\n<p>Good reasons to use the <code>var</code> keyword are for example:</p>\n\n<ul>\n<li>Where it's needed, i.e. to declare a reference for an anonymous type.</li>\n<li>Where it makes the code more readable, i.e. removing repetetive declarations.</li>\n</ul>\n\n<p>Writing out the data type often makes the code easier to follow. It shows what data types you are using, so that you don't have to figure out the data type by first figuring out what the code does.</p>\n"
},
{
"answer_id": 2866088,
"author": "Andrey",
"author_id": 283676,
"author_profile": "https://Stackoverflow.com/users/283676",
"pm_score": 0,
"selected": false,
"text": "<p>First.</p>\n\n<p><code>var</code> is not a type and not some special feature (like c# 4.0 <code>dynamic</code>). It is just a syntax sugar. You ask compiler to infer the type by the right hand side expression. The only necessary place is anonymous types.</p>\n\n<p>I don't think that using <code>var</code> is neither good or evil, it is coding style. Personally i don't use it, but i don't mind using it by other team members.</p>\n"
},
{
"answer_id": 2866092,
"author": "chris",
"author_id": 4782,
"author_profile": "https://Stackoverflow.com/users/4782",
"pm_score": 2,
"selected": false,
"text": "<p>I think you point out the main problem with var in your question: \"I don't have to figure out the type\". As other have pointed out, there is a place for var, but if you don't know the type you're dealing with, there's a pretty good chance that you're going to have problems down the road - not in all cases, but there's enough of a smell there so that you should be suspicious.</p>\n"
},
{
"answer_id": 2866094,
"author": "kastermester",
"author_id": 40240,
"author_profile": "https://Stackoverflow.com/users/40240",
"pm_score": 2,
"selected": false,
"text": "<p>Well this one is pretty much gonna be opinionated all the way through, but I will try to give my view on it - albeit I think my view is so mixed up that you are probably not gonna get much out of it anyways.</p>\n\n<p>First of all - there's anonymous types, for which you need to use the \"var\" keyword in order to assign an object with an anonymous type as its class - there's not much discussion here, \"var\" is needed.</p>\n\n<p>For simpler types however, ints, longs, strings - so forth - I tend to put in the proper types. Mainly because it is a bit of a \"lazy man's tool\" and I don't see much gain here, very few keystrokes and the possible confusion it could provide later down the road just ain't worth it. Especially the various types for floating point numbers (float, double, decimal) confuse me as I am not firm with the postfixes in the literals - I like to see the type in the source code.</p>\n\n<p>With that said, I tend to use var alot if the type is more complex and/or it is explicitly repeated on the righthand-side of the assignment. This could be a <code>List<string></code> or etc, such as:</p>\n\n<pre><code>var list = new List<string>();\n</code></pre>\n\n<p>In a such case, I see no use to repeat the type twice - and especially as you start changing your code and the types change - the generic types might get more and more complicated and as such having to change them twice is just a pain. However of course if you wish to code against an <code>IList<string></code> then you have to name the type explicitly.</p>\n\n<p>So in short I do the following:</p>\n\n<ul>\n<li>Name the type explicitly when the type is short or cannot be read out of context</li>\n<li>Use var when it has to be used (duh)</li>\n<li>Use var to be lazy when it (in my mind) does not hurt readability</li>\n</ul>\n"
},
{
"answer_id": 2866100,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 3,
"selected": false,
"text": "<p>Sure, <code>int</code> is easy, but when the variable's type is <code>IEnumerable<MyStupidLongNamedGenericClass<int, string>></code>, var makes things much easier.</p>\n"
},
{
"answer_id": 2866236,
"author": "Christian Specht",
"author_id": 6884,
"author_profile": "https://Stackoverflow.com/users/6884",
"pm_score": 3,
"selected": false,
"text": "<p>I only use var when it's clear to see what type is used.</p>\n\n<p>For example, I would use var in this case, because you can see immediately that x will be of the type \"MyClass\":</p>\n\n<pre><code>var x = new MyClass();\n</code></pre>\n\n<p>I would NOT use var in cases like this, because you have to drag the mouse over the code and look at the tooltip to see what type MyFunction returns:</p>\n\n<pre><code>var x = MyClass.MyFunction();\n</code></pre>\n\n<p>Especially, I <strong>never</strong> use var in cases where the right side is not even a method, but only a value:</p>\n\n<pre><code>var x = 5;\n</code></pre>\n\n<p><em>(because the compiler can't know if I want a byte, short, int or whatever)</em></p>\n"
},
{
"answer_id": 2866354,
"author": "Christopher Barber",
"author_id": 334526,
"author_profile": "https://Stackoverflow.com/users/334526",
"pm_score": 2,
"selected": false,
"text": "<p>Apart from readability concerns, there is one real issue with the use of 'var'. When used to define variables that are assigned to later in the code it can lead to broken code if the type of the expression used to initialize the variable changes to a narrower type. Normally it would be safe to refactor a method to return a narrower type than it did before: e.g. to replace a return type of 'Object' with some class 'Foo'. But if there is a variable whose type is inferred based on the method, then changing the return type will mean that this variable can longer be assigned a non-Foo object:</p>\n\n<pre><code>var x = getFoo(); // Originally declared to return Object\nx = getNonFoo();\n</code></pre>\n\n<p>So in this example, changing the return type of getFoo would make the assignment from getNonFoo illegal.</p>\n\n<p>This is not such a big deal if getFoo and all of its uses are in the same project, but if getFoo is in a library for use by external projects you can no longer be sure that narrowing the return type will not break some users code if they use 'var' like this.</p>\n\n<p>It was for exactly this reason that when we added a similar type inferencing feature to the Curl programming language (called 'def' in Curl) that we prevent assignments to variables defined using this syntax.</p>\n"
},
{
"answer_id": 2866628,
"author": "kervin",
"author_id": 16549,
"author_profile": "https://Stackoverflow.com/users/16549",
"pm_score": 0,
"selected": false,
"text": "<p>Eric's answer here...</p>\n\n<p><a href=\"https://stackoverflow.com/questions/2590643/namespace-scoped-aliases-for-generic-types-in-c/2593664#2593664\">Namespace scoped aliases for generic types in C#</a></p>\n\n<p>is related. </p>\n\n<p>Part of the issue is that there is no strongly typed aliasing in C#. So many developers use <em>var</em> as a partial surrogate.</p>\n"
},
{
"answer_id": 2866735,
"author": "stormianrootsolver",
"author_id": 339087,
"author_profile": "https://Stackoverflow.com/users/339087",
"pm_score": -1,
"selected": false,
"text": "<p>Don't use that, makes your code unreadable.</p>\n\n<p>ALWAYS use as strict typing as possible, crutches only makes your life hell.</p>\n"
},
{
"answer_id": 2866767,
"author": "Andrew Lewis",
"author_id": 25650,
"author_profile": "https://Stackoverflow.com/users/25650",
"pm_score": 0,
"selected": false,
"text": "<p>It's not wrong, but it can be inappropriate. See all the other responses for examples.</p>\n\n<p>var x = 5; <em>(bad)</em></p>\n\n<p>var x = new SuperDooperClass(); <em>(good)</em></p>\n\n<p>var x = from t in db.Something select new { Property1 = t.Field12 }; <em>(better)</em></p>\n"
},
{
"answer_id": 2866779,
"author": "Joshua",
"author_id": 14768,
"author_profile": "https://Stackoverflow.com/users/14768",
"pm_score": 0,
"selected": false,
"text": "<p>\"The only thing you can really say about my taste is that it is old fashioned, and in time yours will be too.\" -Tolkien.</p>\n"
},
{
"answer_id": 2866857,
"author": "Will Marcouiller",
"author_id": 162167,
"author_profile": "https://Stackoverflow.com/users/162167",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/bb383973.aspx\" rel=\"nofollow noreferrer\"><code>var</code></a> is a placeholder introduced for the <a href=\"http://msdn.microsoft.com/en-us/library/bb397696.aspx\" rel=\"nofollow noreferrer\"><code>anonymous types</code></a> in C# 3.0 and LINQ.</p>\n\n<p>As such, it allows writing LINQ queries for a fewer amount of columns within, let's say, a collection. No need to duplicate the information in memory, only load what's necessary to accomplish what you need to be done.</p>\n\n<p>The use of <code>var</code> is not bad at all, as it is actually not a type, but as mentioned elsewhere, a placeholder for the type which is and has to be defined on the right-hand side of the equation. Then, the compiler will replace the keyword with the type itself.</p>\n\n<p>It is particularly useful when, even with IntelliSense, the name of a type is long to type. Just write <code>var</code>, and instantiate it. The other programmers who will read your code afterward will easily understand what you're doing.</p>\n\n<p>It's like using</p>\n\n<pre><code>public object SomeObject { get; set; }\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>public object SomeObject {\n get {\n return _someObject;\n } \n set {\n _someObject = value;\n }\n}\nprivate object _someObject;\n</code></pre>\n\n<p>Everyone knows what's the property's doing, as everyone knows what the <code>var</code> keyword is doing, and either examples tend to ease readability by making it lighter, and make it more pleasant for the programmer to write effective code.</p>\n"
},
{
"answer_id": 2867274,
"author": "Jerry Liu",
"author_id": 240951,
"author_profile": "https://Stackoverflow.com/users/240951",
"pm_score": 0,
"selected": false,
"text": "<p><code>var</code> is good as it follows the classic <a href=\"http://en.wikipedia.org/wiki/Don't_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> rule, and it is especially elegant when you indicate the type in the same line as declaring the variable. (e.g. <code>var city = new City()</code>)</p>\n"
},
{
"answer_id": 2867468,
"author": "Julie in Austin",
"author_id": 344661,
"author_profile": "https://Stackoverflow.com/users/344661",
"pm_score": 1,
"selected": false,
"text": "<p>If you know the type, use the type.\nIf you don't know the type, why not?\nIf you can't know the type, that's okay -- you've found the only valid use.</p>\n\n<p>And I'm sorry, but if the best you can do is \"it makes the code all line up\", that's not a good answer. Find a different way to format your code.</p>\n"
},
{
"answer_id": 3288508,
"author": "Igor Brejc",
"author_id": 55408,
"author_profile": "https://Stackoverflow.com/users/55408",
"pm_score": 1,
"selected": false,
"text": "<p>One good argument why vars should not be used as a mere \"typing shortcut\", but should instead be used for scenarios they were primarily designed for: Resharper (at least v4.5) cannot find usages of a type if it is represented as a var. This can be a real problem when refactoring or analyzing the source code.</p>\n"
},
{
"answer_id": 3367011,
"author": "Glenn Doten",
"author_id": 277774,
"author_profile": "https://Stackoverflow.com/users/277774",
"pm_score": -1,
"selected": false,
"text": "<p>If you are lazy and use var for anything other than anonymous types, you should be required to use Hungarian notation in the naming of such variables.</p>\n\n<p><code>var iCounter = 0;</code></p>\n\n<p>lives!</p>\n\n<p>Boy, do I miss VB.</p>\n"
},
{
"answer_id": 3466472,
"author": "user418243",
"author_id": 418243,
"author_profile": "https://Stackoverflow.com/users/418243",
"pm_score": 1,
"selected": false,
"text": "<p>what most are ignoring:</p>\n\n<pre><code>var something = new StringBuilder(); \n</code></pre>\n\n<p>isn't normally typed as fast as </p>\n\n<pre><code>StringBuilder something = KEY'TAB'();\n</code></pre>\n"
},
{
"answer_id": 4013498,
"author": "David Mårtensson",
"author_id": 479137,
"author_profile": "https://Stackoverflow.com/users/479137",
"pm_score": 2,
"selected": false,
"text": "<p>With LINQ another very good reason to use <code>var</code> is that the compiler can optimize the query much more.</p>\n\n<p>If you use a static list to store the result it will execute where you assign it to the list but with <code>var</code> it can potential merge the original query with later queries in the code to make more optimized queries to the database.</p>\n\n<p>I had an example where I pulled some data in a first query and then looped over and requested more data to print out a table.</p>\n\n<p>LINQ merges these so that the first only pulled the id.</p>\n\n<p>Then in the loop it added an extra join I had not done there to fetch the data I had included in the original.</p>\n\n<p>When tested this proved much more efficient.</p>\n\n<p>Had we not used <code>var</code> it had made the queries exactly as we had written them.</p>\n"
},
{
"answer_id": 4021071,
"author": "Martin Olsen",
"author_id": 487233,
"author_profile": "https://Stackoverflow.com/users/487233",
"pm_score": 2,
"selected": false,
"text": "<p>I'm fairly new in the C# world, after a decade as a Java professional. My initial thought was along the lines of \"Oh no! There goes type safety down the drain\". However, the more I read about var, the more I like it.</p>\n\n<p>1) Var is every bit as type safe as an explicitly declared type would be. It's all about compile time syntactic sugar.</p>\n\n<p>2) It follows the principle of DRY (don't repeat yourself). DRY is all about avoiding redundancies, and naming the type on both sides is certainly redundant. Avoinding redundancy is all about making your code easier to change.</p>\n\n<p>3) As for knowing the exact type .. well .. I would argue that you always have a general idea is you have an integer, a socket, some UI control, or whatever. Intellisense will guide you from here. Knowing the exact type often does not matter. E.g. I would argue that 99% of the time you don't care if a given variable is a long or an int, a float or a double. For the last 1% of the cases, where it really matters, just hover the mouse pointer above the var keyword.</p>\n\n<p>4) I've seen the ridiculous argument that now we would need to go back to 1980-style Hungarian warts in order to distinguish variable types. After all, this was the only way to tell the types of variables back in the days of Timothy Dalton playing James Bond. But this is 2010. We have learned to name our variables based upon their usage and their contents and let the IDE guide us as to their type. Just keep doing this and var will not hurt you.</p>\n\n<p>To sum it up, var is not a big thing, but it is a really nice thing, and it is a thing that Java better copy soon. All arguments against seem to be based upon pre-IDE fallacies. I would not hesitate to use it, and I'm happy the R# helps me do so.</p>\n"
},
{
"answer_id": 8207749,
"author": "Mel",
"author_id": 642269,
"author_profile": "https://Stackoverflow.com/users/642269",
"pm_score": 0,
"selected": false,
"text": "<p>var is the way to deal with anonymous types, whether from LINQ statements or not. Any other use is heavily dependent on who will read your code and what guidelines are in place. </p>\n\n<p>If you are the only audience or your audience is comfortable with using var or is very familiar with your code then I guess it doesn't matter. If you use it like: <strong>var s = new SqlConnection()</strong> then it largely doesnt matter and probably improves code readability. If people aren't too picky and its okay for them to do a little work to know the type when its not apparent (which is not needed in most cases, how you use it in the following statements would usually explain everything) then its alright.</p>\n\n<p>But if you have picky, close-minded teammates who love to whine or if your company's design guidelines specifically forbid using var when the type is not obvious then you will most likely meet heavy opposition. </p>\n\n<p>If using var makes your code insanely difficult to read, you will probably get shot by using var even if its probably your app design that is to blame.</p>\n\n<p>If var introduces ambiguity (sort of like your IEnumerable/IEnumerable example), just don't use it and be explicit. But var does have its conveniences and in some cases, IMHO, even improves readabilty by reducing clutter.</p>\n"
},
{
"answer_id": 8236836,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>var is like the dotted spaces in kids' books where kids have to fill it. Except in this case the Compiler will fill it with the right type which is usually written after the = sign.</p>\n"
},
{
"answer_id": 8294143,
"author": "Muhammad Atif Agha",
"author_id": 727794,
"author_profile": "https://Stackoverflow.com/users/727794",
"pm_score": 0,
"selected": false,
"text": "<p>Local variables can be given an inferred \"type\" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. </p>\n\n<p>// z is compiled as an int</p>\n\n<pre><code>var z = 100;\n</code></pre>\n\n<p>// s is compiled as a string below</p>\n\n<pre><code>var s = \"Hello\";\n</code></pre>\n\n<p>// a is compiled as int[]</p>\n\n<pre><code>var a = new[] { 0, 1, 2 };\n</code></pre>\n\n<p>// expr is compiled as IEnumerable\n// or perhaps IQueryable</p>\n\n<pre><code>var expr =\n from c in customers\n where c.City == \"London\"\n select c;\n</code></pre>\n\n<p>// anon is compiled as an anonymous type</p>\n\n<pre><code>var anon = new { Name = \"Terry\", Age = 34 };\n</code></pre>\n\n<p>// list is compiled as List </p>\n\n<pre><code>var list = new List<int>();\n\nvar can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.\n</code></pre>\n\n<p>var cannot be used on fields at class scope.</p>\n\n<p>Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);</p>\n\n<p>Multiple implicitly-typed variables cannot be initialized in the same statement.</p>\n\n<p>If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] | After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?
For example I rather lazily used var in questionable circumstances, e.g.:-
```
foreach(var item in someList) { // ... } // Type of 'item' not clear.
var something = someObject.SomeProperty; // Type of 'something' not clear.
var something = someMethod(); // Type of 'something' not clear.
```
More legitimate uses of var are as follows:-
```
var l = new List<string>(); // Obvious what l will be.
var s = new SomeClass(); // Obvious what s will be.
```
Interestingly LINQ seems to be a bit of a grey area, e.g.:-
```
var results = from r in dataContext.SomeTable
select r; // Not *entirely clear* what results will be here.
```
It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.
It's even worse when it comes to LINQ to objects, e.g.:-
```
var results = from item in someList
where item != 3
select item;
```
This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.
There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable<int> and IEnumerable<double> the caller might inadvertently pass in the wrong type.
`var` *does* maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method. | I still think `var` can make code more readable in some cases. If I have a Customer class with an Orders property, and I want to assign that to a variable, I will just do this:
```
var orders = cust.Orders;
```
I don't care if Customer.Orders is `IEnumerable<Order>`, `ObservableCollection<Order>` or `BindingList<Order>` - all I want is to keep that list in memory to iterate over it or get its count or something later on.
Contrast the above declaration with:
```
ObservableCollection<Order> orders = cust.Orders;
```
To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from `ObservableCollection<Order>` to `IList<Order>`) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place. |
41,492 | <p>Is it possible to determine which property of an ActiveX control is the default property? For example, what is the default property of the VB6 control CommandButton and how would I found out any other controls default!</p>
<p><strong>/EDIT:</strong> Without having source to the object itself</p>
| [
{
"answer_id": 41612,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 1,
"selected": false,
"text": "<p>I don't use VB, but here it goes.</p>\n\n<p>I found <a href=\"http://msdn.microsoft.com/en-us/library/aa733705%28VS.60%29.aspx\" rel=\"nofollow noreferrer\">Using the Value of a Control</a>, but it's not a programmatic solution.\nIf you have access to the code, look for</p>\n\n<pre><code>Attribute Value.VB_UserMemId = 0\n</code></pre>\n\n<p>using Notepad.</p>\n"
},
{
"answer_id": 41623,
"author": "DAC",
"author_id": 1111,
"author_profile": "https://Stackoverflow.com/users/1111",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>you have access to the code, look for</p>\n</blockquote>\n\n<p>Unfortunetly I don't have access to the code for most of the controls. However the link is useful for the Microsoft Controls, but I still would like a way to know for other controls.</p>\n"
},
{
"answer_id": 54239,
"author": "John T",
"author_id": 5553,
"author_profile": "https://Stackoverflow.com/users/5553",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on when you want to determine this. You could print the \"value\" of, say, a label control (which has no \"value\" property) to the debugger like:</p>\n\n<pre><code>debug.print \"Value for cmdTest is [\"+format(cmdTest)+\"]\"\n</code></pre>\n\n<p>Which will give you something like:</p>\n\n<blockquote>\n <p>Value for cmdTest is [False]</p>\n</blockquote>\n\n<p>As it turns out, the default value for a command button is it's state (pressed or not), so if you put the code example above in the click event for the control, you will see \"True\", if you execute it somewhere else, you'll see \"False\".</p>\n\n<p>For other results, this method will at least show you the sort of property you're looking for. You could use:</p>\n\n<pre><code>debug.print \"cmdTest's value is of type [\"+TypeName(oObject) +\"]\"\n</code></pre>\n\n<p>which tell you the actual type, namely:</p>\n\n<blockquote>\n <p>cmdTest's value is of type [Boolean]</p>\n</blockquote>\n\n<p>You could use various methods to narrow things down, such as setting the value and seeing what happens.</p>\n"
},
{
"answer_id": 2478693,
"author": "DAC",
"author_id": 1111,
"author_profile": "https://Stackoverflow.com/users/1111",
"pm_score": 2,
"selected": true,
"text": "<p>Use OLE/Com Object Viewer, which is distributed with Microsoft Visual Studio. </p>\n\n<p>Go to type libraries and find the library the control is housed in, for example CommandButton is stored in <strong><em>Microsoft Forms 2.0 Object Library</em></strong>. Right click the library and select view. Find the coclass representing the control and select it:</p>\n\n<p><img src=\"https://i.imgur.com/BervR.png\" alt=\"alt text\"></p>\n\n<p>As can be seen, the default interface for CommandButton is ICommandButton, when you inspect ICommandButton look for a property that has a dispid of 0. The IDL for the dispid 0 property of CommandButton is:</p>\n\n<pre><code>[id(00000000), propput, bindable, displaybind, hidden, helpcontext(0x001e8d04)]\nvoid Value([in] VARIANT_BOOL rhs);\n[id(00000000), propget, bindable, displaybind, hidden, helpcontext(0x001e8d04)]\nVARIANT_BOOL Value();\n</code></pre>\n\n<p>Showing you the default property.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111/"
] | Is it possible to determine which property of an ActiveX control is the default property? For example, what is the default property of the VB6 control CommandButton and how would I found out any other controls default!
**/EDIT:** Without having source to the object itself | Use OLE/Com Object Viewer, which is distributed with Microsoft Visual Studio.
Go to type libraries and find the library the control is housed in, for example CommandButton is stored in ***Microsoft Forms 2.0 Object Library***. Right click the library and select view. Find the coclass representing the control and select it:

As can be seen, the default interface for CommandButton is ICommandButton, when you inspect ICommandButton look for a property that has a dispid of 0. The IDL for the dispid 0 property of CommandButton is:
```
[id(00000000), propput, bindable, displaybind, hidden, helpcontext(0x001e8d04)]
void Value([in] VARIANT_BOOL rhs);
[id(00000000), propget, bindable, displaybind, hidden, helpcontext(0x001e8d04)]
VARIANT_BOOL Value();
```
Showing you the default property. |
41,513 | <p>I am going to be using Subversion for source control on a new J2EE web application. What directory structure will you recommend for organizing code, tests and documentation?</p>
| [
{
"answer_id": 41524,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 4,
"selected": false,
"text": "<p>I usually have</p>\n\n<pre>\nProject Directory\n src - actual source\n doc - documentation\n lib - libraries referenced from source\n dep - installation files for dependencies that don't fit in lib\n db - database installation script\n</pre>\n\n<p>In work with Visual Studio, I'm not sure if this works the same in the java world. But i usually put stuff in different project folders in src. For each source project there's a separate test project. Build files go in the main project directory. I usually put a README there too documenting how to setup the project if it needs more than just checking out.</p>\n\n<p>EDIT: This is the structure for a single working checkout of the project. It will be duplicated for each branch/tag in your revision control system (remember, in most SVN system, copies are cheap). The above example under Subversion would look like:</p>\n\n<pre><code>/project\n /trunk\n /src\n /doc\n /...\n /branches\n /feature1\n /src\n /doc\n /...\n /feature2\n /src\n /doc\n /...\n</code></pre>\n"
},
{
"answer_id": 41536,
"author": "onnodb",
"author_id": 1037,
"author_profile": "https://Stackoverflow.com/users/1037",
"pm_score": 2,
"selected": false,
"text": "<p>I found some old questions here on SO that might be interesting for you:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/5214/whats-a-good-standard-code-layout-for-a-php-application\">Whats a good standard code layout for a php application</a>\n\n<ul>\n<li>Contains a link to an article on <a href=\"http://phpimpact.wordpress.com/2008/08/11/scalable-and-flexible-directory-structure-for-web-applications/\" rel=\"nofollow noreferrer\">Scalable and Flexible Directory Structure for Web Applications</a> (focus on PHP, though)</li>\n</ul></li>\n<li><a href=\"https://stackoverflow.com/questions/7596/how-to-structure-a-java-application-in-other-words-where-do-i-put-my-classes\">How to structure a java application, in other words: where do I put my classes?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/16829/structure-of-projects-in-version-control\">Structure of Projects in Version Control</a></li>\n</ul>\n"
},
{
"answer_id": 41539,
"author": "ryan",
"author_id": 2454,
"author_profile": "https://Stackoverflow.com/users/2454",
"pm_score": 0,
"selected": false,
"text": "<p>I use Eclipse for creating J2EE web applications and this will create the following project structure:</p>\n\n<pre><code>WebAppName\\\n \\lib\n \\src\n \\tests\n etc...\n</code></pre>\n\n<p>I would then create an SVN folder on our trunk called WebAppNameProject. Within this folder I would create folders called WebAppNameSource, Documentation etc. Within the WebAppNameSource folder I would place the project source generated by Eclipse. Thus I would have the following folder structure in SVN:</p>\n\n<pre><code>\\svn\\trunk\\WebAppNameProject\n \\WebAppNameSource\n \\lib\n \\src\n \\tests\n etc...\n \\Documentation \n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 41571,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 2,
"selected": false,
"text": "<p>To expand on what Mendelt Siebenga suggested, I would also add a <code>web</code> directory (for JSP files, WEB-INF, web.xml, etc). </p>\n\n<p>Tests should go in a folder named <code>test</code> that is a sibling of the main <code>src</code> folder - this way your unit test classes can have the same package name as the source code being tested (to ease with situations where you want to test protected methods or classes, for example... see the <a href=\"http://junit.sourceforge.net/doc/faq/faq.htm#tests_10\" rel=\"nofollow noreferrer\">JUnit FAQ for this</a>, and this question also on <a href=\"http://junit.sourceforge.net/doc/faq/faq.htm#organize_1\" rel=\"nofollow noreferrer\">Where should I put my test files?</a>).</p>\n\n<p>I haven't had much use for it myself, but a Maven project will also create a <code>resources</code> folder alongside the src folder for non-source code that you want to package/deploy along with the main source code - things such as properties files, resources bundles, etc. Your mileage may vary on this one.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am going to be using Subversion for source control on a new J2EE web application. What directory structure will you recommend for organizing code, tests and documentation? | I usually have
```
Project Directory
src - actual source
doc - documentation
lib - libraries referenced from source
dep - installation files for dependencies that don't fit in lib
db - database installation script
```
In work with Visual Studio, I'm not sure if this works the same in the java world. But i usually put stuff in different project folders in src. For each source project there's a separate test project. Build files go in the main project directory. I usually put a README there too documenting how to setup the project if it needs more than just checking out.
EDIT: This is the structure for a single working checkout of the project. It will be duplicated for each branch/tag in your revision control system (remember, in most SVN system, copies are cheap). The above example under Subversion would look like:
```
/project
/trunk
/src
/doc
/...
/branches
/feature1
/src
/doc
/...
/feature2
/src
/doc
/...
``` |
41,562 | <p>I've had to do some introspection in python and it wasn't pretty:</p>
<pre><code>name = sys._getframe(1).f_code
name = "%s:%d %s()" %(os.path.split(name.co_filename)[1],name.co_firstlineno,name.co_name)
</code></pre>
<p>To get something like</p>
<pre><code>foo.py:22 bar() blah blah
</code></pre>
<p>In our debugging output.</p>
<p>I'd ideally like to prepend anything to stderr with this sort of information --
Is it possible to change the behaviour of print globally within python?</p>
| [
{
"answer_id": 41574,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 3,
"selected": true,
"text": "<p>A print statement does its IO through \"sys.stdout.write\" so you can override sys.stdout if you want to manipulate the print stream.</p>\n"
},
{
"answer_id": 41921,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 1,
"selected": false,
"text": "<p>The python <a href=\"http://www.python.org/doc/current/lib/module-inspect.html\" rel=\"nofollow noreferrer\">inspect</a> module makes this a lot easier and cleaner. </p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4319/"
] | I've had to do some introspection in python and it wasn't pretty:
```
name = sys._getframe(1).f_code
name = "%s:%d %s()" %(os.path.split(name.co_filename)[1],name.co_firstlineno,name.co_name)
```
To get something like
```
foo.py:22 bar() blah blah
```
In our debugging output.
I'd ideally like to prepend anything to stderr with this sort of information --
Is it possible to change the behaviour of print globally within python? | A print statement does its IO through "sys.stdout.write" so you can override sys.stdout if you want to manipulate the print stream. |
41,568 | <p>this kind of follows on from another <a href="https://stackoverflow.com/questions/41290/file-access-strategy-in-a-multi-threaded-environment-web-app">question</a> of mine.</p>
<p>Basically, once I have the code to access the file (will review the answers there in a minute) what would be the best way to <strong>test</strong> it?</p>
<p>I am thinking of creating a method which just spawns lots of <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="noreferrer">BackgroundWorker</a>'s or something and tells them all load/save the file, and test with varying file/object sizes. Then, get a response back from the threads to see if it failed/succeeded/made the world implode etc.</p>
<p>Can you guys offer any suggestions on the best way to approach this? As I said before, this is all kinda new to me :)</p>
<h3>Edit</h3>
<p>Following <a href="https://stackoverflow.com/questions/41568/whats-the-best-way-to-test-a-method-from-multiple-threads#41572">ajmastrean's</a> post:</p>
<p>I am using a console app to test with Debug.Asserts :)</p>
<hr />
<h2>Update</h2>
<p>I originally rolled with using <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="noreferrer">BackgroundWorker</a> to deal with the threading (since I am used to that from Windows dev) I soon realised that when I was performing tests where multiple ops (threads) needed to complete before continuing, I realised it was going to be a bit of a hack to get it to do this.</p>
<p>I then followed up on <a href="https://stackoverflow.com/questions/41568/whats-the-best-way-to-unit-test-from-multiple-threads#41589">ajmastrean</a>'s post and realised I should really be using the <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread(VS.80).aspx" rel="noreferrer">Thread</a> class for working with concurrent operations. I will now refactor using this method (albeit a different approach).</p>
| [
{
"answer_id": 41578,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": -1,
"selected": false,
"text": "<p>Your idea should work fine. Basically you just want to spawn a bunch of threads, and make sure the ones writing the file take long enough to do it to actually make the readers wait. If all of your threads return without error, and without blocking forever, then the test succeeds.</p>\n"
},
{
"answer_id": 41589,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 5,
"selected": true,
"text": "<p>In .NET, <code>ThreadPool</code> threads won't return without setting up <code>ManualResetEvent</code>s or <code>AutoResetEvent</code>s. I find these overkill for a quick test method (not to mention kind of complicated to create, set, and manage). Background worker is a also a bit complex with the callbacks and such.</p>\n\n<p>Something I have found that works is </p>\n\n<ol>\n<li>Create an array of threads.</li>\n<li>Setup the <code>ThreadStart</code> method of each thread.</li>\n<li>Start each thread.</li>\n<li>Join on all threads (blocks the current thread until all other threads complete or abort) </li>\n</ol>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static void MultiThreadedTest()\n{\n Thread[] threads = new Thread[count];\n\n for (int i = 0; i < threads.Length; i++)\n {\n threads[i] = new Thread(DoSomeWork());\n }\n\n foreach(Thread thread in threads)\n {\n thread.Start();\n }\n\n foreach(Thread thread in threads)\n {\n thread.Join();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 41619,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>@ajmastrean, since unit test result must be predictable we need to synchronize threads somehow. I can't see a simple way to do it without using events.</p>\n<p>I found that <code>ThreadPool.QueueUserWorkItem</code> gives me an easy way to test such use cases</p>\n<pre><code> ThreadPool.QueueUserWorkItem(x => { \n File.Open(fileName, FileMode.Open);\n event1.Set(); // Start 2nd tread;\n event2.WaitOne(); // Blocking the file;\n});\nThreadPool.QueueUserWorkItem(x => { \n try\n {\n event1.WaitOne(); // Waiting until 1st thread open file\n File.Delete(fileName); // Simulating conflict\n }\n catch (IOException e)\n {\n Debug.Write("File access denied");\n }\n});\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | this kind of follows on from another [question](https://stackoverflow.com/questions/41290/file-access-strategy-in-a-multi-threaded-environment-web-app) of mine.
Basically, once I have the code to access the file (will review the answers there in a minute) what would be the best way to **test** it?
I am thinking of creating a method which just spawns lots of [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx)'s or something and tells them all load/save the file, and test with varying file/object sizes. Then, get a response back from the threads to see if it failed/succeeded/made the world implode etc.
Can you guys offer any suggestions on the best way to approach this? As I said before, this is all kinda new to me :)
### Edit
Following [ajmastrean's](https://stackoverflow.com/questions/41568/whats-the-best-way-to-test-a-method-from-multiple-threads#41572) post:
I am using a console app to test with Debug.Asserts :)
---
Update
------
I originally rolled with using [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) to deal with the threading (since I am used to that from Windows dev) I soon realised that when I was performing tests where multiple ops (threads) needed to complete before continuing, I realised it was going to be a bit of a hack to get it to do this.
I then followed up on [ajmastrean](https://stackoverflow.com/questions/41568/whats-the-best-way-to-unit-test-from-multiple-threads#41589)'s post and realised I should really be using the [Thread](http://msdn.microsoft.com/en-us/library/system.threading.thread(VS.80).aspx) class for working with concurrent operations. I will now refactor using this method (albeit a different approach). | In .NET, `ThreadPool` threads won't return without setting up `ManualResetEvent`s or `AutoResetEvent`s. I find these overkill for a quick test method (not to mention kind of complicated to create, set, and manage). Background worker is a also a bit complex with the callbacks and such.
Something I have found that works is
1. Create an array of threads.
2. Setup the `ThreadStart` method of each thread.
3. Start each thread.
4. Join on all threads (blocks the current thread until all other threads complete or abort)
```cs
public static void MultiThreadedTest()
{
Thread[] threads = new Thread[count];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = new Thread(DoSomeWork());
}
foreach(Thread thread in threads)
{
thread.Start();
}
foreach(Thread thread in threads)
{
thread.Join();
}
}
``` |
41,576 | <p>I wonder what the best practice for this scenario is:</p>
<p>I have a Sharepoint Site (MOSS2007) with an ASPX Page on it. However, I cannot use any inline source and stuff like Event handlers do not work, because Sharepoint does not allow Server Side Script on ASPX Pages per default.</p>
<p>Two solutions:</p>
<ol>
<li><p>Change the <code>PageParserPath</code> in <em>web.config</em> as per <a href="http://blogs.msdn.com/kaevans/archive/2007/04/26/code-blocks-are-not-allowed-in-this-file-using-server-side-code-with-sharepoint.aspx" rel="nofollow noreferrer">this site</a> </p>
<pre><code><PageParserPaths>
<PageParserPath VirtualPath="/pages/test.aspx"
CompilationMode="Always" AllowServerSideScript="true" />
</PageParserPaths>
</code></pre></li>
<li><p>Create all the controls and Wire them up to Events in the <em>.CS</em> File, thus completely eliminating some of the benefits of ASP.net</p></li>
</ol>
<p>I wonder, what the best practice would be? Number one looks like it's the correct choice, but changing the <em>web.config</em> is something I want to use sparingly whenever possible.</p>
| [
{
"answer_id": 42248,
"author": "Daniel McPherson",
"author_id": 897,
"author_profile": "https://Stackoverflow.com/users/897",
"pm_score": 1,
"selected": false,
"text": "<p>What does the ASPX page do? What functionality does it add? How are you adding the page into the site? By the looks of it this is just a \"Web Part Page\" in a document library. </p>\n\n<p>I would have to do a little research to be 100%, but my understanding is that inline code is ok, providing it's in a page that remains ghosted, and thereby trusted. Can you add your functionality into the site via a feature? </p>\n\n<p>I would avoide option 1, seems like bad advice to me. Allowing server side code in your page is a security risk as it then becomes possible for someone to inject malicious code. Sure you can secure the page, but we are talking remote execution with likely some pretty serious permissions.</p>\n"
},
{
"answer_id": 42508,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 0,
"selected": false,
"text": "<p>Well, it's a page that hosts user controls. It's a custom .aspx Page that will be created on the site, specially because I do not want to create WebParts.</p>\n\n<p>It's essentially an application running within Sharepoint, utilizing Lists and other functions, but all the functionality is only useful within the application, so flooding the web part gallery with countless web parts that only work in one place is something i'd like to avoid.</p>\n"
},
{
"answer_id": 43255,
"author": "Daniel McPherson",
"author_id": 897,
"author_profile": "https://Stackoverflow.com/users/897",
"pm_score": 2,
"selected": true,
"text": "<p>So in that case I would wrap it up in a feature and deploy it via a solution. This way I think you will avoid the issue you are seeing. This is especially useful if you plan to use this functionality within other sites too. </p>\n\n<p>You can also embed web parts directly in the page, much like you do a WebControl, thereby avoiding any gallery clutter.</p>\n"
},
{
"answer_id": 43728,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks so far. I've successfully tried Andrew Connel's solution:</p>\n\n<p><a href=\"http://www.andrewconnell.com/blog/articles/UsingCodeBehindFilesInSharePointSites.aspx\" rel=\"nofollow noreferrer\">http://www.andrewconnell.com/blog/articles/UsingCodeBehindFilesInSharePointSites.aspx</a></p>\n\n<p>Wrapping it into a solution is part of that, but the main problem was how to get the code into that, and it's more leaning towards Option 2 without having to create the controls in code.</p>\n\n<p>What I was missing:<br>\nIn the .cs File, it is required to manually add the \"protected Button Trigger;\" stuff, because there is no automatically generated .designer.cs file when using a class library.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | I wonder what the best practice for this scenario is:
I have a Sharepoint Site (MOSS2007) with an ASPX Page on it. However, I cannot use any inline source and stuff like Event handlers do not work, because Sharepoint does not allow Server Side Script on ASPX Pages per default.
Two solutions:
1. Change the `PageParserPath` in *web.config* as per [this site](http://blogs.msdn.com/kaevans/archive/2007/04/26/code-blocks-are-not-allowed-in-this-file-using-server-side-code-with-sharepoint.aspx)
```
<PageParserPaths>
<PageParserPath VirtualPath="/pages/test.aspx"
CompilationMode="Always" AllowServerSideScript="true" />
</PageParserPaths>
```
2. Create all the controls and Wire them up to Events in the *.CS* File, thus completely eliminating some of the benefits of ASP.net
I wonder, what the best practice would be? Number one looks like it's the correct choice, but changing the *web.config* is something I want to use sparingly whenever possible. | So in that case I would wrap it up in a feature and deploy it via a solution. This way I think you will avoid the issue you are seeing. This is especially useful if you plan to use this functionality within other sites too.
You can also embed web parts directly in the page, much like you do a WebControl, thereby avoiding any gallery clutter. |
41,590 | <p>I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++.</p>
<p>How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?</p>
| [
{
"answer_id": 41598,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 8,
"selected": true,
"text": "<p>Namespaces are packages essentially. They can be used like this:</p>\n\n<pre><code>namespace MyNamespace\n{\n class MyClass\n {\n };\n}\n</code></pre>\n\n<p>Then in code:</p>\n\n<pre><code>MyNamespace::MyClass* pClass = new MyNamespace::MyClass();\n</code></pre>\n\n<p>Or, if you want to always use a specific namespace, you can do this:</p>\n\n<pre><code>using namespace MyNamespace;\n\nMyClass* pClass = new MyClass();\n</code></pre>\n\n<p><strong>Edit:</strong> Following what <a href=\"https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41624\">bernhardrusch</a> has said, I tend not to use the \"using namespace x\" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).</p>\n\n<p>And as you asked <a href=\"https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41615\">below</a>, you can use as many namespaces as you like.</p>\n"
},
{
"answer_id": 41603,
"author": "Adam Hollidge",
"author_id": 4069,
"author_profile": "https://Stackoverflow.com/users/4069",
"pm_score": 2,
"selected": false,
"text": "<p>Generally speaking, I create a namespace for a body of code if I believe there might possibly be function or type name conflicts with other libraries. It also helps to brand code, ala <a href=\"http://www.boost.org/\" rel=\"nofollow noreferrer\">boost::</a> .</p>\n"
},
{
"answer_id": 41604,
"author": "dmeister",
"author_id": 4194,
"author_profile": "https://Stackoverflow.com/users/4194",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer using a top-level namespace for the application and sub namespaces for the components.</p>\n\n<p>The way you can use classes from other namespaces is surprisingly very similar to the way in java.\nYou can either use \"use NAMESPACE\" which is similar to an \"import PACKAGE\" statement, e.g. use std. Or you specify the package as prefix of the class separated with \"::\", e.g. std::string. This is similar to \"java.lang.String\" in Java.</p>\n"
},
{
"answer_id": 41620,
"author": "Adam Hollidge",
"author_id": 4069,
"author_profile": "https://Stackoverflow.com/users/4069",
"pm_score": 3,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41615\">marius</a></p>\n\n<p>Yes, you can use several namespaces at a time, eg:</p>\n\n<pre><code>using namespace boost; \nusing namespace std; \n\nshared_ptr<int> p(new int(1)); // shared_ptr belongs to boost \ncout << \"cout belongs to std::\" << endl; // cout and endl are in std\n</code></pre>\n\n<p>[Feb. 2014 -- (Has it really been that long?): This particular example is now ambiguous, as Joey points out below. Boost and std:: now each have a shared_ptr.]</p>\n"
},
{
"answer_id": 41622,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 4,
"selected": false,
"text": "<p>In Java:</p>\n\n<pre><code>package somepackage;\nclass SomeClass {}\n</code></pre>\n\n<p>In C++:</p>\n\n<pre><code>namespace somenamespace {\n class SomeClass {}\n}\n</code></pre>\n\n<p>And using them, Java:</p>\n\n<pre><code>import somepackage;\n</code></pre>\n\n<p>And C++:</p>\n\n<pre><code>using namespace somenamespace;\n</code></pre>\n\n<p>Also, full names are \"somepackge.SomeClass\" for Java and \"somenamespace::SomeClass\" for C++. Using those conventions, you can organize like you are used to in Java, including making matching folder names for namespaces. The folder->package and file->class requirements aren't there though, so you can name your folders and classes independently off packages and namespaces.</p>\n"
},
{
"answer_id": 41624,
"author": "bernhardrusch",
"author_id": 3056,
"author_profile": "https://Stackoverflow.com/users/3056",
"pm_score": 7,
"selected": false,
"text": "<p>To avoid saying everything Mark Ingram already said a little tip for using namespaces:</p>\n\n<p>Avoid the \"using namespace\" directive in header files - this opens the namespace for all parts of the program which import this header file. In implementation files (*.cpp) this is normally no big problem - altough I prefer to use the \"using namespace\" directive on the function level.</p>\n\n<p>I think namespaces are mostly used to avoid naming conflicts - not necessarily to organize your code structure. I'd organize C++ programs mainly with header files / the file structure.</p>\n\n<p>Sometimes namespaces are used in bigger C++ projects to hide implementation details.</p>\n\n<p>Additional note to the using directive:\nSome people prefer using \"using\" just for single elements: </p>\n\n<pre><code>using std::cout; \nusing std::endl;\n</code></pre>\n"
},
{
"answer_id": 41637,
"author": "OysterD",
"author_id": 2638,
"author_profile": "https://Stackoverflow.com/users/2638",
"pm_score": 4,
"selected": false,
"text": "<p>Also, note that you can add to a namespace. This is clearer with an example, what I mean is that you can have:</p>\n\n<pre><code>namespace MyNamespace\n{\n double square(double x) { return x * x; }\n}\n</code></pre>\n\n<p>in a file <code>square.h</code>, and</p>\n\n<pre><code>namespace MyNamespace\n{\n double cube(double x) { return x * x * x; }\n}\n</code></pre>\n\n<p>in a file <code>cube.h</code>. This defines a single namespace <code>MyNamespace</code> (that is, you can define a single namespace across multiple files).</p>\n"
},
{
"answer_id": 41642,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 2,
"selected": false,
"text": "<p>Note that a namespace in C++ really is just a name space. They don't provide any of the encapsulation that packages do in Java, so you probably won't use them as much.</p>\n"
},
{
"answer_id": 41682,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 2,
"selected": false,
"text": "<p>I've used C++ namespaces the same way I do in C#, Perl, etc. It's just a semantic separation of symbols between standard library stuff, third party stuff, and my own code. I would place my own app in one namespace, then a reusable library component in another namespace for separation.</p>\n"
},
{
"answer_id": 41823,
"author": "KeithB",
"author_id": 2298,
"author_profile": "https://Stackoverflow.com/users/2298",
"pm_score": 2,
"selected": false,
"text": "<p>Another difference between java and C++, is that in C++, the namespace hierarchy does not need to mach the filesystem layout. So I tend to put an entire reusable library in a single namespace, and subsystems within the library in subdirectories:</p>\n\n<pre><code>#include \"lib/module1.h\"\n#include \"lib/module2.h\"\n\nlib::class1 *v = new lib::class1();\n</code></pre>\n\n<p>I would only put the subsystems in nested namespaces if there was a possibility of a name conflict.</p>\n"
},
{
"answer_id": 41860,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 3,
"selected": false,
"text": "<p>You can also contain \"using namespace ...\" inside a function for example:</p>\n\n<pre><code>void test(const std::string& s) {\n using namespace std;\n cout << s;\n}\n</code></pre>\n"
},
{
"answer_id": 47976,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>Bigger C++ projects I've seen hardly used more than one namespace (e.g. boost library).</p>\n</blockquote>\n\n<p>Actually boost uses tons of namespaces, typically every part of boost has its own namespace for the inner workings and then may put only the public interface in the top-level namespace boost.</p>\n\n<p>Personally I think that the larger a code-base becomes, the more important namespaces become, even within a single application (or library). At work we put each module of our application in its own namespace.</p>\n\n<p>Another use (no pun intended) of namespaces that I use a lot is the anonymous namespace:</p>\n\n<pre><code>namespace {\n const int CONSTANT = 42;\n}\n</code></pre>\n\n<p>This is basically the same as:</p>\n\n<pre><code>static const int CONSTANT = 42;\n</code></pre>\n\n<p>Using an anonymous namespace (instead of static) is however the recommended way for code and data to be visible only within the current compilation unit in C++.</p>\n"
},
{
"answer_id": 48008,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 6,
"selected": false,
"text": "<p>Don't listen to every people telling you that namespaces are just name-spaces.</p>\n\n<p>They are important because they are considered by the compiler to apply the interface principle. Basically, it can be explained by an example:</p>\n\n<pre><code>namespace ns {\n\nclass A\n{\n};\n\nvoid print(A a)\n{\n}\n\n}\n</code></pre>\n\n<p>If you wanted to print an A object, the code would be this one:</p>\n\n<pre><code>ns::A a;\nprint(a);\n</code></pre>\n\n<p>Note that we didn't explicitly mention the namespace when calling the function. This is the interface principle: C++ consider a function taking a type as an argument as being part of the interface for that type, so no need to specify the namespace because the parameter already implied the namespace.</p>\n\n<p>Now why this principle is important? Imagine that the class A author did not provide a print() function for this class. You will have to provide one yourself. As you are a good programmer, you will define this function in your own namespace, or maybe in the global namespace.</p>\n\n<pre><code>namespace ns {\n\nclass A\n{\n};\n\n}\n\nvoid print(A a)\n{\n}\n</code></pre>\n\n<p>And your code can start calling the print(a) function wherever you want. Now imagine that years later, the author decides to provide a print() function, better than yours because he knows the internals of his class and can make a better version than yours.</p>\n\n<p>Then C++ authors decided that his version of the print() function should be used instead of the one provided in another namespace, to respect the interface principle. And that this \"upgrade\" of the print() function should be as easy as possible, which means that you won't have to change every call to the print() function. That's why \"interface functions\" (function in the same namespace as a class) can be called without specifying the namespace in C++.</p>\n\n<p>And that's why you should consider a C++ namespace as an \"interface\" when you use one and keep in mind the interface principle.</p>\n\n<p>If you want better explanation of this behavior, you can refer to the book <a href=\"http://books.google.fr/books?id=mT7E5gDuW_4C&dq=exceptional+C%2B%2B&pg=PP1&ots=AXUPz0dWnW&sig=DAib0u-zXuY3lGCCUFPtzI33pCQ&hl=fr&sa=X&oi=book_result&resnum=1&ct=result#PPA119,M1\" rel=\"noreferrer\">Exceptional C++ from Herb Sutter</a></p>\n"
},
{
"answer_id": 81602,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 6,
"selected": false,
"text": "<p>Vincent Robert is right in his comment <a href=\"https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#48008\">How do you properly use namespaces in C++?</a>.</p>\n<h2>Using namespace</h2>\n<p>Namespaces are used at the very least to help avoid name collision. In Java, this is enforced through the "org.domain" idiom (because it is supposed one won't use anything else than his/her own domain name).</p>\n<p>In C++, you could give a namespace to all the code in your module. For example, for a module MyModule.dll, you could give its code the namespace MyModule. I've see elsewhere someone using MyCompany::MyProject::MyModule. I guess this is overkill, but all in all, it seems correct to me.</p>\n<h2>Using "using"</h2>\n<p>Using should be used with great care because it effectively import one (or all) symbols from a namespace into your current namespace.</p>\n<p>This is evil to do it in a header file because your header will pollute every source including it (it reminds me of macros...), and even in a source file, bad style outside a function scope because it will import at global scope the symbols from the namespace.</p>\n<p>The most secure way to use "using" is to import select symbols:</p>\n<pre><code>void doSomething()\n{\n using std::string ; // string is now "imported", at least,\n // until the end of the function\n string a("Hello World!") ;\n std::cout << a << std::endl ;\n}\n\nvoid doSomethingElse()\n{\n using namespace std ; // everything from std is now "imported", at least,\n // until the end of the function\n string a("Hello World!") ;\n cout << a << endl ;\n}\n</code></pre>\n<p>You'll see a lot of "using namespace std ;" in tutorial or example codes. The reason is to reduce the number of symbols to make the reading easier, not because it is a good idea.</p>\n<p>"using namespace std ;" is discouraged by Scott Meyers (I don't remember exactly which book, but I can find it if necessary).</p>\n<h2>Namespace Composition</h2>\n<p>Namespaces are more than packages. Another example can be found in Bjarne Stroustrup's "The C++ Programming Language".</p>\n<p>In the "Special Edition", at <strong>8.2.8 Namespace Composition</strong>, he describes how you can merge two namespaces AAA and BBB into another one called CCC. Thus CCC becomes an alias for both AAA and BBB:</p>\n<pre><code>namespace AAA\n{\n void doSomething() ;\n}\n\nnamespace BBB\n{\n void doSomethingElse() ;\n}\n\nnamespace CCC\n{\n using namespace AAA ;\n using namespace BBB ;\n}\n\nvoid doSomethingAgain()\n{\n CCC::doSomething() ;\n CCC::doSomethingElse() ;\n}\n</code></pre>\n<p>You could even import select symbols from different namespaces, to build your own custom namespace interface. I have yet to find a practical use of this, but in theory, it is cool.</p>\n"
},
{
"answer_id": 1600792,
"author": "Éric Malenfant",
"author_id": 59781,
"author_profile": "https://Stackoverflow.com/users/59781",
"pm_score": 6,
"selected": false,
"text": "<p>I did not see any mention of it in the other answers, so here are my 2 Canadian cents:</p>\n\n<p>On the \"using namespace\" topic, a useful statement is the namespace alias, allowing you to \"rename\" a namespace, normally to give it a shorter name. For example, instead of:</p>\n\n<pre><code>Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::TheClassName foo;\nSome::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::AnotherClassName bar;\n</code></pre>\n\n<p>you can write:</p>\n\n<pre><code>namespace Shorter = Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally;\nShorter::TheClassName foo;\nShorter::AnotherClassName bar;\n</code></pre>\n"
},
{
"answer_id": 66744177,
"author": "nidhi kumari",
"author_id": 15034008,
"author_profile": "https://Stackoverflow.com/users/15034008",
"pm_score": -1,
"selected": false,
"text": "<p>std :: cout</p>\n<p>The\nprefix std:: indicates that the\nnames cout and endl are\ndefined inside the namespace\nnamed std. Namespaces allow\nus to avoidinadvertent collisions\nbetween the names we define\nand uses of those same names\ninside a library. All the names\ndefined by the standard library\nare in the stdnamespace. Writing std::\ncout uses the scope operator\n(the ::operator) to saythat we\nwant to use the name cout\nthat is defined in the\nnamespace std.\nwill show a simpler way to\naccess names from the library.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1585/"
] | I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++.
How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces? | Namespaces are packages essentially. They can be used like this:
```
namespace MyNamespace
{
class MyClass
{
};
}
```
Then in code:
```
MyNamespace::MyClass* pClass = new MyNamespace::MyClass();
```
Or, if you want to always use a specific namespace, you can do this:
```
using namespace MyNamespace;
MyClass* pClass = new MyClass();
```
**Edit:** Following what [bernhardrusch](https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41624) has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).
And as you asked [below](https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41615), you can use as many namespaces as you like. |
41,594 | <p>I have a table in an access table which contains Product entries, one of the columns has a jpg image stored as an OLE Object. I am trying to import this table to MySQL but nothing seems to work. I have tried the MySQL migration tool but that has a known issue with Access and OLE Objects. (The issue being it doesnt work and leaves the fields blank) I also tried the suggestion on <a href="http://www.plus2net.com/sql_tutorial/access_to_mysql.php" rel="nofollow noreferrer">this site</a>
and while the data is imported it seems as though the image is getting corrupted in the transfer. When i try to preview the image i just get a binary view, if i save it on disk as a jpg image and try to open it i get an error stating the image is corrupt.</p>
<p>The images in Access are fine and can be previewed. Access is storing the data as an OLE Object and when i import it to MySql it is saved in a MediumBlob field.</p>
<p>Has anyone had this issue before and how did they resolve it ?</p>
| [
{
"answer_id": 41617,
"author": "DAC",
"author_id": 1111,
"author_profile": "https://Stackoverflow.com/users/1111",
"pm_score": 1,
"selected": false,
"text": "<p>As far as I remember, the Microsoft \"<a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=D842F8B4-C914-4AC7-B2F3-D25FFF4E24FB&displaylang=en\" rel=\"nofollow noreferrer\">SQL Server Migration Assistant for Access</a>\" will properly migrate OLE Images, but this is only for Access->SQLServer. However, what you can do is use this to migrate to SQLServer Express (free download) and then migrate from SQLServer to MySQL.</p>\n"
},
{
"answer_id": 41985,
"author": "SecretDeveloper",
"author_id": 2720,
"author_profile": "https://Stackoverflow.com/users/2720",
"pm_score": 3,
"selected": true,
"text": "<p>Ok so in the interests of airing my dirty code in public here what i came up with.<br>\nNote : this is a hack designed to be used once and then thrown away.</p>\n\n<p>This Method takes in a datarowview containing 1 row of data from the access table. The Images are wrapped in OLE serialization, im not entirely familiar with how this works but its how Microsoft apps allow any object to be embedded into something else. (eg images into Excel Cells). I needed to remove the serialization junk around the image so i loaded the entire field as a Byte array and searched through it for 3 concurrent entries (FF D8 FF) which represent the beginning of the image data within the field.</p>\n\n<pre><code> Private Function GetImageFromRow(ByRef row As DataRowView, ByVal columnName As String) As Bitmap\n Dim oImage As Bitmap = New Bitmap(\"c:\\default.jpg\")\n Try\n If Not IsDBNull(row(columnName)) Then\n If row(columnName) IsNot Nothing Then\n Dim mStream As New System.IO.MemoryStream(CType(row(columnName), Byte()))\n If mStream.Length > 0 Then\n\n Dim b(Convert.ToInt32(mStream.Length - 1)) As Byte\n mStream.Read(b, 0, Convert.ToInt32(mStream.Length - 1))\n\n Dim position As Integer = 0\n\n For index As Integer = 0 To b.Length - 3\n If b(index) = &HFF And b(index + 1) = &HD8 And b(index + 2) = &HFF Then\n position = index\n Exit For\n End If\n Next\n\n If position > 0 Then\n Dim jpgStream As New System.IO.MemoryStream(b, position, b.Length - position)\n oImage = New Bitmap(jpgStream)\n End If\n End If\n End If\n End If\n Catch ex As Exception\n Throw New ApplicationException(ex.Message, ex)\n End Try\n Return oImage\nEnd Function\n</code></pre>\n\n<p>Then its a matter of pulling out this data into a bitmap. So for each row in the access table i extract the bitmap and then update the corresponding MySQL entry.<br>\nIt worked fine but im guessing i could have removed the serialisation stuff in a better way, perhaps theres an API to do it.</p>\n"
},
{
"answer_id": 10059187,
"author": "ash",
"author_id": 17708,
"author_profile": "https://Stackoverflow.com/users/17708",
"pm_score": 0,
"selected": false,
"text": "<p>There's also <a href=\"https://github.com/shamrin/olefield\" rel=\"nofollow\">olefield</a> - Python module to extract data out of OLE object fields in Access. I successfully extracted BMP files with it. It could probably work with jpeg images, but I haven't tried it.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2720/"
] | I have a table in an access table which contains Product entries, one of the columns has a jpg image stored as an OLE Object. I am trying to import this table to MySQL but nothing seems to work. I have tried the MySQL migration tool but that has a known issue with Access and OLE Objects. (The issue being it doesnt work and leaves the fields blank) I also tried the suggestion on [this site](http://www.plus2net.com/sql_tutorial/access_to_mysql.php)
and while the data is imported it seems as though the image is getting corrupted in the transfer. When i try to preview the image i just get a binary view, if i save it on disk as a jpg image and try to open it i get an error stating the image is corrupt.
The images in Access are fine and can be previewed. Access is storing the data as an OLE Object and when i import it to MySql it is saved in a MediumBlob field.
Has anyone had this issue before and how did they resolve it ? | Ok so in the interests of airing my dirty code in public here what i came up with.
Note : this is a hack designed to be used once and then thrown away.
This Method takes in a datarowview containing 1 row of data from the access table. The Images are wrapped in OLE serialization, im not entirely familiar with how this works but its how Microsoft apps allow any object to be embedded into something else. (eg images into Excel Cells). I needed to remove the serialization junk around the image so i loaded the entire field as a Byte array and searched through it for 3 concurrent entries (FF D8 FF) which represent the beginning of the image data within the field.
```
Private Function GetImageFromRow(ByRef row As DataRowView, ByVal columnName As String) As Bitmap
Dim oImage As Bitmap = New Bitmap("c:\default.jpg")
Try
If Not IsDBNull(row(columnName)) Then
If row(columnName) IsNot Nothing Then
Dim mStream As New System.IO.MemoryStream(CType(row(columnName), Byte()))
If mStream.Length > 0 Then
Dim b(Convert.ToInt32(mStream.Length - 1)) As Byte
mStream.Read(b, 0, Convert.ToInt32(mStream.Length - 1))
Dim position As Integer = 0
For index As Integer = 0 To b.Length - 3
If b(index) = &HFF And b(index + 1) = &HD8 And b(index + 2) = &HFF Then
position = index
Exit For
End If
Next
If position > 0 Then
Dim jpgStream As New System.IO.MemoryStream(b, position, b.Length - position)
oImage = New Bitmap(jpgStream)
End If
End If
End If
End If
Catch ex As Exception
Throw New ApplicationException(ex.Message, ex)
End Try
Return oImage
End Function
```
Then its a matter of pulling out this data into a bitmap. So for each row in the access table i extract the bitmap and then update the corresponding MySQL entry.
It worked fine but im guessing i could have removed the serialisation stuff in a better way, perhaps theres an API to do it. |
41,630 | <p>I would like to execute an OS command from my ruby script but I want to add an argument from a ruby variable.</p>
<p>I know that's possible by using keyword <em>system</em> like that :</p>
<pre><code>#!/usr/bin/env ruby
directory = '/home/paulgreg/'
system 'ls ' + directory
</code></pre>
<p>but is that possible by using the "backquotes or backticks syntax" ?
(I mean by using that syntax : <code>ls</code>)</p>
| [
{
"answer_id": 41635,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 4,
"selected": true,
"text": "<p>No, that will just concatenate the output from <code>ls</code> and the contents of <code>directory</code>.</p>\n\n<p>But you can do this:</p>\n\n<pre><code>#!/usr/bin/env ruby\ndirectory = '/home/paulgreg/'\n`ls #{directory}`\n</code></pre>\n"
},
{
"answer_id": 41892,
"author": "Nick Brosnahan",
"author_id": 528,
"author_profile": "https://Stackoverflow.com/users/528",
"pm_score": 3,
"selected": false,
"text": "<pre><code>`ls #{directory}` \n</code></pre>\n\n<p>isn't very safe because you're going to run into problems with path names that have spaces in them. </p>\n\n<p>It's safer to do something like this:</p>\n\n<pre><code>directory = '/home/paulgreg/'\n\nargs = []\nargs << \"/bin/ls\"\nargs << directory\n\nsystem(*args)\n</code></pre>\n"
},
{
"answer_id": 71636,
"author": "0124816",
"author_id": 11521,
"author_profile": "https://Stackoverflow.com/users/11521",
"pm_score": 1,
"selected": false,
"text": "<p>Nick is right, but there is no need to assemble the args piecewise:</p>\n\n<pre><code>directory = '/Volumes/Omg a space/'\nsystem('/bin/ls', directory)\n</code></pre>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3122/"
] | I would like to execute an OS command from my ruby script but I want to add an argument from a ruby variable.
I know that's possible by using keyword *system* like that :
```
#!/usr/bin/env ruby
directory = '/home/paulgreg/'
system 'ls ' + directory
```
but is that possible by using the "backquotes or backticks syntax" ?
(I mean by using that syntax : `ls`) | No, that will just concatenate the output from `ls` and the contents of `directory`.
But you can do this:
```
#!/usr/bin/env ruby
directory = '/home/paulgreg/'
`ls #{directory}`
``` |
41,638 | <p>The current system that I am working on makes use of Castle Activerecord to provide ORM (Object Relational Mapping) between the Domain objects and the database. This is all well and good and at most times actually works well!</p>
<p>The problem comes about with Castle Activerecords support for asynchronous execution, well, more specifically the SessionScope that manages the session that objects belong to. Long story short, bad stuff happens!</p>
<p>We are therefore looking for a way to easily convert (think automagically) from the Domain objects (who know that a DB exists and care) to the DTO object (who know nothing about the DB and care not for sessions, mapping attributes or all thing ORM).</p>
<p>Does anyone have suggestions on doing this. For the start I am looking for a basic One to One mapping of object. Domain object <strong>Person</strong> will be mapped to say <strong>PersonDTO</strong>. I do not want to do this manually since it is a waste.</p>
<p>Obviously reflection comes to mind, but I am hoping with some of the better IT knowledge floating around this site that <em>"cooler"</em> will be suggested.</p>
<p>Oh, I am working in C#, the ORM objects as said before a mapped with Castle ActiveRecord.</p>
<hr>
<h2>Example code:</h2>
<p>By @ajmastrean's request I have <a href="http://www.fryhard.com/downloads/stackoverflow/ActiveRecordAsync.zip" rel="noreferrer">linked</a> to an example that I have (badly) mocked together. The example has a <strong>capture form</strong>, capture form <strong>controller</strong>, <strong>domain</strong> objects, activerecord <strong>repository</strong> and an <strong>async</strong> helper. It is slightly big (3MB) because I included the ActiveRecored dll's needed to get it running. You will need to create a database called <em>ActiveRecordAsync</em> on your local machine or just change the .config file.</p>
<p>Basic details of example:</p>
<p><strong>The Capture Form</strong></p>
<p>The capture form has a reference to the contoller</p>
<pre><code>private CompanyCaptureController MyController { get; set; }
</code></pre>
<p>On initialise of the form it calls MyController.Load()
private void InitForm ()
{
MyController = new CompanyCaptureController(this);
MyController.Load();
}
This will return back to a method called LoadComplete()</p>
<pre><code>public void LoadCompleted (Company loadCompany)
{
_context.Post(delegate
{
CurrentItem = loadCompany;
bindingSource.DataSource = CurrentItem;
bindingSource.ResetCurrentItem();
//TOTO: This line will thow the exception since the session scope used to fetch loadCompany is now gone.
grdEmployees.DataSource = loadCompany.Employees;
}, null);
}
}
</code></pre>
<p>this is where the <em>"bad stuff"</em> occurs, since we are using the child list of Company that is set as Lazy load.</p>
<p><strong>The Controller</strong></p>
<p>The controller has a Load method that was called from the form, it then calls the Asyc helper to asynchronously call the LoadCompany method and then return to the Capture form's LoadComplete method.</p>
<pre><code>public void Load ()
{
new AsyncListLoad<Company>().BeginLoad(LoadCompany, Form.LoadCompleted);
}
</code></pre>
<p>The LoadCompany() method simply makes use of the Repository to find a know company.</p>
<pre><code>public Company LoadCompany()
{
return ActiveRecordRepository<Company>.Find(Setup.company.Identifier);
}
</code></pre>
<p>The rest of the example is rather generic, it has two domain classes which inherit from a base class, a setup file to instert some data and the repository to provide the <strong>ActiveRecordMediator</strong> abilities.</p>
| [
{
"answer_id": 169708,
"author": "ZeroBugBounce",
"author_id": 11314,
"author_profile": "https://Stackoverflow.com/users/11314",
"pm_score": 3,
"selected": false,
"text": "<p>I solved a problem very similar to this where I copied the data out of a lot of older web service contracts into WCF data contracts. I created a number of methods that had signatures like this:</p>\n\n<pre><code>public static T ChangeType<S, T>(this S source) where T : class, new()\n</code></pre>\n\n<p>The first time this method (or any of the other overloads) executes for two types, it looks at the properties of each type, and decides which ones exist in both based on name and type. It takes this 'member intersection' and uses the DynamicMethod class to emil the IL to copy the source type to the target type, then it caches the resulting delegate in a threadsafe static dictionary.</p>\n\n<p>Once the delegate is created, it's obscenely fast and I have provided other overloads to pass in a delegate to copy over properties that don't match the intersection criteria:</p>\n\n<pre><code>public static T ChangeType<S, T>(this S source, Action<S, T> additionalOperations) where T : class, new()\n</code></pre>\n\n<p>... so you could do this for your Person to PersonDTO example:</p>\n\n<pre><code>Person p = new Person( /* set whatever */);\nPersonDTO = p.ChangeType<Person, PersonDTO>();\n</code></pre>\n\n<p>And any properties on both Person and PersonDTO (again, that have the same name and type) would be copied by a runtime emitted method and any subsequent calls would not have to be emitted, but would reuse the same emitted code <em>for those types in that order</em> (i.e. copying PersonDTO to Person would also incur a hit to emit the code).</p>\n\n<p>It's too much code to post, but if you are interested I will make the effort to upload a sample to SkyDrive and post the link here.</p>\n\n<p>Richard</p>\n"
},
{
"answer_id": 169727,
"author": "MattMcKnight",
"author_id": 8136,
"author_profile": "https://Stackoverflow.com/users/8136",
"pm_score": 0,
"selected": false,
"text": "<p>My apologies for not really putting the details in here, but a basic OO approach would be to make the DTO a member of the ActiveRecord class and have the ActiveRecord delegate the accessors and mutators to the DTO. You could use code generation or refactoring tools to build the DTO classes pretty quickly from the AcitveRecord classes. </p>\n"
},
{
"answer_id": 310554,
"author": "Paul Kapustin",
"author_id": 38325,
"author_profile": "https://Stackoverflow.com/users/38325",
"pm_score": 0,
"selected": false,
"text": "<p>Actually I got totally confussed now.\nBecause you are saying: \"We are therefore looking for a way to easily convert (think automagically) from the Domain objects (who know that a DB exists and care) to the DTO object (who know nothing about the DB and care not for sessions, mapping attributes or all thing ORM).\"</p>\n\n<ol>\n<li><p>Domain objects know and care about DB? Isn't that the whole point of domain objects to contain business logic ONLY and be totally unaware of DB and ORM?....You HAVE to have these objects? You just need to FIX them if they contain all that stuff...that's why I am a bit confused how DTO's come into picture</p></li>\n<li><p>Could you provide more details on what problems you're facing with lazy loading?</p></li>\n</ol>\n"
},
{
"answer_id": 2694387,
"author": "januszstabik",
"author_id": 113911,
"author_profile": "https://Stackoverflow.com/users/113911",
"pm_score": 2,
"selected": false,
"text": "<p>You should automapper that I've blogged about here:</p>\n\n<p><a href=\"http://januszstabik.blogspot.com/2010/04/automatically-map-your-heavyweight-orm.html#links\" rel=\"nofollow noreferrer\">http://januszstabik.blogspot.com/2010/04/automatically-map-your-heavyweight-orm.html#links</a></p>\n\n<p>As long as the properties are named the same on both your objects automapper will handle it.</p>\n"
},
{
"answer_id": 3043748,
"author": "Omu",
"author_id": 112100,
"author_profile": "https://Stackoverflow.com/users/112100",
"pm_score": 2,
"selected": false,
"text": "<p>use <a href=\"http://valueinjecter.codeplex.com/\" rel=\"nofollow noreferrer\">ValueInjecter</a>, with it you can map anything to anything e.g.</p>\n\n<ul>\n<li>object <-> object</li>\n<li>object <-> Form/WebForm</li>\n<li>DataReader -> object</li>\n</ul>\n\n<p>and it has cool features like: flattening and unflattening</p>\n\n<p>the download contains lots of samples</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231/"
] | The current system that I am working on makes use of Castle Activerecord to provide ORM (Object Relational Mapping) between the Domain objects and the database. This is all well and good and at most times actually works well!
The problem comes about with Castle Activerecords support for asynchronous execution, well, more specifically the SessionScope that manages the session that objects belong to. Long story short, bad stuff happens!
We are therefore looking for a way to easily convert (think automagically) from the Domain objects (who know that a DB exists and care) to the DTO object (who know nothing about the DB and care not for sessions, mapping attributes or all thing ORM).
Does anyone have suggestions on doing this. For the start I am looking for a basic One to One mapping of object. Domain object **Person** will be mapped to say **PersonDTO**. I do not want to do this manually since it is a waste.
Obviously reflection comes to mind, but I am hoping with some of the better IT knowledge floating around this site that *"cooler"* will be suggested.
Oh, I am working in C#, the ORM objects as said before a mapped with Castle ActiveRecord.
---
Example code:
-------------
By @ajmastrean's request I have [linked](http://www.fryhard.com/downloads/stackoverflow/ActiveRecordAsync.zip) to an example that I have (badly) mocked together. The example has a **capture form**, capture form **controller**, **domain** objects, activerecord **repository** and an **async** helper. It is slightly big (3MB) because I included the ActiveRecored dll's needed to get it running. You will need to create a database called *ActiveRecordAsync* on your local machine or just change the .config file.
Basic details of example:
**The Capture Form**
The capture form has a reference to the contoller
```
private CompanyCaptureController MyController { get; set; }
```
On initialise of the form it calls MyController.Load()
private void InitForm ()
{
MyController = new CompanyCaptureController(this);
MyController.Load();
}
This will return back to a method called LoadComplete()
```
public void LoadCompleted (Company loadCompany)
{
_context.Post(delegate
{
CurrentItem = loadCompany;
bindingSource.DataSource = CurrentItem;
bindingSource.ResetCurrentItem();
//TOTO: This line will thow the exception since the session scope used to fetch loadCompany is now gone.
grdEmployees.DataSource = loadCompany.Employees;
}, null);
}
}
```
this is where the *"bad stuff"* occurs, since we are using the child list of Company that is set as Lazy load.
**The Controller**
The controller has a Load method that was called from the form, it then calls the Asyc helper to asynchronously call the LoadCompany method and then return to the Capture form's LoadComplete method.
```
public void Load ()
{
new AsyncListLoad<Company>().BeginLoad(LoadCompany, Form.LoadCompleted);
}
```
The LoadCompany() method simply makes use of the Repository to find a know company.
```
public Company LoadCompany()
{
return ActiveRecordRepository<Company>.Find(Setup.company.Identifier);
}
```
The rest of the example is rather generic, it has two domain classes which inherit from a base class, a setup file to instert some data and the repository to provide the **ActiveRecordMediator** abilities. | I solved a problem very similar to this where I copied the data out of a lot of older web service contracts into WCF data contracts. I created a number of methods that had signatures like this:
```
public static T ChangeType<S, T>(this S source) where T : class, new()
```
The first time this method (or any of the other overloads) executes for two types, it looks at the properties of each type, and decides which ones exist in both based on name and type. It takes this 'member intersection' and uses the DynamicMethod class to emil the IL to copy the source type to the target type, then it caches the resulting delegate in a threadsafe static dictionary.
Once the delegate is created, it's obscenely fast and I have provided other overloads to pass in a delegate to copy over properties that don't match the intersection criteria:
```
public static T ChangeType<S, T>(this S source, Action<S, T> additionalOperations) where T : class, new()
```
... so you could do this for your Person to PersonDTO example:
```
Person p = new Person( /* set whatever */);
PersonDTO = p.ChangeType<Person, PersonDTO>();
```
And any properties on both Person and PersonDTO (again, that have the same name and type) would be copied by a runtime emitted method and any subsequent calls would not have to be emitted, but would reuse the same emitted code *for those types in that order* (i.e. copying PersonDTO to Person would also incur a hit to emit the code).
It's too much code to post, but if you are interested I will make the effort to upload a sample to SkyDrive and post the link here.
Richard |
41,647 | <p>When using the php include function the include is succesfully executed, but it is also outputting a char before the output of the include is outputted, the char is of hex value 3F and I have no idea where it is coming from, although it seems to happen with every include. </p>
<p>At first I thbought it was file encoding, but this doesn't seem to be a problem. I have created a test case to demonstrate it: (<strong>link no longer working</strong>) <a href="http://driveefficiently.com/testinclude.php" rel="noreferrer">http://driveefficiently.com/testinclude.php</a> this file consists of only: </p>
<pre><code><? include("include.inc"); ?>
</code></pre>
<p>and include.inc consists of only: </p>
<pre><code><? echo ("hello, world"); ?>
</code></pre>
<p>and yet, the output is: <em>"?hello, world"</em> where the ? is a char with a random value. It is this value that I do not know the origins of and it is sometimes screwing up my sites a bit. </p>
<p>Any ideas of where this could be coming from? At first I thought it might be something to do with file encoding, but I don't think its a problem.</p>
| [
{
"answer_id": 41655,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 0,
"selected": false,
"text": "<p>I see <code>hello, world</code> on the page you linked to. No problems that I can see...</p>\n\n<p>I'm using Firefox 3.0.1 and Windows XP. What browser/OS are you running? Perhaps that might be the problem.</p>\n"
},
{
"answer_id": 41667,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 0,
"selected": false,
"text": "<p>Character 3F actually <em>is</em> the question mark, it isn't just displaying as one.</p>\n\n<p>I get the same results as Thomas, no question mark showing up.</p>\n\n<p>In theory it could be some problem with a web proxy but I am inclined to suspect a stray question mark in your PHP markup...which perhaps you have fixed by now so we don't see the problem.</p>\n"
},
{
"answer_id": 41678,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 1,
"selected": false,
"text": "<p>It doesn't show up on the rendered page in Firefox or IE but you can see the funny character when you View Source in IE</p>\n\n<p><img src=\"https://i.stack.imgur.com/cyPAq.png\" alt=\"enter image description here\"></p>\n\n<p>Is this on a Linux machine? Could you do find & replace with vim or sed to see if you can get rid of the 3F that way? </p>\n\n<p>If it's on Windows, try opening include.inc with Notepad to see if the funny char is visible & can be deleted.</p>\n\n<p>I'd also be curious to see what happens if you copy the code out of the include and just run it by itself.</p>\n"
},
{
"answer_id": 41687,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>Your web server (or your text editor) apparently includes a <a href=\"http://en.wikipedia.org/wiki/Byte_order_mark\" rel=\"nofollow noreferrer\">BOM</a> into the document. I don't see the rogue character in my browser except when I set the site's encoding explicitly to Latin-1. Then, I see two (!) UTF-8 BOMs.</p>\n\n<p>/EDIT: From the fact that there are <em>two</em> BOMs I conclude that the BOM is actually included by your editor at the beginning of the file. What editor do you use? If you use Visual Studio, you've got to say “Save As …” in the File menu and then choose the button “Save with encoding …”. There, choose “UTF-8 without BOM” or something similar.</p>\n"
},
{
"answer_id": 41691,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 5,
"selected": true,
"text": "<p>What you are seeing is a UTF-8 Byte Order Mark:</p>\n<blockquote>\n<p>The UTF-8 representation of the BOM is the byte sequence EF BB BF, which appears as the ISO-8859-1 characters  in most text editors and web browsers not prepared to handle UTF-8.</p>\n<p><a href=\"http://en.wikipedia.org/wiki/Byte_Order_Mark\" rel=\"noreferrer\">Byte Order Mark on Wikipedia</a></p>\n</blockquote>\n<p>PHP does not understand that these characters should be "hidden" and sends these to the browser as if they were normal characters. To get rid of them you will need to open the file using a "proper" text editor that will allow you to save the file as UTF-8 without the leading BOM.</p>\n<p><a href=\"http://juicystudio.com/article/utf-byte-order-mark.php\" rel=\"noreferrer\">You can read more about this problem here</a></p>\n"
},
{
"answer_id": 41693,
"author": "DAC",
"author_id": 1111,
"author_profile": "https://Stackoverflow.com/users/1111",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>I'd also be curious to see what\n happens if you copy the code out of\n the include and just run it by itself.</p>\n</blockquote>\n\n<p>Mark: this is on a shared hosting solution, so I can not get shell access to the file. However, as you can see <a href=\"http://driveefficiently.com/include.inc\" rel=\"nofollow noreferrer\">here</a>, there are no characters that shouldn't be there, and running the same file as a script does not produce this char. (The shared hosting company have been of 0 help, continually telling me it is a browser issue).</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111/"
] | When using the php include function the include is succesfully executed, but it is also outputting a char before the output of the include is outputted, the char is of hex value 3F and I have no idea where it is coming from, although it seems to happen with every include.
At first I thbought it was file encoding, but this doesn't seem to be a problem. I have created a test case to demonstrate it: (**link no longer working**) <http://driveefficiently.com/testinclude.php> this file consists of only:
```
<? include("include.inc"); ?>
```
and include.inc consists of only:
```
<? echo ("hello, world"); ?>
```
and yet, the output is: *"?hello, world"* where the ? is a char with a random value. It is this value that I do not know the origins of and it is sometimes screwing up my sites a bit.
Any ideas of where this could be coming from? At first I thought it might be something to do with file encoding, but I don't think its a problem. | What you are seeing is a UTF-8 Byte Order Mark:
>
> The UTF-8 representation of the BOM is the byte sequence EF BB BF, which appears as the ISO-8859-1 characters  in most text editors and web browsers not prepared to handle UTF-8.
>
>
> [Byte Order Mark on Wikipedia](http://en.wikipedia.org/wiki/Byte_Order_Mark)
>
>
>
PHP does not understand that these characters should be "hidden" and sends these to the browser as if they were normal characters. To get rid of them you will need to open the file using a "proper" text editor that will allow you to save the file as UTF-8 without the leading BOM.
[You can read more about this problem here](http://juicystudio.com/article/utf-byte-order-mark.php) |
41,652 | <p>We have got a custom <code>MembershipProvider</code> in <code>ASP.NET</code>. Now there are 2 possible scenario the user can be validated:</p>
<ol>
<li><p>User login via <code>login.aspx</code> page by entering his username/password. I have used <strong>Login control</strong> and linked it with the <code>MyMembershipProvider</code>. This is working perfectly fine.</p></li>
<li><p>An authentication token is passed via some URL in query string form a different web sites. For this I have one overload in <code>MembershipProvider.Validate(string authenticationToken)</code>, which is actually validating the user. In this case we cannot use the <strong>Login control</strong>. Now how can I use the same <code>MembershipProvider</code> to validate the user without actually using the <strong>Login control</strong>? I tried to call <code>Validate</code> manually, but this is not signing the user in.</p></li>
</ol>
<p>Here is the code snippet I am using </p>
<pre><code>if (!string.IsNullOrEmpty(Request.QueryString["authenticationToken"])) {
string ticket = Request.QueryString["authenticationToken"];
MyMembershipProvider provider = Membership.Provider as MyMembershipProvider;
if (provider != null) {
if (provider.ValidateUser(ticket))
// Login Success
else
// Login Fail
}
}
</code></pre>
| [
{
"answer_id": 41664,
"author": "MartinHN",
"author_id": 2972,
"author_profile": "https://Stackoverflow.com/users/2972",
"pm_score": 5,
"selected": true,
"text": "<p>After validation is successful, you need to sign in the user, by calling FormsAuthentication.Authenticate: <a href=\"http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx</a></p>\n\n<p>EDIT: It is FormsAuthentication.SetAuthCookie:\n<a href=\"http://msdn.microsoft.com/en-us/library/twk5762b.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/twk5762b.aspx</a></p>\n\n<p>Also, to redirect the user back where he wanted to go, call: FormsAuthentication.RedirectFromLoginPage: <a href=\"http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.redirectfromloginpage.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.redirectfromloginpage.aspx</a> </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx\" rel=\"nofollow noreferrer\">link text</a></p>\n"
},
{
"answer_id": 42151,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 2,
"selected": false,
"text": "<p>You can set your own <code>FormsAuthenticationTicket</code> if the validation is successful.</p>\n\n<p>Something like this;</p>\n\n<pre><code>if (provider != null) {\n if (provider.ValidateUser(ticket)) {\n // Login Success\n FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(\n 1, //version\n someUserName, //name\n DateTime.Now, //issue date\n DateTime.Now.AddMinutes(lengthOfSession), //expiration\n false, // persistence of login\n FormsAuthentication.FormsCookiePath\n );\n\n //encrypt the ticket\n string hash = FormsAuthentication.Encrypt(authTicket);\n HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);\n\n Response.Cookies.Add(cookie);\n Response.Redirect(url where you want the user to land);\n } else {\n // Login Fail \n } \n}\n</code></pre>\n"
},
{
"answer_id": 5698869,
"author": "Bernd",
"author_id": 712841,
"author_profile": "https://Stackoverflow.com/users/712841",
"pm_score": 1,
"selected": false,
"text": "<p>You are right in the case of storing the auth information as a cookie directly. But using a strong hash function (e.g. MD5 + SHA1) is great and secure.\nBy the way, if you use sessions (which is also just a hash cookie) you could attach auth information to it.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] | We have got a custom `MembershipProvider` in `ASP.NET`. Now there are 2 possible scenario the user can be validated:
1. User login via `login.aspx` page by entering his username/password. I have used **Login control** and linked it with the `MyMembershipProvider`. This is working perfectly fine.
2. An authentication token is passed via some URL in query string form a different web sites. For this I have one overload in `MembershipProvider.Validate(string authenticationToken)`, which is actually validating the user. In this case we cannot use the **Login control**. Now how can I use the same `MembershipProvider` to validate the user without actually using the **Login control**? I tried to call `Validate` manually, but this is not signing the user in.
Here is the code snippet I am using
```
if (!string.IsNullOrEmpty(Request.QueryString["authenticationToken"])) {
string ticket = Request.QueryString["authenticationToken"];
MyMembershipProvider provider = Membership.Provider as MyMembershipProvider;
if (provider != null) {
if (provider.ValidateUser(ticket))
// Login Success
else
// Login Fail
}
}
``` | After validation is successful, you need to sign in the user, by calling FormsAuthentication.Authenticate: <http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx>
EDIT: It is FormsAuthentication.SetAuthCookie:
<http://msdn.microsoft.com/en-us/library/twk5762b.aspx>
Also, to redirect the user back where he wanted to go, call: FormsAuthentication.RedirectFromLoginPage: <http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.redirectfromloginpage.aspx>
[link text](http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx) |
41,659 | <p>Is there any way in the Servlet API to access properties specified in web.xml (such as initialization parameters) from within a Bean or Factory class that is not associated at all with the web container?</p>
<p>For example, I'm writing a Factory class, and I'd like to include some logic within the Factory to check a hierarchy of files and configuration locations to see which if any are available to determine which implementation class to instantiate - for example, </p>
<ol>
<li>a properties file in the classpath,</li>
<li>a web.xml parameter, </li>
<li>a system property, or </li>
<li>some default logic if nothing else is available. </li>
</ol>
<p>I'd like to be able to do this without injecting any reference to <code>ServletConfig</code> or anything similiar to my Factory - the code should be able to run ok outside of a Servlet Container.</p>
<p>This might sound a little bit uncommon, but I'd like for this component I'm working on to be able to be packaged with one of our webapps, and also be versatile enough to be packaged with some of our command-line tools without requiring a new properties file just for my component - so I was hoping to piggyback on top of other configuration files such as web.xml.</p>
<p>If I recall correctly, .NET has something like <code>Request.GetCurrentRequest()</code> to get a reference to the currently executing <code>Request</code> - but since this is a Java app I'm looking for something simliar that could be used to gain access to <code>ServletConfig</code>.</p>
| [
{
"answer_id": 41767,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 1,
"selected": false,
"text": "<p>Have you considered using the Spring framework for this? That way, your beans don't get any extra cruft, and spring handles the configuration setup for you.</p>\n"
},
{
"answer_id": 41777,
"author": "stjohnroe",
"author_id": 2985,
"author_profile": "https://Stackoverflow.com/users/2985",
"pm_score": 0,
"selected": false,
"text": "<p>I think that you will have to add an associated bootstrap class which takes a reference to a ServletConfig (or ServletContext) and transcribes those values to the Factory class. At least this way you can package it separately.</p>\n\n<p>@toolkit : Excellent, most humbled - This is something that I have been trying to do for a while</p>\n"
},
{
"answer_id": 41814,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 4,
"selected": true,
"text": "<p>One way you could do this is:</p>\n\n<pre><code>public class FactoryInitialisingServletContextListener implements ServletContextListener {\n\n public void contextDestroyed(ServletContextEvent event) {\n }\n\n public void contextInitialized(ServletContextEvent event) {\n Properties properties = new Properties();\n ServletContext servletContext = event.getServletContext();\n Enumeration<?> keys = servletContext.getInitParameterNames();\n while (keys.hasMoreElements()) {\n String key = (String) keys.nextElement();\n String value = servletContext.getInitParameter(key);\n properties.setProperty(key, value);\n }\n Factory.setServletContextProperties(properties);\n }\n}\n\npublic class Factory {\n\n static Properties _servletContextProperties = new Properties();\n\n public static void setServletContextProperties(Properties servletContextProperties) {\n _servletContextProperties = servletContextProperties;\n }\n}\n</code></pre>\n\n<p>And then have the following in your web.xml</p>\n\n<pre><code><listener>\n <listener-class>com.acme.FactoryInitialisingServletContextListener<listener-class>\n</listener>\n</code></pre>\n\n<p>If your application is running in a web container, then the listener will be invoked by the container once the context has been created. In which case, the _servletContextProperties will be replaced with any context-params specified in the web.xml.</p>\n\n<p>If your application is running outside a web container, then _servletContextProperties will be empty.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
] | Is there any way in the Servlet API to access properties specified in web.xml (such as initialization parameters) from within a Bean or Factory class that is not associated at all with the web container?
For example, I'm writing a Factory class, and I'd like to include some logic within the Factory to check a hierarchy of files and configuration locations to see which if any are available to determine which implementation class to instantiate - for example,
1. a properties file in the classpath,
2. a web.xml parameter,
3. a system property, or
4. some default logic if nothing else is available.
I'd like to be able to do this without injecting any reference to `ServletConfig` or anything similiar to my Factory - the code should be able to run ok outside of a Servlet Container.
This might sound a little bit uncommon, but I'd like for this component I'm working on to be able to be packaged with one of our webapps, and also be versatile enough to be packaged with some of our command-line tools without requiring a new properties file just for my component - so I was hoping to piggyback on top of other configuration files such as web.xml.
If I recall correctly, .NET has something like `Request.GetCurrentRequest()` to get a reference to the currently executing `Request` - but since this is a Java app I'm looking for something simliar that could be used to gain access to `ServletConfig`. | One way you could do this is:
```
public class FactoryInitialisingServletContextListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent event) {
}
public void contextInitialized(ServletContextEvent event) {
Properties properties = new Properties();
ServletContext servletContext = event.getServletContext();
Enumeration<?> keys = servletContext.getInitParameterNames();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
String value = servletContext.getInitParameter(key);
properties.setProperty(key, value);
}
Factory.setServletContextProperties(properties);
}
}
public class Factory {
static Properties _servletContextProperties = new Properties();
public static void setServletContextProperties(Properties servletContextProperties) {
_servletContextProperties = servletContextProperties;
}
}
```
And then have the following in your web.xml
```
<listener>
<listener-class>com.acme.FactoryInitialisingServletContextListener<listener-class>
</listener>
```
If your application is running in a web container, then the listener will be invoked by the container once the context has been created. In which case, the \_servletContextProperties will be replaced with any context-params specified in the web.xml.
If your application is running outside a web container, then \_servletContextProperties will be empty. |
41,665 | <p>Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality?</p>
| [
{
"answer_id": 41672,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<p>You can try:</p>\n\n<pre><code>Bitmap.InterpolationMode = InterpolationMode.HighQualityBicubic;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>Bitmap.CompositingQuality = CompositingQuality.HighQuality;\n</code></pre>\n\n<p>Which does keep the quality fairly high, but not the highest possible.</p>\n"
},
{
"answer_id": 41677,
"author": "James Ogden",
"author_id": 3198,
"author_profile": "https://Stackoverflow.com/users/3198",
"pm_score": 1,
"selected": false,
"text": "<p>Fundamentally you won't be able to keep the same quality because jpg is (so far as I'm aware) always lossy even with the highest possible quality settings.</p>\n\n<p>If bit-accurate quality is really important, consider using png, which has some modes which are lossless.</p>\n"
},
{
"answer_id": 41684,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 7,
"selected": true,
"text": "<pre><code>var qualityEncoder = Encoder.Quality;\nvar quality = (long)<desired quality>;\nvar ratio = new EncoderParameter(qualityEncoder, quality );\nvar codecParams = new EncoderParameters(1);\ncodecParams.Param[0] = ratio;\nvar jpegCodecInfo = <one of the codec infos from ImageCodecInfo.GetImageEncoders() with mime type = \"image/jpeg\">;\nbmp.Save(fileName, jpegCodecInfo, codecParams); // Save to JPG\n</code></pre>\n"
},
{
"answer_id": 43258,
"author": "paan",
"author_id": 2976,
"author_profile": "https://Stackoverflow.com/users/2976",
"pm_score": 1,
"selected": false,
"text": "<p>Just want to say that JPEG is by nature a lossy format. So in thoery even at the highest settings you are going to have some information loss, but it depends a lot on the image.But png is lossless.</p>\n"
},
{
"answer_id": 2412375,
"author": "jestro",
"author_id": 417811,
"author_profile": "https://Stackoverflow.com/users/417811",
"pm_score": 5,
"selected": false,
"text": "<pre><code>public static class BitmapExtensions\n{\n public static void SaveJPG100(this Bitmap bmp, string filename)\n { \n EncoderParameters encoderParameters = new EncoderParameters(1);\n encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);\n bmp.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParameters);\n }\n\n public static void SaveJPG100(this Bitmap bmp, Stream stream)\n {\n EncoderParameters encoderParameters = new EncoderParameters(1);\n encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);\n bmp.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);\n }\n\n public static ImageCodecInfo GetEncoder(ImageFormat format)\n {\n ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();\n\n foreach (ImageCodecInfo codec in codecs)\n {\n if (codec.FormatID == format.Guid)\n {\n return codec;\n }\n }\n\n return null;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8703634,
"author": "net_prog",
"author_id": 355264,
"author_profile": "https://Stackoverflow.com/users/355264",
"pm_score": 4,
"selected": false,
"text": "<p>Provided BitmapExtensions by jestro are great, I used them. However would like to show the corrected version - works for Image parent class which is more convenient as I think and provides a way to supply quality:</p>\n\n<pre><code>public static class ImageExtensions\n{\n public static void SaveJpeg(this Image img, string filePath, long quality)\n {\n var encoderParameters = new EncoderParameters(1);\n encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);\n img.Save(filePath, GetEncoder(ImageFormat.Jpeg), encoderParameters);\n }\n\n public static void SaveJpeg(this Image img, Stream stream, long quality)\n {\n var encoderParameters = new EncoderParameters(1);\n encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);\n img.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);\n }\n\n static ImageCodecInfo GetEncoder(ImageFormat format)\n {\n ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();\n return codecs.Single(codec => codec.FormatID == format.Guid);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 32166157,
"author": "Jeff R",
"author_id": 4161426,
"author_profile": "https://Stackoverflow.com/users/4161426",
"pm_score": 1,
"selected": false,
"text": "<p>I am working on an expense report app, and I am really pleased with the default quality settings for JPG (and PNG) when saving from a Bitmap object.</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/9t4syfhh%28v=vs.110%29.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/9t4syfhh%28v=vs.110%29.aspx</a></p>\n\n<pre><code>Bitmap finalBitmap = ....; //from disk or whatever\nfinalBitmap.Save(xpsFileName + \".final.jpg\", ImageFormat.Jpeg);\nfinalBitmap.Save(xpsFileName + \".final.png\", ImageFormat.Png);\n</code></pre>\n\n<p>I'm on .NET 4.6...perhaps the quality has improved in subsequent framework releases.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] | Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality? | ```
var qualityEncoder = Encoder.Quality;
var quality = (long)<desired quality>;
var ratio = new EncoderParameter(qualityEncoder, quality );
var codecParams = new EncoderParameters(1);
codecParams.Param[0] = ratio;
var jpegCodecInfo = <one of the codec infos from ImageCodecInfo.GetImageEncoders() with mime type = "image/jpeg">;
bmp.Save(fileName, jpegCodecInfo, codecParams); // Save to JPG
``` |
41,674 | <p>In Visual Studio you can create a template XML document from an existing schema. The new <a href="http://msdn.microsoft.com/en-us/library/cc716766.aspx" rel="noreferrer">XML Schema Explorer</a> in VS2008 SP1 takes this a stage further and can create a sample XML document complete with data.
Is there a class library in .NET to do this automatically without having to use Visual Studio? I found the <a href="http://msdn.microsoft.com/en-us/library/aa302296.aspx" rel="noreferrer">XmlSampleGenerator</a> article on MSDN but it was written in 2004 so maybe there is something already included in .NET to do this now?</p>
| [
{
"answer_id": 174148,
"author": "curtisk",
"author_id": 17651,
"author_profile": "https://Stackoverflow.com/users/17651",
"pm_score": 0,
"selected": false,
"text": "<p>Directly, none that I can think of, other than third party add-ons. You could utilize the <a href=\"http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.80).aspx\" rel=\"nofollow noreferrer\">xsd schema definition tool</a> to take your XSD and create a .NET object/class, once you have that, you could, to quote the linked page: </p>\n\n<blockquote>\n <p>XSD to Classes: Generates runtime classes from an XSD schema file. The generated classes can be used in conjunction with <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(VS.80).aspx\" rel=\"nofollow noreferrer\">System.Xml.Serialization.XmlSerializer</a> to read and write XML code that follows the schema.</p>\n</blockquote>\n"
},
{
"answer_id": 245461,
"author": "Andrew Theken",
"author_id": 32238,
"author_profile": "https://Stackoverflow.com/users/32238",
"pm_score": 3,
"selected": false,
"text": "<p>some footwork is involved, but you could load the xsd into a DataSet object, iterate over the Tables and add a few rows in each by calling calling NewRow() on each and then adding those rows back into their respective tables.. then save the DataSet out to a file:</p>\n\n<pre><code>DataSet ds = new DataSet();\nds.ReadXmlSchema(\"c:/xsdfile.xsd\");\n\nforeach(DataTable t in ds.Tables)\n{\nvar row = t.NewRow();\nt.Rows.Add(row);\n}\n\nds.WriteXml(\"c:/example.xml\");\n</code></pre>\n\n<p>P.S. A little extra work, but instead of just iterating over each table type and adding empty rows, you could build a nice winform that would allow you to drop in some data for each of the rows. I built something like this in about an hour a few weeks ago.</p>\n"
},
{
"answer_id": 7797060,
"author": "SoftwareSavant",
"author_id": 729820,
"author_profile": "https://Stackoverflow.com/users/729820",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried <a href=\"http://xsd2code.codeplex.com/\" rel=\"nofollow\">http://xsd2code.codeplex.com/</a>????</p>\n\n<p>It worked for me, it can work for you.</p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3873/"
] | In Visual Studio you can create a template XML document from an existing schema. The new [XML Schema Explorer](http://msdn.microsoft.com/en-us/library/cc716766.aspx) in VS2008 SP1 takes this a stage further and can create a sample XML document complete with data.
Is there a class library in .NET to do this automatically without having to use Visual Studio? I found the [XmlSampleGenerator](http://msdn.microsoft.com/en-us/library/aa302296.aspx) article on MSDN but it was written in 2004 so maybe there is something already included in .NET to do this now? | some footwork is involved, but you could load the xsd into a DataSet object, iterate over the Tables and add a few rows in each by calling calling NewRow() on each and then adding those rows back into their respective tables.. then save the DataSet out to a file:
```
DataSet ds = new DataSet();
ds.ReadXmlSchema("c:/xsdfile.xsd");
foreach(DataTable t in ds.Tables)
{
var row = t.NewRow();
t.Rows.Add(row);
}
ds.WriteXml("c:/example.xml");
```
P.S. A little extra work, but instead of just iterating over each table type and adding empty rows, you could build a nice winform that would allow you to drop in some data for each of the rows. I built something like this in about an hour a few weeks ago. |
41,686 | <p>I've got some Java code using a servlet and Apache Commons FileUpload to upload a file to a set directory. It's working fine for character data (e.g. text files) but image files are coming out garbled. I can open them but the image doesn't look like it should. Here's my code:</p>
<p>Servlet</p>
<pre><code>protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String customerPath = "\\leetest\\";
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
if (item.isFormField()) {
// Form field. Ignore for now
} else {
BufferedInputStream stream = new BufferedInputStream(item
.openStream());
if (stream == null) {
LOGGER
.error("Something went wrong with fetching the stream for field "
+ name);
}
byte[] bytes = StreamUtils.getBytes(stream);
FileManager.createFile(customerPath, item.getName(), bytes);
stream.close();
}
}
}
} catch (Exception e) {
throw new UploadException("An error occured during upload: "
+ e.getMessage());
}
}
</code></pre>
<p>StreamUtils.getBytes(stream) looks like:</p>
<pre><code>public static byte[] getBytes(InputStream src, int buffsize)
throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] buff = new byte[buffsize];
while (true) {
int nBytesRead = src.read(buff);
if (nBytesRead < 0) {
break;
}
byteStream.write(buff);
}
byte[] result = byteStream.toByteArray();
byteStream.close();
return result;
}
</code></pre>
<p>And finally FileManager.createFile looks like:</p>
<pre><code>public static void createFile(String customerPath, String filename,
byte[] fileData) throws IOException {
customerPath = getFullPath(customerPath + filename);
File newFile = new File(customerPath);
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}
FileOutputStream outputStream = new FileOutputStream(newFile);
outputStream.write(fileData);
outputStream.close();
}
</code></pre>
<p>Can anyone spot what I'm doing wrong?</p>
<p>Cheers,
Lee</p>
| [
{
"answer_id": 41694,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>Are you sure that the image isn't coming through garbled or that you aren't dropping some packets on the way in. </p>\n"
},
{
"answer_id": 41748,
"author": "Ben",
"author_id": 1417,
"author_profile": "https://Stackoverflow.com/users/1417",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know what difference it makes, but there seems to be a mismatch of method signatures. The <code>getBytes()</code> method called in your <code>doPost()</code> method has only one argument:</p>\n\n<pre><code>byte[] bytes = StreamUtils.getBytes(stream);\n</code></pre>\n\n<p>while the method source you included has two arguments:</p>\n\n<pre><code>public static byte[] getBytes(InputStream src, int buffsize)\n</code></pre>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 41753,
"author": "Craig",
"author_id": 1611,
"author_profile": "https://Stackoverflow.com/users/1611",
"pm_score": 0,
"selected": false,
"text": "<p>Can you perform a checksum on your original file, and the uploaded file and see if there is any immediate differences?</p>\n\n<p>If there are then you can look at performing a diff, to determine the exact part(s) of the file that are missing changed.</p>\n\n<p>Things that pop to mind is beginning or end of stream, or endianness.</p>\n"
},
{
"answer_id": 42202,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 3,
"selected": true,
"text": "<p>One thing I don't like is here in this block from StreamUtils.getBytes():</p>\n\n<pre><code> 1 while (true) {\n 2 int nBytesRead = src.read(buff);\n 3 if (nBytesRead < 0) {\n 4 break;\n 5 }\n 6 byteStream.write(buff);\n 7 }\n</code></pre>\n\n<p>At line 6, it writes the entire buffer, no matter how many bytes are read in. I am not convinced this will always be the case. It would be more correct like this:</p>\n\n<pre><code> 1 while (true) {\n 2 int nBytesRead = src.read(buff);\n 3 if (nBytesRead < 0) {\n 4 break;\n 5 } else {\n 6 byteStream.write(buff, 0, nBytesRead);\n 7 }\n 8 }\n</code></pre>\n\n<p>Note the 'else' on line 5, along with the two additional parameters (array index start position and length to copy) on line 6.</p>\n\n<p>I could imagine that for larger files, like images, the buffer returns before it is filled (maybe it is waiting for more). That means you'd be unintentionally writing old data that was remaining in the tail end of the buffer. This is almost certainly happening most of the time at EoF, assuming a buffer > 1 byte, but extra data at EoF is probably not the cause of your corruption...it is just not desirable. </p>\n"
},
{
"answer_id": 42470,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 1,
"selected": false,
"text": "<p>I'd just use <a href=\"http://commons.apache.org/io/\" rel=\"nofollow noreferrer\">commons io</a> Then you could just do an IOUtils.copy(InputStream, OutputStream);</p>\n\n<p>It's got lots of other useful utility methods. </p>\n"
}
] | 2008/09/03 | [
"https://Stackoverflow.com/questions/41686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1900/"
] | I've got some Java code using a servlet and Apache Commons FileUpload to upload a file to a set directory. It's working fine for character data (e.g. text files) but image files are coming out garbled. I can open them but the image doesn't look like it should. Here's my code:
Servlet
```
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String customerPath = "\\leetest\\";
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
if (item.isFormField()) {
// Form field. Ignore for now
} else {
BufferedInputStream stream = new BufferedInputStream(item
.openStream());
if (stream == null) {
LOGGER
.error("Something went wrong with fetching the stream for field "
+ name);
}
byte[] bytes = StreamUtils.getBytes(stream);
FileManager.createFile(customerPath, item.getName(), bytes);
stream.close();
}
}
}
} catch (Exception e) {
throw new UploadException("An error occured during upload: "
+ e.getMessage());
}
}
```
StreamUtils.getBytes(stream) looks like:
```
public static byte[] getBytes(InputStream src, int buffsize)
throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] buff = new byte[buffsize];
while (true) {
int nBytesRead = src.read(buff);
if (nBytesRead < 0) {
break;
}
byteStream.write(buff);
}
byte[] result = byteStream.toByteArray();
byteStream.close();
return result;
}
```
And finally FileManager.createFile looks like:
```
public static void createFile(String customerPath, String filename,
byte[] fileData) throws IOException {
customerPath = getFullPath(customerPath + filename);
File newFile = new File(customerPath);
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}
FileOutputStream outputStream = new FileOutputStream(newFile);
outputStream.write(fileData);
outputStream.close();
}
```
Can anyone spot what I'm doing wrong?
Cheers,
Lee | One thing I don't like is here in this block from StreamUtils.getBytes():
```
1 while (true) {
2 int nBytesRead = src.read(buff);
3 if (nBytesRead < 0) {
4 break;
5 }
6 byteStream.write(buff);
7 }
```
At line 6, it writes the entire buffer, no matter how many bytes are read in. I am not convinced this will always be the case. It would be more correct like this:
```
1 while (true) {
2 int nBytesRead = src.read(buff);
3 if (nBytesRead < 0) {
4 break;
5 } else {
6 byteStream.write(buff, 0, nBytesRead);
7 }
8 }
```
Note the 'else' on line 5, along with the two additional parameters (array index start position and length to copy) on line 6.
I could imagine that for larger files, like images, the buffer returns before it is filled (maybe it is waiting for more). That means you'd be unintentionally writing old data that was remaining in the tail end of the buffer. This is almost certainly happening most of the time at EoF, assuming a buffer > 1 byte, but extra data at EoF is probably not the cause of your corruption...it is just not desirable. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.