qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
100,860 | <p>As most of you would know, if I drop a file named app_offline.htm in the root of an asp.net application, it takes the application offline <a href="http://asp-net-whidbey.blogspot.com/2006/04/aspnet-20-features-appofflinehtm.html" rel="nofollow noreferrer">as detailed here</a>.</p>
<p>You would also know, that while this is great, IIS actually returns a 404 code when this is in process and Microsoft is not going to do anything about it <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=319986" rel="nofollow noreferrer">as mentioned here</a>.</p>
<p>Now, since Asp.Net in general is so extensible, I am thinking that shouldn't there be a way to over ride this status code to return a 503 instead? The problem is, I don't know where to start looking to make this change.</p>
<p>HELP!</p>
| [
{
"answer_id": 100881,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 1,
"selected": false,
"text": "<p>You can try turning it off in the web.config.</p>\n\n<pre><code><httpRuntime enable = \"False\"/>\n</code></pre>\n"
},
{
"answer_id": 100926,
"author": "jules",
"author_id": 18655,
"author_profile": "https://Stackoverflow.com/users/18655",
"pm_score": 1,
"selected": false,
"text": "<p>You could probably do it by writing your own HTTP Handler (a .NET component that implements the System.Web.IHttpHandler interface).</p>\n\n<p>There's a good primer article here:\n<a href=\"http://www.15seconds.com/issue/020417.htm\" rel=\"nofollow noreferrer\">link text</a></p>\n"
},
{
"answer_id": 100928,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 4,
"selected": true,
"text": "<p>The handling of app_offline.htm is hardcoded in the ASP.NET pipeline, and can't be modified: see <code>CheckApplicationEnabled()</code> in <code>HttpRuntime.cs</code>, where it throws a very non-configurable 404 error if the application is deemed to be offline.</p>\n\n<p>However, <a href=\"http://support.microsoft.com/kb/307996\" rel=\"nofollow noreferrer\">creating your own HTTP module</a> to do something similar is of course trivial -- the OnBeginRequest handler could look as follows in this case (implementation for a HttpHandler shown, but in a HttpModule the idea is exactly the same):</p>\n\n<pre><code>Public Sub ProcessRequest(ByVal ctx As System.Web.HttpContext) Implements IHttpHandler.ProcessRequest\n If IO.File.Exists(ctx.Server.MapPath(\"/app_unavailable.htm\")) Then\n ctx.Response.Status = \"503 Unavailable (in Maintenance Mode)\"\n ctx.Response.Write(String.Format(\"<html><h1>{0}</h1></html>\", ctx.Response.Status))\n ctx.Response.End()\n End If\nEnd Sub\n</code></pre>\n\n<p>This is just a starting point, of course: by making the returned HTML a bit friendlier, you can display a nice \"we'll be right back\" page to your users as well.</p>\n"
},
{
"answer_id": 5729751,
"author": "Glen",
"author_id": 484110,
"author_profile": "https://Stackoverflow.com/users/484110",
"pm_score": 0,
"selected": false,
"text": "<p>An advantage of app_offline.htm and httpRuntime enable = \"False\", highlighted in the 1st link in the original question, is that the app domain of the application is no longer loaded, which may be desirable for substantial site changes. A slight modification to leppie's answer (which still serves 404's) is to add a defaultRedirect to another website which would allow the source site to be in the shut down state, the target site would then serve a simple 503 generating page</p>\n\n<p>web.config source site</p>\n\n<pre><code><httpRuntime enable=\"false\" />\n<customErrors mode=\"On\" defaultRedirect=\"/maintainance.aspx\"/>\n</code></pre>\n\n<p>maintainance.aspx in dest site</p>\n\n<pre><code><%@Page Language=\"C#\"%>\n<% \n Response.StatusCode = 503;\n Response.Write(\"App offline for maintainance\"); \n%>\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
]
| As most of you would know, if I drop a file named app\_offline.htm in the root of an asp.net application, it takes the application offline [as detailed here](http://asp-net-whidbey.blogspot.com/2006/04/aspnet-20-features-appofflinehtm.html).
You would also know, that while this is great, IIS actually returns a 404 code when this is in process and Microsoft is not going to do anything about it [as mentioned here](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=319986).
Now, since Asp.Net in general is so extensible, I am thinking that shouldn't there be a way to over ride this status code to return a 503 instead? The problem is, I don't know where to start looking to make this change.
HELP! | The handling of app\_offline.htm is hardcoded in the ASP.NET pipeline, and can't be modified: see `CheckApplicationEnabled()` in `HttpRuntime.cs`, where it throws a very non-configurable 404 error if the application is deemed to be offline.
However, [creating your own HTTP module](http://support.microsoft.com/kb/307996) to do something similar is of course trivial -- the OnBeginRequest handler could look as follows in this case (implementation for a HttpHandler shown, but in a HttpModule the idea is exactly the same):
```
Public Sub ProcessRequest(ByVal ctx As System.Web.HttpContext) Implements IHttpHandler.ProcessRequest
If IO.File.Exists(ctx.Server.MapPath("/app_unavailable.htm")) Then
ctx.Response.Status = "503 Unavailable (in Maintenance Mode)"
ctx.Response.Write(String.Format("<html><h1>{0}</h1></html>", ctx.Response.Status))
ctx.Response.End()
End If
End Sub
```
This is just a starting point, of course: by making the returned HTML a bit friendlier, you can display a nice "we'll be right back" page to your users as well. |
100,898 | <p>What's the best / simplest / most accurate way to detect the browser of a user?</p>
<p>Ease of extendability and implementation is a plus.</p>
<p>The less technologies used, the better.</p>
<p>The solution can be server side, client side, or both. The results should eventually end up at the server, though.</p>
<p>The solution can be framework agnostic.</p>
<p>The solution will only be used for reporting purposes.</p>
| [
{
"answer_id": 100908,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"http://jquery.thewikies.com/browser/\" rel=\"noreferrer\">JQuery Browser Plugin</a> will do it client-side for you.</p>\n\n<blockquote>\n <p><strong>What is the jQuery Browser Plugin?</strong></p>\n \n <p>The jQuery Browser Plugin is an addon for jQuery that makes it easy to uniquely identify your visitors' browsers.</p>\n \n <p><strong>What does it do?</strong></p>\n \n <p>It gives you an object in javascript that contains all of the information about the browser being used. It also adds CSS browser selectors, which means you can style elements or write functions for specific browsers, browser versions, layouts, layout versions, and even operating systems. Image of the jQuery Browser Plugin in action.</p>\n</blockquote>\n\n<p>The plug-in makes <code>$.browser</code> available, which you can re-submit to your server via an AJAX call, if you really need it server-side.</p>\n\n<pre><code>alert($.browser.name); // Alerts Firefox for me\n</code></pre>\n\n<p>The plug-in will only be as effective as the browsers it's been tested against, however. The plugin listed above has a list of <a href=\"http://jquery.thewikies.com/browser/test.html\" rel=\"noreferrer\">browsers recognised in it's tests</a>, but there's always the risk that a new browser will come sneaking out (<a href=\"http://www.google.com/chrome\" rel=\"noreferrer\">Google Chrome..</a>) that will require a re-write of the recognition rules. That said, this plug-in seems to be regularly updated.</p>\n"
},
{
"answer_id": 100910,
"author": "Johannes Hädrich",
"author_id": 18246,
"author_profile": "https://Stackoverflow.com/users/18246",
"pm_score": 0,
"selected": false,
"text": "<p>as Dan said: it depends on the used technology. </p>\n\n<p>For PHP server side browser detection i recommend Harald Hope's Browser detection:</p>\n\n<p><a href=\"http://techpatterns.com/downloads/php_browser_detection.php\" rel=\"nofollow noreferrer\">http://techpatterns.com/downloads/php_browser_detection.php</a></p>\n\n<p>Published under GPL.</p>\n"
},
{
"answer_id": 100918,
"author": "Twan",
"author_id": 6702,
"author_profile": "https://Stackoverflow.com/users/6702",
"pm_score": 1,
"selected": false,
"text": "<p>Since I just posted this in a (now-deleted question) and it's still in my paste buffer, I'll just repost.\nNote: this is a server-side PHP solution</p>\n\n<p>I currently use the following code for this. It is not nearly an exhausting solution, but it should be easy to implement more browsers. I didn't know about <a href=\"http://user-agents.org/\" rel=\"nofollow noreferrer\">user-agents.org</a> (thanks PConroy), \"one of these days\" I'll loop through it and see if I can update and add to my list.</p>\n\n<pre><code>define(\"BROWSER_OPERA\",\"Opera\");\ndefine(\"BROWSER_IE\",\"IE\");\ndefine(\"BROWSER_OMNIWEB\",\"Omniweb\");\ndefine(\"BROWSER_KONQUEROR\",\"Konqueror\");\ndefine(\"BROWSER_SAFARI\",\"Safari\");\ndefine(\"BROWSER_MOZILLA\",\"Mozilla\");\ndefine(\"BROWSER_OTHER\",\"other\");\n\n$aBrowsers = array\n(\n array(\"regexp\" => \"@Opera(/| )([0-9].[0-9]{1,2})@\", \"browser\" => BROWSER_OPERA, \"index\" => 2),\n array(\"regexp\" => \"@MSIE ([0-9].[0-9]{1,2})@\", \"browser\" => BROWSER_IE, \"index\" => 1),\n array(\"regexp\" => \"@OmniWeb/([0-9].[0-9]{1,2})@\", \"browser\" => BROWSER_OMNIWEB, \"index\" => 1),\n array(\"regexp\" => \"@(Konqueror/)(.*)(;)@\", \"browser\" => BROWSER_KONQUEROR, \"index\" => 2),\n array(\"regexp\" => \"@Safari/([0-9]*)@\", \"browser\" => BROWSER_SAFARI, \"index\" => 1),\n array(\"regexp\" => \"@Mozilla/([0-9].[0-9]{1,2})@\", \"browser\" => BROWSER_MOZILLA, \"index\" => 1)\n);\n\nforeach($aBrowsers as $aBrowser)\n{\n if (preg_match($aBrowser[\"regexp\"], $_SERVER[\"HTTP_USER_AGENT\"], $aBrowserVersion))\n {\n define(\"BROWSER_AGENT\",$aBrowser[\"browser\"]);\n define(\"BROWSER_VERSION\",$aBrowserVersion[$aBrowser[\"index\"]]);\n break;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 100925,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 5,
"selected": true,
"text": "<p>On the server you're pretty much limited to the UserAgent string the browser provides (which is fraught with problems, have a read about the <a href=\"http://www.webaim.org/blog/user-agent-string-history/\" rel=\"noreferrer\">UserAgent string's history</a>).</p>\n\n<p>On the client (ie in Javascript), you have more options. But the best option is to not actually worry about working out which browser it is. Simply check to make sure whatever feature you want to use actually exists.</p>\n\n<p>For example, you might want to use setCapture, which only MSIE provides:</p>\n\n<pre><code>if (element.setCapture) element.setCapture()\n</code></pre>\n\n<p>Rather than working out what the browser is, and then inferring its capabilities, we're simply seeing if it supports something before using it - who knows what browsers will support what in the future, do you really want to have to go back and update your scripts if Safari decides to support setCapture?</p>\n"
},
{
"answer_id": 100947,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 2,
"selected": false,
"text": "<p>When using javascript: <strong>Don't use browser detection</strong></p>\n\n<p>Write code that tests itself for given cases exhibited by browsers, otherwise you'll simply be writing code for a very very small population. Its better to use <code>\"typeof foo == 'undefined'\"</code> and browser specific tricks where you need them. </p>\n\n<p>jQuery does this all over its codebase ( if you look at the code you'll see it implementing behaviours for different browser tecnologies )</p>\n\n<p>Its better in the long run.</p>\n"
},
{
"answer_id": 105286,
"author": "Toby Mills",
"author_id": 12377,
"author_profile": "https://Stackoverflow.com/users/12377",
"pm_score": -1,
"selected": false,
"text": "<p>For internet explorer and Style sheets you can use the following syntax:</p>\n\n<pre><code><!--[if lte IE 6]><link href=\"/style.css\" rel=\"stylesheet\" type=\"text/css\" /><![endif]-->\n</code></pre>\n\n<p>This applys to IE 6 or earlier.\nYou can change the IE version and also have:</p>\n\n<pre><code><!--[if eq IE 7]> = Equal too IE 7\n<!--[if gt IE 6]> = Greater than IE 6\n</code></pre>\n\n<p>Im not sure if this works with other parts of the page but works when placed within the <code><head></code> tag. See this <a href=\"http://www.quirksmode.org/css/condcom.html\" rel=\"nofollow noreferrer\">example</a> for more information</p>\n"
},
{
"answer_id": 105345,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 0,
"selected": false,
"text": "<p>Don't use browser detection:</p>\n\n<ul>\n<li>Browser detection is not 100% reliable at the best of times, but things get worse than this:</li>\n<li>There are lots of variants of browsers (MSIE customisations etc)</li>\n<li>Browsers can lie about their identity (Opera actually has this feature built-in)</li>\n<li>Gateways hide or obfuscate the browser's identity</li>\n<li>Customisation and gateway vendors write their own rubbish in the USER_AGENT</li>\n</ul>\n\n<p>It's better to do feature detection in client-script. You hopefully only need browser-detection to work around a bug in a specific browser and version.</p>\n"
},
{
"answer_id": 132928,
"author": "Jrgns",
"author_id": 6681,
"author_profile": "https://Stackoverflow.com/users/6681",
"pm_score": 0,
"selected": false,
"text": "<p>I originally asked the question because I want to be able to record the browsers and operations systems people use to access my site. Yes, the user agent string can't be trusted, and yes, you shouldn't use browser detection to determine what code to run in JS, but, I'd like to have as accurate as possible statistics.</p>\n\n<p>I did the following.</p>\n\n<p>I'm using a combination of JavaScript and PHP to record the stats. JavaScript to determine what browser and OS (as this is <em>probably</em> the most accurate), and PHP to record it:</p>\n\n<p>The JavaScript comes from <a href=\"http://www.quirksmode.org/js/detect.html\" rel=\"nofollow noreferrer\">Quirksmode</a>, the PHP is rather self evident. I use the <a href=\"http://mootools.net\" rel=\"nofollow noreferrer\">MooTools</a> JS framework.</p>\n\n<p>Add the following to the BrowserDetect script:</p>\n\n<pre><code>window.addEvent('domready', function() {\n if (BrowserDetect) {\n var q_data = 'ajax=true&browser=' + BrowserDetect.browser + '&version=' + BrowserDetect.version + '&os=' + BrowserDetect.OS;\n var query = 'record_browser.php'\n var req = new Request.JSON({url: query, onComplete: setSelectWithJSON, data: q_data}).post();\n }\n});\n</code></pre>\n\n<p>This determines the browser, browser version and OS of the user's browser, and sends it to the <code>record_browser.php</code> script. The <code>record_browser.php</code> script just add's the information, along with the PHP <code>session_id</code> and the current <code>user_id</code>, if present.</p>\n\n<p>MySQL Table:</p>\n\n<pre><code>CREATE TABLE `browser_detects` (\n `id` int(11) NOT NULL auto_increment,\n `session` varchar(255) NOT NULL default '',\n `user_id` int(11) NOT NULL default '0',\n `browser` varchar(255) NOT NULL default '',\n `version` varchar(255) NOT NULL default '',\n `os` varchar(255) NOT NULL default '',\n PRIMARY KEY (`id`),\n UNIQUE KEY `sessionUnique` (`session`)\n)\n</code></pre>\n\n<p>PHP Code:</p>\n\n<pre><code>if ($_SERVER['REQUEST_METHOD'] == 'POST') {\n $session = session_id();\n $user_id = isset($user_id) ? $user_id ? 0;\n $browser = isset($_POST['browser']) ? $_POST['browser'] ? '';\n $version = isset($_POST['version']) ? $_POST['version'] ? '';\n $os = isset($_POST['os']) ? $_POST['os'] ? '';\n $q = $conn->prepare('INSERT INTO browser_detects (`session`, `user`, `browser`, `version`, `os`) VALUES (:session :user, :browser, :version, :os)');\n $q->execute(array(\n ':session' => $session,\n ':user' => $user_id,\n ':browser' => $browser,\n ':version' => $version,\n ':os' => $os\n ));\n}\n</code></pre>\n"
},
{
"answer_id": 132946,
"author": "stalepretzel",
"author_id": 1615,
"author_profile": "https://Stackoverflow.com/users/1615",
"pm_score": -1,
"selected": false,
"text": "<p>Generally, when a browser makes a request, it sends a bunch of information to you (time, name date, user-agent...). You should try to look at the headers the client sent and go to the one that tells you their browser (I think it's \"User-Agent:\".</p>\n"
},
{
"answer_id": 748659,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 0,
"selected": false,
"text": "<p>As stated by many, browser detection can go very wrong... however in the interests of Code Golf.</p>\n\n<p>This is a very fast way to detect IE.</p>\n\n<pre><code><script>\n if('\\v'=='v'){\n alert('I am IE');\n } else {\n alert('NOT IE');\n }\n</script>\n</code></pre>\n\n<p>Its pretty neat actually because it picks out IE without tripping up on Opera.</p>\n\n<p>Bonus points if you know <strong>why</strong> this works in IE. ;-)</p>\n"
},
{
"answer_id": 2999361,
"author": "Chuck Le Butt",
"author_id": 199700,
"author_profile": "https://Stackoverflow.com/users/199700",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Edit</strong>: The solution below isn't recommended. Try this instead: <a href=\"http://whichbrowser.net/\" rel=\"nofollow noreferrer\">http://whichbrowser.net/</a></p>\n\n<p>This once worked for me, but looking at the code now, I have no idea how. Use the above instead :-/</p>\n\n<pre><code><script type=\"text/javascript\">\n // </) || [])[1];\n this.safari = /webkit/.test(userAgent) && !/chrome/.test(userAgent);\n this.opera = /opera/.test(userAgent);\n this.msie = /msie/.test(userAgent) && !/opera/.test(userAgent);\n this.mozilla = /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent);\n this.chrome = /chrome/.test(userAgent);\n }\n }); \n // ]]>\n</script>\n</code></pre>\n\n<p>Don't forget that you need to initialize it to use it, so put this in your code:</p>\n\n<pre><code>var UserBrowser = new BrowserCheck();\n</code></pre>\n\n<p>And then check for a browser type and version like so: (e.g. Internet Explorer 8)</p>\n\n<pre><code>if ((UserBrowser.msie == true) && (UserBrowser.version == 8))\n</code></pre>\n\n<p>etc.</p>\n\n<p>Hope it does the job for you like it has for us, but remember that no browser detection is bullet proof!</p>\n"
},
{
"answer_id": 4650781,
"author": "SoftwareARM",
"author_id": 570304,
"author_profile": "https://Stackoverflow.com/users/570304",
"pm_score": 0,
"selected": false,
"text": "<p>This is the C # code I use, I hope will be helpful.</p>\n\n<pre><code>StringBuilder strb = new StringBuilder();\nstrb.AppendFormat ( \"User Agent: {0}{1}\", Request.ServerVariables[\"http_user_agent\"].ToString(), Environment.NewLine );\nstrb.AppendFormat ( \"Browser: {0}{1}\", Request.Browser.Browser.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"Version: {0}{1}\", Request.Browser.Version.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"Major Version: {0}{1}\", Request.Browser.MajorVersion.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"Minor Version: {0}{1}\", Request.Browser.MinorVersion.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"Platform: {0}{1}\", Request.Browser.Platform.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"ECMA Script version: {0}{1}\", Request.Browser.EcmaScriptVersion.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"Type: {0}{1}\", Request.Browser.Type.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"-------------------------------------------------------------------------------{0}\", Environment.NewLine );\nstrb.AppendFormat ( \"ActiveX Controls: {0}{1}\", Request.Browser.ActiveXControls.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"Background Sounds: {0}{1}\", Request.Browser.BackgroundSounds.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"AOL: {0}{1}\", Request.Browser.AOL.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"Beta: {0}{1}\", Request.Browser.Beta.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"CDF: {0}{1}\", Request.Browser.CDF.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"ClrVersion: {0}{1}\", Request.Browser.ClrVersion.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"Cookies: {0}{1}\", Request.Browser.Cookies.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"Crawler: {0}{1}\", Request.Browser.Crawler.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"Frames: {0}{1}\", Request.Browser.Frames.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"Tables: {0}{1}\", Request.Browser.Tables.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"JavaApplets: {0}{1}\", Request.Browser.JavaApplets.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"JavaScript: {0}{1}\", Request.Browser.JavaScript.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"MSDomVersion: {0}{1}\", Request.Browser.MSDomVersion.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"TagWriter: {0}{1}\", Request.Browser.TagWriter.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"VBScript: {0}{1}\", Request.Browser.VBScript.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"W3CDomVersion: {0}{1}\", Request.Browser.W3CDomVersion.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"Win16: {0}{1}\", Request.Browser.Win16.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"Win32: {0}{1}\", Request.Browser.Win32.ToString ( ), Environment.NewLine );\nstrb.AppendFormat ( \"-------------------------------------------------------------------------------{0}\", Environment.NewLine );\nstrb.AppendFormat ( \"MachineName: {0}{1}\", Environment.MachineName, Environment.NewLine );\nstrb.AppendFormat ( \"OSVersion: {0}{1}\", Environment.OSVersion, Environment.NewLine );\nstrb.AppendFormat ( \"ProcessorCount: {0}{1}\", Environment.ProcessorCount, Environment.NewLine );\nstrb.AppendFormat ( \"UserName: {0}{1}\", Environment.UserName, Environment.NewLine );\nstrb.AppendFormat ( \"Version: {0}{1}\", Environment.Version, Environment.NewLine );\nstrb.AppendFormat ( \"UserInteractive: {0}{1}\", Environment.UserInteractive, Environment.NewLine );\nstrb.AppendFormat ( \"UserDomainName: {0}{1}\", Environment.UserDomainName, Environment.NewLine );\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6681/"
]
| What's the best / simplest / most accurate way to detect the browser of a user?
Ease of extendability and implementation is a plus.
The less technologies used, the better.
The solution can be server side, client side, or both. The results should eventually end up at the server, though.
The solution can be framework agnostic.
The solution will only be used for reporting purposes. | On the server you're pretty much limited to the UserAgent string the browser provides (which is fraught with problems, have a read about the [UserAgent string's history](http://www.webaim.org/blog/user-agent-string-history/)).
On the client (ie in Javascript), you have more options. But the best option is to not actually worry about working out which browser it is. Simply check to make sure whatever feature you want to use actually exists.
For example, you might want to use setCapture, which only MSIE provides:
```
if (element.setCapture) element.setCapture()
```
Rather than working out what the browser is, and then inferring its capabilities, we're simply seeing if it supports something before using it - who knows what browsers will support what in the future, do you really want to have to go back and update your scripts if Safari decides to support setCapture? |
100,904 | <p>Per man pages, snprintf is returning number of bytes written from glibc version 2.2 onwards. But on lower versions of libc2.2 and HP-UX, it returns a positive integer, which could lead to a buffer overflow.</p>
<p>How can one overcome this and write portable code?</p>
<p>Edit : For want of more clarity</p>
<p>This code is working perfectly in lib 2.3</p>
<pre><code> if ( snprintf( cmd, cmdLen + 1, ". %s%s", myVar1, myVar2 ) != cmdLen )
{
fprintf( stderr, "\nError: Unable to copy bmake command!!!");
returnCode = ERR_COPY_FILENAME_FAILED;
}
</code></pre>
<p>It returns the length of the string (10) on Linux. But the same code is returning a positive number that is greater than the number of characters printed on HP-UX machine. Hope this explanation is fine.</p>
| [
{
"answer_id": 100936,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 0,
"selected": false,
"text": "<p>I have found one portable way to predict and/or limit the number of characters returned by sprintf and related functions, but it's inefficient and many consider it inelegant.</p>\n\n<p>What you do is create a temporary file with tmpfile(), fprintf() to that (which reliably returns the number of bytes written), then rewind and read all or part of the text into a buffer.</p>\n\n<p>Example:</p>\n\n<pre><code>int my_snprintf(char *buf, size_t n, const char *fmt, ...)\n{\n va_list va;\n int nchars;\n FILE *tf = tmpfile();\n\n va_start(va, n);\n nchars = vfprintf(tf, fmt, va);\n if (nchars >= (int) n)\n nchars = (int) n - 1;\n va_end(va);\n memset(buf, 0, 1 + (size_t) nchars);\n\n if (nchars > 0)\n {\n rewind(tf);\n fread(buf, 1, (size_t) nchars, tf);\n }\n\n fclose(tf);\n\n return nchars; \n}\n</code></pre>\n"
},
{
"answer_id": 100991,
"author": "INS",
"author_id": 13136,
"author_profile": "https://Stackoverflow.com/users/13136",
"pm_score": 3,
"selected": true,
"text": "<p>you could create a snprintf wrapper that returns -1 for each case when there is not enough space in the buffer.</p>\n\n<p>See the <a href=\"http://linux.die.net/man/3/snprintf\" rel=\"nofollow noreferrer\">man page</a> for more docs. It has also an example which threats all the cases.</p>\n\n<pre><code> while (1) {\n /* Try to print in the allocated space. */\n va_start(ap, fmt);\n n = vsnprintf (p, size, fmt, ap);\n va_end(ap);\n /* If that worked, return the string. */\n if (n > -1 && n < size)\n return p;\n /* Else try again with more space. */\n if (n > -1) /* glibc 2.1 */\n size = n+1; /* precisely what is needed */\n else /* glibc 2.0 */\n size *= 2; /* twice the old size */\n if ((np = realloc (p, size)) == NULL) {\n free(p);\n return NULL;\n } else {\n p = np;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 101255,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Have you considered a portable implementation of printf? I looked for one a little while ago and settled on trio. </p>\n\n<p><a href=\"http://daniel.haxx.se/projects/trio/\" rel=\"nofollow noreferrer\">http://daniel.haxx.se/projects/trio/</a></p>\n"
},
{
"answer_id": 102484,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 1,
"selected": false,
"text": "<p>Your question is still unclear. The <a href=\"http://linux.die.net/man/3/snprintf\" rel=\"nofollow noreferrer\">man page</a> linked to speaks thus:</p>\n\n<blockquote>\n <p>The functions snprintf() and vsnprintf() <strong>do not write more than size bytes</strong> (including\n the trailing '\\0'). If the output was truncated due to this limit then the return value is the number of characters (not including the trailing '\\0') which <strong>would</strong> have been written to the final string if enough space had been available. Thus, <strong>a return value of size or more means that the output was truncated.</strong></p>\n</blockquote>\n\n<p>So, if you want to know if your output was truncated:</p>\n\n<pre><code>int ret = snprintf(cmd, cmdLen + 1, \". %s%s\", myVar1, myVar2 ) == -1)\nif(ret == -1 || ret > cmdLen)\n{\n //output was truncated\n}\nelse\n{\n //everything is groovy\n}\n</code></pre>\n"
},
{
"answer_id": 102533,
"author": "mbac32768",
"author_id": 18446,
"author_profile": "https://Stackoverflow.com/users/18446",
"pm_score": 0,
"selected": false,
"text": "<p>Use the much superior asprintf() instead.</p>\n\n<p>It's a GNU extension, but it's worth copying to the target platform in the event that it's not natively available.</p>\n"
},
{
"answer_id": 103404,
"author": "James Antill",
"author_id": 10314,
"author_profile": "https://Stackoverflow.com/users/10314",
"pm_score": 1,
"selected": false,
"text": "<p>There are a whole host of problems with *printf portability, and realistically you probably want to follow one of three paths:</p>\n\n<ol>\n<li><p>Require a c99 compliant *printf, because 9 years should be enough for anyone, and just say the platform is broken otherwise.</p></li>\n<li><p>Have a my_snprintf() with a bunch of #ifdef's for the specific platforms you want to support all calling the vsnprintf() underneath (understanding the lowest common denominator is what you have).</p></li>\n<li><p>Just carry around a copy of vsnprintf() with your code, for simple usecases it's actually <a href=\"http://www.and.org/texts/simple_printf.c\" rel=\"nofollow noreferrer\">pretty simple</a> and for others you'd probably want to look at <a href=\"http://www.and.org/vstr/\" rel=\"nofollow noreferrer\">vstr</a> and you'll get customer formatters for free.</p></li>\n</ol>\n\n<p>...as other people have suggested you can do a hack merging #1 and #2, just for the -1 case, but that is risky due to the fact that c99 *printf can/does return -1 in certain conditions.</p>\n\n<p>Personally I'd recommend just going with <a href=\"http://www.and.org/ustr/\" rel=\"nofollow noreferrer\">a string library like ustr</a>, which does the simple workarounds for you and gives you managed strings for free. If you really care you can combine with <a href=\"http://www.and.org/vstr/\" rel=\"nofollow noreferrer\">vstr</a>.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18657/"
]
| Per man pages, snprintf is returning number of bytes written from glibc version 2.2 onwards. But on lower versions of libc2.2 and HP-UX, it returns a positive integer, which could lead to a buffer overflow.
How can one overcome this and write portable code?
Edit : For want of more clarity
This code is working perfectly in lib 2.3
```
if ( snprintf( cmd, cmdLen + 1, ". %s%s", myVar1, myVar2 ) != cmdLen )
{
fprintf( stderr, "\nError: Unable to copy bmake command!!!");
returnCode = ERR_COPY_FILENAME_FAILED;
}
```
It returns the length of the string (10) on Linux. But the same code is returning a positive number that is greater than the number of characters printed on HP-UX machine. Hope this explanation is fine. | you could create a snprintf wrapper that returns -1 for each case when there is not enough space in the buffer.
See the [man page](http://linux.die.net/man/3/snprintf) for more docs. It has also an example which threats all the cases.
```
while (1) {
/* Try to print in the allocated space. */
va_start(ap, fmt);
n = vsnprintf (p, size, fmt, ap);
va_end(ap);
/* If that worked, return the string. */
if (n > -1 && n < size)
return p;
/* Else try again with more space. */
if (n > -1) /* glibc 2.1 */
size = n+1; /* precisely what is needed */
else /* glibc 2.0 */
size *= 2; /* twice the old size */
if ((np = realloc (p, size)) == NULL) {
free(p);
return NULL;
} else {
p = np;
}
}
``` |
100,917 | <p>I'm trying to read data from a Delphi DBIV database, every time I access the database it creates a Paradox.lck and a Pdoxusrs.lck file. I'm using only a TQuery Object to do this (nothing else). can I access a Delphi DBIV database without it creating these lock files?</p>
| [
{
"answer_id": 100936,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 0,
"selected": false,
"text": "<p>I have found one portable way to predict and/or limit the number of characters returned by sprintf and related functions, but it's inefficient and many consider it inelegant.</p>\n\n<p>What you do is create a temporary file with tmpfile(), fprintf() to that (which reliably returns the number of bytes written), then rewind and read all or part of the text into a buffer.</p>\n\n<p>Example:</p>\n\n<pre><code>int my_snprintf(char *buf, size_t n, const char *fmt, ...)\n{\n va_list va;\n int nchars;\n FILE *tf = tmpfile();\n\n va_start(va, n);\n nchars = vfprintf(tf, fmt, va);\n if (nchars >= (int) n)\n nchars = (int) n - 1;\n va_end(va);\n memset(buf, 0, 1 + (size_t) nchars);\n\n if (nchars > 0)\n {\n rewind(tf);\n fread(buf, 1, (size_t) nchars, tf);\n }\n\n fclose(tf);\n\n return nchars; \n}\n</code></pre>\n"
},
{
"answer_id": 100991,
"author": "INS",
"author_id": 13136,
"author_profile": "https://Stackoverflow.com/users/13136",
"pm_score": 3,
"selected": true,
"text": "<p>you could create a snprintf wrapper that returns -1 for each case when there is not enough space in the buffer.</p>\n\n<p>See the <a href=\"http://linux.die.net/man/3/snprintf\" rel=\"nofollow noreferrer\">man page</a> for more docs. It has also an example which threats all the cases.</p>\n\n<pre><code> while (1) {\n /* Try to print in the allocated space. */\n va_start(ap, fmt);\n n = vsnprintf (p, size, fmt, ap);\n va_end(ap);\n /* If that worked, return the string. */\n if (n > -1 && n < size)\n return p;\n /* Else try again with more space. */\n if (n > -1) /* glibc 2.1 */\n size = n+1; /* precisely what is needed */\n else /* glibc 2.0 */\n size *= 2; /* twice the old size */\n if ((np = realloc (p, size)) == NULL) {\n free(p);\n return NULL;\n } else {\n p = np;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 101255,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Have you considered a portable implementation of printf? I looked for one a little while ago and settled on trio. </p>\n\n<p><a href=\"http://daniel.haxx.se/projects/trio/\" rel=\"nofollow noreferrer\">http://daniel.haxx.se/projects/trio/</a></p>\n"
},
{
"answer_id": 102484,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 1,
"selected": false,
"text": "<p>Your question is still unclear. The <a href=\"http://linux.die.net/man/3/snprintf\" rel=\"nofollow noreferrer\">man page</a> linked to speaks thus:</p>\n\n<blockquote>\n <p>The functions snprintf() and vsnprintf() <strong>do not write more than size bytes</strong> (including\n the trailing '\\0'). If the output was truncated due to this limit then the return value is the number of characters (not including the trailing '\\0') which <strong>would</strong> have been written to the final string if enough space had been available. Thus, <strong>a return value of size or more means that the output was truncated.</strong></p>\n</blockquote>\n\n<p>So, if you want to know if your output was truncated:</p>\n\n<pre><code>int ret = snprintf(cmd, cmdLen + 1, \". %s%s\", myVar1, myVar2 ) == -1)\nif(ret == -1 || ret > cmdLen)\n{\n //output was truncated\n}\nelse\n{\n //everything is groovy\n}\n</code></pre>\n"
},
{
"answer_id": 102533,
"author": "mbac32768",
"author_id": 18446,
"author_profile": "https://Stackoverflow.com/users/18446",
"pm_score": 0,
"selected": false,
"text": "<p>Use the much superior asprintf() instead.</p>\n\n<p>It's a GNU extension, but it's worth copying to the target platform in the event that it's not natively available.</p>\n"
},
{
"answer_id": 103404,
"author": "James Antill",
"author_id": 10314,
"author_profile": "https://Stackoverflow.com/users/10314",
"pm_score": 1,
"selected": false,
"text": "<p>There are a whole host of problems with *printf portability, and realistically you probably want to follow one of three paths:</p>\n\n<ol>\n<li><p>Require a c99 compliant *printf, because 9 years should be enough for anyone, and just say the platform is broken otherwise.</p></li>\n<li><p>Have a my_snprintf() with a bunch of #ifdef's for the specific platforms you want to support all calling the vsnprintf() underneath (understanding the lowest common denominator is what you have).</p></li>\n<li><p>Just carry around a copy of vsnprintf() with your code, for simple usecases it's actually <a href=\"http://www.and.org/texts/simple_printf.c\" rel=\"nofollow noreferrer\">pretty simple</a> and for others you'd probably want to look at <a href=\"http://www.and.org/vstr/\" rel=\"nofollow noreferrer\">vstr</a> and you'll get customer formatters for free.</p></li>\n</ol>\n\n<p>...as other people have suggested you can do a hack merging #1 and #2, just for the -1 case, but that is risky due to the fact that c99 *printf can/does return -1 in certain conditions.</p>\n\n<p>Personally I'd recommend just going with <a href=\"http://www.and.org/ustr/\" rel=\"nofollow noreferrer\">a string library like ustr</a>, which does the simple workarounds for you and gives you managed strings for free. If you really care you can combine with <a href=\"http://www.and.org/vstr/\" rel=\"nofollow noreferrer\">vstr</a>.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'm trying to read data from a Delphi DBIV database, every time I access the database it creates a Paradox.lck and a Pdoxusrs.lck file. I'm using only a TQuery Object to do this (nothing else). can I access a Delphi DBIV database without it creating these lock files? | you could create a snprintf wrapper that returns -1 for each case when there is not enough space in the buffer.
See the [man page](http://linux.die.net/man/3/snprintf) for more docs. It has also an example which threats all the cases.
```
while (1) {
/* Try to print in the allocated space. */
va_start(ap, fmt);
n = vsnprintf (p, size, fmt, ap);
va_end(ap);
/* If that worked, return the string. */
if (n > -1 && n < size)
return p;
/* Else try again with more space. */
if (n > -1) /* glibc 2.1 */
size = n+1; /* precisely what is needed */
else /* glibc 2.0 */
size *= 2; /* twice the old size */
if ((np = realloc (p, size)) == NULL) {
free(p);
return NULL;
} else {
p = np;
}
}
``` |
100,922 | <p>Can someone explain to me the advantages of using an IOC container over simply hardcoding the default implementation into a default constructor?</p>
<p>In other words, what is wrong about this code?</p>
<pre><code>public class MyClass
{
private IMyInterface _myInterface;
public MyClass()
{
_myInterface = new DefaultMyInterface();
}
public MyClass(IMyInterface myInterface)
{
_myInterface = myInterface;
}
}
</code></pre>
<p>As far as I can tell, this class supports constructor injection enough so unit testing and mocking is easily done. In addition to which, the default constructor removes the computational overhead of the IOC container (not to mention the whole process is a lot more transparent).</p>
<p>The only benefits i can see to using an IOC container is if you need to switch out the implementation of your interfaces frequently. Am I missing something?</p>
| [
{
"answer_id": 100951,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 5,
"selected": true,
"text": "<p>The idea of IoC is to delegate part of your component's functionality to another part of the system. In IoC world, you have components that don't know about each other. Your example violates this, as you're creating tight coupling between MyClass and some implementation of IMyInterface. <strong>The main idea</strong> is that your component <strong>has no knowledge</strong> about how it will be used. In your example, your component <strong>makes some assumptions</strong> about its use.</p>\n\n<p>Actually this approach can work, but mixing IoC and explicit object initialization is not a good practice IMO.</p>\n\n<p>IoC gives you loose coupling by performing late binding for the price of code clarity. When you add additional behavior to this process, it makes things even more complicated and can lead to bugs when some components can potentially receive object with unwanted or unpredicted behavior.</p>\n"
},
{
"answer_id": 100952,
"author": "Sergio Acosta",
"author_id": 2954,
"author_profile": "https://Stackoverflow.com/users/2954",
"pm_score": 0,
"selected": false,
"text": "<p>I don't see why your technique of hardcoding the default implementation could not be used together with an IOC container. Just, the dependencies you don't specify in the configuration would take the default implementation.</p>\n\n<p>Or am I missing something?</p>\n"
},
{
"answer_id": 100962,
"author": "Seb Rose",
"author_id": 12405,
"author_profile": "https://Stackoverflow.com/users/12405",
"pm_score": 0,
"selected": false,
"text": "<p>One reason you might want to use an IOC Container would be to facilitate late configuration of your software.</p>\n\n<p>Say, for instance, you provide several implementations of a particular interface - the customer (or your professional services team) can decide which one to use by modifying the IOC configuration file.</p>\n"
},
{
"answer_id": 101007,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "<p>Pick a side :)</p>\n\n<p>In short IOC is recommended. The problem with the code is that I cannot swap out the default implementation of the dependency without recompiling the code as you have stated at the end. IOC allows you to change the configuration or composition of your object in an external file without recompilation.<br>\n<strong>IOC takes over the \"construction and assembly\" responsibility from the rest of the code.</strong>\nThe purpose of IOC is not to make your code testable... it is a pleasant side-effect. (Just like TDDed code leads to better design)</p>\n"
},
{
"answer_id": 101010,
"author": "Paco",
"author_id": 13376,
"author_profile": "https://Stackoverflow.com/users/13376",
"pm_score": 1,
"selected": false,
"text": "<p>Besides loose coupling, an IoC will reduce code duplication. When you use an IoC and you want to change the default implementation of your interface, you have to change it at only one place. When you use default contructors to inject the default implementation, you have to change it everywhere the interface is used.</p>\n"
},
{
"answer_id": 101049,
"author": "Tahir Akhtar",
"author_id": 18027,
"author_profile": "https://Stackoverflow.com/users/18027",
"pm_score": 2,
"selected": false,
"text": "<p>There is nothing wrong with this code and you can still use it with Dependency Injection frameworks like Spring and Guice. </p>\n\n<p>Many developers see Spring's XML configuration file as an advantage over wiring dependencies within code as you can switch implementations without needing a compilation step. This benefit actually is realized in situations where you already have several implementations compiled in your class path and you want to choose the implementation at deployment time. You can imagine a situation where a component is provided by a third party after deployment. Similarly there can be a case when you want to ship additional implementations as a patch after deployment.</p>\n\n<p>But not all DI frameworks use XML configuration. Google Guice for example have Modules written as Java classes that must be compiled like any other java class.</p>\n\n<p>So what is the advantage of DI if you even need a compilation step?\nThis takes us back to your original question.\nI can see following advantages:</p>\n\n<ol>\n<li>Standard approach to DI throughout application.</li>\n<li>Configuration neatly separated out from other logic. </li>\n<li>Ability to inject proxies. Spring for example allows you to do declarative Transaction handling by injecting proxies instead of your implementation</li>\n<li>Easier re-use of configuration logic. When you use DI extensively, you will see a complex tree of dependencies evolving over time. Managing it without a clearly separated out configuration layer and framework support can be a nightmare. DI frameworks make it easy to re-use configuration logic through inheritance and other means.</li>\n</ol>\n"
},
{
"answer_id": 226846,
"author": "Glenn Block",
"author_id": 18419,
"author_profile": "https://Stackoverflow.com/users/18419",
"pm_score": 1,
"selected": false,
"text": "<p>In addition to the other comments, one could argue the DRY (Do Not Repeat Yourself) principle in these cases. It's redudnant to have to put that default construction code in every class. It's also introducign special case handling where there doesn't need to be any. </p>\n"
},
{
"answer_id": 2631896,
"author": "Brent Arias",
"author_id": 284758,
"author_profile": "https://Stackoverflow.com/users/284758",
"pm_score": 2,
"selected": false,
"text": "<p>The only concern I have is (1) if your default service dependency itself has another / secondary service dependency (and so on...your DefaultMyInterface depends on ILogger) and (2) you need to isolate the first service dependency from the second (need to test DefaultMyInterface with a stub ILogger). In that case you evidently will need to lose the default \"new DefaultMyInterface\" and instead do one of: (1) pure dependency injection or (2) service locator or (3) container.BuildUp(new DefaultMyInterface());</p>\n\n<p>Some of the concerns other posters listed might not be fair to your question. You were not asking about multiple \"production\" implementations. You are asking about <em>unit testing.</em> In the case of unit tesing your approach, with my first caveat stated, seems legitimate; I too would consider using it in simple unit test cases.</p>\n\n<p>Likewise, a couple responders expressed concern over repititiousness. I don't like repitition either, but if (1) your default implementation really is your default (YAGNI: you don't have plans on changing the default) and (2) you don't believe the first caveat I stated applies and (3) prefer the simpler code approach you've shared, then I don't think this particular form of repitition is an issue.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
]
| Can someone explain to me the advantages of using an IOC container over simply hardcoding the default implementation into a default constructor?
In other words, what is wrong about this code?
```
public class MyClass
{
private IMyInterface _myInterface;
public MyClass()
{
_myInterface = new DefaultMyInterface();
}
public MyClass(IMyInterface myInterface)
{
_myInterface = myInterface;
}
}
```
As far as I can tell, this class supports constructor injection enough so unit testing and mocking is easily done. In addition to which, the default constructor removes the computational overhead of the IOC container (not to mention the whole process is a lot more transparent).
The only benefits i can see to using an IOC container is if you need to switch out the implementation of your interfaces frequently. Am I missing something? | The idea of IoC is to delegate part of your component's functionality to another part of the system. In IoC world, you have components that don't know about each other. Your example violates this, as you're creating tight coupling between MyClass and some implementation of IMyInterface. **The main idea** is that your component **has no knowledge** about how it will be used. In your example, your component **makes some assumptions** about its use.
Actually this approach can work, but mixing IoC and explicit object initialization is not a good practice IMO.
IoC gives you loose coupling by performing late binding for the price of code clarity. When you add additional behavior to this process, it makes things even more complicated and can lead to bugs when some components can potentially receive object with unwanted or unpredicted behavior. |
100,948 | <p>I installed MySQL via <a href="http://en.wikipedia.org/wiki/MacPorts" rel="noreferrer">MacPorts</a>. What is the command I need to stop the server (I need to test how my application behave when MySQL is dead)?</p>
| [
{
"answer_id": 100953,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 4,
"selected": false,
"text": "<p>Apparently you want:</p>\n\n<pre><code>sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop\n</code></pre>\n\n<p>Have a further read in <em><a href=\"http://www.simplisticcomplexity.com/2007/10/27/start-and-stop-mysql-in-mac-os-x-105-leopard/\" rel=\"noreferrer\">Jeez People, Stop Fretting Over Installing RMagic</a></em>.</p>\n"
},
{
"answer_id": 100958,
"author": "Bartosz Blimke",
"author_id": 18715,
"author_profile": "https://Stackoverflow.com/users/18715",
"pm_score": 1,
"selected": false,
"text": "<p>If you installed the MySQL 5 package with MacPorts:</p>\n\n<pre><code>sudo launchctl unload -w /Library/LaunchDaemons/org.macports.mysql.plist \n</code></pre>\n\n<p>Or </p>\n\n<pre><code>sudo launchctl unload -w /Library/LaunchDaemons/org.macports.mysql5-devel.plist \n</code></pre>\n\n<p>if you installed the <code>mysql5-devel</code> package.</p>\n"
},
{
"answer_id": 100963,
"author": "Rimantas",
"author_id": 6906,
"author_profile": "https://Stackoverflow.com/users/6906",
"pm_score": 6,
"selected": false,
"text": "<p>You can always use command \"mysqladmin shutdown\"</p>\n"
},
{
"answer_id": 100970,
"author": "John Montgomery",
"author_id": 5868,
"author_profile": "https://Stackoverflow.com/users/5868",
"pm_score": 2,
"selected": false,
"text": "<p>Well, if all else fails, you could just take the ruthless approach and kill the process running MySQL manually.</p>\n\n<p>That is,</p>\n\n<pre><code>ps -Af\n</code></pre>\n\n<p>to list all processes, then do \"<code>kill <pid></code>\" where <code><pid></code> is the process id of the MySQL daemon (mysqld).</p>\n"
},
{
"answer_id": 102094,
"author": "mloughran",
"author_id": 18751,
"author_profile": "https://Stackoverflow.com/users/18751",
"pm_score": 10,
"selected": true,
"text": "<p>There are different cases depending on whether you installed <a href=\"http://en.wikipedia.org/wiki/MySQL\" rel=\"noreferrer\">MySQL</a> with the official binary installer, using <a href=\"http://en.wikipedia.org/wiki/MacPorts\" rel=\"noreferrer\">MacPorts</a>, or using <a href=\"http://brew.sh/\" rel=\"noreferrer\">Homebrew</a>:</p>\n\n<h2>Homebrew</h2>\n\n<pre><code>brew services start mysql\nbrew services stop mysql\nbrew services restart mysql\n</code></pre>\n\n<h2>MacPorts</h2>\n\n<pre><code>sudo port load mysql57-server\nsudo port unload mysql57-server\n</code></pre>\n\n<p>Note: this is persistent after a reboot.</p>\n\n<h2>Binary installer</h2>\n\n<pre><code>sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop\nsudo /Library/StartupItems/MySQLCOM/MySQLCOM start\nsudo /Library/StartupItems/MySQLCOM/MySQLCOM restart\n</code></pre>\n"
},
{
"answer_id": 2052686,
"author": "katy lavallee",
"author_id": 111362,
"author_profile": "https://Stackoverflow.com/users/111362",
"pm_score": 4,
"selected": false,
"text": "<p><code>sudo /opt/local/etc/LaunchDaemons/org.macports.mysql5/mysql5.wrapper stop</code></p>\n\n<p>You can also use start and restart here. I found this by looking at the contents of /Library/LaunchDaemons/org.macports.mysql.plist.</p>\n"
},
{
"answer_id": 3524087,
"author": "zack",
"author_id": 126600,
"author_profile": "https://Stackoverflow.com/users/126600",
"pm_score": 4,
"selected": false,
"text": "<p>Try </p>\n\n<pre><code>sudo <path to mysql>/support-files/mysql.server start\nsudo <path to mysql>/support-files/mysql.server stop\n</code></pre>\n\n<p>Else try:</p>\n\n<pre><code>sudo /Library/StartupItems/MySQLCOM/MySQLCOM start\nsudo /Library/StartupItems/MySQLCOM/MySQLCOM stop<br>\nsudo /Library/StartupItems/MySQLCOM/MySQLCOM restart\n</code></pre>\n\n<p>However, I found that the second option only worked (OS X 10.6, MySQL 5.1.50) if the .plist has been loaded with:</p>\n\n<pre><code>sudo launchctl load -w /Library/LaunchDaemons/com.mysql.mysqld.plist\n</code></pre>\n\n<p>PS: I also found that I needed to unload the .plist to get an unrelated install of <a href=\"http://en.wikipedia.org/wiki/MAMP\" rel=\"noreferrer\">MAMP</a>-MySQL to start / stop correctly. After running running this, MAMP-MySQL starts just fine:</p>\n\n<p>sudo launchctl unload -w /Library/LaunchDaemons/com.mysql.mysqld.plist</p>\n"
},
{
"answer_id": 6533179,
"author": "Allisone",
"author_id": 317083,
"author_profile": "https://Stackoverflow.com/users/317083",
"pm_score": 2,
"selected": false,
"text": "<p>For me it's working with a \"mysql5\"</p>\n\n<pre><code>sudo launchctl unload -w /Library/LaunchDaemons/org.macports.mysql5.plist\nsudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql5.plist\n</code></pre>\n"
},
{
"answer_id": 8913870,
"author": "pjammer",
"author_id": 156561,
"author_profile": "https://Stackoverflow.com/users/156561",
"pm_score": 7,
"selected": false,
"text": "<p>For those who used homebrew to install MySQL use the following commands below to start, stop, or restart MySQL</p>\n\n<p><strong>Brew start</strong></p>\n\n<pre><code>/usr/local/bin/mysql.server start\n</code></pre>\n\n<p><strong>Brew restart</strong></p>\n\n<pre><code>/usr/local/bin/mysql.server restart\n</code></pre>\n\n<p><strong>Brew stop</strong></p>\n\n<pre><code>/usr/local/bin/mysql.server stop\n</code></pre>\n"
},
{
"answer_id": 11991959,
"author": "Moesio",
"author_id": 1113510,
"author_profile": "https://Stackoverflow.com/users/1113510",
"pm_score": 5,
"selected": false,
"text": "<p>sudo /usr/local/mysql/support-files/mysql.server stop</p>\n"
},
{
"answer_id": 14849461,
"author": "Manuel_B",
"author_id": 1059979,
"author_profile": "https://Stackoverflow.com/users/1059979",
"pm_score": 0,
"selected": false,
"text": "<p>I installed mysql5 and mysql55 over macports. For me the mentioned files here are located at the following places:</p>\n\n<p>(mysql55-server)\n/opt/local/etc/LaunchDaemons/org.macports.mysql55-server/org.macports.mysql55-server.plist</p>\n\n<p>(mysql5)\n/opt/local/etc/LaunchDaemons/org.macports.mysql5/org.macports.mysql5.plist</p>\n\n<p>So stopping for these works like this:</p>\n\n<p>mysql55-server:</p>\n\n<pre><code>sudo launchctl unload -w /opt/local/etc/LaunchDaemons/org.macports.mysql55-server/org.macports.mysql55-server.plist\n</code></pre>\n\n<p>mysql5:</p>\n\n<pre><code>sudo launchctl unload -w /opt/local/etc/LaunchDaemons/org.macports.mysql5/org.macports.mysql5.plist \n</code></pre>\n\n<p>You can check if the service is still running with:</p>\n\n<pre><code>ps ax | grep mysql\n</code></pre>\n\n<p>Further you can check the log files in my case here:</p>\n\n<p>mysql55-server</p>\n\n<pre><code>sudo tail -n 100 /opt/local/var/db/mysql55/<MyName>-MacBook-Pro.local.err\n...\n130213 08:56:41 mysqld_safe mysqld from pid file /opt/local/var/db/mysql55/<MyName>-MacBook-Pro.local.pid ended\n</code></pre>\n\n<p>mysql5:</p>\n\n<pre><code>sudo tail -n 100 /opt/local/var/db/mysql5/<MyName>-MacBook-Pro.local.err\n...\n130213 09:23:57 mysqld ended\n</code></pre>\n"
},
{
"answer_id": 17525998,
"author": "Steve",
"author_id": 1433158,
"author_profile": "https://Stackoverflow.com/users/1433158",
"pm_score": 4,
"selected": false,
"text": "<p>Use:</p>\n\n<pre><code>sudo mysqladmin shutdown --user=*user* --password=*password*\n</code></pre>\n\n<p>One could probably get away with not using <a href=\"http://en.wikipedia.org/wiki/Sudo\">sudo</a>. The <em>user</em> could be root for example (that is, the MySQL root user).</p>\n"
},
{
"answer_id": 22849416,
"author": "Jack Peng",
"author_id": 726373,
"author_profile": "https://Stackoverflow.com/users/726373",
"pm_score": 0,
"selected": false,
"text": "<p>mysql> show variables where variable_name like '%dir%';</p>\n\n<p>| datadir | /opt/local/var/db/mysql5/ |</p>\n"
},
{
"answer_id": 33144436,
"author": "sweetfa",
"author_id": 490614,
"author_profile": "https://Stackoverflow.com/users/490614",
"pm_score": 2,
"selected": false,
"text": "<p>On OSX Snow Leopard</p>\n\n<pre><code>launchctl unload /System/Library/LaunchDaemons/org.mysql.mysqld.plist\n</code></pre>\n"
},
{
"answer_id": 36145691,
"author": "Duc Chi",
"author_id": 5849920,
"author_profile": "https://Stackoverflow.com/users/5849920",
"pm_score": 3,
"selected": false,
"text": "<p>On my mac osx yosemite 10.10. This command worked:</p>\n\n<pre><code>sudo launchctl load -w /Library/LaunchDaemons/com.mysql.mysql.plist\nsudo launchctl unload -w /Library/LaunchDaemons/com.mysql.mysql.plist\n</code></pre>\n\n<p>You can find your mysql file in folder /Library/LaunchDaemons/ to run</p>\n"
},
{
"answer_id": 37211622,
"author": "Jan",
"author_id": 977017,
"author_profile": "https://Stackoverflow.com/users/977017",
"pm_score": 6,
"selected": false,
"text": "<p>If you are using <code>homebrew</code> you can use</p>\n\n<pre><code>brew services restart mysql\nbrew services start mysql\nbrew services stop mysql\n</code></pre>\n\n<p>for a list of available services </p>\n\n<pre><code>brew services list\n</code></pre>\n"
},
{
"answer_id": 37994161,
"author": "ppostma1",
"author_id": 884757,
"author_profile": "https://Stackoverflow.com/users/884757",
"pm_score": 3,
"selected": false,
"text": "<p>Latest OSX (10.8) and mysql 5.6, the file is under Launch Daemons and is com.oracle.oss.mysql.mysqld.plist. It presents an option under System Options, usually the bottom of the list. So go to system settings, click on Mysql, and turn it off from the option box. <a href=\"https://dev.mysql.com/doc/refman/5.6/en/osx-installation-launchd.html\" rel=\"noreferrer\">https://dev.mysql.com/doc/refman/5.6/en/osx-installation-launchd.html</a></p>\n"
},
{
"answer_id": 51239170,
"author": "bronze man",
"author_id": 1586797,
"author_profile": "https://Stackoverflow.com/users/1586797",
"pm_score": 1,
"selected": false,
"text": "<p>After try all those command line, and it is not work.I have to do following stuff:</p>\n\n<pre><code>mv /usr/local/Cellar/mysql/5.7.16/bin/mysqld /usr/local/Cellar/mysql/5.7.16/bin/mysqld.bak\nmysql.server stop\n</code></pre>\n\n<p>This way works, the mysqld process is gone. but the /var/log/system.log have a lot of rubbish:</p>\n\n<pre><code>Jul 9 14:10:54 xxx com.apple.xpc.launchd[1] (homebrew.mxcl.mysql[78049]): Service exited with abnormal code: 1\nJul 9 14:10:54 xxx com.apple.xpc.launchd[1] (homebrew.mxcl.mysql): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.\n</code></pre>\n"
},
{
"answer_id": 61183721,
"author": "Abhijeet Khangarot",
"author_id": 7088648,
"author_profile": "https://Stackoverflow.com/users/7088648",
"pm_score": 5,
"selected": false,
"text": "<p>In my case, it kept on restarting as soon as I killed the process using PID. Also <code>brew stop</code> command didn't work as I installed without using homebrew. Then I went to mac system preferences and we have MySQL installed there. Just open it and stop the MySQL server and you're done. Here in the screenshot, you can find MySQL in bottom of system preferences. <a href=\"https://i.stack.imgur.com/NqLCN.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/NqLCN.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 63554833,
"author": "Szekelygobe",
"author_id": 6792829,
"author_profile": "https://Stackoverflow.com/users/6792829",
"pm_score": 0,
"selected": false,
"text": "<p>This worked for me on macOS 10.13.6 with 8.0.12 MySQL</p>\n<p><code>/usr/local/mysql/support-files/mysql.server start</code></p>\n<p><code>/usr/local/mysql/support-files/mysql.server restart</code></p>\n<p><code>/usr/local/mysql/support-files/mysql.server stop</code></p>\n"
},
{
"answer_id": 65072168,
"author": "codeaprendiz",
"author_id": 5761011,
"author_profile": "https://Stackoverflow.com/users/5761011",
"pm_score": 2,
"selected": false,
"text": "<p>For me the following solution worked <a href=\"https://stackoverflow.com/questions/29375253/unable-to-stop-mysql-on-os-x-10-10\">Unable to stop MySQL on OS X 10.10</a></p>\n<p>To stop the auto start I used:</p>\n<pre><code>sudo launchctl unload -w /Library/LaunchDaemons/com.mysql.mysql.plist\n</code></pre>\n<p>And to kill the service I used:</p>\n<pre><code>sudo pkill mysqld\n</code></pre>\n"
},
{
"answer_id": 68468566,
"author": "Gediminas",
"author_id": 1412149,
"author_profile": "https://Stackoverflow.com/users/1412149",
"pm_score": 2,
"selected": false,
"text": "<p>Get instance name:</p>\n<pre><code>ls /Library/LaunchDaemons | grep mysql\n</code></pre>\n<p>Stop MySQL instance (Works on MacOS Catalina, MySQL 8):</p>\n<pre><code>sudo launchctl unload /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist\n</code></pre>\n<p>Or, you can Stop MySQL instance in</p>\n<pre><code>MacOS Settings > MySQL > Stop MySQL Server \n</code></pre>\n<p>Also, check here for more methods:\n<a href=\"https://tableplus.com/blog/2018/10/how-to-start-stop-restart-mysql-server.html\" rel=\"nofollow noreferrer\">https://tableplus.com/blog/2018/10/how-to-start-stop-restart-mysql-server.html</a></p>\n"
},
{
"answer_id": 68487108,
"author": "Jaime Bula",
"author_id": 1617836,
"author_profile": "https://Stackoverflow.com/users/1617836",
"pm_score": 2,
"selected": false,
"text": "<p>As @gediminas said</p>\n<p>System Preferences > MySQL > Stop MySQL Server</p>\n<p>Was the easiest way. With binary installer downloaded from Oracle.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7473/"
]
| I installed MySQL via [MacPorts](http://en.wikipedia.org/wiki/MacPorts). What is the command I need to stop the server (I need to test how my application behave when MySQL is dead)? | There are different cases depending on whether you installed [MySQL](http://en.wikipedia.org/wiki/MySQL) with the official binary installer, using [MacPorts](http://en.wikipedia.org/wiki/MacPorts), or using [Homebrew](http://brew.sh/):
Homebrew
--------
```
brew services start mysql
brew services stop mysql
brew services restart mysql
```
MacPorts
--------
```
sudo port load mysql57-server
sudo port unload mysql57-server
```
Note: this is persistent after a reboot.
Binary installer
----------------
```
sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop
sudo /Library/StartupItems/MySQLCOM/MySQLCOM start
sudo /Library/StartupItems/MySQLCOM/MySQLCOM restart
``` |
100,990 | <p>How could I get the Fault Detail sent by a SoapFaultClientException ?
I use a WebServiceTemplate as shown below :</p>
<pre><code>WebServiceTemplate ws = new WebServiceTemplate();
ws.setMarshaller(client.getMarshaller());
ws.setUnmarshaller(client.getUnMarshaller());
try {
MyResponse resp = (MyResponse) = ws.marshalSendAndReceive(WS_URI, req);
} catch (SoapFaultClientException e) {
SoapFault fault = e.getSoapFault();
SoapFaultDetail details = e.getSoapFault().getFaultDetail();
//details always NULL ? Bug?
}
</code></pre>
<p>The Web Service Fault sent seems correct :</p>
<pre><code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<soapenv:Fault>
<faultcode>soapenv:Client</faultcode>
<faultstring>Validation error</faultstring>
<faultactor/>
<detail>
<ws:ValidationError xmlns:ws="http://ws.x.y.com">ERR_UNKNOWN</ws:ValidationError>
</detail>
</soapenv:Fault>
</soapenv:Body>
</code></pre>
<p></p>
<p>Thanks</p>
<p>Willome</p>
| [
{
"answer_id": 105872,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 1,
"selected": false,
"text": "<p>From the Javadocs for the <a href=\"http://static.springframework.org/spring-ws/sites/1.5/apidocs/org/springframework/ws/client/core/WebServiceOperations.html#marshalSendAndReceive%28java.lang.String,%20java.lang.Object%29\" rel=\"nofollow noreferrer\">marshalSendAndReceive method</a>\nit looks like the SoapFaultClientException in the catch block will never happen. </p>\n\n<p>From the API it looks like the best bet for determining the details of the fault is to set a custom <a href=\"http://static.springframework.org/spring-ws/sites/1.5/apidocs/org/springframework/ws/client/core/WebServiceTemplate.html#setFaultMessageResolver%28org.springframework.ws.client.core.FaultMessageResolver%29\" rel=\"nofollow noreferrer\">Fault Message Receiver</a>. </p>\n"
},
{
"answer_id": 11082098,
"author": "holmis83",
"author_id": 1463522,
"author_profile": "https://Stackoverflow.com/users/1463522",
"pm_score": 3,
"selected": false,
"text": "<p>I also had the problem that getFaultDetail() returned null (for a SharePoint web service). I could get the detail element out by using a method similar to this:</p>\n\n<pre><code>private Element getDetail(SoapFaultClientException e) throws TransformerException {\n TransformerFactory transformerFactory = TransformerFactory.newInstance();\n Transformer transformer = transformerFactory.newTransformer();\n DOMResult result = new DOMResult();\n transformer.transform(e.getSoapFault().getSource(), result);\n NodeList nl = ((Document)result.getNode()).getElementsByTagName(\"detail\");\n return (Element)nl.item(0);\n}\n</code></pre>\n\n<p>After that, you can call getTextContent() on the returned Element or whatever you want.</p>\n"
},
{
"answer_id": 37047393,
"author": "Premek",
"author_id": 1151925,
"author_profile": "https://Stackoverflow.com/users/1151925",
"pm_score": 3,
"selected": false,
"text": "<p>Check out what type of HTTP response you get when receiving Soap Fault. I had the same problem when SOAP Fault responses using HTTP 200 instead of HTTP 500. Then you get:</p>\n\n<blockquote>\n <p>JAXB unmarshalling exception; nested exception is\n javax.xml.bind.UnmarshalException</p>\n</blockquote>\n\n<p>When you change WebServiceTemplate connection fault settings as below: </p>\n\n<pre><code>WebServiceTemplate webServiceTemplate = getWebServiceTemplate();\nwebServiceTemplate.setCheckConnectionForFault(false);\n</code></pre>\n\n<p>then you can properly catch <strong>SoapFaultClientException</strong></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/100990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18714/"
]
| How could I get the Fault Detail sent by a SoapFaultClientException ?
I use a WebServiceTemplate as shown below :
```
WebServiceTemplate ws = new WebServiceTemplate();
ws.setMarshaller(client.getMarshaller());
ws.setUnmarshaller(client.getUnMarshaller());
try {
MyResponse resp = (MyResponse) = ws.marshalSendAndReceive(WS_URI, req);
} catch (SoapFaultClientException e) {
SoapFault fault = e.getSoapFault();
SoapFaultDetail details = e.getSoapFault().getFaultDetail();
//details always NULL ? Bug?
}
```
The Web Service Fault sent seems correct :
```
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<soapenv:Fault>
<faultcode>soapenv:Client</faultcode>
<faultstring>Validation error</faultstring>
<faultactor/>
<detail>
<ws:ValidationError xmlns:ws="http://ws.x.y.com">ERR_UNKNOWN</ws:ValidationError>
</detail>
</soapenv:Fault>
</soapenv:Body>
```
Thanks
Willome | I also had the problem that getFaultDetail() returned null (for a SharePoint web service). I could get the detail element out by using a method similar to this:
```
private Element getDetail(SoapFaultClientException e) throws TransformerException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMResult result = new DOMResult();
transformer.transform(e.getSoapFault().getSource(), result);
NodeList nl = ((Document)result.getNode()).getElementsByTagName("detail");
return (Element)nl.item(0);
}
```
After that, you can call getTextContent() on the returned Element or whatever you want. |
101,012 | <p>Our rails app is designed as a single code base linking to multiple client databases. Based on the subdomain the app determines which db to connect to.</p>
<p>We use liquid templates to customise the presentation for each client. We are unable to customise the generic 'We're Sorry, somethign went wrong..' message for each client.</p>
<p>Can anyone recommend an approach that would allow us to do this.</p>
<p>Thanks</p>
<p>DOm</p>
| [
{
"answer_id": 101027,
"author": "mislav",
"author_id": 11687,
"author_profile": "https://Stackoverflow.com/users/11687",
"pm_score": 4,
"selected": true,
"text": "<p>For catching exceptions in Rails 2, <code>rescue_from</code> controller method is a great way to specify actions which handle various cases.</p>\n\n<pre><code>class ApplicationController < ActionController::Base\n rescue_from MyAppError, :with => :show_errors\n\n def show_errors\n render :action => \"...\"\n end\nend\n</code></pre>\n\n<p>This way you can make dynamic error pages to replace the static \"public/500.html\" page.</p>\n"
},
{
"answer_id": 108743,
"author": "scottru",
"author_id": 8192,
"author_profile": "https://Stackoverflow.com/users/8192",
"pm_score": 0,
"selected": false,
"text": "<p>It's not clear if you're trying to do inline error messaging or new page error messaging, but if you want to improve the text around inline error messaging, <a href=\"http://www.softiesonrails.com/2008/4/23/better-messages-for-activerecord-validation-errors\" rel=\"nofollow noreferrer\">this post</a> provides good information.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Our rails app is designed as a single code base linking to multiple client databases. Based on the subdomain the app determines which db to connect to.
We use liquid templates to customise the presentation for each client. We are unable to customise the generic 'We're Sorry, somethign went wrong..' message for each client.
Can anyone recommend an approach that would allow us to do this.
Thanks
DOm | For catching exceptions in Rails 2, `rescue_from` controller method is a great way to specify actions which handle various cases.
```
class ApplicationController < ActionController::Base
rescue_from MyAppError, :with => :show_errors
def show_errors
render :action => "..."
end
end
```
This way you can make dynamic error pages to replace the static "public/500.html" page. |
101,033 | <p>I want to create a stored procedure with one argument which will return different sets of records depending on the argument. What is the way to do this? Can I call it from plain SQL?</p>
| [
{
"answer_id": 101064,
"author": "Thilo",
"author_id": 14955,
"author_profile": "https://Stackoverflow.com/users/14955",
"pm_score": 5,
"selected": false,
"text": "<p>I think you want to return a REFCURSOR:</p>\n\n<pre><code>create function test_cursor \n return sys_refcursor\n is\n c_result sys_refcursor;\n begin\n open c_result for\n select * from dual;\n return c_result;\n end;\n</code></pre>\n\n<p><strong>Update</strong>: If you need to call this from SQL, use a table function like @Tony Andrews suggested.</p>\n"
},
{
"answer_id": 101178,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 6,
"selected": false,
"text": "<p>Here is how to build a function that returns a result set that can be queried as if it were a table:</p>\n\n<pre><code>SQL> create type emp_obj is object (empno number, ename varchar2(10));\n 2 /\n\nType created.\n\nSQL> create type emp_tab is table of emp_obj;\n 2 /\n\nType created.\n\nSQL> create or replace function all_emps return emp_tab\n 2 is\n 3 l_emp_tab emp_tab := emp_tab();\n 4 n integer := 0;\n 5 begin\n 6 for r in (select empno, ename from emp)\n 7 loop\n 8 l_emp_tab.extend;\n 9 n := n + 1;\n 10 l_emp_tab(n) := emp_obj(r.empno, r.ename);\n 11 end loop;\n 12 return l_emp_tab;\n 13 end;\n 14 /\n\nFunction created.\n\nSQL> select * from table (all_emps);\n\n EMPNO ENAME\n---------- ----------\n 7369 SMITH\n 7499 ALLEN\n 7521 WARD\n 7566 JONES\n 7654 MARTIN\n 7698 BLAKE\n 7782 CLARK\n 7788 SCOTT\n 7839 KING\n 7844 TURNER\n 7902 FORD\n 7934 MILLER\n</code></pre>\n"
},
{
"answer_id": 105867,
"author": "John Smithers",
"author_id": 1069,
"author_profile": "https://Stackoverflow.com/users/1069",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to use it in plain SQL, I would let the store procedure fill a table or temp table with the resulting rows (or go for @Tony Andrews approach).<br>\nIf you want to use @Thilo's solution, you have to loop the cursor using PL/SQL.\nHere an example: (I used a procedure instead of a function, like @Thilo did) </p>\n\n<pre><code>create or replace procedure myprocedure(retval in out sys_refcursor) is\nbegin\n open retval for\n select TABLE_NAME from user_tables;\nend myprocedure;\n\n declare \n myrefcur sys_refcursor;\n tablename user_tables.TABLE_NAME%type;\n begin\n myprocedure(myrefcur);\n loop\n fetch myrefcur into tablename;\n exit when myrefcur%notfound;\n dbms_output.put_line(tablename);\n end loop;\n close myrefcur;\n end;\n</code></pre>\n"
},
{
"answer_id": 14760504,
"author": "Mohsen Heydari",
"author_id": 2039695,
"author_profile": "https://Stackoverflow.com/users/2039695",
"pm_score": 3,
"selected": false,
"text": "<p>You may use Oracle pipelined functions</p>\n\n<blockquote>\n <p>Basically, when you would like a PLSQL (or java or c) routine to be the «source»\n of data -- instead of a table -- you would use a pipelined function.</p>\n</blockquote>\n\n<p>Simple Example - Generating Some Random Data <br>\n<em>How could you create N unique random numbers depending on the input argument?</em></p>\n\n<pre><code>create type array\nas table of number;\n\n\ncreate function gen_numbers(n in number default null)\nreturn array\nPIPELINED\nas\nbegin\n for i in 1 .. nvl(n,999999999)\n loop\n pipe row(i);\n end loop;\n return;\nend;\n</code></pre>\n\n<p>Suppose we needed three rows for something. We can now do that in one of two ways:</p>\n\n<pre><code>select * from TABLE(gen_numbers(3));\n</code></pre>\n\n<p>COLUMN_VALUE</p>\n\n<hr>\n\n<pre><code> 1\n 2\n 3\n</code></pre>\n\n<p>or</p>\n\n<pre><code>select * from TABLE(gen_numbers)\n where rownum <= 3;\n</code></pre>\n\n<p>COLUMN_VALUE</p>\n\n<hr>\n\n<pre><code> 1\n 2\n 3\n</code></pre>\n\n<p><a href=\"http://www.oracle-base.com/articles/misc/pipelined-table-functions.php\" rel=\"noreferrer\">pipelied Functions1</a>\n<a href=\"http://www.akadia.com/services/ora_pipe_functions.html\" rel=\"noreferrer\">pipelied Functions2</a></p>\n"
},
{
"answer_id": 26362189,
"author": "S. Mayol",
"author_id": 4066742,
"author_profile": "https://Stackoverflow.com/users/4066742",
"pm_score": 2,
"selected": false,
"text": "<pre><code>create procedure <procedure_name>(p_cur out sys_refcursor) as begin open p_cur for select * from <table_name> end;\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I want to create a stored procedure with one argument which will return different sets of records depending on the argument. What is the way to do this? Can I call it from plain SQL? | Here is how to build a function that returns a result set that can be queried as if it were a table:
```
SQL> create type emp_obj is object (empno number, ename varchar2(10));
2 /
Type created.
SQL> create type emp_tab is table of emp_obj;
2 /
Type created.
SQL> create or replace function all_emps return emp_tab
2 is
3 l_emp_tab emp_tab := emp_tab();
4 n integer := 0;
5 begin
6 for r in (select empno, ename from emp)
7 loop
8 l_emp_tab.extend;
9 n := n + 1;
10 l_emp_tab(n) := emp_obj(r.empno, r.ename);
11 end loop;
12 return l_emp_tab;
13 end;
14 /
Function created.
SQL> select * from table (all_emps);
EMPNO ENAME
---------- ----------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7902 FORD
7934 MILLER
``` |
101,070 | <p>If you are writing a <em>simple</em> little loop, what <em>should</em> you name the counter?</p>
<p><em>Provide example loops!</em></p>
| [
{
"answer_id": 101071,
"author": "just mike",
"author_id": 12293,
"author_profile": "https://Stackoverflow.com/users/12293",
"pm_score": 4,
"selected": false,
"text": "<p>My experience is that most people use single letters, e.g.:\n<code>i</code>,\n<code>j</code>,\n<code>k</code>,\n...\nor\n<code>x</code>,\n<code>y</code>,\nor\n<code>r</code>,\n<code>c</code> (for row/column)\nor\n<code>w</code>,\n<code>h</code> (for width/height)\n, etc.</p>\n\n<p>But I learned a great alternative a long time ago, and have used it ever since: double letter variables.</p>\n\n<pre><code>// recommended style ● // \"typical\" single-letter style\n ●\nfor (ii=0; ii<10; ++ii) { ● for (i=0; i<10; ++i) {\n for (jj=0; jj<10; ++jj) { ● for (j=0; j<10; ++j) {\n mm[ii][jj] = ii * jj; ● m[i][j] = i * j;\n } ● }\n} ● }</code></pre>\n\n<p>In case the benefit isn't immediately obvious: searching through code for any single letter will find many things that <em>aren't</em> what you're looking for. The letter <code>i</code> occurs quite often in code where it isn't the variable you're looking for.</p>\n"
},
{
"answer_id": 101095,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 3,
"selected": false,
"text": "<p>Always try to name the variable something meaningful and in context.</p>\n\n<p>If you cannot decide, then use \"index\", if only so that someone else (maybe you!) can more easily click on it for refactoring later.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/101070/what-is-an-ideal-variable-naming-convention-for-loop-variables#101239\">Paul Stephenson</a> See this answer for an example.</p>\n"
},
{
"answer_id": 101097,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 2,
"selected": false,
"text": "<p>I use single letters only when the loop counter is an index. I like the thinking behind the double letter, but it makes the code quite unreadable.</p>\n"
},
{
"answer_id": 101098,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 0,
"selected": false,
"text": "<p>I've started using perlisms in php. </p>\n\n<p>if its a singular iteration, <code>$_</code> is a good name for those who know its use.</p>\n"
},
{
"answer_id": 101112,
"author": "Simon Munro",
"author_id": 3893,
"author_profile": "https://Stackoverflow.com/users/3893",
"pm_score": 0,
"selected": false,
"text": "<p>My habit is to use 't' - close to 'r' so it follows easily aftewr typing 'for'</p>\n"
},
{
"answer_id": 101113,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 3,
"selected": false,
"text": "<p><code>i</code></p>\n\n<p>if I have a nested loop then also <code>j</code>.</p>\n\n<p>This convention is so common that if you manage to come across a variable <code>i</code> in a block of code that you can't see the start of you still instantly recognise it for what it is. </p>\n"
},
{
"answer_id": 101114,
"author": "m_pGladiator",
"author_id": 446104,
"author_profile": "https://Stackoverflow.com/users/446104",
"pm_score": 5,
"selected": false,
"text": "<p>1) For normal old style small loops - i, j, k - If you need more than 3 level nested loops, this means that either the algorithm is very specific and complex, or you should consider refactoring the code.</p>\n\n<p>Java Example:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for(int i = 0; i < ElementsList.size(); i++) {\n Element element = ElementsList.get(i);\n someProcessing(element);\n ....\n}\n</code></pre>\n\n<p>2) For the new style java loops like <code>for(Element element: ElementsList)</code> it is better to use normal meanigful name</p>\n\n<p>Java Example:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for(Element element: ElementsList) {\n someProcessing(element);\n ....\n}\n</code></pre>\n\n<p>3) If it is possible with the language you use, convert the loop to use iterator</p>\n\n<p>Java Iterator Example: <a href=\"http://www.javadeveloper.co.in/java-example/java-iterator-example.html\" rel=\"nofollow noreferrer\">click here</a></p>\n"
},
{
"answer_id": 101181,
"author": "Emile",
"author_id": 18756,
"author_profile": "https://Stackoverflow.com/users/18756",
"pm_score": 2,
"selected": false,
"text": "<p>Like a previous poster, I also use ii, jj,.. mainly because in many fonts a single i looks very similar to 1.</p>\n"
},
{
"answer_id": 101220,
"author": "Jez",
"author_id": 15478,
"author_profile": "https://Stackoverflow.com/users/15478",
"pm_score": 2,
"selected": false,
"text": "<p>If the counter is to be used as an index to a container, I use <code>i</code>, <code>j</code>, <code>k</code>.</p>\n\n<p>If it is to be used to iterate over a range (or perform a set number of iterations), I often use <code>n</code>. Though, if nesting is required I'll usually revert to <code>i</code>, <code>j</code>, <code>k</code>.</p>\n\n<p>In languages which provide a <code>foreach</code>-style construct, I usually write like this:</p>\n\n<pre><code>foreach widget in widgets do\n foo(widget)\nend\n</code></pre>\n\n<p>I think some people will tell me off for naming <code>widget</code> so similarly to <code>widgets</code>, but I find it quite readable.</p>\n"
},
{
"answer_id": 101234,
"author": "Learning",
"author_id": 18275,
"author_profile": "https://Stackoverflow.com/users/18275",
"pm_score": 1,
"selected": false,
"text": "<p>I use \"counter\" or \"loop\" as the variable name. Modern IDEs usually do the word completion , so longer variable names are not as tedious to use. Besides , to name the variable to its functionality makes it clear to the programmer who is going to maintain your code as to what your intentions were.</p>\n"
},
{
"answer_id": 101239,
"author": "Paul Stephenson",
"author_id": 5536,
"author_profile": "https://Stackoverflow.com/users/5536",
"pm_score": 6,
"selected": false,
"text": "<p>I always use a <strong>meaningful name</strong> unless it's a single-level loop and the variable has no meaning other than \"the number of times I've been through this loop\", in which case I use <code>i</code>.</p>\n\n<p>When using meaningful names:</p>\n\n<ul>\n<li>the code is more understandable to colleagues reading your code,</li>\n<li>it's easier to find bugs in the loop logic, and</li>\n<li>text searches for the variable name to return relevant pieces of code operating on the same data are more reliable.</li>\n</ul>\n\n<h2>Example - spot the bug</h2>\n\n<p>It can be tricky to find the bug in this nested loop using single letters:</p>\n\n<pre><code>int values[MAX_ROWS][MAX_COLS];\n\nint sum_of_all_values()\n{\n int i, j, total;\n\n total = 0;\n for (i = 0; i < MAX_COLS; i++)\n for (j = 0; j < MAX_ROWS; j++)\n total += values[i][j];\n return total;\n}\n</code></pre>\n\n<p>whereas it is easier when using meaningful names:</p>\n\n<pre><code>int values[MAX_ROWS][MAX_COLS];\n\nint sum_of_all_values()\n{\n int row_num, col_num, total;\n\n total = 0;\n for (row_num = 0; row_num < MAX_COLS; row_num++)\n for (col_num = 0; col_num < MAX_ROWS; col_num++)\n total += values[row_num][col_num];\n return total;\n}\n</code></pre>\n\n<h3>Why <code>row_num</code>? - rejected alternatives</h3>\n\n<p>In response to some other answers and comments, these are some alternative suggestions to using <code>row_num</code> and <code>col_num</code> and why I choose not to use them:</p>\n\n<ul>\n<li><strong><code>r</code></strong> and <strong><code>c</code></strong>: This is slightly better than <code>i</code> and <code>j</code>. I would only consider using them if my organisation's standard were for single-letter variables to be integers, and also always to be the first letter of the equivalent descriptive name. The system would fall down if I had two variables in the function whose name began with \"r\", and readability would suffer even if other objects beginning with \"r\" appeared anywhere in the code.</li>\n<li><strong><code>rr</code></strong> and <strong><code>cc</code></strong>: This looks weird to me, but I'm not used to a double-letter loop variable style. If it were the standard in my organisation then I imagine it would be slightly better than <code>r</code> and <code>c</code>.</li>\n<li><strong><code>row</code></strong> and <strong><code>col</code></strong>: At first glance this seems more succinct than <code>row_num</code> and <code>col_num</code>, and just as descriptive. However, I would expect bare nouns like \"row\" and \"column\" to refer to structures, objects or pointers to these. If <code>row</code> could mean <em>either</em> the row structure itself, <em>or</em> a row number, then confusion will result.</li>\n<li><strong><code>iRow</code></strong> and <strong><code>iCol</code></strong>: This conveys extra information, since <code>i</code> can mean it's a loop counter while <code>Row</code> and <code>Col</code> tell you what it's counting. However, I prefer to be able to read the code almost in English:\n\n<ul>\n<li><code>row_num < MAX_COLS</code> reads as \"the <strong>row num</strong>ber is <strong>less than</strong> the <strong>max</strong>imum (number of) <strong>col</strong>umn<b>s</b>\";</li>\n<li><code>iRow < MAX_COLS</code> at best reads as \"the <strong>integer loop counter</strong> for the <strong>row</strong> is <strong>less than</strong> the <strong>max</strong>imum (number of) <strong>col</strong>umn<b>s</b>\".</li>\n<li>It may be a personal thing but I prefer the first reading.</li>\n</ul></li>\n</ul>\n\n<p>An alternative to <code>row_num</code> I would accept is <code>row_idx</code>: the word \"index\" uniquely refers to an array position, unless the application's domain is in database engine design, financial markets or similar.</p>\n\n<p>My example above is as small as I could make it, and as such some people might not see the point in naming the variables descriptively since they can hold the whole function in their head in one go. In real code, however, the functions would be larger, and the logic more complex, so decent names become more important to aid readability and to avoid bugs.</p>\n\n<p>In summary, my aim with all variable naming (not just loops) is to be <strong>completely unambiguous</strong>. If <em>anybody</em> reads any portion of my code and can't work out what a variable is for immediately, then I have failed.</p>\n"
},
{
"answer_id": 101457,
"author": "Karthi",
"author_id": 5794,
"author_profile": "https://Stackoverflow.com/users/5794",
"pm_score": 0,
"selected": false,
"text": "<p>If it is a simple counter, I stick to using 'i' otherwise, have name that denotes the context. I tend to keep the variable length to 4. This is mainly from code reading point of view, writing is doesn't count as we have auto complete feature.</p>\n"
},
{
"answer_id": 101643,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 2,
"selected": false,
"text": "<p>I have long used the i/j/k naming scheme. But recently I've started to adapt a more consequent naming method.</p>\n\n<p>I allready named all my variables by its meaning, so why not name the loop variable in the same deterministic way. </p>\n\n<p>As requested a few examples:</p>\n\n<p>If you need to loop trough a item collection.</p>\n\n<pre><code>for (int currentItemIndex = 0; currentItemIndex < list.Length; currentItemIndex++)\n{\n ...\n}\n</code></pre>\n\n<p>But i try to avoid the normal for loops, because I tend to want the real item in the list and use that, not the actual position in the list. so instead of beginning the for block with a:</p>\n\n<pre><code>Item currentItem = list[currentItemIndex];\n</code></pre>\n\n<p>I try to use the foreach construct of the language. which transforms the.</p>\n\n<pre><code>for (int currentItemIndex = 0; currentItemIndex < list.Length; currentItemIndex++)\n{\n Item currentItem = list[currentItemIndex];\n ...\n}\n</code></pre>\n\n<p>into</p>\n\n<pre><code>foreach (Item currentItem in list)\n{\n ...\n}\n</code></pre>\n\n<p>Which makes it easier to read because only the real meaning of the code is expressed (process the items in the list) and not the way we want to process the items (keep an index of the current item en increase it until it reaches the length of the list and thereby meaning the end of the item collection).</p>\n\n<p>The only time I still use one letter variables is when I'm looping trough dimensions. But then I will use x, y and sometimes z.</p>\n"
},
{
"answer_id": 101644,
"author": "Ande Turner",
"author_id": 4857,
"author_profile": "https://Stackoverflow.com/users/4857",
"pm_score": 4,
"selected": false,
"text": "<h1>Examples: <em>. . . In Java</em></h1>\n\n<p><br></p>\n\n<h2>Non-Iterative Loops:</h2>\n\n<p><br>\n<strong>Non-Nested Loops:</strong> . . . The Index is a value.</p>\n\n<blockquote>\n <p>. . . <em>using</em> <code>i</code>, <em>as you would in Algebra, is the most common practise</em> . . .</p>\n</blockquote>\n\n<pre><code>for (int i = 0; i < LOOP_LENGTH; i++) {\n\n // LOOP_BODY\n}\n</code></pre>\n\n<p><br>\n<strong>Nested Loops:</strong> . . . Differentiating Indices lends to comprehension.</p>\n\n<blockquote>\n <p>. . . <em>using a descriptive suffix</em> . . .</p>\n</blockquote>\n\n<pre><code>for (int iRow = 0; iRow < ROWS; iRow++) {\n\n for (int iColumn = 0; iColumn < COLUMNS; iColumn++) {\n\n // LOOP_BODY\n }\n}\n</code></pre>\n\n<p><br>\n<strong><code>foreach</code> Loops:</strong> . . . An <code>Object</code> needs a name. </p>\n\n<blockquote>\n <p><em>. . . using a descriptive name . . .</em></p>\n</blockquote>\n\n<pre><code>for (Object something : somethings) {\n\n // LOOP_BODY\n}\n</code></pre>\n\n<p><br></p>\n\n<h2>Iterative Loops:</h2>\n\n<p><br>\n<strong><code>for</code> Loops:</strong> . . . Iterators reference Objects. An Iterator it is neither; an Index, nor an Indice.</p>\n\n<blockquote>\n <p>. . . <code>iter</code> <em>abreviates an Iterators purpose</em> . . .</p>\n</blockquote>\n\n<pre><code>for (Iterator iter = collection.iterator(); iter.hasNext(); /* N/A */) {\n\n Object object = iter.next();\n\n // LOOP_BODY\n}\n</code></pre>\n\n<p><br>\n<strong><code>while</code> Loops:</strong> . . . Limit the scope of the Iterator.</p>\n\n<blockquote>\n <p>. . . <em>commenting on the loops purpose</em> . . .</p>\n</blockquote>\n\n<pre><code>/* LOOP_DESCRIPTION */ {\n\n Iterator iter = collection.iterator();\n\n while (iter.hasNext()) {\n\n // LOOP_BODY\n }\n}\n</code></pre>\n\n<blockquote>\n <p><em>This last example reads badly without comments, thereby encouraging them.</em> \n <em>It's verbose perhaps, but useful in scope limiting loops in C.</em></p>\n</blockquote>\n"
},
{
"answer_id": 104673,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 1,
"selected": false,
"text": "<h1>Perl standard</h1>\n<p>In Perl, the standard variable name for an inner loop is <strong>$_</strong>. The <strong>for</strong>, <strong>foreach</strong>, and <strong>while</strong> statements default to this variable, so you don't need to declare it. Usually, <strong>$_</strong> may be read like the neuter generic pronoun "it". So a fairly standard loop might look like:</p>\n<pre><code>foreach (@item){\n $item_count{$_}++;\n}\n</code></pre>\n<p>In English, that translates to:</p>\n<blockquote>\n<p>For each item, increment it's item_count.</p>\n</blockquote>\n<p>Even more common, however, is to not use a variable at all. Many Perl functions and operators default to <strong>$_</strong>:</p>\n<pre><code>for (@item){\n print;\n}\n</code></pre>\n<p>In English:</p>\n<blockquote>\n<p>For [each] item, print [it].</p>\n</blockquote>\n<p>This also is the standard for counters. (But counters are used far less often in Perl than in other languages such as C). So to print the squares of integers from 1 to 100:</p>\n<pre><code>for (1..100){\n print "$_*$_\\n";\n}\n</code></pre>\n<p>Since only one loop can use the <strong>$_</strong> variable, usually it's used in the inner-most loop. This usage matches the way English usually works:</p>\n<blockquote>\n<p>For each car, look at each tire and check it's pressure.</p>\n</blockquote>\n<p>In Perl:</p>\n<pre><code>foreach $car (@cars){\n for (@{$car->{tires}}){\n check_pressure($_);\n }\n}\n</code></pre>\n<p>As above, it's best to use longer, descriptive names in outer loops, since it can be hard to remember in a long block of code what a generic loop variable name really means.</p>\n<p>Occasionally, it makes sense to use shorter, non-descriptive, generic names such as <strong>$i</strong>, <strong>$j</strong>, and <strong>$k</strong>, rather than <strong>$_</strong> or a descriptive name. For instance, it's useful to match the variables use in a published algorithm, such as <a href=\"http://en.wikipedia.org/wiki/Cross_product\" rel=\"nofollow noreferrer\">cross product</a>.</p>\n"
},
{
"answer_id": 106074,
"author": "Ande Turner",
"author_id": 4857,
"author_profile": "https://Stackoverflow.com/users/4857",
"pm_score": 1,
"selected": false,
"text": "<p>@JustMike . . . <strong>A FEW C EXAMPLES:</strong> . . . to accompany the Java ones.<br><br></p>\n\n<p><strong>NON-NESTED loop:</strong> . . . limiting scope where possible </p>\n\n<pre><code>/*LOOP_DESCRIPTION*/ {\n\n int i;\n\n for (i = 0; i < LOOP_LENGTH; i++) {\n\n // loop body\n } \n}\n</code></pre>\n\n<p><br>\n<strong>NESTED loop:</strong> . . . ditto</p>\n\n<pre><code>/*LOOP_DESCRIPTION*/ {\n\n int row, column;\n\n for (row = 0; row < ROWS; row++) {\n\n for (column = 0; column < COLUMNS; column++) {\n\n // loop body\n }\n } \n}\n</code></pre>\n\n<p>One good thing about this layout is it reads badly without comments, thereby encouraging them.<br>It's verbose perhaps, but personally this is how I do loops in C.\n<br><br>\nAlso: <em>I did use \"index\" and \"idx\" when I started, but this usually got changed to \"i\" by my peers.</em></p>\n"
},
{
"answer_id": 106346,
"author": "Oddmund",
"author_id": 4417,
"author_profile": "https://Stackoverflow.com/users/4417",
"pm_score": 3,
"selected": false,
"text": "<p>I use i, ii, iii, iv, v ... Never got higher than iii, though.</p>\n"
},
{
"answer_id": 106541,
"author": "Tim Ottinger",
"author_id": 15929,
"author_profile": "https://Stackoverflow.com/users/15929",
"pm_score": 1,
"selected": false,
"text": "<p>The first rule is that the length of the variable name should match the scope of the variable. The second rule is that meaningful names make bugs more shallow. The third rule is that if you feel like adding comment to a variable name, you chose the wrong variable name. The final rule is do as your teammates do, so long as it does not counteract the prior rules.</p>\n"
},
{
"answer_id": 108796,
"author": "petr k.",
"author_id": 15497,
"author_profile": "https://Stackoverflow.com/users/15497",
"pm_score": 3,
"selected": false,
"text": "<p>I use <strong>i</strong>, <strong>j</strong>, <strong>k</strong> (or <strong>r</strong> & <strong>c</strong> for row-column looping). If you need <strong>more than three loop variables in a method</strong>, the the method is probably too long and complex and your code would likely <strong>benefit from splitting the method up</strong> into more methods and <strong>naming</strong> them <strong>properly</strong>.</p>\n"
},
{
"answer_id": 108882,
"author": "Tim Gradwell",
"author_id": 16676,
"author_profile": "https://Stackoverflow.com/users/16676",
"pm_score": 0,
"selected": false,
"text": "<p>I've started to use context-relevant loop variable names mixed with <a href=\"http://c2.com/cgi/wiki?HungarianNotation\" rel=\"nofollow noreferrer\">hungarian</a>.</p>\n\n<p>When looping through rows, I'll use <code>iRow</code>. When looping through columns I'll use <code>iCol</code>. When looping through cars I'll use <code>iCar</code>. You get the idea.</p>\n"
},
{
"answer_id": 108906,
"author": "Midhat",
"author_id": 9425,
"author_profile": "https://Stackoverflow.com/users/9425",
"pm_score": 1,
"selected": false,
"text": "<p>for numerical computations, matlab, and the likes of it, dont use i, j</p>\n\n<p>these are reserved constants, but matlab wont complain.</p>\n\n<p>My personal favs are</p>\n\n<p>index\nfirst,second\ncounter\ncount</p>\n"
},
{
"answer_id": 109415,
"author": "Ed L",
"author_id": 13099,
"author_profile": "https://Stackoverflow.com/users/13099",
"pm_score": 0,
"selected": false,
"text": "<p>My favorite convention for looping over a matrix-like set is to use x+y as they are used in cartesian coordinates:</p>\n\n<pre><code>for x in width:\n for y in height:\n do_something_interesting(x,y)\n</code></pre>\n"
},
{
"answer_id": 115104,
"author": "Derek Clegg",
"author_id": 19783,
"author_profile": "https://Stackoverflow.com/users/19783",
"pm_score": 1,
"selected": false,
"text": "<p>Whatever you choose, use the same index consistently in your code wherever it has the same meaning. For example, to walk through an array, you can use <code>i</code>, <code>jj</code>, <code>kappa</code>, whatever, but always do it the same way everywhere:</p>\n\n<pre><code>for (i = 0; i < count; i++) ...\n</code></pre>\n\n<p>The best practice is to make this part of the loop look the same throughout your code (including consistently using <code>count</code> as the limit), so that it becomes an idiom that you can skip over mentally in order to focus on the meat of the code, the body of the loop.</p>\n\n<p>Similarly, if you're walking through an 2d array of pixels, for example, you might write</p>\n\n<pre><code>for (y = 0; y < height; y++)\n for (x = 0; x < width; x++)\n ...\n</code></pre>\n\n<p>Just do it the same way in every place that you write this type of loop.</p>\n\n<p>You want your readers to be able to ignore the boring setup and see the brilliance of what you're doing in the actual loop.</p>\n"
},
{
"answer_id": 127110,
"author": "Onorio Catenacci",
"author_id": 2820,
"author_profile": "https://Stackoverflow.com/users/2820",
"pm_score": 1,
"selected": false,
"text": "<p>Steve McConnell's <em><a href=\"http://www.cc2e.com/\" rel=\"nofollow noreferrer\">Code Complete</a></em> has, as usual, some excellent advice in this regard. The relevant pages (in the first edition anyway) are 340 and 341. Definitely advise anyone who's interested in improving their loop coding to give this a look. McConnell recommends meaningful loop counter names but people should read what he's got to say themselves rather than relying on my weak summary.</p>\n"
},
{
"answer_id": 131236,
"author": "Riddari",
"author_id": 2145,
"author_profile": "https://Stackoverflow.com/users/2145",
"pm_score": 0,
"selected": false,
"text": "<p>I usually use:</p>\n\n<pre><code>for(lcObject = 0; lcObject < Collection.length(); lcObject++)\n{\n //do stuff\n}\n</code></pre>\n"
},
{
"answer_id": 142741,
"author": "Randy L",
"author_id": 13800,
"author_profile": "https://Stackoverflow.com/users/13800",
"pm_score": 1,
"selected": false,
"text": "<p>i also use the double-letter convention. ii, jj, kk. you can grep those and not come up with a bunch of unwanted matches.</p>\n\n<p>i think using those letters, even though they're doubled, is the best way to go. it's a familiar convention, even with the doubling. </p>\n\n<p>there's a lot to say for sticking with conventions. it makes things a lot more readable.</p>\n"
},
{
"answer_id": 142755,
"author": "loudej",
"author_id": 6056,
"author_profile": "https://Stackoverflow.com/users/6056",
"pm_score": 0,
"selected": false,
"text": "<p>For integers I use int index, unless it's nested then I use an Index suffix over what's being iterated like int groupIndex and int userIndex.</p>\n"
},
{
"answer_id": 320787,
"author": "J.T. Hurley",
"author_id": 39851,
"author_profile": "https://Stackoverflow.com/users/39851",
"pm_score": 0,
"selected": false,
"text": "<p>In Python, I use i, j, and k if I'm only counting times through. I use x, y, and z if the iteration count is being used as an index. If I'm actually generating a series of arguments, however, I'll use a meaningful name.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12293/"
]
| If you are writing a *simple* little loop, what *should* you name the counter?
*Provide example loops!* | I always use a **meaningful name** unless it's a single-level loop and the variable has no meaning other than "the number of times I've been through this loop", in which case I use `i`.
When using meaningful names:
* the code is more understandable to colleagues reading your code,
* it's easier to find bugs in the loop logic, and
* text searches for the variable name to return relevant pieces of code operating on the same data are more reliable.
Example - spot the bug
----------------------
It can be tricky to find the bug in this nested loop using single letters:
```
int values[MAX_ROWS][MAX_COLS];
int sum_of_all_values()
{
int i, j, total;
total = 0;
for (i = 0; i < MAX_COLS; i++)
for (j = 0; j < MAX_ROWS; j++)
total += values[i][j];
return total;
}
```
whereas it is easier when using meaningful names:
```
int values[MAX_ROWS][MAX_COLS];
int sum_of_all_values()
{
int row_num, col_num, total;
total = 0;
for (row_num = 0; row_num < MAX_COLS; row_num++)
for (col_num = 0; col_num < MAX_ROWS; col_num++)
total += values[row_num][col_num];
return total;
}
```
### Why `row_num`? - rejected alternatives
In response to some other answers and comments, these are some alternative suggestions to using `row_num` and `col_num` and why I choose not to use them:
* **`r`** and **`c`**: This is slightly better than `i` and `j`. I would only consider using them if my organisation's standard were for single-letter variables to be integers, and also always to be the first letter of the equivalent descriptive name. The system would fall down if I had two variables in the function whose name began with "r", and readability would suffer even if other objects beginning with "r" appeared anywhere in the code.
* **`rr`** and **`cc`**: This looks weird to me, but I'm not used to a double-letter loop variable style. If it were the standard in my organisation then I imagine it would be slightly better than `r` and `c`.
* **`row`** and **`col`**: At first glance this seems more succinct than `row_num` and `col_num`, and just as descriptive. However, I would expect bare nouns like "row" and "column" to refer to structures, objects or pointers to these. If `row` could mean *either* the row structure itself, *or* a row number, then confusion will result.
* **`iRow`** and **`iCol`**: This conveys extra information, since `i` can mean it's a loop counter while `Row` and `Col` tell you what it's counting. However, I prefer to be able to read the code almost in English:
+ `row_num < MAX_COLS` reads as "the **row num**ber is **less than** the **max**imum (number of) **col**umn**s**";
+ `iRow < MAX_COLS` at best reads as "the **integer loop counter** for the **row** is **less than** the **max**imum (number of) **col**umn**s**".
+ It may be a personal thing but I prefer the first reading.
An alternative to `row_num` I would accept is `row_idx`: the word "index" uniquely refers to an array position, unless the application's domain is in database engine design, financial markets or similar.
My example above is as small as I could make it, and as such some people might not see the point in naming the variables descriptively since they can hold the whole function in their head in one go. In real code, however, the functions would be larger, and the logic more complex, so decent names become more important to aid readability and to avoid bugs.
In summary, my aim with all variable naming (not just loops) is to be **completely unambiguous**. If *anybody* reads any portion of my code and can't work out what a variable is for immediately, then I have failed. |
101,072 | <p>Was this an oversight? Or is it to do with the JVM?</p>
| [
{
"answer_id": 101084,
"author": "Confusion",
"author_id": 16784,
"author_profile": "https://Stackoverflow.com/users/16784",
"pm_score": 1,
"selected": false,
"text": "<p>I guess it has to do with the fact that the JVM is coded in C++. Apart from that, pointers and references are nearly similar. You could say that the reference mechanism in Java is implemented using C++ pointers and the name 'NullPointerException' allows that implementation detail to shine through.</p>\n"
},
{
"answer_id": 692078,
"author": "David Citron",
"author_id": 5309,
"author_profile": "https://Stackoverflow.com/users/5309",
"pm_score": 6,
"selected": true,
"text": "<p>Java does indeed have pointers--pointers on which you cannot perform pointer arithmetic.</p>\n\n<p>From the venerable <a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.1\" rel=\"noreferrer\">JLS</a>:</p>\n\n<blockquote>\n <p>There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3).</p>\n</blockquote>\n\n<p>And <a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.3.1\" rel=\"noreferrer\">later</a>:</p>\n\n<blockquote>\n <p>An <em>object</em> is a <em>class instance</em> or an <em>array</em>.</p>\n \n <p>The reference values (often just <em>references</em>) are <em>pointers</em> to these objects, and a special null reference, which refers to no object.</p>\n</blockquote>\n\n<p>(emphasis theirs)</p>\n\n<p>So, to interpret, if you write:</p>\n\n<pre><code>Object myObj = new Object();\n</code></pre>\n\n<p>then <code>myObj</code> is a <em>reference type</em> which contains a <em>reference value</em> that is itself a <em>pointer</em> to the newly-created <code>Object</code>.</p>\n\n<p>Thus if you set <code>myObj</code> to <code>null</code> you are setting the <em>reference value</em> (aka <em>pointer</em>) to <code>null</code>. Hence a NullPointerException is reasonably thrown when the variable is dereferenced.</p>\n\n<p>Don't worry: this topic has been <a href=\"http://groups.google.com/group/comp.lang.java.programmer/browse_thread/thread/65bf7e9d6bffb1b9/\" rel=\"noreferrer\">heartily debated</a> before.</p>\n"
},
{
"answer_id": 4658029,
"author": "David Svarrer",
"author_id": 571302,
"author_profile": "https://Stackoverflow.com/users/571302",
"pm_score": 2,
"selected": false,
"text": "<p>In Java they use the nomenclature REFERENCE for referring to dynamically created objects. In previous languages, it is named POINTER. Just as the naming of METHODS in object oriented languages has taken over from former FUNCTION's and PROCEDURE's in earlier (object oriented as well as not object oriented) languages. There is no particular better or worse in this naming or new standard, it is just another way of naming the phenomenon of being able to create former dynamic objects, hanging in the air (heap space) and being referred to by a fixed object reference (or dynamic reference also hanging in the air). The authors of the new standard (use of METHODS and REFERENCES) particularly mentioned that the new standards were implemented to make it conformant with the upcoming planning systems - such as UML and UP, where the use of the Object oriented terminology prescribes use of ATTRIBUTES, METHODS and REFERENCES, and not VARIABLES, FUNCTIONS and POINTERS.</p>\n\n<p>Now, you may think now, that it was merely a renaming, but that would be simplifying the description of the process and not be just to the long road which the languages have taken in the name of development. A method is different in nature from a procedure, in that it operates within a scope of a class, while the procedure in its nature operates on the global scope. Similarly an attribute is not just a new name for variable, as the attribute is a property of a class (and its instance - an object). Similarly the reference, which is the question behind this little writing here, is different in that it is typed, thus it does not have the typical property of pointers, being raw references to memory cells, thus again, a reference is a structured reference to memory based objects.</p>\n\n<p>Now, inside of Java, that is - in the stomach of Java, there is an arbitration layer between the underlying C-code and the Java code (the Virtual Machine). In that arbitration layer, an abstraction occurs in that the underlying (bare metal) implementation of the references, as done by the Virtual machine, protects the references from referring bare metal (memory cells without structure). The raw truth is therefore, that the NullPointerException is truly a Null Pointer Exception, and not just a Null Reference Exception. However, that truth may be completely irrelevant for the programmer in the Java environment, as he/she will not at any point be in contact with the bare metal JVM. </p>\n"
},
{
"answer_id": 6227525,
"author": "Stephen C",
"author_id": 139985,
"author_profile": "https://Stackoverflow.com/users/139985",
"pm_score": 2,
"selected": false,
"text": "<p>I think that the answer is that we'll never really know the real answer.</p>\n<p>I suspect that some time before Java 1.0 was released, someone defined a class called <code>NullPointerException</code>. Either that person got the name wrong, or the terminology hadn't stabilized; i.e. the decision to use the term "reference" instead of "pointer" hadn't been made.</p>\n<p>Either way, it is likely that by the time the inconsistency<sup>1</sup> was noticed it couldn't be fixed without breaking backwards compatibility.</p>\n<p>But this is just conjecture.</p>\n<hr />\n<p><sup>1 - You can find other minor inconsistencies like this in the standard Java SE libraries if you look really hard. And a few more serious issues that couldn't be fixed for the same reason.</sup></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
]
| Was this an oversight? Or is it to do with the JVM? | Java does indeed have pointers--pointers on which you cannot perform pointer arithmetic.
From the venerable [JLS](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.1):
>
> There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3).
>
>
>
And [later](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.3.1):
>
> An *object* is a *class instance* or an *array*.
>
>
> The reference values (often just *references*) are *pointers* to these objects, and a special null reference, which refers to no object.
>
>
>
(emphasis theirs)
So, to interpret, if you write:
```
Object myObj = new Object();
```
then `myObj` is a *reference type* which contains a *reference value* that is itself a *pointer* to the newly-created `Object`.
Thus if you set `myObj` to `null` you are setting the *reference value* (aka *pointer*) to `null`. Hence a NullPointerException is reasonably thrown when the variable is dereferenced.
Don't worry: this topic has been [heartily debated](http://groups.google.com/group/comp.lang.java.programmer/browse_thread/thread/65bf7e9d6bffb1b9/) before. |
101,096 | <p>I have an Exchange mailbox linked as a table in an MS Access app. This is primarily used for reading, but I would also like to be able to "move" messages to another folder. </p>
<p>Unfortunately this is not as simple as writing in a second linked mailbox, because apparently I can not edit some fields. Some critical fields like the To: field are unavailable, as I get the following error </p>
<p><em>"Field 'To' is based on an expression and cannot be edited".</em> </p>
<p>Using <em>CreateObject("Outlook.Application")</em> instead is not an option here, because as far as I know, this gives a security dialog when called from Access.</p>
<p>Any solutions?*</p>
| [
{
"answer_id": 102406,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 1,
"selected": false,
"text": "<p>Is this two problems? Mail can be moved using the Move method. Here is a snippet:</p>\n\n<pre><code> Set oApp = CreateObject(\"Outlook.Application\")\n\nSet oNS = oApp.GetNamespace(\"MAPI\")\n\nSet oMailItems = oNS.GetDefaultFolder(olFolderInbox)\nSet itm = oMailItems.Items(6)\nitm.Move oNS.GetDefaultFolder(olFolderDeletedItems)\n</code></pre>\n\n<p>However, Recipients (To) is read only, even, I believe, with Outlook Redemtion.</p>\n"
},
{
"answer_id": 178403,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think Access is the right tool for the job. You will not get around using an Outlook.Application object or a MAPI wrapper like CDO. CDO will be the more elegant and performant way, but it must explicitly be installed on the client via Office Setup.</p>\n\n<p>If you want to avoid the script security dialog (and some of the CDO incapabilities in general), you should give <a href=\"http://www.dimastr.com/redemption/\" rel=\"nofollow noreferrer\">Outlook Redemption</a> a try.</p>\n\n<p>Redemption is a drop-in replacement for CDO and you will be instantly familiar to it when you did any CDO/Outlook VBA coding before.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have an Exchange mailbox linked as a table in an MS Access app. This is primarily used for reading, but I would also like to be able to "move" messages to another folder.
Unfortunately this is not as simple as writing in a second linked mailbox, because apparently I can not edit some fields. Some critical fields like the To: field are unavailable, as I get the following error
*"Field 'To' is based on an expression and cannot be edited".*
Using *CreateObject("Outlook.Application")* instead is not an option here, because as far as I know, this gives a security dialog when called from Access.
Any solutions?\* | Is this two problems? Mail can be moved using the Move method. Here is a snippet:
```
Set oApp = CreateObject("Outlook.Application")
Set oNS = oApp.GetNamespace("MAPI")
Set oMailItems = oNS.GetDefaultFolder(olFolderInbox)
Set itm = oMailItems.Items(6)
itm.Move oNS.GetDefaultFolder(olFolderDeletedItems)
```
However, Recipients (To) is read only, even, I believe, with Outlook Redemtion. |
101,125 | <p>Is there a way to check if the user has a different version of the CSS cached by their browser and if so force their browser to pull the new version?</p>
| [
{
"answer_id": 101131,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 0,
"selected": false,
"text": "<p>You should possibly just share a common ancestor class, then you can flick it with a single js command if need be.</p>\n\n<pre><code><body class=\"style2\">\n\n<body class=\"style1\">\n</code></pre>\n\n<p>etc.</p>\n"
},
{
"answer_id": 101165,
"author": "yann.kmm",
"author_id": 15780,
"author_profile": "https://Stackoverflow.com/users/15780",
"pm_score": 2,
"selected": false,
"text": "<p>Without using js, you can just keep the css filename in a session variable. When a request is made to the Main Page, you simply compose the css link tag with the session variable name.</p>\n\n<p>Being the ccs file name different, you force the broswer to download it without needing to check what was previusly loaded in the browser.</p>\n"
},
{
"answer_id": 101188,
"author": "David Heggie",
"author_id": 4309,
"author_profile": "https://Stackoverflow.com/users/4309",
"pm_score": 0,
"selected": false,
"text": "<p>I know the question was specifically about C# and I assume from that Windows Server of some flavour. Since I don't know either of those technologies well, I'll give an answer that'll work in PHP and Apache, and you may get something from it.</p>\n\n<p>As suggested earlier, just set an ID or a class on the body of the page dependent on the specific query eg (in PHP)</p>\n\n<pre><code><?php\nif($_GET['admin_page']) {\n $body_id = 'admin';\n} else {\n $body_id = 'normal';\n}\n?>\n...\n<body id=\"<?php echo $body_id; ?>\">\n...\n</body>\n</code></pre>\n\n<p>And your CSS can target this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>body#admin h1 {\n color: red;\n}\n\nbody#normal h1 {\n color: blue;\n}\n</code></pre>\n\n<p>etc</p>\n\n<p>As for the forcing of CSS download, you could do this in Apache with the mod_expires or mod_headers modules - for mod_headers, this in .htaccess would stop css files being cached:</p>\n\n<pre><code><FilesMatch \"\\.(css)$\">\nHeader set Cache-Control \"max-age=0, private, no-store, no-cache, must-revalidate\"\n</FilesMatch>\n</code></pre>\n\n<p>But since you're probably not using apache, that won't help you much :(</p>\n"
},
{
"answer_id": 101200,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Answer for question 1</strong></p>\n\n<p>You could write a <strong>Server Control</strong> inheriting from System.Web.UI.Control overriding the <strong>Render</strong> method:</p>\n\n<pre><code>public class CSSLink : System.Web.UI.Control\n{\n\n protected override void Render(System.Web.UI.HtmlTextWriter writer)\n {\n\n if ( ... querystring params == ... )\n writer.WriteLine(\"<link href=\\\"/styles/css1.css\\\" type=\\\"text/css\\\" rel=\\\"stylesheet\\\" />\")\n else\n writer.WriteLine(\"<link href=\\\"/styles/css2.css\\\" type=\\\"text/css\\\" rel=\\\"stylesheet\\\" />\")\n\n }\n\n}\n</code></pre>\n\n<p>and insert an instance of this class in your MasterPage:</p>\n\n<pre><code><%@ Register TagPrefix=\"mycontrols\" Namespace=\"MyNamespace\" Assembly=\"MyAssembly\" %>\n...\n<head runat=\"server\">\n ...\n <mycontrols:CSSLink id=\"masterCSSLink\" runat=\"server\" />\n</head>\n...\n</code></pre>\n"
},
{
"answer_id": 515904,
"author": "jeroen",
"author_id": 42139,
"author_profile": "https://Stackoverflow.com/users/42139",
"pm_score": 6,
"selected": true,
"text": "<p>I don´t know if it is correct usage, but I think you can force a reload of the css file using a query string:</p>\n\n<pre><code><link href=\"mystyle.css?SOME_UNIQUE_TEXT\" type=\"text/css\" rel=\"stylesheet\" />\n</code></pre>\n\n<p>I remember I used this method years ago to force a reload of a web-cam image, but time has probably moved on...</p>\n"
},
{
"answer_id": 540867,
"author": "Leandro López",
"author_id": 22695,
"author_profile": "https://Stackoverflow.com/users/22695",
"pm_score": 2,
"selected": false,
"text": "<p>As <a href=\"https://stackoverflow.com/questions/101125/dynamically-choose-change-css-at-run-time/515904#515904\">jeroen suggested</a> you can have somthing like:</p>\n\n<pre><code><link href=\"StyleSelector.aspx?foo=bar&baz=foz\" type=\"text/css\" rel=\"stylesheet\" />\n</code></pre>\n\n<p>Then your StyleSelector.aspx file should be something like this:</p>\n\n<pre><code><%@ Page Language=\"cs\" AutoEventWireup=\"false\" Inherits=\"Demo.StyleSelector\" Codebehind=\"StyleSelector.aspx.cs\" %>\n</code></pre>\n\n<p>And your StyleSelector.aspx.cs like this:</p>\n\n<pre><code>using System.IO;\n\nnamespace Demo\n{\n public partial class StyleSelector : System.Web.UI.Page\n {\n public StyleSelector()\n {\n Me.Load += New EventHandler(doLoad);\n }\n\n protected void doLoad(object sender, System.EventArgs e)\n {\n // Make sure you add this line\n Response.ContentType = \"text/css\";\n\n string cssFileName = Request.QueryString(\"foo\");\n\n // I'm assuming you have your CSS in a css/ folder\n Response.WriteFile(\"css/\" + cssFileName + \".css\");\n }\n }\n}\n</code></pre>\n\n<p>This would send the user the contents of a CSS file (actually any file, see security note) based on query string arguments. Now the tricky part is doing the Conditional GET, which is the fancy name for checking if the user has the page in the cache or not.</p>\n\n<p>First of all I highly recommend you reading <a href=\"http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers/\" rel=\"nofollow noreferrer\">HTTP Conditional GET for RSS hackers</a>, a great article that explains the basics of HTTP Conditional GET mechanism. It is a <strong>must read</strong>, believe me.</p>\n\n<p>I've posted a <a href=\"https://stackoverflow.com/questions/204886/can-i-use-http-header-to-check-if-a-dynamic-page-has-been-changed/236380#236380\">similar answer</a> (but with PHP code, sorry) to the SO question <a href=\"https://stackoverflow.com/questions/204886/can-i-use-http-header-to-check-if-a-dynamic-page-has-been-changed\">can i use “http header” to check if a dynamic page has been changed</a>. It should be easy to port the code from PHP to C# (I'll do it if later I have the time.)</p>\n\n<p>Security note: it is highly insecure doing something like (\"css/\" + cssFileName + \".css\"), as you may send a relative path string and thus you may send the user the content of a different file. You are to come up with a better way to find out what CSS file to send.</p>\n\n<p>Design note: instead of an .aspx page you might want to use an <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ihttpmodule.aspx\" rel=\"nofollow noreferrer\"><code>IHttpModule</code></a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ihttphandler.aspx\" rel=\"nofollow noreferrer\"><code>IHttpHandler</code></a>, but this way works just fine.</p>\n"
},
{
"answer_id": 3153526,
"author": "Brian Rogers",
"author_id": 267448,
"author_profile": "https://Stackoverflow.com/users/267448",
"pm_score": 0,
"selected": false,
"text": "<p>I like jeroen's suggestion to add a querystring to the stylesheet URL. You could add the time stamp when the stylesheet file was last modified. It seems to me like a good candidate for a helper function or custom control that would generate the LINK tag for you.</p>\n"
},
{
"answer_id": 61276089,
"author": "focus.style",
"author_id": 3187127,
"author_profile": "https://Stackoverflow.com/users/3187127",
"pm_score": 0,
"selected": false,
"text": "<p>Like in correct answer, i am using some similar method, but with some differences</p>\n\n<pre><code><link href=\"mystyle.css?v=DIGIT\" type=\"text/css\" rel=\"stylesheet\" /> \n</code></pre>\n\n<p>As a DIGIT you can use a real number, set manually or automatically in your template. For example, on my projects i'm using Cache clearing modules in admin panel, and each time use this cache cleaner, it increments the DIGIT automatically. </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Is there a way to check if the user has a different version of the CSS cached by their browser and if so force their browser to pull the new version? | I don´t know if it is correct usage, but I think you can force a reload of the css file using a query string:
```
<link href="mystyle.css?SOME_UNIQUE_TEXT" type="text/css" rel="stylesheet" />
```
I remember I used this method years ago to force a reload of a web-cam image, but time has probably moved on... |
101,128 | <p>How do I read text from the (windows) clipboard with python?</p>
| [
{
"answer_id": 101143,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 2,
"selected": false,
"text": "<p>Try win32clipboard from the win32all package (that's probably installed if you're on ActiveState Python).</p>\n\n<p>See sample here: <a href=\"http://code.activestate.com/recipes/474121/\" rel=\"nofollow noreferrer\">http://code.activestate.com/recipes/474121/</a></p>\n"
},
{
"answer_id": 101167,
"author": "Sakin",
"author_id": 12818,
"author_profile": "https://Stackoverflow.com/users/12818",
"pm_score": 8,
"selected": true,
"text": "<p>You can use the module called <a href=\"http://docs.activestate.com/activepython/2.5/pywin32/win32clipboard.html\" rel=\"noreferrer\">win32clipboard</a>, which is part of <a href=\"https://github.com/mhammond/pywin32\" rel=\"noreferrer\">pywin32</a>.</p>\n\n<p>Here is an example that first sets the clipboard data then gets it:</p>\n\n<pre><code>import win32clipboard\n\n# set clipboard data\nwin32clipboard.OpenClipboard()\nwin32clipboard.EmptyClipboard()\nwin32clipboard.SetClipboardText('testing 123')\nwin32clipboard.CloseClipboard()\n\n# get clipboard data\nwin32clipboard.OpenClipboard()\ndata = win32clipboard.GetClipboardData()\nwin32clipboard.CloseClipboard()\nprint data\n</code></pre>\n\n<p>An important reminder from the documentation:</p>\n\n<blockquote>\n <p>When the window has finished examining or changing the clipboard,\n close the clipboard by calling CloseClipboard. This enables other\n windows to access the clipboard. Do not place an object on the\n clipboard after calling CloseClipboard.</p>\n</blockquote>\n"
},
{
"answer_id": 8039424,
"author": "Buttons840",
"author_id": 565879,
"author_profile": "https://Stackoverflow.com/users/565879",
"pm_score": 5,
"selected": false,
"text": "<p>I've seen many suggestions to use the win32 module, but Tkinter provides the shortest and easiest method I've seen, as in this post: <a href=\"https://stackoverflow.com/questions/579687/how-do-i-copy-a-string-to-the-clipboard-on-windows-using-python/4203897#4203897\">How do I copy a string to the clipboard on Windows using Python?</a></p>\n\n<p>Plus, Tkinter is in the python standard library.</p>\n"
},
{
"answer_id": 11096779,
"author": "born",
"author_id": 1441864,
"author_profile": "https://Stackoverflow.com/users/1441864",
"pm_score": 4,
"selected": false,
"text": "<p>The most upvoted answer above is weird in a way that it simply clears the Clipboard and then gets the content (which is then empty). One could clear the clipboard to be sure that some clipboard content type like \"formated text\" does not \"cover\" your plain text content you want to save in the clipboard.</p>\n\n<p>The following piece of code replaces all newlines in the clipboard by spaces, then removes all double spaces and finally saves the content back to the clipboard:</p>\n\n<pre><code>import win32clipboard\n\nwin32clipboard.OpenClipboard()\nc = win32clipboard.GetClipboardData()\nwin32clipboard.EmptyClipboard()\nc = c.replace('\\n', ' ')\nc = c.replace('\\r', ' ')\nwhile c.find(' ') != -1:\n c = c.replace(' ', ' ')\nwin32clipboard.SetClipboardText(c)\nwin32clipboard.CloseClipboard()\n</code></pre>\n"
},
{
"answer_id": 23285159,
"author": "kichik",
"author_id": 492773,
"author_profile": "https://Stackoverflow.com/users/492773",
"pm_score": 5,
"selected": false,
"text": "<p>If you don't want to install extra packages, <code>ctypes</code> can get the job done as well.</p>\n\n<pre><code>import ctypes\n\nCF_TEXT = 1\n\nkernel32 = ctypes.windll.kernel32\nkernel32.GlobalLock.argtypes = [ctypes.c_void_p]\nkernel32.GlobalLock.restype = ctypes.c_void_p\nkernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]\nuser32 = ctypes.windll.user32\nuser32.GetClipboardData.restype = ctypes.c_void_p\n\ndef get_clipboard_text():\n user32.OpenClipboard(0)\n try:\n if user32.IsClipboardFormatAvailable(CF_TEXT):\n data = user32.GetClipboardData(CF_TEXT)\n data_locked = kernel32.GlobalLock(data)\n text = ctypes.c_char_p(data_locked)\n value = text.value\n kernel32.GlobalUnlock(data_locked)\n return value\n finally:\n user32.CloseClipboard()\n\nprint(get_clipboard_text())\n</code></pre>\n"
},
{
"answer_id": 23844754,
"author": "kmonsoor",
"author_id": 617185,
"author_profile": "https://Stackoverflow.com/users/617185",
"pm_score": 6,
"selected": false,
"text": "<p>you can easily get this done through the built-in module <a href=\"https://docs.python.org/2/library/tkinter.html\" rel=\"noreferrer\">Tkinter</a> which is basically a GUI library. This code creates a blank widget to get the clipboard content from OS.</p>\n<pre><code>from tkinter import Tk # Python 3\n#from Tkinter import Tk # for Python 2.x\nTk().clipboard_get()\n</code></pre>\n"
},
{
"answer_id": 27995097,
"author": "user136036",
"author_id": 2441026,
"author_profile": "https://Stackoverflow.com/users/2441026",
"pm_score": 3,
"selected": false,
"text": "<p>For my <strong>console program</strong> the answers with tkinter above did not quite work for me because the .destroy() always gave an error,:</p>\n\n<blockquote>\n <p>can't invoke \"event\" command: application has been destroyed while executing...</p>\n</blockquote>\n\n<p>or when using .withdraw() the console window did not get the focus back.</p>\n\n<p>To solve this you also have to call .update() before the .destroy(). Example:</p>\n\n<pre><code># Python 3\nimport tkinter\n\nr = tkinter.Tk()\ntext = r.clipboard_get()\nr.withdraw()\nr.update()\nr.destroy()\n</code></pre>\n\n<p>The r.withdraw() prevents the frame from showing for a milisecond, and then it will be destroyed giving the focus back to the console.</p>\n"
},
{
"answer_id": 36886989,
"author": "Dan",
"author_id": 2084578,
"author_profile": "https://Stackoverflow.com/users/2084578",
"pm_score": 3,
"selected": false,
"text": "<p>Use Pythons library <a href=\"https://pypi.python.org/pypi/clipboard/0.0.4\" rel=\"noreferrer\">Clipboard </a> </p>\n\n<p>Its simply used like this:</p>\n\n<pre><code>import clipboard\nclipboard.copy(\"this text is now in the clipboard\")\nprint clipboard.paste() \n</code></pre>\n"
},
{
"answer_id": 38171680,
"author": "np8",
"author_id": 3015186,
"author_profile": "https://Stackoverflow.com/users/3015186",
"pm_score": 6,
"selected": false,
"text": "<p>I found <a href=\"https://github.com/asweigart/pyperclip\" rel=\"noreferrer\">pyperclip</a> to be the easiest way to get access to the clipboard from python:</p>\n<ol>\n<li><p>Install pyperclip:\n<code>pip install pyperclip</code></p>\n</li>\n<li><p>Usage:</p>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>import pyperclip\n \ns = pyperclip.paste()\npyperclip.copy(s)\n \n# the type of s is string\n</code></pre>\n<p>With supports Windows, Linux and Mac, and seems to work with non-ASCII characters, too.\nTested characters include ±°©©αβγθΔΨΦåäö</p>\n"
},
{
"answer_id": 49646482,
"author": "Paul Sumpner",
"author_id": 1429282,
"author_profile": "https://Stackoverflow.com/users/1429282",
"pm_score": 4,
"selected": false,
"text": "<p>The python standard library does it...</p>\n\n<pre><code>try:\n # Python3\n import tkinter as tk\nexcept ImportError:\n # Python2\n import Tkinter as tk\n\ndef getClipboardText():\n root = tk.Tk()\n # keep the window from showing\n root.withdraw()\n return root.clipboard_get()\n</code></pre>\n"
},
{
"answer_id": 56947041,
"author": "see2",
"author_id": 11691686,
"author_profile": "https://Stackoverflow.com/users/11691686",
"pm_score": 1,
"selected": false,
"text": "<p>A not very direct trick:</p>\n\n<p>Use pyautogui hotkey:</p>\n\n<pre><code>Import pyautogui\npyautogui.hotkey('ctrl', 'v')\n</code></pre>\n\n<p>Therefore, you can paste the clipboard data as you like.</p>\n"
},
{
"answer_id": 67323780,
"author": "kirgizmustafa17",
"author_id": 11804828,
"author_profile": "https://Stackoverflow.com/users/11804828",
"pm_score": 2,
"selected": false,
"text": "<p>After whole 12 years, I have a solution and you can use it without installing any package.</p>\n<pre><code>from tkinter import Tk, TclError\nfrom time import sleep\n\nwhile True:\n try:\n clipboard = Tk().clipboard_get()\n print(clipboard)\n sleep(5)\n except TclError:\n print("Clipboard is empty.")\n sleep(5)\n</code></pre>\n"
},
{
"answer_id": 70248479,
"author": "asdf101",
"author_id": 12337195,
"author_profile": "https://Stackoverflow.com/users/12337195",
"pm_score": 0,
"selected": false,
"text": "<p>For users of Anaconda: distributions don't come with pyperclip, but they do come with pandas which redistributes pyperclip:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> from pandas.io.clipboard import clipboard_get, clipboard_set\n>>> clipboard_get()\n'from pandas.io.clipboard import clipboard_get, clipboard_set'\n>>> clipboard_set("Hello clipboard!")\n>>> clipboard_get()\n'Hello clipboard!'\n</code></pre>\n<p>I find this easier to use than pywin32 (which is also included in distributions).</p>\n"
},
{
"answer_id": 70254906,
"author": "Athii",
"author_id": 2197624,
"author_profile": "https://Stackoverflow.com/users/2197624",
"pm_score": 1,
"selected": false,
"text": "<pre><code>import pandas as pd\ndf = pd.read_clipboard()\n</code></pre>\n"
},
{
"answer_id": 71168816,
"author": "东临碣石",
"author_id": 14817883,
"author_profile": "https://Stackoverflow.com/users/14817883",
"pm_score": 1,
"selected": false,
"text": "<p>Why not try calling powershell?</p>\n<pre><code>import subprocess\n\ndef getClipboard():\n ret = subprocess.getoutput("powershell.exe -Command Get-Clipboard")\n return ret\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17493/"
]
| How do I read text from the (windows) clipboard with python? | You can use the module called [win32clipboard](http://docs.activestate.com/activepython/2.5/pywin32/win32clipboard.html), which is part of [pywin32](https://github.com/mhammond/pywin32).
Here is an example that first sets the clipboard data then gets it:
```
import win32clipboard
# set clipboard data
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText('testing 123')
win32clipboard.CloseClipboard()
# get clipboard data
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
print data
```
An important reminder from the documentation:
>
> When the window has finished examining or changing the clipboard,
> close the clipboard by calling CloseClipboard. This enables other
> windows to access the clipboard. Do not place an object on the
> clipboard after calling CloseClipboard.
>
>
> |
101,145 | <p>How can someone validate that a specific element exists in an XML file? Say I have an ever changing XML file and I need to verify every element exists before reading/parsing it. </p>
| [
{
"answer_id": 101160,
"author": "Chris James",
"author_id": 3193,
"author_profile": "https://Stackoverflow.com/users/3193",
"pm_score": 6,
"selected": false,
"text": "<pre><code>if(doc.SelectSingleNode(\"//mynode\")==null)....\n</code></pre>\n\n<p>Should do it (where doc is your XmlDocument object, obviously)</p>\n\n<p>Alternatively you could use an XSD and validate against that</p>\n"
},
{
"answer_id": 101163,
"author": "paul",
"author_id": 11249,
"author_profile": "https://Stackoverflow.com/users/11249",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure what you're wanting to do but using a DTD or schema might be all you need to <strong>validate</strong> the xml. </p>\n\n<p>Otherwise, if you want to <strong>find</strong> an element you could use an xpath query to search for a particular element.</p>\n"
},
{
"answer_id": 101169,
"author": "Ash Wilson",
"author_id": 10556,
"author_profile": "https://Stackoverflow.com/users/10556",
"pm_score": 1,
"selected": false,
"text": "<p>You can validate that and much more by using an XML schema language, like <a href=\"http://www.w3schools.com/Schema/default.asp\" rel=\"nofollow noreferrer\">XSD</a>.</p>\n\n<p>If you mean conditionally, within code, then <a href=\"http://www.w3schools.com/XPath/default.asp\" rel=\"nofollow noreferrer\">XPath</a> is worth a look as well.</p>\n"
},
{
"answer_id": 6649224,
"author": "sangam",
"author_id": 47043,
"author_profile": "https://Stackoverflow.com/users/47043",
"pm_score": 3,
"selected": false,
"text": "<p>You can iterate through each and every node and see if a node exists.</p>\n\n<pre><code>doc.Load(xmlPath);\n XmlNodeList node = doc.SelectNodes(\"//Nodes/Node\");\n foreach (XmlNode chNode in node)\n {\n try{\n if (chNode[\"innerNode\"]==null)\n return true; //node exists\n //if ... check for any other nodes you need to\n }catch(Exception e){return false; //some node doesn't exists.}\n }\n</code></pre>\n\n<p>You iterate through every Node elements under Nodes (say this is root) and check to see if node named 'innerNode' (add others if you need) exists. try..catch is because I suspect this will throw popular 'object reference not set' error if the node does not exist.</p>\n"
},
{
"answer_id": 10154151,
"author": "Priyadarshi Kunal",
"author_id": 188936,
"author_profile": "https://Stackoverflow.com/users/188936",
"pm_score": 0,
"selected": false,
"text": "<p>Following is a simple function to check if a particular node is present or not in the xml file. </p>\n\n<pre><code>public boolean envParamExists(String xmlFilePath, String paramName){\n try{\n Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(xmlFilePath));\n doc.getDocumentElement().normalize();\n if(doc.getElementsByTagName(paramName).getLength()>0)\n return true;\n else\n return false;\n }catch (Exception e) {\n //error handling\n }\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 12130206,
"author": "siddharth",
"author_id": 1150659,
"author_profile": "https://Stackoverflow.com/users/1150659",
"pm_score": 2,
"selected": false,
"text": "<p>additionally to <code>sangam</code> code</p>\n\n<pre><code>if (chNode[\"innerNode\"][\"innermostNode\"]==null)\n return true; //node *parentNode*/innerNode/innermostNode exists\n</code></pre>\n"
},
{
"answer_id": 12815870,
"author": "jomsk1e",
"author_id": 1638261,
"author_profile": "https://Stackoverflow.com/users/1638261",
"pm_score": 2,
"selected": false,
"text": "<p>How about trying this: </p>\n\n<pre><code>using (XmlTextReader reader = new XmlTextReader(xmlPath))\n{\n while (reader.Read())\n {\n if (reader.NodeType == XmlNodeType.Element)\n { \n //do your code here\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 26961433,
"author": "user4258853",
"author_id": 4258853,
"author_profile": "https://Stackoverflow.com/users/4258853",
"pm_score": 3,
"selected": false,
"text": "<p>//if the problem is \"just\" to verify that the element exist in the xml-file before you\n//extract the value you could do like this</p>\n\n<pre><code>XmlNodeList YOURTEMPVARIABLE = doc.GetElementsByTagName(\"YOUR_ELEMENTNAME\");\n\n if (YOURTEMPVARIABLE.Count > 0 )\n {\n doctype = YOURTEMPVARIABLE[0].InnerXml;\n\n }\n else\n {\n doctype = \"\";\n }\n</code></pre>\n"
},
{
"answer_id": 37634639,
"author": "Mazinger",
"author_id": 3648561,
"author_profile": "https://Stackoverflow.com/users/3648561",
"pm_score": 0,
"selected": false,
"text": "<p>A little bit late, but if it helps, this works for me...</p>\n\n<pre><code>XmlNodeList NodoEstudios = DocumentoXML.SelectNodes(\"//ALUMNOS/ALUMNO[@id=\\\"\" + Id + \"\\\"]/estudios\");\n\nstring Proyecto = \"\";\n\nforeach(XmlElement ElementoProyecto in NodoEstudios)\n{\n XmlNodeList EleProyecto = ElementoProyecto.GetElementsByTagName(\"proyecto\");\n Proyecto = (EleProyecto[0] == null)?\"\": EleProyecto[0].InnerText;\n}\n</code></pre>\n"
},
{
"answer_id": 41354369,
"author": "Sumit",
"author_id": 7347910,
"author_profile": "https://Stackoverflow.com/users/7347910",
"pm_score": 0,
"selected": false,
"text": "<p>//Check xml element value if exists using XmlReader </p>\n\n<pre><code> using (XmlReader xmlReader = XmlReader.Create(new StringReader(\"XMLSTRING\")))\n {\n\n if (xmlReader.ReadToFollowing(\"XMLNODE\")) \n\n {\n string nodeValue = xmlReader.ReadElementString(\"XMLNODE\"); \n }\n } \n</code></pre>\n"
},
{
"answer_id": 52558533,
"author": "Jiving Rockabilly",
"author_id": 4921102,
"author_profile": "https://Stackoverflow.com/users/4921102",
"pm_score": 0,
"selected": false,
"text": "<p>Just came across the same problem and the <strong>null-coalescing operator</strong> with <strong>SelectSingleNode</strong> worked a treat, assigning null with string.Empty </p>\n\n<pre><code> foreach (XmlNode txElement in txElements)\n {\n var txStatus = txElement.SelectSingleNode(\".//ns:TxSts\", nsmgr).InnerText ?? string.Empty;\n var endToEndId = txElement.SelectSingleNode(\".//ns:OrgnlEndToEndId\", nsmgr).InnerText ?? string.Empty;\n var paymentAmount = txElement.SelectSingleNode(\".//ns:InstdAmt\", nsmgr).InnerText ?? string.Empty;\n var paymentAmountCcy = txElement.SelectSingleNode(\".//ns:InstdAmt\", nsmgr).Attributes[\"Ccy\"].Value ?? string.Empty;\n var clientId = txElement.SelectSingleNode(\".//ns:OrgnlEndToEndId\", nsmgr).InnerText ?? string.Empty;\n var bankSortCode = txElement.SelectSingleNode(\".//ns:OrgnlEndToEndId\", nsmgr).InnerText ?? string.Empty; \n\n //TODO finish Object creation and Upsert DB\n }\n</code></pre>\n"
},
{
"answer_id": 54802098,
"author": "Mir Saleem",
"author_id": 11094573,
"author_profile": "https://Stackoverflow.com/users/11094573",
"pm_score": -1,
"selected": false,
"text": "<p>//I am finding childnode ERNO at 2nd but last place</p>\n\n<pre><code>If StrComp(xmlnode(i).ChildNodes.Item(xmlnode(i).ChildNodes.Count - 1).Name.ToString(), \"ERNO\", CompareMethod.Text) = 0 Then\n xmlnode(i).ChildNodes.Item(xmlnode(i).ChildNodes.Count - 1).InnerText = c\n Else\n elem = xmldoc.CreateElement(\"ERNo\")\n elem.InnerText = c.ToString\n root.ChildNodes(i).AppendChild(elem)\n End If\n</code></pre>\n"
},
{
"answer_id": 63112427,
"author": "fredm73",
"author_id": 5253084,
"author_profile": "https://Stackoverflow.com/users/5253084",
"pm_score": 0,
"selected": false,
"text": "<pre><code> string name = "some node name";\n var xDoc = XDocument.Load("yourFile");\n var docRoot = xDoc.Element("your docs root name");\n\n var aNode = docRoot.Elements().Where(x => x.Name == name).FirstOrDefault();\n if (aNode == null)\n {\n return $"file has no {name}";\n }\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| How can someone validate that a specific element exists in an XML file? Say I have an ever changing XML file and I need to verify every element exists before reading/parsing it. | ```
if(doc.SelectSingleNode("//mynode")==null)....
```
Should do it (where doc is your XmlDocument object, obviously)
Alternatively you could use an XSD and validate against that |
101,151 | <p>I have the following scenario:</p>
<pre>
public class CarManager
{
..
public long AddCar(Car car)
{
try
{
string username = _authorizationManager.GetUsername();
...
long id = _carAccessor.AddCar(username, car.Id, car.Name, ....);
if(id == 0)
{
throw new Exception("Car was not added");
}
return id;
} catch (Exception ex) {
throw new AddCarException(ex);
}
}
public List AddCars(List cars)
{
List ids = new List();
foreach(Car car in cars)
{
ids.Add(AddCar(car));
}
return ids;
}
}
</pre>
<p>I am mocking out _reportAccessor, _authorizationManager etc.</p>
<p>Now I want to unittest the CarManager class.
Should I have multiple tests for AddCar() such as </p>
<pre>
AddCarTest()
AddCarTestAuthorizationManagerException()
AddCarTestCarAccessorNoId()
AddCarTestCarAccessorException()
</pre>
<p>For AddCars() should I repeat all previous tests as AddCars() calls AddCar() - it seems like repeating oneself? Should I perhaps not be calling AddCar() from AddCars()? < p/></p>
<p>Please help.</p>
| [
{
"answer_id": 101190,
"author": "Andreas Bakurov",
"author_id": 7400,
"author_profile": "https://Stackoverflow.com/users/7400",
"pm_score": 1,
"selected": false,
"text": "<p>Unit Test should focus only to its corresponding class under testing. All attributes of class that are not of same type should be mocked.</p>\n\n<p>Suppose you have a class (CarRegistry) that uses some kind of data access object (for example CarPlatesDAO) which loads/stores car plate numbers from Relational database.</p>\n\n<p>When you are testing the CarRegistry you should not care about if CarPlateDAO performs correctly; Since our DAO has it's own unit test.</p>\n\n<p>You just create mock that behaves like DAO and returns correct or wrong values according to expected behavior. You plug this mock DAO to your CarRegistry and test only the target class without caring if all aggregated classes are \"green\".</p>\n\n<p>Mocking allows separation of testable classes and better focus on specific functionality.</p>\n"
},
{
"answer_id": 101308,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 2,
"selected": false,
"text": "<p>There are two issues here:</p>\n\n<ul>\n<li>Unit tests should do more than test methods one at a time. They should be designed to prove that your class can do the job it was designed for when integrated with the rest of the system. So you should mock out the dependencies and then write a test for each way in which you class will actually be used. For each (non-trivial) class you write there will be scenarios that involve the client code calling methods in a particular pattern.</li>\n<li>There is nothing wrong with AddCars calling AddCar. You should repeat tests for error handling but only when it serves a purpose. One of the unofficial rules of unit testing is 'test to the point of boredom' or (as I like to think of it) 'test till the fear goes away'. Otherwise you would be writing tests forever. So if you are confident a test will add no value them don't write it. You may be wrong of course, in which case you can come back later and add it in. You don't have to produce a perfect test first time round, just a firm basis on which you can build as you better understand what your class needs to do.</li>\n</ul>\n"
},
{
"answer_id": 101328,
"author": "MvdD",
"author_id": 18044,
"author_profile": "https://Stackoverflow.com/users/18044",
"pm_score": 1,
"selected": false,
"text": "<p>When unittesting the AddCar class, create tests that will exercise every codepath. If _authorizationManager.GetUsername() can throw an exception, create a test where your mock for this object will throw. BTW: don't throw or catch instances of Exception, but derive a meaningful Exception class.</p>\n\n<p>For the AddCars method, you definitely should call AddCar. But you might consider making AddCar virtual and override it just to test that it's called with all cars in the list.</p>\n\n<p>Sometimes you'll have to change the class design for testability.</p>\n"
},
{
"answer_id": 101438,
"author": "Josh Freed",
"author_id": 14548,
"author_profile": "https://Stackoverflow.com/users/14548",
"pm_score": 1,
"selected": false,
"text": "<p>Writing tests that explore every possible scenario within a method is good practice. That's how I unit test in my projects. Tests like <code>AddCarTestAuthorizationManagerException()</code>, <code>AddCarTestCarAccessorNoId()</code>, or <code>AddCarTestCarAccessorException()</code> get you thinking about all the different ways your code can fail which has led to me find new kinds of failures for a method I might have otherwise missed as well as improve the overall design of the class.</p>\n\n<p>In a situation like <code>AddCars()</code> calling <code>AddCar()</code> I would mock the <code>AddCar()</code> method and count the number of times it's called by <code>AddCars()</code>. The mocking library I use allows me to create a mock of CarManager and mock only the <code>AddCar()</code> method but not <code>AddCars()</code>. Then your unit test can set how many times it expects <code>AddCar()</code> to be called which you would know from the size of the list of cars passed in.</p>\n"
},
{
"answer_id": 491767,
"author": "Paul Smith",
"author_id": 23461,
"author_profile": "https://Stackoverflow.com/users/23461",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Should I have multiple tests for\n AddCar() such as</p>\n \n <p>AddCarTest()\n AddCarTestAuthorizationManagerException()\n AddCarTestCarAccessorNoId()\n AddCarTestCarAccessorException()</p>\n</blockquote>\n\n<p>Absolutely! This tells you valuable information</p>\n\n<blockquote>\n <p>For AddCars() should I repeat all previous tests as AddCars() calls AddCar() - it seems\n like repeating oneself? Should I perhaps not be calling AddCar() from AddCars()?</p>\n</blockquote>\n\n<p>Calling AddCar from AddCars is a great idea, it avoids violating the DRY principle. Similarly, you should be repeating tests. Think of it this way - <em>you already wrote tests for AddCar</em>, so when testing AddCards you can <em>assume AddCar does what it says on the tin</em>.</p>\n\n<p>Let's put it this way - imagine AddCar was in a different class. You would have no knowledge of an authorisation manager. Test AddCars <strong>without</strong> the knowledge of what AddCar has to do.</p>\n\n<p>For AddCars, you need to test all normal boundary conditions (does an empty list work, etc.) You probably don't need to test the situation where AddCar throws an exception, as you're not attempting to catch it in AddCars.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15771/"
]
| I have the following scenario:
```
public class CarManager
{
..
public long AddCar(Car car)
{
try
{
string username = _authorizationManager.GetUsername();
...
long id = _carAccessor.AddCar(username, car.Id, car.Name, ....);
if(id == 0)
{
throw new Exception("Car was not added");
}
return id;
} catch (Exception ex) {
throw new AddCarException(ex);
}
}
public List AddCars(List cars)
{
List ids = new List();
foreach(Car car in cars)
{
ids.Add(AddCar(car));
}
return ids;
}
}
```
I am mocking out \_reportAccessor, \_authorizationManager etc.
Now I want to unittest the CarManager class.
Should I have multiple tests for AddCar() such as
```
AddCarTest()
AddCarTestAuthorizationManagerException()
AddCarTestCarAccessorNoId()
AddCarTestCarAccessorException()
```
For AddCars() should I repeat all previous tests as AddCars() calls AddCar() - it seems like repeating oneself? Should I perhaps not be calling AddCar() from AddCars()? < p/>
Please help. | There are two issues here:
* Unit tests should do more than test methods one at a time. They should be designed to prove that your class can do the job it was designed for when integrated with the rest of the system. So you should mock out the dependencies and then write a test for each way in which you class will actually be used. For each (non-trivial) class you write there will be scenarios that involve the client code calling methods in a particular pattern.
* There is nothing wrong with AddCars calling AddCar. You should repeat tests for error handling but only when it serves a purpose. One of the unofficial rules of unit testing is 'test to the point of boredom' or (as I like to think of it) 'test till the fear goes away'. Otherwise you would be writing tests forever. So if you are confident a test will add no value them don't write it. You may be wrong of course, in which case you can come back later and add it in. You don't have to produce a perfect test first time round, just a firm basis on which you can build as you better understand what your class needs to do. |
101,156 | <p>I need to count and check how much of some images is placed in folder od web server.
Example- images get names from <code>user_id</code>, and on example I have <code>user_id 27</code>, and my images are:</p>
<pre><code>27_1.jpg, 27_2.jpg, 27_3.jpg, ...
</code></pre>
<p>How to check and write to database this thing?</p>
<p>Thanks</p>
| [
{
"answer_id": 101230,
"author": "hometoast",
"author_id": 2009,
"author_profile": "https://Stackoverflow.com/users/2009",
"pm_score": 2,
"selected": false,
"text": "<p>Once you know your path you can use IO.Directory.GetFiles() method.</p>\n\n<pre><code>IO.Directory.GetFiles(\"\\translated\\path\",\"27_*.jpg\").Count()\n</code></pre>\n\n<p>will give you what you're looking for.</p>\n"
},
{
"answer_id": 101236,
"author": "WebDude",
"author_id": 15360,
"author_profile": "https://Stackoverflow.com/users/15360",
"pm_score": 0,
"selected": false,
"text": "<p>Using the System.IO namespace, you can do something like this</p>\n\n<pre><code>public File[] GetUserFiles(int userId)\n{\n List<File> files = new List<File>();\n\n DirectoryInfo di = new DirectoryInfo(@\"c:\\folderyoulookingfor\");\n foreach(File f in di.GetFiles())\n {\n if(f.ToString().StartsWith(userId.ToString()))\n files.Add(f);\n }\n return file.ToArray();\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205368/"
]
| I need to count and check how much of some images is placed in folder od web server.
Example- images get names from `user_id`, and on example I have `user_id 27`, and my images are:
```
27_1.jpg, 27_2.jpg, 27_3.jpg, ...
```
How to check and write to database this thing?
Thanks | Once you know your path you can use IO.Directory.GetFiles() method.
```
IO.Directory.GetFiles("\translated\path","27_*.jpg").Count()
```
will give you what you're looking for. |
101,162 | <p>How do you return a serialized JSON object to the client side using ASP.NET MVC via an AJAX call?</p>
| [
{
"answer_id": 101256,
"author": "David Bick",
"author_id": 4914,
"author_profile": "https://Stackoverflow.com/users/4914",
"pm_score": 6,
"selected": true,
"text": "<p>From the controller you can just return a JsonResult:</p>\n\n<pre><code>public ActionResult MyAction()\n{\n ... // Populate myObject\n return new JsonResult{ Data = myObject };\n}\n</code></pre>\n\n<p>The form of the Ajax call will depend on which library you're using, of course. Using jQuery it would be something like:</p>\n\n<pre><code>$.getJSON(\"/controllerName/MyAction\", callbackFunction);\n</code></pre>\n\n<p>where the <code>callbackFunction</code> takes a parameter which is the data from the XHR request.</p>\n"
},
{
"answer_id": 102693,
"author": "Matt",
"author_id": 17803,
"author_profile": "https://Stackoverflow.com/users/17803",
"pm_score": 3,
"selected": false,
"text": "<p>Depending on your syntax preferences, the following also works:</p>\n\n<pre><code>public ActionResult MyAction()\n{\n return Json(new {Data = myObject});\n}\n</code></pre>\n"
},
{
"answer_id": 24030151,
"author": "Md Nazmoon Noor",
"author_id": 870118,
"author_profile": "https://Stackoverflow.com/users/870118",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to send JSON in response to a GET, you'll need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet.</p>\n\n<pre><code>public JsonResult Foo()\n{\n return Json(\"Secrets\", JsonRequestBehavior.AllowGet);\n}\n</code></pre>\n"
},
{
"answer_id": 45564416,
"author": "Thisara Subath",
"author_id": 6602130,
"author_profile": "https://Stackoverflow.com/users/6602130",
"pm_score": 2,
"selected": false,
"text": "<p>This is the Small block of code for just understand , how we can use JsonResults in MVC Controllers. </p>\n\n<pre><code> public JsonResult ASD()\n {\n string aaa = \"Hi There is a sample Json\";\n return Json(aaa);\n }\n</code></pre>\n"
},
{
"answer_id": 50997671,
"author": "Oshada Ekanayake",
"author_id": 4904744,
"author_profile": "https://Stackoverflow.com/users/4904744",
"pm_score": 1,
"selected": false,
"text": "<p>You can also System.Web.Script.Serialization; as below</p>\n\n<pre><code>using System.Web.Script.Serialization;\n\npublic ActionResult MyAction(string myParam)\n{\n\n return new JavaScriptSerializer().Serialize(myObject);\n}\n</code></pre>\n\n<p>Ajax </p>\n\n<pre><code>$.ajax({\n type: 'POST',\n url: '@Url.Action(\"MyAction\",\"MyMethod\")',\n dataType: 'json',\n contentType: \"application/json; charset=utf-8\",\n data: JSON.stringify({ \"myParam\": \"your data\" }),\n success: function(data)\n {\n console.log(data)\n },\n error: function (request, status, error) {\n\n }\n});\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| How do you return a serialized JSON object to the client side using ASP.NET MVC via an AJAX call? | From the controller you can just return a JsonResult:
```
public ActionResult MyAction()
{
... // Populate myObject
return new JsonResult{ Data = myObject };
}
```
The form of the Ajax call will depend on which library you're using, of course. Using jQuery it would be something like:
```
$.getJSON("/controllerName/MyAction", callbackFunction);
```
where the `callbackFunction` takes a parameter which is the data from the XHR request. |
101,174 | <p>In Python there is a really neat function called <code>zip</code> which can be used to iterate through two lists at the same time:</p>
<pre><code>list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
for v1, v2 in zip(list1, list2):
print v1 + " " + v2
</code></pre>
<p>The above code should produce the following:</p>
<pre>1 a
2 b
3 c</pre>
<p>I wonder if there is a method like it available in .Net? I'm thinking about writing it myself, but there is no point if it's already available.</p>
| [
{
"answer_id": 101207,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "<p>Nope, there is no such function in .NET. You have roll out your own. Note that C# doesn't support tuples, so python-like syntax sugar is missing too.</p>\n\n<p>You can use something like this:</p>\n\n<pre><code>class Pair<T1, T2>\n{\n public T1 First { get; set;}\n public T2 Second { get; set;}\n}\n\nstatic IEnumerable<Pair<T1, T2>> Zip<T1, T2>(IEnumerable<T1> first, IEnumerable<T2> second)\n{\n if (first.Count() != second.Count())\n throw new ArgumentException(\"Blah blah\");\n\n using (IEnumerator<T1> e1 = first.GetEnumerator())\n using (IEnumerator<T2> e2 = second.GetEnumerator())\n {\n while (e1.MoveNext() && e2.MoveNext())\n {\n yield return new Pair<T1, T2>() {First = e1.Current, Second = e2.Current};\n }\n }\n}\n\n...\n\nvar ints = new int[] {1, 2, 3};\nvar strings = new string[] {\"A\", \"B\", \"C\"};\n\nforeach (var pair in Zip(ints, strings))\n{\n Console.WriteLine(pair.First + \":\" + pair.Second);\n}\n</code></pre>\n"
},
{
"answer_id": 101222,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 6,
"selected": true,
"text": "<p>Update: It is built-in in C# 4 as <a href=\"https://msdn.microsoft.com/en-us/library/vstudio/dd267698(v=vs.110).aspx\" rel=\"nofollow noreferrer\">System.Linq.Enumerable.Zip Method</a></p>\n\n<p>Here is a C# 3 version:</p>\n\n<pre><code>IEnumerable<TResult> Zip<TResult,T1,T2>\n (IEnumerable<T1> a,\n IEnumerable<T2> b,\n Func<T1,T2,TResult> combine)\n{\n using (var f = a.GetEnumerator())\n using (var s = b.GetEnumerator())\n {\n while (f.MoveNext() && s.MoveNext())\n yield return combine(f.Current, s.Current);\n }\n}\n</code></pre>\n\n<p>Dropped the C# 2 version as it was showing its age.</p>\n"
},
{
"answer_id": 101227,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 3,
"selected": false,
"text": "<p>As far as I know there is not. I wrote one for myself (as well as a few other useful extensions and put them in a project called <a href=\"http://www.codeplex.com/nextension\" rel=\"nofollow noreferrer\">NExtension</a> on Codeplex.</p>\n\n<p>Apparently the Parallel extensions for .NET have a Zip function.</p>\n\n<p>Here's a simplified version from NExtension (but please check it out for more useful extension methods):</p>\n\n<pre><code>public static IEnumerable<TResult> Zip<T1, T2, TResult>(this IEnumerable<T1> source1, IEnumerable<T2> source2, Func<T1, T2, TResult> combine)\n{\n using (IEnumerator<T1> data1 = source1.GetEnumerator())\n using (IEnumerator<T2> data2 = source2.GetEnumerator())\n while (data1.MoveNext() && data2.MoveNext())\n {\n yield return combine(data1.Current, data2.Current);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>int[] list1 = new int[] {1, 2, 3};\nstring[] list2 = new string[] {\"a\", \"b\", \"c\"};\n\nforeach (var result in list1.Zip(list2, (i, s) => i.ToString() + \" \" + s))\n Console.WriteLine(result);\n</code></pre>\n"
},
{
"answer_id": 101284,
"author": "TraumaPony",
"author_id": 18658,
"author_profile": "https://Stackoverflow.com/users/18658",
"pm_score": 2,
"selected": false,
"text": "<p>There's also one in F#:</p>\n\n<p>let zipped = Seq.zip firstEnumeration secondEnumation</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16047/"
]
| In Python there is a really neat function called `zip` which can be used to iterate through two lists at the same time:
```
list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
for v1, v2 in zip(list1, list2):
print v1 + " " + v2
```
The above code should produce the following:
```
1 a
2 b
3 c
```
I wonder if there is a method like it available in .Net? I'm thinking about writing it myself, but there is no point if it's already available. | Update: It is built-in in C# 4 as [System.Linq.Enumerable.Zip Method](https://msdn.microsoft.com/en-us/library/vstudio/dd267698(v=vs.110).aspx)
Here is a C# 3 version:
```
IEnumerable<TResult> Zip<TResult,T1,T2>
(IEnumerable<T1> a,
IEnumerable<T2> b,
Func<T1,T2,TResult> combine)
{
using (var f = a.GetEnumerator())
using (var s = b.GetEnumerator())
{
while (f.MoveNext() && s.MoveNext())
yield return combine(f.Current, s.Current);
}
}
```
Dropped the C# 2 version as it was showing its age. |
101,180 | <p>I need to communicate with an XML-RPC server from a .NET 2.0 client. Can you recommend any libraries?</p>
<p>EDIT: Having tried XML-RPC.Net, I like the way it generates dynamic proxies, it is very neat. Unfortunately, as always, things are not so simple. I am accessing an XML-RPC service which uses the unorthodox technique of having object names in the names of the methods, like so:</p>
<pre><code>object1.object2.someMethod(string1)
</code></pre>
<p>This means I can't use the attributes to set the names of my methods, as they are not known until run-time. If you start trying to get closer to the raw calls, XML-RPC.Net starts to get pretty messy.</p>
<p>So, anyone know of a simple and straightforward XML-RPC library that'll just let me do (pseudocode):</p>
<pre><code>x = new xmlrpc(host, port)
x.makeCall("methodName", "arg1");
</code></pre>
<p>I had a look at a thing by Michael somebody on Codeproject, but there are no unit tests and the code looks pretty dire.</p>
<p>Unless someone has a better idea looks like I am going to have to start an open source project myself!</p>
| [
{
"answer_id": 101204,
"author": "Matthias Kestenholz",
"author_id": 317346,
"author_profile": "https://Stackoverflow.com/users/317346",
"pm_score": 2,
"selected": false,
"text": "<p>I've used the library from <a href=\"http://www.xml-rpc.net/\" rel=\"nofollow noreferrer\">www.xml-rpc.net</a> some time ago with some success and can recommend it -- it did feel well designed and functional.</p>\n"
},
{
"answer_id": 375036,
"author": "Troy J. Farrell",
"author_id": 26244,
"author_profile": "https://Stackoverflow.com/users/26244",
"pm_score": 3,
"selected": true,
"text": "<p>If the method name is all that is changing (i.e., the method signature is static) XML-RPC.NET can handle this for you. This is addressed <a href=\"http://xml-rpc.net/faq/xmlrpcnetfaq.html#2.23\" rel=\"nofollow noreferrer\">in the FAQ</a>, noting \"However, there are some XML-RPC APIs which require the method name to be generated dynamically at runtime...\" From the FAQ:</p>\n\n<pre><code>ISumAndDiff proxy = (ISumAndDiff)XmlRpcProxyGen.Create(typeof(ISumAndDiff));\nproxy.XmlRpcMethod = \"Id1234_SumAndDifference\"\nproxy.SumAndDifference(3, 4);\n</code></pre>\n\n<p>This generates an XmlRpcProxy which implementes the specified interface. Setting the XmlRpcMethod attribute causes methodCalls to use the new method name.</p>\n"
},
{
"answer_id": 1813551,
"author": "Shailesh Kumar",
"author_id": 208890,
"author_profile": "https://Stackoverflow.com/users/208890",
"pm_score": 1,
"selected": false,
"text": "<p>I had also tried to run <a href=\"http://www.xml-rpc.net/\" rel=\"nofollow noreferrer\">www.xml-rpc.net </a> with <a href=\"http://www.mono-project.com/Main_Page\" rel=\"nofollow noreferrer\">Mono </a> on Windows XP and it worked in Mono .NET Runtime also properly. Just for information for everybody. </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16881/"
]
| I need to communicate with an XML-RPC server from a .NET 2.0 client. Can you recommend any libraries?
EDIT: Having tried XML-RPC.Net, I like the way it generates dynamic proxies, it is very neat. Unfortunately, as always, things are not so simple. I am accessing an XML-RPC service which uses the unorthodox technique of having object names in the names of the methods, like so:
```
object1.object2.someMethod(string1)
```
This means I can't use the attributes to set the names of my methods, as they are not known until run-time. If you start trying to get closer to the raw calls, XML-RPC.Net starts to get pretty messy.
So, anyone know of a simple and straightforward XML-RPC library that'll just let me do (pseudocode):
```
x = new xmlrpc(host, port)
x.makeCall("methodName", "arg1");
```
I had a look at a thing by Michael somebody on Codeproject, but there are no unit tests and the code looks pretty dire.
Unless someone has a better idea looks like I am going to have to start an open source project myself! | If the method name is all that is changing (i.e., the method signature is static) XML-RPC.NET can handle this for you. This is addressed [in the FAQ](http://xml-rpc.net/faq/xmlrpcnetfaq.html#2.23), noting "However, there are some XML-RPC APIs which require the method name to be generated dynamically at runtime..." From the FAQ:
```
ISumAndDiff proxy = (ISumAndDiff)XmlRpcProxyGen.Create(typeof(ISumAndDiff));
proxy.XmlRpcMethod = "Id1234_SumAndDifference"
proxy.SumAndDifference(3, 4);
```
This generates an XmlRpcProxy which implementes the specified interface. Setting the XmlRpcMethod attribute causes methodCalls to use the new method name. |
101,184 | <p>I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is. I want to confirm that the database type is indeed Oracle, and if possible, what version of Oracle they are running by sending a SQL statement to the datasource.</p>
| [
{
"answer_id": 101197,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 9,
"selected": true,
"text": "<p>Run this SQL:</p>\n\n<pre><code>select * from v$version;\n</code></pre>\n\n<p>And you'll get a result like: </p>\n\n<pre><code>BANNER\n----------------------------------------------------------------\nOracle Database 10g Release 10.2.0.3.0 - 64bit Production\nPL/SQL Release 10.2.0.3.0 - Production\nCORE 10.2.0.3.0 Production\nTNS for Solaris: Version 10.2.0.3.0 - Production\nNLSRTL Version 10.2.0.3.0 - Production\n</code></pre>\n"
},
{
"answer_id": 101240,
"author": "Peter Lang",
"author_id": 17343,
"author_profile": "https://Stackoverflow.com/users/17343",
"pm_score": 3,
"selected": false,
"text": "<p>You can either use</p>\n\n<pre><code>SELECT * FROM v$version;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>SET SERVEROUTPUT ON\nEXEC dbms_output.put_line( dbms_db_version.version );\n</code></pre>\n\n<p>if you don't want to parse the output of v$version.</p>\n"
},
{
"answer_id": 101248,
"author": "Lawrence",
"author_id": 17621,
"author_profile": "https://Stackoverflow.com/users/17621",
"pm_score": 6,
"selected": false,
"text": "<p>Two methods:</p>\n\n<pre><code>select * from v$version;\n</code></pre>\n\n<p>will give you:</p>\n\n<pre><code>Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - 64bit Production\nPL/SQL Release 11.1.0.6.0 - Production\nCORE 11.1.0.6.0 Production\nTNS for Solaris: Version 11.1.0.6.0 - Production\nNLSRTL Version 11.1.0.6.0 - Production\n</code></pre>\n\n<p>OR <a href=\"https://docs.oracle.com/database/121/ADMIN/dba.htm#ADMIN11032\" rel=\"noreferrer\">Identifying Your Oracle Database Software Release</a>:</p>\n\n<pre><code>select * from product_component_version;\n</code></pre>\n\n<p>will give you:</p>\n\n<pre><code>PRODUCT VERSION STATUS\nNLSRTL 11.1.0.6.0 Production\nOracle Database 11g Enterprise Edition 11.1.0.6.0 64bit Production\nPL/SQL 11.1.0.6.0 Production\nTNS for Solaris: 11.1.0.6.0 Production\n</code></pre>\n"
},
{
"answer_id": 8135737,
"author": "Ugur",
"author_id": 611688,
"author_profile": "https://Stackoverflow.com/users/611688",
"pm_score": 5,
"selected": false,
"text": "<pre><code>SQL> SELECT version FROM v$instance;\nVERSION\n-----------------\n11.2.0.3.0\n</code></pre>\n"
},
{
"answer_id": 16966359,
"author": "user2460369",
"author_id": 2460369,
"author_profile": "https://Stackoverflow.com/users/2460369",
"pm_score": -1,
"selected": false,
"text": "<p>Here's a simple function:</p>\n\n<pre><code>CREATE FUNCTION fn_which_edition\n RETURN VARCHAR2\n IS\n\n /*\n\n Purpose: determine which database edition\n\n MODIFICATION HISTORY\n Person Date Comments\n --------- ------ -------------------------------------------\n dcox 6/6/2013 Initial Build\n\n */\n\n -- Banner\n CURSOR c_get_banner\n IS\n SELECT banner\n FROM v$version\n WHERE UPPER(banner) LIKE UPPER('Oracle Database%');\n\n vrec_banner c_get_banner%ROWTYPE; -- row record\n v_database VARCHAR2(32767); --\n\nBEGIN\n -- Get banner to get edition\n OPEN c_get_banner;\n FETCH c_get_banner INTO vrec_banner;\n CLOSE c_get_banner;\n\n -- Check for Database type\n IF INSTR( UPPER(vrec_banner.banner), 'EXPRESS') > 0\n THEN\n v_database := 'EXPRESS';\n ELSIF INSTR( UPPER(vrec_banner.banner), 'STANDARD') > 0\n THEN\n v_database := 'STANDARD';\n ELSIF INSTR( UPPER(vrec_banner.banner), 'PERSONAL') > 0\n THEN\n v_database := 'PERSONAL';\n ELSIF INSTR( UPPER(vrec_banner.banner), 'ENTERPRISE') > 0\n THEN\n v_database := 'ENTERPRISE';\n ELSE\n v_database := 'UNKNOWN';\n END IF;\n\n RETURN v_database;\nEXCEPTION\n WHEN OTHERS\n THEN\n RETURN 'ERROR:' || SQLERRM(SQLCODE);\nEND fn_which_edition; -- function fn_which_edition\n/\n</code></pre>\n\n<p>Done.</p>\n"
},
{
"answer_id": 23002006,
"author": "user3362908",
"author_id": 3362908,
"author_profile": "https://Stackoverflow.com/users/3362908",
"pm_score": 2,
"selected": false,
"text": "<p>If your instance is down, you are look for version information in alert.log</p>\n\n<p>Or another crude way is to look into Oracle binary, If DB in hosted on Linux, try strings on Oracle binary.</p>\n\n<pre><code>strings -a $ORACLE_HOME/bin/oracle |grep RDBMS | grep RELEASE\n</code></pre>\n"
},
{
"answer_id": 36998091,
"author": "Jack",
"author_id": 4652311,
"author_profile": "https://Stackoverflow.com/users/4652311",
"pm_score": 2,
"selected": false,
"text": "<p>For Oracle use:</p>\n\n<pre><code>Select * from v$version;\n</code></pre>\n\n<p>For SQL server use:</p>\n\n<pre><code>Select @@VERSION as Version\n</code></pre>\n\n<p>and for MySQL use:</p>\n\n<pre><code>Show variables LIKE \"%version%\";\n</code></pre>\n"
},
{
"answer_id": 53619137,
"author": "Pancho",
"author_id": 3051627,
"author_profile": "https://Stackoverflow.com/users/3051627",
"pm_score": 0,
"selected": false,
"text": "<p>The following SQL statement:</p>\n\n<pre><code>select edition,version from v$instance\n</code></pre>\n\n<p>returns:</p>\n\n<ul>\n<li>database edition eg. \"XE\"</li>\n<li>database version eg. \"12.1.0.2.0\"</li>\n</ul>\n\n<p>(select privilege on the v$instance view is of course necessary)</p>\n"
},
{
"answer_id": 55711356,
"author": "Lova Chittumuri",
"author_id": 5256337,
"author_profile": "https://Stackoverflow.com/users/5256337",
"pm_score": 0,
"selected": false,
"text": "<p>We can use the below Methods to get the version Number of Oracle.</p>\n\n<p>Method No : 1</p>\n\n<pre><code>set serveroutput on;\nBEGIN \nDBMS_OUTPUT.PUT_LINE(DBMS_DB_VERSION.VERSION || '.' || DBMS_DB_VERSION.RELEASE); \nEND;\n</code></pre>\n\n<p>Method No : 2</p>\n\n<pre><code>SQL> select *\n 2 from v$version;\n</code></pre>\n"
},
{
"answer_id": 63905716,
"author": "Prokhozhii",
"author_id": 8848025,
"author_profile": "https://Stackoverflow.com/users/8848025",
"pm_score": 0,
"selected": false,
"text": "<p>This will work starting from Oracle 10</p>\n<pre><code>select version\n , regexp_substr(banner, '[^[:space:]]+', 1, 4) as edition \nfrom v$instance\n , v$version where regexp_like(banner, 'edition', 'i');\n</code></pre>\n"
},
{
"answer_id": 64331709,
"author": "santosh tiwary",
"author_id": 9912306,
"author_profile": "https://Stackoverflow.com/users/9912306",
"pm_score": 2,
"selected": false,
"text": "<p>There are different ways to check Oracle Database Version. Easiest way is to run the below SQL query to check <a href=\"https://orahow.com/oracle-plsql-checking-oracle-version-information/\" rel=\"nofollow noreferrer\">Oracle Version</a>.</p>\n<pre>SQL> SELECT * FROM PRODUCT_COMPONENT_VERSION;</pre>\n<pre><code>SQL> SELECT * FROM v$version;\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10750/"
]
| I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is. I want to confirm that the database type is indeed Oracle, and if possible, what version of Oracle they are running by sending a SQL statement to the datasource. | Run this SQL:
```
select * from v$version;
```
And you'll get a result like:
```
BANNER
----------------------------------------------------------------
Oracle Database 10g Release 10.2.0.3.0 - 64bit Production
PL/SQL Release 10.2.0.3.0 - Production
CORE 10.2.0.3.0 Production
TNS for Solaris: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production
``` |
101,198 | <p>I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is. I want to confirm that the database type is indeed Postgres, and if possible, what version of Postgres they are running by sending a SQL statement to the datasource.</p>
| [
{
"answer_id": 101210,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT version();\n</code></pre>\n"
},
{
"answer_id": 101214,
"author": "Matthias Kestenholz",
"author_id": 317346,
"author_profile": "https://Stackoverflow.com/users/317346",
"pm_score": 3,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code>mk=# SELECT version();\n version \n-----------------------------------------------------------------------------------------------\n PostgreSQL 8.3.3 on i486-pc-linux-gnu, compiled by GCC cc (GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu7)\n(1 row)\n</code></pre>\n\n<p>The command works too in MySQL:</p>\n\n<pre><code>mysql> select version();\n+--------------------------------+\n| version() |\n+--------------------------------+\n| 5.0.32-Debian_7etch1~bpo.1-log | \n+--------------------------------+\n1 row in set (0.01 sec)\n</code></pre>\n\n<p>There is no version command in sqlite as far as I can see.</p>\n"
},
{
"answer_id": 101215,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 2,
"selected": false,
"text": "<p>PostgreSQL has a version() function you can call.</p>\n\n<pre><code>SELECT version();\n</code></pre>\n\n<p>It will return something like this:</p>\n\n<pre><code> version\n-----------------------------------------------------------------------------------------------\nPostgreSQL 8.3.3 on i486-pc-linux-gnu, compiled by GCC cc (GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu7)\n</code></pre>\n"
},
{
"answer_id": 101218,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>This is DB dependent, and in case this function exists in another dbms, this says PostgreSQL in the output</p>\n\n<pre><code>select version()\n</code></pre>\n"
},
{
"answer_id": 101253,
"author": "Milen A. Radev",
"author_id": 15785,
"author_profile": "https://Stackoverflow.com/users/15785",
"pm_score": 2,
"selected": false,
"text": "<p><code>SHOW server_version;</code></p>\n\n<p>(for completeness)</p>\n"
},
{
"answer_id": 101269,
"author": "Learning",
"author_id": 18275,
"author_profile": "https://Stackoverflow.com/users/18275",
"pm_score": 0,
"selected": false,
"text": "<p>Interesting ... version() is a function! I wonder why? Version is not going to change or return different values under different inputs/circumstances. </p>\n\n<p>Curious because I remember from old days that in Sybase it used to be a global variable and version could be found out by doing \"select @@version\"</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10750/"
]
| I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is. I want to confirm that the database type is indeed Postgres, and if possible, what version of Postgres they are running by sending a SQL statement to the datasource. | Try this:
```
mk=# SELECT version();
version
-----------------------------------------------------------------------------------------------
PostgreSQL 8.3.3 on i486-pc-linux-gnu, compiled by GCC cc (GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu7)
(1 row)
```
The command works too in MySQL:
```
mysql> select version();
+--------------------------------+
| version() |
+--------------------------------+
| 5.0.32-Debian_7etch1~bpo.1-log |
+--------------------------------+
1 row in set (0.01 sec)
```
There is no version command in sqlite as far as I can see. |
101,212 | <p>Net::HTTP can be rather cumbersome for the standard use case!</p>
| [
{
"answer_id": 101289,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This is what I use: <a href=\"http://rubyforge.org/projects/restful-rails/\" rel=\"nofollow noreferrer\">http://rubyforge.org/projects/restful-rails/</a>.</p>\n"
},
{
"answer_id": 101542,
"author": "Aaron Hinni",
"author_id": 12086,
"author_profile": "https://Stackoverflow.com/users/12086",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://rubyforge.org/projects/rest-open-uri/\" rel=\"noreferrer\">rest-open-uri</a> is the one that is used heavily throughout the <a href=\"http://oreilly.com/catalog/9780596529260/\" rel=\"noreferrer\">RESTful Web Services</a> book.</p>\n\n<pre><code>gem install rest-open-uri\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>response = open('https://wherever/foo',\n :method => :put,\n :http_basic_authentication => ['my-user', 'my-passwd'],\n :body => 'payload')\n\nputs response.read\n</code></pre>\n"
},
{
"answer_id": 101680,
"author": "Clinton Dreisbach",
"author_id": 6262,
"author_profile": "https://Stackoverflow.com/users/6262",
"pm_score": 4,
"selected": false,
"text": "<p>If you only have to deal with REST, the <a href=\"https://github.com/rest-client/rest-client\" rel=\"noreferrer\">rest-client</a> library is fantastic.</p>\n\n<p>If the APIs you're using aren't completely RESTful - or even if they are - <a href=\"http://railstips.org/2008/7/29/it-s-an-httparty-and-everyone-is-invited\" rel=\"noreferrer\">HTTParty</a> is really worth checking out. It simplifies using REST APIs, as well as non-RESTful web APIs. Check out this code (copied from the above link):</p>\n\n<pre><code>require 'rubygems'\nrequire 'httparty'\n\nclass Representative\n include HTTParty\n format :xml\n\n def self.find_by_zip(zip)\n get('http://whoismyrepresentative.com/whoismyrep.php', :query => {:zip => zip})\n end\nend\n\nputs Representative.find_by_zip(46544).inspect\n# {\"result\"=>{\"n\"=>\"1\", \"rep\"=>{\"name\"=>\"Joe Donnelly\", \"district\"=>\"2\", \"office\"=>\"1218 Longworth\", \"phone\"=>\"(202) 225-3915\", \"link\"=>\"http://donnelly.house.gov/\", \"state\"=>\"IN\"}}}\n</code></pre>\n"
},
{
"answer_id": 106229,
"author": "Bill Turner",
"author_id": 17773,
"author_profile": "https://Stackoverflow.com/users/17773",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://github.com/lukegalea/hyperactiveresource/wikis\" rel=\"nofollow noreferrer\">HyperactiveResource</a> is in its infancy, but it's looking pretty good.</p>\n"
},
{
"answer_id": 289786,
"author": "tomtaylor",
"author_id": 19079,
"author_profile": "https://Stackoverflow.com/users/19079",
"pm_score": 2,
"selected": false,
"text": "<p>I'm a big fan of <a href=\"https://github.com/rest-client/rest-client\" rel=\"nofollow noreferrer\">rest-client</a>, which does just enough to be useful without getting in the way of your implementation. It handles exceptions intelligently, and supports logging and auth, out of the box.</p>\n"
},
{
"answer_id": 817969,
"author": "asplake",
"author_id": 51362,
"author_profile": "https://Stackoverflow.com/users/51362",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at asplake's (i.e. my) described_routes and path-to projects/gems on github (which I can't seem to link to from here. Path-to uses HTTParty, but rather than hard-coded URLs like some of the other answers to this question, it uses metadata provided by described_routes. There are several articles describing these gems at positiveincline.com, of which the most relevant to your question is <a href=\"http://positiveincline.com/?p=173\" rel=\"nofollow noreferrer\">Nested path-to/described_routes and HTTParty</a>.</p>\n"
},
{
"answer_id": 1075808,
"author": "asymmetric",
"author_id": 112538,
"author_profile": "https://Stackoverflow.com/users/112538",
"pm_score": 0,
"selected": false,
"text": "<p>Well, there's always ActiveResource, provided you're on Rails :)</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18751/"
]
| Net::HTTP can be rather cumbersome for the standard use case! | If you only have to deal with REST, the [rest-client](https://github.com/rest-client/rest-client) library is fantastic.
If the APIs you're using aren't completely RESTful - or even if they are - [HTTParty](http://railstips.org/2008/7/29/it-s-an-httparty-and-everyone-is-invited) is really worth checking out. It simplifies using REST APIs, as well as non-RESTful web APIs. Check out this code (copied from the above link):
```
require 'rubygems'
require 'httparty'
class Representative
include HTTParty
format :xml
def self.find_by_zip(zip)
get('http://whoismyrepresentative.com/whoismyrep.php', :query => {:zip => zip})
end
end
puts Representative.find_by_zip(46544).inspect
# {"result"=>{"n"=>"1", "rep"=>{"name"=>"Joe Donnelly", "district"=>"2", "office"=>"1218 Longworth", "phone"=>"(202) 225-3915", "link"=>"http://donnelly.house.gov/", "state"=>"IN"}}}
``` |
101,244 | <pre><code>/etc/init.d/*
/etc/rc{1-5}.d/*
</code></pre>
| [
{
"answer_id": 101246,
"author": "px.",
"author_id": 18769,
"author_profile": "https://Stackoverflow.com/users/18769",
"pm_score": 2,
"selected": false,
"text": "<p><code>/sbin/chkconfig</code> — The <code>/sbin/chkconfig</code> utility is a simple command line tool for maintaining the <code>/etc/rc.d/init.d/</code> directory hierarchy. </p>\n"
},
{
"answer_id": 101277,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 1,
"selected": true,
"text": "<p>in one word: <code>init</code>.</p>\n\n<p>This process always has pid of 1 and controls (spawns) all other processes in your unix according to the rules in <code>/etc/init.d</code>.</p>\n\n<p>init is usually called with a number as an argument, e.g. <code>init 3</code> This will make it run the contents of the <code>rc3.d</code> folder.</p>\n\n<p>For more information: <a href=\"http://en.wikipedia.org/wiki/Init\" rel=\"nofollow noreferrer\">Wikipedia article for init</a>.</p>\n\n<p>Edit: Forgot to mention, what actually controls what rc level you start off in is your bootloader.</p>\n"
},
{
"answer_id": 186350,
"author": "jtimberman",
"author_id": 7672,
"author_profile": "https://Stackoverflow.com/users/7672",
"pm_score": 1,
"selected": false,
"text": "<p>As mentioned by px, the proper way to manage the links to scripts from /etc/init.d to /etc/rc?.d is the /sbin/chkconfig command.</p>\n\n<p>Scripts should have comments near the top that specify how chkconfig is to handle them. For example, /etc/init.d/httpd:</p>\n\n<pre><code># chkconfig: - 85 15\n# description: Apache is a World Wide Web server. It is used to serve \\\n# HTML files and CGI.\n# processname: httpd\n# config: /etc/httpd/conf/httpd.conf\n# config: /etc/sysconfig/httpd\n# pidfile: /var/run/httpd.pid\n</code></pre>\n\n<p>Also, use the /sbin/service command to start and stop services when run from the shell.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18769/"
]
| ```
/etc/init.d/*
/etc/rc{1-5}.d/*
``` | in one word: `init`.
This process always has pid of 1 and controls (spawns) all other processes in your unix according to the rules in `/etc/init.d`.
init is usually called with a number as an argument, e.g. `init 3` This will make it run the contents of the `rc3.d` folder.
For more information: [Wikipedia article for init](http://en.wikipedia.org/wiki/Init).
Edit: Forgot to mention, what actually controls what rc level you start off in is your bootloader. |
101,258 | <p>I want to search for <code>$maximumTotalAllowedAfterFinish</code> and replace it with <code>$minimumTotalAllowedAfterFinish</code>. Instead of typing the long text:</p>
<pre><code>:%s/$maximumTotalAllowedAfterFinish/$minimumTotalAllowedAfterFinish/g
</code></pre>
<p>Is there a way to COPY these long variable names down into the search line, since, on the command line I can't type "<code>p</code>" to paste?</p>
| [
{
"answer_id": 101281,
"author": "Johannes Hoff",
"author_id": 3102,
"author_profile": "https://Stackoverflow.com/users/3102",
"pm_score": 4,
"selected": false,
"text": "<p>Type <code>q:</code> to get into history editing mode in a new buffer. Then edit the last line of the buffer and press <code>Enter</code> to execute it.</p>\n"
},
{
"answer_id": 101285,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<p>Typically, you would do that with mouse selecting (perhaps <kbd>Ctrl</kbd><kbd>Ins</kbd> or <kbd>Ctrl</kbd><kbd>C</kbd> after selecting) and then, when in the command/search line, middle-clicking (or <kbd>Shift</kbd><kbd>Ins</kbd> or <kbd>Ctrl</kbd><kbd>V</kbd>).</p>\n\n<p>Another way, is to write your command/search line in the text buffer with all the editing available in text buffers, starting with <code>:</code> and all, then, on the line, do:</p>\n\n<pre><code>\"add@a\n</code></pre>\n\n<p>which will store the whole command line in buffer <code>a</code>, and then execute it. It won't be stored in the command history, though.</p>\n\n<p>Try creating the following line in the text buffer as an example for the key presses above:</p>\n\n<pre><code>:%s/$maximumTotalAllowedAfterFinish/$minimumTotalAllowedAfterFinish/g\n</code></pre>\n\n<p>Finally, you can enter <code>q:</code> to enter history editing in a text buffer.</p>\n"
},
{
"answer_id": 101292,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 8,
"selected": true,
"text": "<p>You can insert the contents of a numbered or named register by typing <kbd>CTRL</kbd><kbd>R</kbd> <kbd><code>{0-9a-z\"%#:-=.}</code></kbd>. By typing <kbd>CTRL-R</kbd> <kbd>CTRL-W</kbd> you can paste the current word under the cursor. See:</p>\n\n<pre><code>:he cmdline-editing\n</code></pre>\n\n<p>for more information.</p>\n"
},
{
"answer_id": 101312,
"author": "Ned",
"author_id": 1105,
"author_profile": "https://Stackoverflow.com/users/1105",
"pm_score": 6,
"selected": false,
"text": "<p>Copy it as normal, then do <kbd>Ctrl</kbd><kbd>R</kbd><kbd>\"</kbd> to paste. There are lots of other <kbd>Ctrl</kbd><kbd>R</kbd> shortcuts (e.g, a calculator, current filename, clipboard contents). Type <code>:help c_<C-R></code> to see the full list.</p>\n"
},
{
"answer_id": 101682,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 2,
"selected": false,
"text": "<p>Or create the command in a vim buffer , e.g. type it in the buffer:</p>\n\n<pre><code>s/foo/bar/gci\n</code></pre>\n\n<p>And copy it to a named register, with <code>\"ayy</code> (if the cursor is on that line!).</p>\n\n<p>Now you can execute the contents of the \"<code>a</code>\" register from Vim's Ex command line with:</p>\n\n<pre><code>:[OPTIONAL_RANGE]@a\n</code></pre>\n\n<p>I use it all the time.</p>\n"
},
{
"answer_id": 43527298,
"author": "Jason",
"author_id": 2218905,
"author_profile": "https://Stackoverflow.com/users/2218905",
"pm_score": 5,
"selected": false,
"text": "<p>Copy:<br/>\n1) <code>v</code> (or highlight with mouse, in visual mode) <br/>\n2) <code>y</code> (yank)<br/></p>\n\n<p>Paste:<br/>\n1) <code>/</code> (search mode)<br/>\n2) <code>Ctrl + R + 0</code> (paste from yanked register)<br/></p>\n"
},
{
"answer_id": 48702485,
"author": "boosted regressor",
"author_id": 9337601,
"author_profile": "https://Stackoverflow.com/users/9337601",
"pm_score": 2,
"selected": false,
"text": "<p>You can place the cursor on the word that you want to add to your pattern and then press <kbd>/</kbd> or <kbd>:</kbd> to enter either the search or the command mode, and then press <kbd>Ctrl</kbd><kbd>R</kbd><kbd>Ctrl</kbd><kbd>W</kbd> to copy the word. <a href=\"http://www.commandlinefu.com/commands/view/1870/bring-the-word-under-the-cursor-on-the-ex-line-in-vim\" rel=\"nofollow noreferrer\">Source</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
]
| I want to search for `$maximumTotalAllowedAfterFinish` and replace it with `$minimumTotalAllowedAfterFinish`. Instead of typing the long text:
```
:%s/$maximumTotalAllowedAfterFinish/$minimumTotalAllowedAfterFinish/g
```
Is there a way to COPY these long variable names down into the search line, since, on the command line I can't type "`p`" to paste? | You can insert the contents of a numbered or named register by typing `CTRL``R` ``{0-9a-z"%#:-=.}``. By typing `CTRL-R` `CTRL-W` you can paste the current word under the cursor. See:
```
:he cmdline-editing
```
for more information. |
101,265 | <p>Inspired by another question asking about the missing <code>Zip</code> function:</p>
<p>Why is there no <code>ForEach</code> extension method on the <code>IEnumerable</code> interface? Or anywhere? The only class that gets a <code>ForEach</code> method is <code>List<></code>. Is there a reason why it's missing, maybe performance?</p>
| [
{
"answer_id": 101274,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 2,
"selected": false,
"text": "<p>Most of the LINQ extension methods return results. ForEach does not fit into this pattern as it returns nothing.</p>\n"
},
{
"answer_id": 101278,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 6,
"selected": false,
"text": "<p>ForEach method was added before LINQ. If you add ForEach extension, it will never be called for List instances because of extension methods constraints. I think the reason it was not added is to not interference with existing one.</p>\n\n<p>However, if you really miss this little nice function, you can roll out your own version</p>\n\n<pre><code>public static void ForEach<T>(\n this IEnumerable<T> source,\n Action<T> action)\n{\n foreach (T element in source) \n action(element);\n}\n</code></pre>\n"
},
{
"answer_id": 101303,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 4,
"selected": false,
"text": "<p>I've always wondered that myself, that is why that I always carry this with me:</p>\n\n<pre><code>public static void ForEach<T>(this IEnumerable<T> col, Action<T> action)\n{\n if (action == null)\n {\n throw new ArgumentNullException(\"action\");\n }\n foreach (var item in col)\n {\n action(item);\n }\n}\n</code></pre>\n\n<p>Nice little extension method.</p>\n"
},
{
"answer_id": 101313,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 9,
"selected": true,
"text": "<p>There is already a <code>foreach</code> statement included in the language that does the job most of the time.</p>\n<p>I'd hate to see the following:</p>\n<pre><code>list.ForEach( item =>\n{\n item.DoSomething();\n} );\n</code></pre>\n<p>Instead of:</p>\n<pre><code>foreach(Item item in list)\n{\n item.DoSomething();\n}\n</code></pre>\n<p>The latter is clearer and easier to read <strong>in most situations</strong>, although maybe a bit longer to type.</p>\n<p>However, I must admit I changed my stance on that issue; a <code>ForEach()</code> extension method would indeed be useful in some situations.</p>\n<p>Here are the major differences between the statement and the method:</p>\n<ul>\n<li>Type checking: foreach is done at runtime, <code>ForEach()</code> is at compile time (Big Plus!)</li>\n<li>The syntax to call a delegate is indeed much simpler: objects.ForEach(DoSomething);</li>\n<li>ForEach() could be chained: although evilness/usefulness of such a feature is open to discussion.</li>\n</ul>\n<p>Those are all great points made by many people here and I can see why people are missing the function. I wouldn't mind Microsoft adding a standard ForEach method in the next framework iteration.</p>\n"
},
{
"answer_id": 101331,
"author": "TraumaPony",
"author_id": 18658,
"author_profile": "https://Stackoverflow.com/users/18658",
"pm_score": 2,
"selected": false,
"text": "<p>If you have F# (which will be in the next version of .NET), you can use</p>\n\n<p><code>Seq.iter doSomething myIEnumerable</code></p>\n"
},
{
"answer_id": 101781,
"author": "user18784",
"author_id": 18784,
"author_profile": "https://Stackoverflow.com/users/18784",
"pm_score": 2,
"selected": false,
"text": "<p>Is it me or is the List<T>.Foreach pretty much been made obsolete by Linq. \nOriginally there was </p>\n\n<pre><code>foreach(X x in Y) \n</code></pre>\n\n<p>where Y simply had to be IEnumerable (Pre 2.0), and implement a GetEnumerator().\nIf you look at the MSIL generated you can see that it is exactly the same as</p>\n\n<pre><code>IEnumerator<int> enumerator = list.GetEnumerator();\nwhile (enumerator.MoveNext())\n{\n int i = enumerator.Current;\n\n Console.WriteLine(i);\n}\n</code></pre>\n\n<p>(See <a href=\"http://alski.net/post/0a-for-foreach-forFirst-forLast0a-0a-.aspx\" rel=\"nofollow noreferrer\">http://alski.net/post/0a-for-foreach-forFirst-forLast0a-0a-.aspx</a> for the MSIL)</p>\n\n<p>Then in DotNet2.0 Generics came along and the List. Foreach has always felt to me to be an implementation of the Vistor pattern, (see Design Patterns by Gamma, Helm, Johnson, Vlissides).</p>\n\n<p>Now of course in 3.5 we can instead use a Lambda to the same effect, for an example try \n<a href=\"http://dotnet-developments.blogs.techtarget.com/2008/09/02/iterators-lambda-and-linq-oh-my/\" rel=\"nofollow noreferrer\">http://dotnet-developments.blogs.techtarget.com/2008/09/02/iterators-lambda-and-linq-oh-my/</a></p>\n"
},
{
"answer_id": 102092,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 3,
"selected": false,
"text": "<p>So there has been a lot of comments about the fact that a ForEach extension method isn't appropriate because it doesn't return a value like the LINQ extension methods. While this is a factual statement, it isn't entirely true.</p>\n\n<p>The LINQ extension methods do all return a value so they can be chained together:</p>\n\n<pre><code>collection.Where(i => i.Name = \"hello\").Select(i => i.FullName);\n</code></pre>\n\n<p>However, just because LINQ is implemented using extension methods does not mean that extension methods <strong>must</strong> be used in the same way and return a value. Writing an extension method to expose common functionality that does not return a value is a perfectly valid use.</p>\n\n<p>The specific arguement about ForEach is that, based on the constraints on extension methods (namely that an extension method will <strong>never</strong> override an inherited method with the <strong>same signature</strong>), there may be a situation where the custom extension method is available on all classes that impelement IEnumerable<code><T</code>> except List<code><T</code>>. This can cause confusion when the methods start to behave differently depending on whether or not the extension method or the inherit method is being called.</p>\n"
},
{
"answer_id": 102123,
"author": "Paco",
"author_id": 13376,
"author_profile": "https://Stackoverflow.com/users/13376",
"pm_score": 2,
"selected": false,
"text": "<p>You can use select when you want to return something.\nIf you don't, you can use ToList first, because you probably don't want to modify anything in the collection.</p>\n"
},
{
"answer_id": 102512,
"author": "Chris Zwiryk",
"author_id": 734,
"author_profile": "https://Stackoverflow.com/users/734",
"pm_score": 5,
"selected": false,
"text": "<p>While I agree that it's better to use the built-in <code>foreach</code> construct in most cases, I find the use of this variation on the ForEach<> extension to be a little nicer than having to manage the index in a regular <code>foreach</code> myself:</p>\n\n<pre><code>public static int ForEach<T>(this IEnumerable<T> list, Action<int, T> action)\n{\n if (action == null) throw new ArgumentNullException(\"action\");\n\n var index = 0;\n\n foreach (var elem in list)\n action(index++, elem);\n\n return index;\n}\n</code></pre>\n\nExample\n\n<pre><code>var people = new[] { \"Moe\", \"Curly\", \"Larry\" };\npeople.ForEach((i, p) => Console.WriteLine(\"Person #{0} is {1}\", i, p));\n</code></pre>\n\n<p>Would give you:</p>\n\n<pre><code>Person #0 is Moe\nPerson #1 is Curly\nPerson #2 is Larry\n</code></pre>\n"
},
{
"answer_id": 195333,
"author": "mancaus",
"author_id": 13797,
"author_profile": "https://Stackoverflow.com/users/13797",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/2dddb3b1-5ea3-41a6-880a-f994acf0a68b/\" rel=\"noreferrer\">The discussion here</a> gives the answer:</p>\n\n<blockquote>\n <p>Actually, the specific discussion I witnessed did in fact hinge over functional purity. In an expression, there are frequently assumptions made about not having side-effects. Having ForEach is specifically inviting side-effects rather than just putting up with them. -- Keith Farmer (Partner)</p>\n</blockquote>\n\n<p>Basically the decision was made to keep the extension methods functionally \"pure\". A ForEach would encourage side-effects when using the Enumerable extension methods, which was not the intent.</p>\n"
},
{
"answer_id": 216654,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 4,
"selected": false,
"text": "<p>One workaround is to write <code>.ToList().ForEach(x => ...)</code>. </p>\n\n<p><strong>pros</strong></p>\n\n<p>Easy to understand - reader only needs to know what ships with C#, not any additional extension methods.</p>\n\n<p>Syntactic noise is very mild (only adds a little extranious code).</p>\n\n<p>Doesn't usually cost extra memory, since a native <code>.ForEach()</code> would have to realize the whole collection, anyway.</p>\n\n<p><strong>cons</strong></p>\n\n<p>Order of operations isn't ideal. I'd rather realize one element, then act on it, then repeat. This code realizes all elements first, then acts on them each in sequence.</p>\n\n<p>If realizing the list throws an exception, you never get to act on a single element.</p>\n\n<p>If the enumeration is infinite (like the natural numbers), you're out of luck.</p>\n"
},
{
"answer_id": 216668,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 6,
"selected": false,
"text": "<p>You could write this extension method:</p>\n\n<pre><code>// Possibly call this \"Do\"\nIEnumerable<T> Apply<T> (this IEnumerable<T> source, Action<T> action)\n{\n foreach (var e in source)\n {\n action(e);\n yield return e;\n }\n}\n</code></pre>\n\n<p><strong>Pros</strong></p>\n\n<p>Allows chaining:</p>\n\n<pre><code>MySequence\n .Apply(...)\n .Apply(...)\n .Apply(...);\n</code></pre>\n\n<p><strong>Cons</strong></p>\n\n<p>It won't actually do anything until you do something to force iteration. For that reason, it shouldn't be called <code>.ForEach()</code>. You could write <code>.ToList()</code> at the end, or you could write this extension method, too:</p>\n\n<pre><code>// possibly call this \"Realize\"\nIEnumerable<T> Done<T> (this IEnumerable<T> source)\n{\n foreach (var e in source)\n {\n // do nothing\n ;\n }\n\n return source;\n}\n</code></pre>\n\n<p>This may be too significant a departure from the shipping C# libraries; readers who are not familiar with your extension methods won't know what to make of your code.</p>\n"
},
{
"answer_id": 255500,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>@Coincoin</p>\n\n<p>The real power of the foreach extension method involves reusability of the <code>Action<></code> without adding unnecessary methods to your code. Say that you have 10 lists and you want to perform the same logic on them, and a corresponding function doesn't fit into your class and is not reused. Instead of having ten for loops, or a generic function that is obviously a helper that doesn't belong, you can keep all of your logic in one place (the <code>Action<></code>. So, dozens of lines get replaced with</p>\n\n<pre><code>Action<blah,blah> f = { foo };\n\nList1.ForEach(p => f(p))\nList2.ForEach(p => f(p))\n</code></pre>\n\n<p>etc...</p>\n\n<p>The logic is in one place and you haven't polluted your class.</p>\n"
},
{
"answer_id": 280569,
"author": "Squirrel",
"author_id": 11835,
"author_profile": "https://Stackoverflow.com/users/11835",
"pm_score": -1,
"selected": false,
"text": "<p>No one has yet pointed out that ForEach<T> results in compile time type checking where the foreach keyword is runtime checked.</p>\n\n<p>Having done some refactoring where both methods were used in the code, I favor .ForEach, as I had to hunt down test failures / runtime failures to find the foreach problems.</p>\n"
},
{
"answer_id": 501571,
"author": "Kirill Osenkov",
"author_id": 37899,
"author_profile": "https://Stackoverflow.com/users/37899",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote a blog post about it:\n<a href=\"http://blogs.msdn.com/kirillosenkov/archive/2009/01/31/foreach.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/kirillosenkov/archive/2009/01/31/foreach.aspx</a></p>\n\n<p>You can vote here if you'd like to see this method in .NET 4.0:\n<a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=279093\" rel=\"nofollow noreferrer\">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=279093</a></p>\n"
},
{
"answer_id": 1716623,
"author": "Neil",
"author_id": 24315,
"author_profile": "https://Stackoverflow.com/users/24315",
"pm_score": 2,
"selected": false,
"text": "<p>In 3.5, all the extension methods added to IEnumerable are there for LINQ support (notice that they are defined in the System.Linq.Enumerable class). In this post, I explain why foreach doesn't belong in LINQ: \n<a href=\"https://stackoverflow.com/questions/317874/existing-linq-extension-method-similar-to-parallel-for/318493#318493\">Existing LINQ extension method similar to Parallel.For?</a></p>\n"
},
{
"answer_id": 14997597,
"author": "Martijn",
"author_id": 381801,
"author_profile": "https://Stackoverflow.com/users/381801",
"pm_score": 3,
"selected": false,
"text": "<p>You could use the (chainable, but lazily evaluated) <code>Select</code>, first doing your operation, and then returning identity (or something else if you prefer)</p>\n\n<pre><code>IEnumerable<string> people = new List<string>(){\"alica\", \"bob\", \"john\", \"pete\"};\npeople.Select(p => { Console.WriteLine(p); return p; });\n</code></pre>\n\n<p>You will need to make sure it is still evaluated, either with <code>Count()</code> (the cheapest operation to enumerate afaik) or another operation you needed anyway.</p>\n\n<p>I would love to see it brought in to the standard library though:</p>\n\n<pre><code>static IEnumerable<T> WithLazySideEffect(this IEnumerable<T> src, Action<T> action) {\n return src.Select(i => { action(i); return i; } );\n}\n</code></pre>\n\n<p>The above code then becomes <code>people.WithLazySideEffect(p => Console.WriteLine(p))</code> which is effectively equivalent to foreach, but lazy and chainable.</p>\n"
},
{
"answer_id": 20873090,
"author": "Dave Clausen",
"author_id": 394007,
"author_profile": "https://Stackoverflow.com/users/394007",
"pm_score": 3,
"selected": false,
"text": "<p>Note that the <strong>MoreLINQ</strong> NuGet provides the <code>ForEach</code> extension method you're looking for (as well as a <code>Pipe</code> method which executes the delegate and yields its result). See:</p>\n\n<ul>\n<li><a href=\"https://www.nuget.org/packages/morelinq\" rel=\"noreferrer\">https://www.nuget.org/packages/morelinq</a></li>\n<li><a href=\"https://code.google.com/p/morelinq/wiki/OperatorsOverview\" rel=\"noreferrer\">https://code.google.com/p/morelinq/wiki/OperatorsOverview</a></li>\n</ul>\n"
},
{
"answer_id": 35456376,
"author": "fredefox",
"author_id": 1021134,
"author_profile": "https://Stackoverflow.com/users/1021134",
"pm_score": 2,
"selected": false,
"text": "<p>I would like to expand on <a href=\"https://stackoverflow.com/a/216668/1021134\">Aku's answer</a>.</p>\n\n<p>If you want to call a method for the sole purpose of it's side-effect without iterating the whole enumerable first you can use this:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>private static IEnumerable<T> ForEach<T>(IEnumerable<T> xs, Action<T> f) {\n foreach (var x in xs) {\n f(x); yield return x;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 52800192,
"author": "McKay",
"author_id": 8384,
"author_profile": "https://Stackoverflow.com/users/8384",
"pm_score": 2,
"selected": false,
"text": "<p>Partially it's because the language designers disagree with it from a philosophical perspective.</p>\n\n<ul>\n<li>Not having (and testing...) a feature is less work than having a feature.</li>\n<li>It's not really shorter (there's some passing function cases where it is, but that wouldn't be the primary use).</li>\n<li>It's purpose is to have side effects, which isn't what linq is about.</li>\n<li>Why have another way to do the same thing as a feature we've already got? (foreach keyword)</li>\n</ul>\n\n<p><a href=\"https://blogs.msdn.microsoft.com/ericlippert/2009/05/18/foreach-vs-foreach/\" rel=\"nofollow noreferrer\">https://blogs.msdn.microsoft.com/ericlippert/2009/05/18/foreach-vs-foreach/</a></p>\n"
},
{
"answer_id": 67588800,
"author": "Liran Barniv",
"author_id": 1552782,
"author_profile": "https://Stackoverflow.com/users/1552782",
"pm_score": 0,
"selected": false,
"text": "<p>My version an extension method which would allow you to use ForEach on IEnumerable of T</p>\n<pre><code>public static class EnumerableExtension\n{\n public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)\n {\n source.All(x =>\n {\n action.Invoke(x);\n return true;\n });\n }\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3820/"
]
| Inspired by another question asking about the missing `Zip` function:
Why is there no `ForEach` extension method on the `IEnumerable` interface? Or anywhere? The only class that gets a `ForEach` method is `List<>`. Is there a reason why it's missing, maybe performance? | There is already a `foreach` statement included in the language that does the job most of the time.
I'd hate to see the following:
```
list.ForEach( item =>
{
item.DoSomething();
} );
```
Instead of:
```
foreach(Item item in list)
{
item.DoSomething();
}
```
The latter is clearer and easier to read **in most situations**, although maybe a bit longer to type.
However, I must admit I changed my stance on that issue; a `ForEach()` extension method would indeed be useful in some situations.
Here are the major differences between the statement and the method:
* Type checking: foreach is done at runtime, `ForEach()` is at compile time (Big Plus!)
* The syntax to call a delegate is indeed much simpler: objects.ForEach(DoSomething);
* ForEach() could be chained: although evilness/usefulness of such a feature is open to discussion.
Those are all great points made by many people here and I can see why people are missing the function. I wouldn't mind Microsoft adding a standard ForEach method in the next framework iteration. |
101,267 | <p>When I used to write libraries in C/C++ I got into the habit of having a method to return the compile date/time. This was always a compiled into the library so would differentiate builds of the library. I got this by returning a #define in the code:</p>
<p>C++:</p>
<pre><code>#ifdef _BuildDateTime_
char* SomeClass::getBuildDateTime() {
return _BuildDateTime_;
}
#else
char* SomeClass::getBuildDateTime() {
return "Undefined";
}
#endif
</code></pre>
<p>Then on the compile I had a '-D_BuildDateTime_=<code>Date</code>' in the build script.</p>
<p>Is there any way to achieve this or similar in Java without needing to remember to edit any files manually or distributing any seperate files.</p>
<p>One suggestion I got from a co-worker was to get the ant file to create a file on the classpath and to package that into the JAR and have it read by the method. </p>
<p>Something like (assuming the file created was called 'DateTime.dat'):</p>
<pre><code>// I know Exceptions and proper open/closing
// of the file are not done. This is just
// to explain the point!
String getBuildDateTime() {
return new BufferedReader(getClass()
.getResourceAsStream("DateTime.dat")).readLine();
}
</code></pre>
<p>To my mind that's a hack and could be circumvented/broken by someone having a similarly named file <em>outside</em> the JAR, but on the classpath.</p>
<p>Anyway, my question is whether there is any way to inject a constant into a class at compile time</p>
<p>EDIT</p>
<p>The reason I consider using an externally generated file in the JAR a hack is because this <em>is</em>) a library and will be embedded in client apps. These client apps may define their own classloaders meaning I can't rely on the standard JVM class loading rules.</p>
<p>My personal preference would be to go with using the date from the JAR file as suggested by serg10.</p>
| [
{
"answer_id": 101293,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 1,
"selected": false,
"text": "<p>Unless you want to run your Java source through a C/C++ Preprocessor (which is a BIG NO-NO), use the jar method. There are other ways to get the correct resources out of a jar to make sure someone didn't put a duplicate resource on the classpath. You could also consider using the Jar manifest for this. My project does exactly what you're trying to do (with build dates, revisions, author, etc) using the manifest.</p>\n\n<p>You'll want to use this:</p>\n\n<pre><code>Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(\"META-INF/MANIFEST.MF\");\n</code></pre>\n\n<p>This will get you ALL of the manifests on the classpath. You can figure out which jar they can from by parsing the URL.</p>\n"
},
{
"answer_id": 101323,
"author": "jon",
"author_id": 12215,
"author_profile": "https://Stackoverflow.com/users/12215",
"pm_score": 2,
"selected": false,
"text": "<p>AFAIK there is not a way to do this with javac. This can easily be done with Ant -- I would create a first class object called BuildTimestamp.java and generate that file at compile time via an Ant target. </p>\n\n<p><a href=\"http://ant.apache.org/manual/Types/filterchain.html#replacetokens\" rel=\"nofollow noreferrer\">Here's an Ant type</a> that will be helpful.</p>\n"
},
{
"answer_id": 101334,
"author": "MB.",
"author_id": 11961,
"author_profile": "https://Stackoverflow.com/users/11961",
"pm_score": 1,
"selected": false,
"text": "<p>Personally I'd go for a separate properties file in your jar that you'd load at runtime... The classloader has a defined order for searching for files - I can't remember how it works exactly off hand, but I don't think another file with the same name somewhere on the classpath would be likely to cause issues.</p>\n\n<p>But another way you could do it would be to use Ant to copy your .java files into a different directory before compiling them, filtering in String constants as appropriate. You could use something like:</p>\n\n<pre><code>public String getBuildDateTime() {\n return \"@BUILD_DATE_TIME@\";\n}\n</code></pre>\n\n<p>and write a filter in your Ant file to replace that with a build property.</p>\n"
},
{
"answer_id": 101355,
"author": "Paul A. Hoadley",
"author_id": 18493,
"author_profile": "https://Stackoverflow.com/users/18493",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>One suggestion I got from a co-worker\n was to get the ant file to create a\n file on the classpath and to package\n that into the JAR and have it read by\n the method. ... To my mind that's a\n hack and could be circumvented/broken\n by someone having a similarly named\n file outside the JAR, but on the\n classpath.</p>\n</blockquote>\n\n<p>I'm not sure that getting Ant to generate a file is a terribly egregious hack, if it's a hack at all. Why not generate a properties file and use <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html\" rel=\"nofollow noreferrer\">java.util.Properties</a> to handle it?</p>\n"
},
{
"answer_id": 101359,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps a more Java-style way of indicating your library's version would be to add a version number to the JAR's manifest, as described in the <a href=\"http://java.sun.com/developer/Books/javaprogramming/JAR/basics/manifest.html\" rel=\"nofollow noreferrer\">manifest documentation</a>.</p>\n"
},
{
"answer_id": 101376,
"author": "Karl",
"author_id": 17613,
"author_profile": "https://Stackoverflow.com/users/17613",
"pm_score": 4,
"selected": false,
"text": "<p>I remember seeing something similar in an open source project:</p>\n\n<pre><code>class Version... {\n public static String tstamp() {\n return \"@BUILDTIME@\";\n }\n}\n</code></pre>\n\n<p>in a template file. With Ant's filtering copy you can give this macro a value:</p>\n\n<pre><code><copy src=\"templatefile\" dst=\"Version.java\" filtering=\"true\">\n <filter token=\"BUILDTIME\" value=\"${build.tstamp}\" />\n</copy>\n</code></pre>\n\n<p>use this to create a Version.java source file in your build process, before the compilation step.</p>\n"
},
{
"answer_id": 102747,
"author": "serg10",
"author_id": 1853,
"author_profile": "https://Stackoverflow.com/users/1853",
"pm_score": 5,
"selected": true,
"text": "<p><strong>I would favour the standards based approach.</strong> Put your version information (along with other useful publisher stuff such as build number, subversion revision number, author, company details, etc) in the jar's <a href=\"http://java.sun.com/developer/Books/javaprogramming/JAR/basics/manifest.html\" rel=\"noreferrer\">Manifest File</a>. </p>\n\n<p><strong>This is a well documented and understood Java specification.</strong> Strong tool support exists for creating manifest files (a <a href=\"http://ant.apache.org/manual/Tasks/manifest.html\" rel=\"noreferrer\">core Ant task</a> for example, or the <a href=\"http://maven.apache.org/plugins/maven-jar-plugin/\" rel=\"noreferrer\">maven jar plugin</a>). These can help with setting some of the attributes automatically - I have maven configured to put the jar's maven version number, Subversion revision and timestamp into the manifest for me at build time.</p>\n\n<p>You can read the contents of the manifest at runtime with standard java api calls - something like:</p>\n\n<pre><code>import java.util.jar.*;\n\n...\n\nJarFile myJar = new JarFile(\"nameOfJar.jar\"); // various constructors available\nManifest manifest = myJar.getManifest();\nMap<String,Attributes> manifestContents = manifest.getAttributes();\n</code></pre>\n\n<p>To me, that feels like a more Java standard approach, so will probably prove more easy for subsequent code maintainers to follow.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18744/"
]
| When I used to write libraries in C/C++ I got into the habit of having a method to return the compile date/time. This was always a compiled into the library so would differentiate builds of the library. I got this by returning a #define in the code:
C++:
```
#ifdef _BuildDateTime_
char* SomeClass::getBuildDateTime() {
return _BuildDateTime_;
}
#else
char* SomeClass::getBuildDateTime() {
return "Undefined";
}
#endif
```
Then on the compile I had a '-D\_BuildDateTime\_=`Date`' in the build script.
Is there any way to achieve this or similar in Java without needing to remember to edit any files manually or distributing any seperate files.
One suggestion I got from a co-worker was to get the ant file to create a file on the classpath and to package that into the JAR and have it read by the method.
Something like (assuming the file created was called 'DateTime.dat'):
```
// I know Exceptions and proper open/closing
// of the file are not done. This is just
// to explain the point!
String getBuildDateTime() {
return new BufferedReader(getClass()
.getResourceAsStream("DateTime.dat")).readLine();
}
```
To my mind that's a hack and could be circumvented/broken by someone having a similarly named file *outside* the JAR, but on the classpath.
Anyway, my question is whether there is any way to inject a constant into a class at compile time
EDIT
The reason I consider using an externally generated file in the JAR a hack is because this *is*) a library and will be embedded in client apps. These client apps may define their own classloaders meaning I can't rely on the standard JVM class loading rules.
My personal preference would be to go with using the date from the JAR file as suggested by serg10. | **I would favour the standards based approach.** Put your version information (along with other useful publisher stuff such as build number, subversion revision number, author, company details, etc) in the jar's [Manifest File](http://java.sun.com/developer/Books/javaprogramming/JAR/basics/manifest.html).
**This is a well documented and understood Java specification.** Strong tool support exists for creating manifest files (a [core Ant task](http://ant.apache.org/manual/Tasks/manifest.html) for example, or the [maven jar plugin](http://maven.apache.org/plugins/maven-jar-plugin/)). These can help with setting some of the attributes automatically - I have maven configured to put the jar's maven version number, Subversion revision and timestamp into the manifest for me at build time.
You can read the contents of the manifest at runtime with standard java api calls - something like:
```
import java.util.jar.*;
...
JarFile myJar = new JarFile("nameOfJar.jar"); // various constructors available
Manifest manifest = myJar.getManifest();
Map<String,Attributes> manifestContents = manifest.getAttributes();
```
To me, that feels like a more Java standard approach, so will probably prove more easy for subsequent code maintainers to follow. |
101,268 | <p>What are the lesser-known but useful features of the Python programming language?</p>
<ul>
<li>Try to limit answers to Python core.</li>
<li>One feature per answer.</li>
<li>Give an example and short description of the feature, not just a link to documentation.</li>
<li>Label the feature using a title as the first line.</li>
</ul>
<h2>Quick links to answers:</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#111176">Argument Unpacking</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#112303">Braces</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101945">Chaining Comparison Operators</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101447">Decorators</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#113198">Default Argument Gotchas / Dangers of Mutable Default arguments</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#102062">Descriptors</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#111970">Dictionary default <code>.get</code> value</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#102065">Docstring Tests</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python/112316#112316">Ellipsis Slicing Syntax</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#117116">Enumeration</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#114420">For/else</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#102202">Function as iter() argument</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101310">Generator expressions</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101276"><code>import this</code></a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#102037">In Place Value Swapping</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101840">List stepping</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#112286"><code>__missing__</code> items</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101537">Multi-line Regex</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#113164">Named string formatting</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101549">Nested list/generator comprehensions</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#108297">New types at runtime</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#113833"><code>.pth</code> files</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#1024693">ROT13 Encoding</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#143636">Regex Debugging</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#101739">Sending to Generators</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#168270">Tab Completion in Interactive Interpreter</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#116480">Ternary Expression</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#114157"><code>try/except/else</code></a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#3267903">Unpacking+<code>print()</code> function</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python#109182"><code>with</code> statement</a></li>
</ul>
| [
{
"answer_id": 101276,
"author": "cleg",
"author_id": 29503,
"author_profile": "https://Stackoverflow.com/users/29503",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Main messages :)</strong></p>\n\n<pre><code>import this\n# btw look at this module's source :)\n</code></pre>\n\n<hr>\n\n<p><a href=\"http://svn.python.org/view/python/trunk/Lib/this.py?view=markup\" rel=\"nofollow noreferrer\">De-cyphered</a>:</p>\n\n<blockquote>\n <p>The Zen of Python, by Tim Peters </p>\n \n <p>Beautiful is better than ugly.<br>\n Explicit is better than implicit.<br>\n Simple is better than complex.<br>\n Complex is better than complicated.<br>\n Flat is better than nested.<br>\n Sparse is better than dense.<br>\n Readability counts.<br>\n Special cases aren't special enough to break the rules.<br>\n Although practicality beats purity.<br>\n Errors should never pass silently.<br>\n Unless explicitly silenced.<br>\n In the face of ambiguity, refuse the temptation to guess.\n There should be one-- and preferably only one --obvious way to do it.<br>\n Although that way may not be obvious at first unless you're Dutch.<br>\n Now is better than never.<br>\n Although never is often better than <em>right</em> now.<br>\n If the implementation is hard to explain, it's a bad idea.<br>\n If the implementation is easy to explain, it may be a good idea.<br>\n Namespaces are one honking great idea -- let's do more of those! </p>\n</blockquote>\n"
},
{
"answer_id": 101280,
"author": "Oko",
"author_id": 9402,
"author_profile": "https://Stackoverflow.com/users/9402",
"pm_score": 3,
"selected": false,
"text": "<p><strong>List comprehensions</strong></p>\n\n<p><a href=\"http://www.secnetix.de/olli/Python/list_comprehensions.hawk\" rel=\"nofollow noreferrer\">list comprehensions</a></p>\n\n<p>Compare the more traditional (without list comprehension):</p>\n\n<pre><code>foo = []\nfor x in xrange(10):\n if x % 2 == 0:\n foo.append(x)\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>foo = [x for x in xrange(10) if x % 2 == 0]\n</code></pre>\n"
},
{
"answer_id": 101286,
"author": "Matthias Kestenholz",
"author_id": 317346,
"author_profile": "https://Stackoverflow.com/users/317346",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Metaclasses</strong></p>\n\n<p>of course :-) <a href=\"https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python\">What is a metaclass in Python?</a></p>\n"
},
{
"answer_id": 101288,
"author": "cleg",
"author_id": 29503,
"author_profile": "https://Stackoverflow.com/users/29503",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Special methods</strong></p>\n\n<p><a href=\"http://docs.python.org/ref/specialnames.html\" rel=\"nofollow noreferrer\">Absolute power!</a> </p>\n"
},
{
"answer_id": 101310,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 9,
"selected": false,
"text": "<p><strong>Creating generators objects</strong></p>\n\n<p>If you write </p>\n\n<pre><code>x=(n for n in foo if bar(n))\n</code></pre>\n\n<p>you can get out the generator and assign it to x. Now it means you can do</p>\n\n<pre><code>for n in x:\n</code></pre>\n\n<p>The advantage of this is that you don't need intermediate storage, which you would need if you did</p>\n\n<pre><code>x = [n for n in foo if bar(n)]\n</code></pre>\n\n<p>In some cases this can lead to significant speed up.</p>\n\n<p>You can append many if statements to the end of the generator, basically replicating nested for loops:</p>\n\n<pre><code>>>> n = ((a,b) for a in range(0,2) for b in range(4,6))\n>>> for i in n:\n... print i \n\n(0, 4)\n(0, 5)\n(1, 4)\n(1, 5)\n</code></pre>\n"
},
{
"answer_id": 101447,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 8,
"selected": false,
"text": "<p><strong>Decorators</strong></p>\n\n<p><a href=\"http://docs.python.org/ref/function.html#tok-decorators\" rel=\"nofollow noreferrer\">Decorators</a> allow to wrap a function or method in another function that can add functionality, modify arguments or results, etc. You write decorators one line above the function definition, beginning with an \"at\" sign (@).</p>\n\n<p>Example shows a <code>print_args</code> decorator that prints the decorated function's arguments before calling it:</p>\n\n<pre><code>>>> def print_args(function):\n>>> def wrapper(*args, **kwargs):\n>>> print 'Arguments:', args, kwargs\n>>> return function(*args, **kwargs)\n>>> return wrapper\n\n>>> @print_args\n>>> def write(text):\n>>> print text\n\n>>> write('foo')\nArguments: ('foo',) {}\nfoo\n</code></pre>\n"
},
{
"answer_id": 101537,
"author": "MvdD",
"author_id": 18044,
"author_profile": "https://Stackoverflow.com/users/18044",
"pm_score": 8,
"selected": false,
"text": "<p><strong>Readable regular expressions</strong></p>\n\n<p>In Python you can split a regular expression over multiple lines, name your matches and insert comments.</p>\n\n<p>Example verbose syntax (from <a href=\"http://diveintopython.net/regular_expressions/index.html\" rel=\"nofollow noreferrer\">Dive into Python</a>):</p>\n\n<pre><code>>>> pattern = \"\"\"\n... ^ # beginning of string\n... M{0,4} # thousands - 0 to 4 M's\n... (CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's),\n... # or 500-800 (D, followed by 0 to 3 C's)\n... (XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's),\n... # or 50-80 (L, followed by 0 to 3 X's)\n... (IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's),\n... # or 5-8 (V, followed by 0 to 3 I's)\n... $ # end of string\n... \"\"\"\n>>> re.search(pattern, 'M', re.VERBOSE)\n</code></pre>\n\n<p>Example naming matches (from <a href=\"http://www.amk.ca/python/howto/regex/\" rel=\"nofollow noreferrer\">Regular Expression HOWTO</a>)</p>\n\n<pre><code>>>> p = re.compile(r'(?P<word>\\b\\w+\\b)')\n>>> m = p.search( '(((( Lots of punctuation )))' )\n>>> m.group('word')\n'Lots'\n</code></pre>\n\n<p>You can also verbosely write a regex without using <code>re.VERBOSE</code> thanks to string literal concatenation.</p>\n\n<pre><code>>>> pattern = (\n... \"^\" # beginning of string\n... \"M{0,4}\" # thousands - 0 to 4 M's\n... \"(CM|CD|D?C{0,3})\" # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's),\n... # or 500-800 (D, followed by 0 to 3 C's)\n... \"(XC|XL|L?X{0,3})\" # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's),\n... # or 50-80 (L, followed by 0 to 3 X's)\n... \"(IX|IV|V?I{0,3})\" # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's),\n... # or 5-8 (V, followed by 0 to 3 I's)\n... \"$\" # end of string\n... )\n>>> print pattern\n\"^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$\"\n</code></pre>\n"
},
{
"answer_id": 101549,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 7,
"selected": false,
"text": "<p>Nested list comprehensions and generator expressions:</p>\n\n<pre><code>[(i,j) for i in range(3) for j in range(i) ] \n((i,j) for i in range(4) for j in range(i) )\n</code></pre>\n\n<p>These can replace huge chunks of nested-loop code.</p>\n"
},
{
"answer_id": 101731,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Getter functions in module operator</strong></p>\n\n<p>The functions <code>attrgetter()</code> and <code>itemgetter()</code> in module <code>operator</code> can be used to generate fast access functions for use in sorting and search objects and dictionaries</p>\n\n<p><a href=\"http://docs.python.org/lib/module-operator.html\" rel=\"nofollow noreferrer\">Chapter 6.7</a> in the Python Library Docs</p>\n"
},
{
"answer_id": 101739,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 8,
"selected": false,
"text": "<p><a href=\"http://www.python.org/dev/peps/pep-0342/\" rel=\"nofollow noreferrer\">Sending values into generator functions</a>. For example having this function:</p>\n\n<pre><code>def mygen():\n \"\"\"Yield 5 until something else is passed back via send()\"\"\"\n a = 5\n while True:\n f = (yield a) #yield a and possibly get f in return\n if f is not None: \n a = f #store the new value\n</code></pre>\n\n<p>You can:</p>\n\n<pre><code>>>> g = mygen()\n>>> g.next()\n5\n>>> g.next()\n5\n>>> g.send(7) #we send this back to the generator\n7\n>>> g.next() #now it will yield 7 until we send something else\n7\n</code></pre>\n"
},
{
"answer_id": 101744,
"author": "Paweł Hajdan",
"author_id": 9403,
"author_profile": "https://Stackoverflow.com/users/9403",
"pm_score": 3,
"selected": false,
"text": "<p>Ability to substitute even things like file deletion, file opening etc. - direct manipulation of language library. This is a huge advantage when <strong>testing.</strong> You don't have to wrap everything in complicated containers. Just substitute a function/method and go. This is also called <strong>monkey-patching.</strong></p>\n"
},
{
"answer_id": 101778,
"author": "Kevin Little",
"author_id": 14028,
"author_profile": "https://Stackoverflow.com/users/14028",
"pm_score": 1,
"selected": false,
"text": "<pre><code>>>> x=[1,1,2,'a','a',3]\n>>> y = [ _x for _x in x if not _x in locals()['_[1]'] ]\n>>> y\n[1, 2, 'a', 3]\n</code></pre>\n\n<p><br>\n\"locals()['_[1]']\" is the \"secret name\" of the list being created. Very useful when state of list being built affects subsequent build decisions.</p>\n"
},
{
"answer_id": 101840,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 8,
"selected": false,
"text": "<p>The step argument in slice operators. For example:</p>\n\n<pre><code>a = [1,2,3,4,5]\n>>> a[::2] # iterate over the whole list in 2-increments\n[1,3,5]\n</code></pre>\n\n<p>The special case <code>x[::-1]</code> is a useful idiom for 'x reversed'.</p>\n\n<pre><code>>>> a[::-1]\n[5,4,3,2,1]\n</code></pre>\n"
},
{
"answer_id": 101892,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 5,
"selected": false,
"text": "<p>Implicit concatenation:</p>\n\n<pre><code>>>> print \"Hello \" \"World\"\nHello World\n</code></pre>\n\n<p>Useful when you want to make a long text fit on several lines in a script:</p>\n\n<pre><code>hello = \"Greaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Hello \" \\\n \"Word\"\n</code></pre>\n\n<p>or</p>\n\n<pre><code>hello = (\"Greaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Hello \" \n \"Word\")\n</code></pre>\n"
},
{
"answer_id": 101919,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 6,
"selected": false,
"text": "<p>You can use <a href=\"http://docs.python.org/library/functions.html#property\" rel=\"nofollow noreferrer\">property</a> to make your class interfaces more strict.</p>\n\n<pre><code>class C(object):\n def __init__(self, foo, bar):\n self.foo = foo # read-write property\n self.bar = bar # simple attribute\n\n def _set_foo(self, value):\n self._foo = value\n\n def _get_foo(self):\n return self._foo\n\n def _del_foo(self):\n del self._foo\n\n # any of fget, fset, fdel and doc are optional,\n # so you can make a write-only and/or delete-only property.\n foo = property(fget = _get_foo, fset = _set_foo,\n fdel = _del_foo, doc = 'Hello, I am foo!')\n\nclass D(C):\n def _get_foo(self):\n return self._foo * 2\n\n def _set_foo(self, value):\n self._foo = value / 2\n\n foo = property(fget = _get_foo, fset = _set_foo,\n fdel = C.foo.fdel, doc = C.foo.__doc__)\n</code></pre>\n\n<p>In Python <a href=\"http://docs.python.org/dev/whatsnew/2.6.html\" rel=\"nofollow noreferrer\">2.6 and 3.0</a>:</p>\n\n<pre><code>class C(object):\n def __init__(self, foo, bar):\n self.foo = foo # read-write property\n self.bar = bar # simple attribute\n\n @property\n def foo(self):\n '''Hello, I am foo!'''\n\n return self._foo\n\n @foo.setter\n def foo(self, value):\n self._foo = value\n\n @foo.deleter\n def foo(self):\n del self._foo\n\nclass D(C):\n @C.foo.getter\n def foo(self):\n return self._foo * 2\n\n @foo.setter\n def foo(self, value):\n self._foo = value / 2\n</code></pre>\n\n<p>To learn more about how property works refer to <a href=\"http://docs.python.org/howto/descriptor.html\" rel=\"nofollow noreferrer\">descriptors</a>.</p>\n"
},
{
"answer_id": 101945,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 10,
"selected": false,
"text": "<h2>Chaining comparison operators:</h2>\n\n<pre><code>>>> x = 5\n>>> 1 < x < 10\nTrue\n>>> 10 < x < 20 \nFalse\n>>> x < 10 < x*10 < 100\nTrue\n>>> 10 > x <= 9\nTrue\n>>> 5 == x > 4\nTrue\n</code></pre>\n\n<p>In case you're thinking it's doing <code>1 < x</code>, which comes out as <code>True</code>, and then comparing <code>True < 10</code>, which is also <code>True</code>, then no, that's really not what happens (see the last example.) It's really translating into <code>1 < x and x < 10</code>, and <code>x < 10 and 10 < x * 10 and x*10 < 100</code>, but with less typing and each term is only evaluated once.</p>\n"
},
{
"answer_id": 101971,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Everything is dynamic</strong></p>\n\n<p>\"There is no compile-time\". Everything in Python is runtime. A module is 'defined' by executing the module's source top-to-bottom, just like a script, and the resulting namespace is the module's attribute-space. Likewise, a class is 'defined' by executing the class body top-to-bottom, and the resulting namespace is the class's attribute-space. A class body can contain completely arbitrary code -- including import statements, loops and other class statements. Creating a class, function or even module 'dynamically', as is sometimes asked for, isn't hard; in fact, it's impossible to avoid, since everything is 'dynamic'.</p>\n"
},
{
"answer_id": 102006,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Re-raising exceptions</strong>:</p>\n\n<pre><code># Python 2 syntax\ntry:\n some_operation()\nexcept SomeError, e:\n if is_fatal(e):\n raise\n handle_nonfatal(e)\n\n# Python 3 syntax\ntry:\n some_operation()\nexcept SomeError as e:\n if is_fatal(e):\n raise\n handle_nonfatal(e)\n</code></pre>\n\n<p>The 'raise' statement with no arguments inside an error handler tells Python to re-raise the exception <em>with the original traceback intact</em>, allowing you to say \"oh, sorry, sorry, I didn't mean to catch that, sorry, sorry.\"</p>\n\n<p>If you wish to print, store or fiddle with the original traceback, you can get it with sys.exc_info(), and printing it like Python would is done with the 'traceback' module.</p>\n"
},
{
"answer_id": 102037,
"author": "Lucas S.",
"author_id": 7363,
"author_profile": "https://Stackoverflow.com/users/7363",
"pm_score": 8,
"selected": false,
"text": "<p><strong>In-place value swapping</strong></p>\n\n<pre><code>>>> a = 10\n>>> b = 5\n>>> a, b\n(10, 5)\n\n>>> a, b = b, a\n>>> a, b\n(5, 10)\n</code></pre>\n\n<p>The right-hand side of the assignment is an expression that creates a new tuple. The left-hand side of the assignment immediately unpacks that (unreferenced) tuple to the names <code>a</code> and <code>b</code>.</p>\n\n<p>After the assignment, the new tuple is unreferenced and marked for garbage collection, and the values bound to <code>a</code> and <code>b</code> have been swapped.</p>\n\n<p>As noted in the <a href=\"http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences\" rel=\"nofollow noreferrer\">Python tutorial section on data structures</a>,</p>\n\n<blockquote>\n <p>Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.</p>\n</blockquote>\n"
},
{
"answer_id": 102062,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 7,
"selected": false,
"text": "<h2>Descriptors</h2>\n\n<p>They're the magic behind a whole bunch of core Python features. </p>\n\n<p>When you use dotted access to look up a member (eg, x.y), Python first looks for the member in the instance dictionary. If it's not found, it looks for it in the class dictionary. If it finds it in the class dictionary, and the object implements the descriptor protocol, instead of just returning it, Python executes it. A descriptor is any class that implements the <code>__get__</code>, <code>__set__</code>, or <code>__delete__</code> methods.</p>\n\n<p>Here's how you'd implement your own (read-only) version of property using descriptors:</p>\n\n<pre><code>class Property(object):\n def __init__(self, fget):\n self.fget = fget\n\n def __get__(self, obj, type):\n if obj is None:\n return self\n return self.fget(obj)\n</code></pre>\n\n<p>and you'd use it just like the built-in property():</p>\n\n<pre><code>class MyClass(object):\n @Property\n def foo(self):\n return \"Foo!\"\n</code></pre>\n\n<p>Descriptors are used in Python to implement properties, bound methods, static methods, class methods and slots, amongst other things. Understanding them makes it easy to see why a lot of things that previously looked like Python 'quirks' are the way they are.</p>\n\n<p>Raymond Hettinger has <a href=\"http://users.rcn.com/python/download/Descriptor.htm\" rel=\"noreferrer\">an excellent tutorial</a> that does a much better job of describing them than I do.</p>\n"
},
{
"answer_id": 102065,
"author": "Pierre-Jean Coudert",
"author_id": 8450,
"author_profile": "https://Stackoverflow.com/users/8450",
"pm_score": 7,
"selected": false,
"text": "<h2><a href=\"http://docs.python.org/lib/module-doctest.html\" rel=\"nofollow noreferrer\">Doctest</a>: documentation and unit-testing at the same time.</h2>\n\n<p>Example extracted from the Python documentation:</p>\n\n<pre><code>def factorial(n):\n \"\"\"Return the factorial of n, an exact integer >= 0.\n\n If the result is small enough to fit in an int, return an int.\n Else return a long.\n\n >>> [factorial(n) for n in range(6)]\n [1, 1, 2, 6, 24, 120]\n >>> factorial(-1)\n Traceback (most recent call last):\n ...\n ValueError: n must be >= 0\n\n Factorials of floats are OK, but the float must be an exact integer:\n \"\"\"\n\n import math\n if not n >= 0:\n raise ValueError(\"n must be >= 0\")\n if math.floor(n) != n:\n raise ValueError(\"n must be exact integer\")\n if n+1 == n: # catch a value like 1e300\n raise OverflowError(\"n too large\")\n result = 1\n factor = 2\n while factor <= n:\n result *= factor\n factor += 1\n return result\n\ndef _test():\n import doctest\n doctest.testmod() \n\nif __name__ == \"__main__\":\n _test()\n</code></pre>\n"
},
{
"answer_id": 102202,
"author": "mbac32768",
"author_id": 18446,
"author_profile": "https://Stackoverflow.com/users/18446",
"pm_score": 8,
"selected": false,
"text": "<p><strong>iter() can take a callable argument</strong></p>\n\n<p>For instance:</p>\n\n<pre><code>def seek_next_line(f):\n for c in iter(lambda: f.read(1),'\\n'):\n pass\n</code></pre>\n\n<p>The <code>iter(callable, until_value)</code> function repeatedly calls <code>callable</code> and yields its result until <code>until_value</code> is returned. </p>\n"
},
{
"answer_id": 103198,
"author": "pi.",
"author_id": 15274,
"author_profile": "https://Stackoverflow.com/users/15274",
"pm_score": 3,
"selected": false,
"text": "<p>Too lazy to initialize every field in a dictionary? No problem:</p>\n\n<p>In Python > 2.3:</p>\n\n<pre><code>from collections import defaultdict\n</code></pre>\n\n<p>In Python <= 2.3:</p>\n\n<pre><code>def defaultdict(type_):\n class Dict(dict):\n def __getitem__(self, key):\n return self.setdefault(key, type_())\n return Dict()\n</code></pre>\n\n<p>In any version:</p>\n\n<pre><code>d = defaultdict(list)\nfor stuff in lots_of_stuff:\n d[stuff.name].append(stuff)\n</code></pre>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>Thanks <a href=\"https://stackoverflow.com/users/69707/ken-arnold\">Ken Arnold</a>. I reimplemented a more sophisticated version of defaultdict. It should behave exactly as <a href=\"http://docs.python.org/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\">the one in the standard library</a>.</p>\n\n<pre><code>def defaultdict(default_factory, *args, **kw): \n\n class defaultdict(dict):\n\n def __missing__(self, key):\n if default_factory is None:\n raise KeyError(key)\n return self.setdefault(key, default_factory())\n\n def __getitem__(self, key):\n try:\n return dict.__getitem__(self, key)\n except KeyError:\n return self.__missing__(key)\n\n return defaultdict(*args, **kw)\n</code></pre>\n"
},
{
"answer_id": 105325,
"author": "davidavr",
"author_id": 8247,
"author_profile": "https://Stackoverflow.com/users/8247",
"pm_score": 5,
"selected": false,
"text": "<p><strong>The Python Interpreter</strong></p>\n\n<pre><code>>>> \n</code></pre>\n\n<p>Maybe not lesser known, but certainly one of my favorite features of Python.</p>\n"
},
{
"answer_id": 106868,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 4,
"selected": false,
"text": "<p><strong>First-class functions</strong></p>\n\n<p>It's not really a hidden feature, but the fact that functions are first class objects is simply great. You can pass them around like any other variable.</p>\n\n<pre><code>>>> def jim(phrase):\n... return 'Jim says, \"%s\".' % phrase\n>>> def say_something(person, phrase):\n... print person(phrase)\n\n>>> say_something(jim, 'hey guys')\n'Jim says, \"hey guys\".'\n</code></pre>\n"
},
{
"answer_id": 108297,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 8,
"selected": false,
"text": "<h2>Creating new types in a fully dynamic manner</h2>\n\n<pre><code>>>> NewType = type(\"NewType\", (object,), {\"x\": \"hello\"})\n>>> n = NewType()\n>>> n.x\n\"hello\"\n</code></pre>\n\n<p>which is exactly the same as</p>\n\n<pre><code>>>> class NewType(object):\n>>> x = \"hello\"\n>>> n = NewType()\n>>> n.x\n\"hello\"\n</code></pre>\n\n<p>Probably not the most useful thing, but nice to know.</p>\n\n<p><strong>Edit</strong>: Fixed name of new type, should be <code>NewType</code> to be the exact same thing as with <code>class</code> statement.</p>\n\n<p><strong>Edit</strong>: Adjusted the title to more accurately describe the feature.</p>\n"
},
{
"answer_id": 108312,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Interleaving <code>if</code> and <code>for</code> in list comprehensions</strong></p>\n\n<pre><code>>>> [(x, y) for x in range(4) if x % 2 == 1 for y in range(4)]\n[(1, 0), (1, 1), (1, 2), (1, 3), (3, 0), (3, 1), (3, 2), (3, 3)]\n</code></pre>\n\n<p>I never realized this until I learned Haskell.</p>\n"
},
{
"answer_id": 109182,
"author": "Ycros",
"author_id": 10495,
"author_profile": "https://Stackoverflow.com/users/10495",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Context managers and the \"<code>with</code>\" Statement</strong></p>\n\n<p>Introduced in <a href=\"http://www.python.org/dev/peps/pep-0343/\" rel=\"nofollow noreferrer\">PEP 343</a>, a <a href=\"http://docs.python.org/library/stdtypes.html#context-manager-types\" rel=\"nofollow noreferrer\">context manager</a> is an object that acts as a run-time context for a suite of statements.</p>\n\n<p>Since the feature makes use of new keywords, it is introduced gradually: it is available in Python 2.5 via the <a href=\"http://docs.python.org/lib/module-future.html\" rel=\"nofollow noreferrer\"><code>__future__</code></a> directive. Python 2.6 and above (including Python 3) has it available by default.</p>\n\n<p>I have used the <a href=\"http://www.python.org/dev/peps/pep-0343/\" rel=\"nofollow noreferrer\">\"with\" statement</a> a lot because I think it's a very useful construct, here is a quick demo:</p>\n\n<pre><code>from __future__ import with_statement\n\nwith open('foo.txt', 'w') as f:\n f.write('hello!')\n</code></pre>\n\n<p>What's happening here behind the scenes, is that the <a href=\"http://www.python.org/dev/peps/pep-0343/\" rel=\"nofollow noreferrer\">\"with\" statement</a> calls the special <code>__enter__</code> and <code>__exit__</code> methods on the file object. Exception details are also passed to <code>__exit__</code> if any exception was raised from the with statement body, allowing for exception handling to happen there.</p>\n\n<p>What this does for you in this particular case is that it guarantees that the file is closed when execution falls out of scope of the <code>with</code> suite, regardless if that occurs normally or whether an exception was thrown. It is basically a way of abstracting away common exception-handling code.</p>\n\n<p>Other common use cases for this include locking with threads and database transactions. </p>\n"
},
{
"answer_id": 109194,
"author": "daniel",
"author_id": 19741,
"author_profile": "https://Stackoverflow.com/users/19741",
"pm_score": 4,
"selected": false,
"text": "<p>Some of the <strong>builtin</strong> favorites, map(), reduce(), and filter(). All extremely fast and powerful.</p>\n"
},
{
"answer_id": 111176,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 8,
"selected": false,
"text": "<p><strong>Function argument unpacking</strong></p>\n\n<p>You can unpack a list or a dictionary as function arguments using <code>*</code> and <code>**</code>.</p>\n\n<p>For example:</p>\n\n<pre><code>def draw_point(x, y):\n # do some magic\n\npoint_foo = (3, 4)\npoint_bar = {'y': 3, 'x': 2}\n\ndraw_point(*point_foo)\ndraw_point(**point_bar)\n</code></pre>\n\n<p>Very useful shortcut since lists, tuples and dicts are widely used as containers.</p>\n"
},
{
"answer_id": 111970,
"author": "Amandasaurus",
"author_id": 161922,
"author_profile": "https://Stackoverflow.com/users/161922",
"pm_score": 7,
"selected": false,
"text": "<h2>Dictionaries have a get() method</h2>\n\n<p>Dictionaries have a 'get()' method. If you do d['key'] and key isn't there, you get an exception. If you do d.get('key'), you get back None if 'key' isn't there. You can add a second argument to get that item back instead of None, eg: d.get('key', 0).</p>\n\n<p>It's great for things like adding up numbers:</p>\n\n<p><code>sum[value] = sum.get(value, 0) + 1</code></p>\n"
},
{
"answer_id": 112274,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 2,
"selected": false,
"text": "<p>If you use <code>exec</code> in a function the variable lookup rules change drastically. Closures are no longer possible but Python allows arbitrary identifiers in the function. This gives you a \"modifiable locals()\" and can be used to star-import identifiers. On the downside it makes every lookup slower because the variables end up in a dict rather than slots in the frame:</p>\n\n<pre><code>>>> def f():\n... exec \"a = 42\"\n... return a\n... \n>>> def g():\n... a = 42\n... return a\n... \n>>> import dis\n>>> dis.dis(f)\n 2 0 LOAD_CONST 1 ('a = 42')\n 3 LOAD_CONST 0 (None)\n 6 DUP_TOP \n 7 EXEC_STMT \n\n 3 8 LOAD_NAME 0 (a)\n 11 RETURN_VALUE \n>>> dis.dis(g)\n 2 0 LOAD_CONST 1 (42)\n 3 STORE_FAST 0 (a)\n\n 3 6 LOAD_FAST 0 (a)\n 9 RETURN_VALUE \n</code></pre>\n"
},
{
"answer_id": 112286,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 8,
"selected": false,
"text": "<p>From 2.5 onwards dicts have a special method <code>__missing__</code> that is invoked for missing items:</p>\n\n<pre><code>>>> class MyDict(dict):\n... def __missing__(self, key):\n... self[key] = rv = []\n... return rv\n... \n>>> m = MyDict()\n>>> m[\"foo\"].append(1)\n>>> m[\"foo\"].append(2)\n>>> dict(m)\n{'foo': [1, 2]}\n</code></pre>\n\n<p>There is also a dict subclass in <code>collections</code> called <code>defaultdict</code> that does pretty much the same but calls a function without arguments for not existing items:</p>\n\n<pre><code>>>> from collections import defaultdict\n>>> m = defaultdict(list)\n>>> m[\"foo\"].append(1)\n>>> m[\"foo\"].append(2)\n>>> dict(m)\n{'foo': [1, 2]}\n</code></pre>\n\n<p>I recommend converting such dicts to regular dicts before passing them to functions that don't expect such subclasses. A lot of code uses <code>d[a_key]</code> and catches KeyErrors to check if an item exists which would add a new item to the dict.</p>\n"
},
{
"answer_id": 112296,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using descriptors on your classes Python completely bypasses <code>__dict__</code> for that key which makes it a nice place to store such values:</p>\n\n<pre><code>>>> class User(object):\n... def _get_username(self):\n... return self.__dict__['username']\n... def _set_username(self, value):\n... print 'username set'\n... self.__dict__['username'] = value\n... username = property(_get_username, _set_username)\n... del _get_username, _set_username\n... \n>>> u = User()\n>>> u.username = \"foo\"\nusername set\n>>> u.__dict__\n{'username': 'foo'}\n</code></pre>\n\n<p>This helps to keep <code>dir()</code> clean.</p>\n"
},
{
"answer_id": 112303,
"author": "eduffy",
"author_id": 7536,
"author_profile": "https://Stackoverflow.com/users/7536",
"pm_score": 8,
"selected": false,
"text": "<p>If you don't like using whitespace to denote scopes, you can use the C-style {} by issuing:</p>\n\n<pre><code>from __future__ import braces\n</code></pre>\n"
},
{
"answer_id": 112306,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 4,
"selected": false,
"text": "<p><code>__slots__</code> is a nice way to save memory, but it's very hard to get a dict of the values of the object. Imagine the following object:</p>\n\n<pre><code>class Point(object):\n __slots__ = ('x', 'y')\n</code></pre>\n\n<p>Now that object obviously has two attributes. Now we can create an instance of it and build a dict of it this way:</p>\n\n<pre><code>>>> p = Point()\n>>> p.x = 3\n>>> p.y = 5\n>>> dict((k, getattr(p, k)) for k in p.__slots__)\n{'y': 5, 'x': 3}\n</code></pre>\n\n<p>This however won't work if point was subclassed and new slots were added. However Python automatically implements <code>__reduce_ex__</code> to help the <code>copy</code> module. This can be abused to get a dict of values:</p>\n\n<pre><code>>>> p.__reduce_ex__(2)[2][1]\n{'y': 5, 'x': 3}\n</code></pre>\n"
},
{
"answer_id": 112316,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 6,
"selected": false,
"text": "<p>Python's advanced slicing operation has a barely known syntax element, the ellipsis:</p>\n\n<pre><code>>>> class C(object):\n... def __getitem__(self, item):\n... return item\n... \n>>> C()[1:2, ..., 3]\n(slice(1, 2, None), Ellipsis, 3)\n</code></pre>\n\n<p>Unfortunately it's barely useful as the ellipsis is only supported if tuples are involved.</p>\n"
},
{
"answer_id": 112325,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 3,
"selected": false,
"text": "<p>Builtin methods or functions don't implement the descriptor protocol which makes it impossible to do stuff like this:</p>\n\n<pre><code>>>> class C(object):\n... id = id\n... \n>>> C().id()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: id() takes exactly one argument (0 given)\n</code></pre>\n\n<p>However you can create a small bind descriptor that makes this possible:</p>\n\n<pre><code>>>> from types import MethodType\n>>> class bind(object):\n... def __init__(self, callable):\n... self.callable = callable\n... def __get__(self, obj, type=None):\n... if obj is None:\n... return self\n... return MethodType(self.callable, obj, type)\n... \n>>> class C(object):\n... id = bind(id)\n... \n>>> C().id()\n7414064\n</code></pre>\n"
},
{
"answer_id": 113164,
"author": "Pasi Savolainen",
"author_id": 20195,
"author_profile": "https://Stackoverflow.com/users/20195",
"pm_score": 7,
"selected": false,
"text": "<h2>Named formatting</h2>\n\n<p>% -formatting takes a dictionary (also applies %i/%s etc. validation).</p>\n\n<pre><code>>>> print \"The %(foo)s is %(bar)i.\" % {'foo': 'answer', 'bar':42}\nThe answer is 42.\n\n>>> foo, bar = 'question', 123\n\n>>> print \"The %(foo)s is %(bar)i.\" % locals()\nThe question is 123.\n</code></pre>\n\n<p>And since locals() is also a dictionary, you can simply pass that as a dict and have % -substitions from your local variables. I think this is frowned upon, but simplifies things..</p>\n\n<p><strong>New Style Formatting</strong></p>\n\n<pre><code>>>> print(\"The {foo} is {bar}\".format(foo='answer', bar=42))\n</code></pre>\n"
},
{
"answer_id": 113198,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 8,
"selected": false,
"text": "<p><strong>Be careful with mutable default arguments</strong></p>\n\n<pre><code>>>> def foo(x=[]):\n... x.append(1)\n... print x\n... \n>>> foo()\n[1]\n>>> foo()\n[1, 1]\n>>> foo()\n[1, 1, 1]\n</code></pre>\n\n<p>Instead, you should use a sentinel value denoting \"not given\" and replace with the mutable you'd like as default:</p>\n\n<pre><code>>>> def foo(x=None):\n... if x is None:\n... x = []\n... x.append(1)\n... print x\n>>> foo()\n[1]\n>>> foo()\n[1]\n</code></pre>\n"
},
{
"answer_id": 113319,
"author": "ianb",
"author_id": 20218,
"author_profile": "https://Stackoverflow.com/users/20218",
"pm_score": 5,
"selected": false,
"text": "<p>Tuple unpacking:</p>\n\n<pre><code>>>> (a, (b, c), d) = [(1, 2), (3, 4), (5, 6)]\n>>> a\n(1, 2)\n>>> b\n3\n>>> c, d\n(4, (5, 6))\n</code></pre>\n\n<p>More obscurely, you can do this in function arguments (in Python 2.x; Python 3.x will not allow this anymore):</p>\n\n<pre><code>>>> def addpoints((x1, y1), (x2, y2)):\n... return (x1+x2, y1+y2)\n>>> addpoints((5, 0), (3, 5))\n(8, 5)\n</code></pre>\n"
},
{
"answer_id": 113472,
"author": "Paddy3118",
"author_id": 10562,
"author_profile": "https://Stackoverflow.com/users/10562",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://paddy3118.blogspot.com/2007/02/unzip-un-needed-in-python.html\" rel=\"nofollow noreferrer\">unzip un-needed in Python</a></p>\n\n<p>Someone blogged about Python not having an unzip function to go with zip(). unzip is straight-forward to calculate because:</p>\n\n<pre><code>>>> t1 = (0,1,2,3)\n>>> t2 = (7,6,5,4)\n>>> [t1,t2] == zip(*zip(t1,t2))\nTrue\n</code></pre>\n\n<p>On reflection though, I'd rather have an explicit unzip().</p>\n"
},
{
"answer_id": 113833,
"author": "dgrant",
"author_id": 9484,
"author_profile": "https://Stackoverflow.com/users/9484",
"pm_score": 7,
"selected": false,
"text": "<p>To add more python modules (espcially 3rd party ones), most people seem to use PYTHONPATH environment variables or they add symlinks or directories in their site-packages directories. Another way, is to use *.pth files. Here's the official python doc's explanation:</p>\n\n<blockquote>\n <p>\"The most convenient way [to modify\n python's search path] is to add a path\n configuration file to a directory\n that's already on Python's path,\n usually to the .../site-packages/\n directory. Path configuration files\n have an extension of .pth, and each\n line must contain a single path that\n will be appended to sys.path. (Because\n the new paths are appended to\n sys.path, modules in the added\n directories will not override standard\n modules. This means you can't use this\n mechanism for installing fixed\n versions of standard modules.)\"</p>\n</blockquote>\n"
},
{
"answer_id": 114157,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 7,
"selected": false,
"text": "<p>Exception <strong>else</strong> clause:</p>\n\n<pre><code>try:\n put_4000000000_volts_through_it(parrot)\nexcept Voom:\n print \"'E's pining!\"\nelse:\n print \"This parrot is no more!\"\nfinally:\n end_sketch()\n</code></pre>\n\n<p>The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.</p>\n\n<p>See <a href=\"http://docs.python.org/tut/node10.html\" rel=\"nofollow noreferrer\">http://docs.python.org/tut/node10.html</a></p>\n"
},
{
"answer_id": 114420,
"author": "rlerallut",
"author_id": 20055,
"author_profile": "https://Stackoverflow.com/users/20055",
"pm_score": 8,
"selected": false,
"text": "<p>The for...else syntax (see <a href=\"http://docs.python.org/ref/for.html\" rel=\"nofollow noreferrer\">http://docs.python.org/ref/for.html</a> )</p>\n\n<pre><code>for i in foo:\n if i == 0:\n break\nelse:\n print(\"i was never 0\")\n</code></pre>\n\n<p>The \"else\" block will be normally executed at the end of the for loop, unless the break is called.</p>\n\n<p>The above code could be emulated as follows:</p>\n\n<pre><code>found = False\nfor i in foo:\n if i == 0:\n found = True\n break\nif not found: \n print(\"i was never 0\")\n</code></pre>\n"
},
{
"answer_id": 116280,
"author": "lacker",
"author_id": 2652,
"author_profile": "https://Stackoverflow.com/users/2652",
"pm_score": 6,
"selected": false,
"text": "<p>Many people don't know about the \"dir\" function. It's a great way to figure out what an object can do from the interpreter. For example, if you want to see a list of all the string methods:</p>\n\n<pre><code>>>> dir(\"foo\")\n['__add__', '__class__', '__contains__', (snipped a bunch), 'title',\n 'translate', 'upper', 'zfill']\n</code></pre>\n\n<p>And then if you want more information about a particular method you can call \"help\" on it.</p>\n\n<pre><code>>>> help(\"foo\".upper)\n Help on built-in function upper:\n\nupper(...)\n S.upper() -> string\n\n Return a copy of the string S converted to uppercase.\n</code></pre>\n"
},
{
"answer_id": 116391,
"author": "amix",
"author_id": 20081,
"author_profile": "https://Stackoverflow.com/users/20081",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Access Dictionary elements as\n attributes (properties). so if an\n a1=AttrDict() has key 'name' ->\n instead of a1['name'] we can easily\n access name attribute of a1 using ->\n a1.name</p>\n</blockquote>\n\n<hr>\n\n<pre><code>class AttrDict(dict):\n\n def __getattr__(self, name):\n if name in self:\n return self[name]\n raise AttributeError('%s not found' % name)\n\n def __setattr__(self, name, value):\n self[name] = value\n\n def __delattr__(self, name):\n del self[name]\n\nperson = AttrDict({'name': 'John Doe', 'age': 66})\nprint person['name']\nprint person.name\n\nperson.name = 'Frodo G'\nprint person.name\n\ndel person.age\n\nprint person\n</code></pre>\n"
},
{
"answer_id": 116440,
"author": "amix",
"author_id": 20081,
"author_profile": "https://Stackoverflow.com/users/20081",
"pm_score": 5,
"selected": false,
"text": "<p>Python sort function sorts tuples correctly (i.e. using the familiar lexicographical order):</p>\n\n<pre><code>a = [(2, \"b\"), (1, \"a\"), (2, \"a\"), (3, \"c\")]\nprint sorted(a)\n#[(1, 'a'), (2, 'a'), (2, 'b'), (3, 'c')]\n</code></pre>\n\n<p>Useful if you want to sort a list of persons after age and then name.</p>\n"
},
{
"answer_id": 116480,
"author": "tghw",
"author_id": 2363,
"author_profile": "https://Stackoverflow.com/users/2363",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Conditional Assignment</strong></p>\n\n<pre><code>x = 3 if (y == 1) else 2\n</code></pre>\n\n<p>It does exactly what it sounds like: \"assign 3 to x if y is 1, otherwise assign 2 to x\". Note that the parens are not necessary, but I like them for readability. You can also chain it if you have something more complicated:</p>\n\n<pre><code>x = 3 if (y == 1) else 2 if (y == -1) else 1\n</code></pre>\n\n<p>Though at a certain point, it goes a little too far.</p>\n\n<p>Note that you can use if ... else in any expression. For example:</p>\n\n<pre><code>(func1 if y == 1 else func2)(arg1, arg2) \n</code></pre>\n\n<p>Here func1 will be called if y is 1 and func2, otherwise. In both cases the corresponding function will be called with arguments arg1 and arg2.</p>\n\n<p>Analogously, the following is also valid:</p>\n\n<pre><code>x = (class1 if y == 1 else class2)(arg1, arg2)\n</code></pre>\n\n<p>where class1 and class2 are two classes.</p>\n"
},
{
"answer_id": 116580,
"author": "Tzury Bar Yochay",
"author_id": 9296,
"author_profile": "https://Stackoverflow.com/users/9296",
"pm_score": 6,
"selected": false,
"text": "<ul>\n<li>The underscore, it contains the most recent output value displayed by the interpreter (in an interactive session):</li>\n</ul>\n\n<pre>\n>>> (a for a in xrange(10000))\n<generator object at 0x81a8fcc>\n>>> b = 'blah'\n>>> _\n<generator object at 0x81a8fcc>\n</pre>\n\n<ul>\n<li>A convenient Web-browser controller:</li>\n</ul>\n\n<pre>>>> import webbrowser\n>>> webbrowser.open_new_tab('http://www.stackoverflow.com')</pre>\n\n<ul>\n<li>A built-in http server. To serve the files in the current directory:</li>\n</ul>\n\n<pre>python -m SimpleHTTPServer 8000</pre>\n\n<ul>\n<li>AtExit</li>\n</ul>\n\n<pre>>>> import atexit</pre>\n"
},
{
"answer_id": 116724,
"author": "tghw",
"author_id": 2363,
"author_profile": "https://Stackoverflow.com/users/2363",
"pm_score": 3,
"selected": false,
"text": "<p><strong>__getattr__()</strong></p>\n\n<p><code>getattr</code> is a really nice way to make generic classes, which is especially useful if you're writing an API. For example, in the <a href=\"http://support.fogcreek.com/default.asp?W1048\" rel=\"noreferrer\">FogBugz Python API</a>, <code>getattr</code> is used to pass method calls on to the web service seamlessly:</p>\n\n<pre><code>class FogBugz:\n ...\n\n def __getattr__(self, name):\n # Let's leave the private stuff to Python\n if name.startswith(\"__\"):\n raise AttributeError(\"No such attribute '%s'\" % name)\n\n if not self.__handlerCache.has_key(name):\n def handler(**kwargs):\n return self.__makerequest(name, **kwargs)\n self.__handlerCache[name] = handler\n return self.__handlerCache[name]\n ...\n</code></pre>\n\n<p>When someone calls <code>FogBugz.search(q='bug')</code>, they don't get actually call a <code>search</code> method. Instead, <code>getattr</code> handles the call by creating a new function that wraps the <code>makerequest</code> method, which crafts the appropriate HTTP request to the web API. Any errors will be dispatched by the web service and passed back to the user.</p>\n"
},
{
"answer_id": 117116,
"author": "Dave",
"author_id": 4072,
"author_profile": "https://Stackoverflow.com/users/4072",
"pm_score": 9,
"selected": false,
"text": "<p><strong>enumerate</strong></p>\n\n<p>Wrap an iterable with enumerate and it will yield the item along with its index.</p>\n\n<p>For example:</p>\n\n<pre><code>\n>>> a = ['a', 'b', 'c', 'd', 'e']\n>>> for index, item in enumerate(a): print index, item\n...\n0 a\n1 b\n2 c\n3 d\n4 e\n>>>\n</code></pre>\n\n<p>References:</p>\n\n<ul>\n<li><a href=\"http://docs.python.org/tutorial/datastructures.html#looping-techniques\" rel=\"nofollow noreferrer\">Python tutorial—looping techniques</a></li>\n<li><a href=\"http://docs.python.org/library/functions.html#enumerate\" rel=\"nofollow noreferrer\">Python docs—built-in functions—<code>enumerate</code></a></li>\n<li><a href=\"http://www.python.org/dev/peps/pep-0279/\" rel=\"nofollow noreferrer\">PEP 279</a></li>\n</ul>\n"
},
{
"answer_id": 118202,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Ternary operator</strong></p>\n\n<pre><code>>>> 'ham' if True else 'spam'\n'ham'\n>>> 'ham' if False else 'spam'\n'spam'\n</code></pre>\n\n<p>This was added in 2.5, prior to that you could use:</p>\n\n<pre><code>>>> True and 'ham' or 'spam'\n'ham'\n>>> False and 'ham' or 'spam'\n'spam'\n</code></pre>\n\n<p>However, if the values you want to work with would be considered false, there is a difference:</p>\n\n<pre><code>>>> [] if True else 'spam'\n[]\n>>> True and [] or 'spam'\n'spam'\n</code></pre>\n"
},
{
"answer_id": 118312,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 4,
"selected": false,
"text": "<p>You can build up a dictionary from a set of length-2 sequences. Extremely handy when you have a list of values and a list of arrays.</p>\n\n<pre><code>>>> dict([ ('foo','bar'),('a',1),('b',2) ])\n{'a': 1, 'b': 2, 'foo': 'bar'}\n\n>>> names = ['Bob', 'Marie', 'Alice']\n>>> ages = [23, 27, 36]\n>>> dict(zip(names, ages))\n{'Alice': 36, 'Bob': 23, 'Marie': 27}\n</code></pre>\n"
},
{
"answer_id": 120074,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 2,
"selected": false,
"text": "<p>Tuple unpacking in for loops, list comprehensions and generator expressions:</p>\n\n<pre><code>>>> l=[(1,2),(3,4)]\n>>> [a+b for a,b in l ] \n[3,7]\n</code></pre>\n\n<p>Useful in this idiom for iterating over (key,data) pairs in dictionaries:</p>\n\n<pre><code>d = { 'x':'y', 'f':'e'}\nfor name, value in d.items(): # one can also use iteritems()\n print \"name:%s, value:%s\" % (name,value)\n</code></pre>\n\n<p>prints:</p>\n\n<pre><code>name:x, value:y\nname:f, value:e\n</code></pre>\n"
},
{
"answer_id": 120247,
"author": "csl",
"author_id": 21028,
"author_profile": "https://Stackoverflow.com/users/21028",
"pm_score": 3,
"selected": false,
"text": "<p><strong>\"Unpacking\" to function parameters</strong></p>\n\n<pre><code>def foo(a, b, c):\n print a, b, c\n\nbar = (3, 14, 15)\nfoo(*bar)\n</code></pre>\n\n<p>When executed prints:</p>\n\n<pre><code>3 14 15\n</code></pre>\n"
},
{
"answer_id": 122577,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Objects in boolean context</strong></p>\n\n<p>Empty tuples, lists, dicts, strings and many other objects are equivalent to False in boolean context (and non-empty are equivalent to True).</p>\n\n<pre><code>empty_tuple = ()\nempty_list = []\nempty_dict = {}\nempty_string = ''\nempty_set = set()\nif empty_tuple or empty_list or empty_dict or empty_string or empty_set:\n print 'Never happens!'\n</code></pre>\n\n<p>This allows logical operations to return one of it's operands instead of True/False, which is useful in some situations:</p>\n\n<pre><code>s = t or \"Default value\" # s will be assigned \"Default value\"\n # if t is false/empty/none\n</code></pre>\n"
},
{
"answer_id": 125185,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 2,
"selected": false,
"text": "<p>The first-classness of everything ('everything is an object'), and the mayhem this can cause.</p>\n\n<pre><code>>>> x = 5\n>>> y = 10\n>>> \n>>> def sq(x):\n... return x * x\n... \n>>> def plus(x):\n... return x + x\n... \n>>> (sq,plus)[y>x](y)\n20\n</code></pre>\n\n<p>The last line creates a tuple containing the two functions, then evaluates y>x (True) and uses that as an index to the tuple (by casting it to an int, 1), and then calls that function with parameter y and shows the result.</p>\n\n<p>For further abuse, if you were returning an object with an index (e.g. a list) you could add further square brackets on the end; if the contents were callable, more parentheses, and so on. For extra perversion, use the result of code like this as the expression in another example (i.e. replace y>x with this code):</p>\n\n<pre><code>(sq,plus)[y>x](y)[4](x)\n</code></pre>\n\n<p>This showcases two facets of Python - the 'everything is an object' philosophy taken to the extreme, and the methods by which improper or poorly-conceived use of the language's syntax can lead to completely unreadable, unmaintainable spaghetti code that fits in a single expression.</p>\n"
},
{
"answer_id": 135024,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 4,
"selected": false,
"text": "<p>Assigning and deleting slices:</p>\n\n<pre><code>>>> a = range(10)\n>>> a\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> a[:5] = [42]\n>>> a\n[42, 5, 6, 7, 8, 9]\n>>> a[:1] = range(5)\n>>> a\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> del a[::2]\n>>> a\n[1, 3, 5, 7, 9]\n>>> a[::2] = a[::-2]\n>>> a\n[9, 3, 5, 7, 1]\n</code></pre>\n\n<p><em>Note</em>: when assigning to extended slices (<code>s[start:stop:step]</code>), the assigned iterable must have the same length as the slice.</p>\n"
},
{
"answer_id": 141900,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>dict's constructor accepts keyword arguments:</p>\n\n<pre><code>>>> dict(foo=1, bar=2)\n{'foo': 1, 'bar': 2}\n</code></pre>\n"
},
{
"answer_id": 143636,
"author": "BatchyX",
"author_id": 22985,
"author_profile": "https://Stackoverflow.com/users/22985",
"pm_score": 9,
"selected": false,
"text": "<p><strong>Get the python regex parse tree to debug your regex.</strong></p>\n\n<p>Regular expressions are a great feature of python, but debugging them can be a pain, and it's all too easy to get a regex wrong.</p>\n\n<p>Fortunately, python can print the regex parse tree, by passing the undocumented, experimental, hidden flag <code>re.DEBUG</code> (actually, 128) to <code>re.compile</code>.</p>\n\n<pre><code>>>> re.compile(\"^\\[font(?:=(?P<size>[-+][0-9]{1,2}))?\\](.*?)[/font]\",\n re.DEBUG)\nat at_beginning\nliteral 91\nliteral 102\nliteral 111\nliteral 110\nliteral 116\nmax_repeat 0 1\n subpattern None\n literal 61\n subpattern 1\n in\n literal 45\n literal 43\n max_repeat 1 2\n in\n range (48, 57)\nliteral 93\nsubpattern 2\n min_repeat 0 65535\n any None\nin\n literal 47\n literal 102\n literal 111\n literal 110\n literal 116\n</code></pre>\n\n<p>Once you understand the syntax, you can spot your errors. There we can see that I forgot to escape the <code>[]</code> in <code>[/font]</code>.</p>\n\n<p>Of course you can combine it with whatever flags you want, like commented regexes:</p>\n\n<pre><code>>>> re.compile(\"\"\"\n ^ # start of a line\n \\[font # the font tag\n (?:=(?P<size> # optional [font=+size]\n [-+][0-9]{1,2} # size specification\n ))?\n \\] # end of tag\n (.*?) # text between the tags\n \\[/font\\] # end of the tag\n \"\"\", re.DEBUG|re.VERBOSE|re.DOTALL)\n</code></pre>\n"
},
{
"answer_id": 143659,
"author": "spiv",
"author_id": 22701,
"author_profile": "https://Stackoverflow.com/users/22701",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Built-in base64, zlib, and rot13 codecs</strong></p>\n\n<p>Strings have <code>encode</code> and <code>decode</code> methods. Usually this is used for converting <code>str</code> to <code>unicode</code> and vice versa, e.g. with <code>u = s.encode('utf8')</code>. But there are some other handy builtin codecs. Compression and decompression with zlib (and bz2) is available without an explicit import:</p>\n\n<pre><code>>>> s = 'a' * 100\n>>> s.encode('zlib')\n'x\\x9cKL\\xa4=\\x00\\x00zG%\\xe5'\n</code></pre>\n\n<p>Similarly you can encode and decode base64:</p>\n\n<pre><code>>>> 'Hello world'.encode('base64')\n'SGVsbG8gd29ybGQ=\\n'\n>>> 'SGVsbG8gd29ybGQ=\\n'.decode('base64')\n'Hello world'\n</code></pre>\n\n<p>And, of course, you can rot13:</p>\n\n<pre><code>>>> 'Secret message'.encode('rot13')\n'Frperg zrffntr'\n</code></pre>\n"
},
{
"answer_id": 148211,
"author": "tadeusz",
"author_id": 7593,
"author_profile": "https://Stackoverflow.com/users/7593",
"pm_score": 5,
"selected": false,
"text": "<p>Obviously, the antigravity module.\n<a href=\"http://xkcd.com/353/\" rel=\"nofollow noreferrer\">xkcd #353</a></p>\n"
},
{
"answer_id": 165138,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Generators</strong></p>\n\n<p>I think that a lot of beginning Python developers pass over generators without really grasping what they're for or getting any sense of their power. It wasn't until I read David M. Beazley's PyCon presentation on generators (it's available <a href=\"http://www.dabeaz.com/generators/\" rel=\"nofollow noreferrer\">here</a>) that I realized how useful (essential, really) they are. That presentation illuminated what was for me an entirely new way of programming, and I recommend it to anyone who doesn't have a deep understanding of generators.</p>\n"
},
{
"answer_id": 168270,
"author": "mjard",
"author_id": 10357,
"author_profile": "https://Stackoverflow.com/users/10357",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Interactive Interpreter Tab Completion</strong></p>\n\n<pre><code>try:\n import readline\nexcept ImportError:\n print \"Unable to load readline module.\"\nelse:\n import rlcompleter\n readline.parse_and_bind(\"tab: complete\")\n\n\n>>> class myclass:\n... def function(self):\n... print \"my function\"\n... \n>>> class_instance = myclass()\n>>> class_instance.<TAB>\nclass_instance.__class__ class_instance.__module__\nclass_instance.__doc__ class_instance.function\n>>> class_instance.f<TAB>unction()\n</code></pre>\n\n<p>You will also have to set a PYTHONSTARTUP environment variable.</p>\n"
},
{
"answer_id": 171767,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Python has GOTO</strong></p>\n\n<p>...and it's implemented by <a href=\"http://entrian.com/goto/\" rel=\"nofollow noreferrer\">external pure-Python module</a> :)</p>\n\n<pre><code>from goto import goto, label\nfor i in range(1, 10):\n for j in range(1, 20):\n for k in range(1, 30):\n print i, j, k\n if k == 3:\n goto .end # breaking out from a deeply nested loop\nlabel .end\nprint \"Finished\"\n</code></pre>\n"
},
{
"answer_id": 196225,
"author": "pixelbeat",
"author_id": 4421,
"author_profile": "https://Stackoverflow.com/users/4421",
"pm_score": 2,
"selected": false,
"text": "<p>Taking advantage of python's dynamic nature to have an apps\nconfig files in python syntax. For example if you had the following\nin a config file:</p>\n\n<pre><code>{\n \"name1\": \"value1\",\n \"name2\": \"value2\"\n}\n</code></pre>\n\n<p>Then you could trivially read it like:</p>\n\n<pre><code>config = eval(open(\"filename\").read())\n</code></pre>\n"
},
{
"answer_id": 196275,
"author": "ironfroggy",
"author_id": 19687,
"author_profile": "https://Stackoverflow.com/users/19687",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Nested Function Parameter Re-binding</strong></p>\n\n<pre><code>def create_printers(n):\n for i in xrange(n):\n def printer(i=i): # Doesn't work without the i=i\n print i\n yield printer\n</code></pre>\n"
},
{
"answer_id": 205889,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 4,
"selected": false,
"text": "<p>A slight misfeature of python. The normal fast way to join a list of strings together is,</p>\n\n<pre><code>''.join(list_of_strings)\n</code></pre>\n"
},
{
"answer_id": 208087,
"author": "Gurch",
"author_id": 21006,
"author_profile": "https://Stackoverflow.com/users/21006",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://xkcd.com/353/\" rel=\"nofollow noreferrer\">import antigravity</a></p>\n"
},
{
"answer_id": 210921,
"author": "zaphod",
"author_id": 13871,
"author_profile": "https://Stackoverflow.com/users/13871",
"pm_score": 2,
"selected": false,
"text": "<h3>Private methods and data hiding (encapsulation)</h3>\n\n<p>There's a common idiom in Python of denoting methods and other class members that are not intended to be part of the class's external API by giving them names that start with underscores. This is convenient and works very well in practice, but it gives the false impression that Python does not support true encapsulation of private code and/or data. In fact, Python automatically gives you <a href=\"http://en.wikipedia.org/wiki/Lexical_closure\" rel=\"nofollow noreferrer\">lexical closures</a>, which make it very easy to encapsulate data in a much more bulletproof way when the situation really warrants it. Here's a contrived example of a class that makes use of this technique:</p>\n\n<pre><code>class MyClass(object):\n def __init__(self):\n\n privateData = {}\n\n self.publicData = 123\n\n def privateMethod(k):\n print privateData[k] + self.publicData\n\n def privilegedMethod():\n privateData['foo'] = \"hello \"\n privateMethod('foo')\n\n self.privilegedMethod = privilegedMethod\n\n def publicMethod(self):\n print self.publicData\n</code></pre>\n\n<p>And here's a contrived example of its use:</p>\n\n<pre><code>>>> obj = MyClass()\n>>> obj.publicMethod()\n123\n>>> obj.publicData = 'World'\n>>> obj.publicMethod()\nWorld\n>>> obj.privilegedMethod()\nhello World\n>>> obj.privateMethod()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'MyClass' object has no attribute 'privateMethod'\n>>> obj.privateData\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'MyClass' object has no attribute 'privateData'\n</code></pre>\n\n<p>The key is that <code>privateMethod</code> and <code>privateData</code> aren't really attributes of obj at all, so they can't be accessed from outside, nor do they show up in <code>dir()</code> or similar. They're local variables in the constructor, completely inaccessible outside of <code>__init__</code>. However, because of the magic of closures, they really are per-instance variables with the same lifetime as the object with which they're associated, even though there's no way to access them from outside except (in this example) by invoking <code>privilegedMethod</code>. Often this sort of very strict encapsulation is overkill, but sometimes it really can be very handy for keeping an API or a namespace squeaky clean.</p>\n\n<p>In Python 2.x, the only way to have mutable private state is with a mutable object (such as the dict in this example). Many people have remarked on how annoying this can be. Python 3.x will remove this restriction by introducing the <code>nonlocal</code> keyword described in <a href=\"http://www.python.org/dev/peps/pep-3104/\" rel=\"nofollow noreferrer\">PEP 3104</a>.</p>\n"
},
{
"answer_id": 215326,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Using keyword arguments as assignments</strong></p>\n\n<p>Sometimes one wants to build a range of functions depending on one or more parameters. However this might easily lead to closures all referring to the same object and value:</p>\n\n<pre><code>funcs = [] \nfor k in range(10):\n funcs.append( lambda: k)\n\n>>> funcs[0]()\n9\n>>> funcs[7]()\n9\n</code></pre>\n\n<p>This behaviour can be avoided by turning the lambda expression into a function depending only on its arguments. A keyword parameter stores the current value that is bound to it. The function call doesn't have to be altered:</p>\n\n<pre><code>funcs = [] \nfor k in range(10):\n funcs.append( lambda k = k: k)\n\n>>> funcs[0]()\n0\n>>> funcs[7]()\n7\n</code></pre>\n"
},
{
"answer_id": 218177,
"author": "Tupteq",
"author_id": 29564,
"author_profile": "https://Stackoverflow.com/users/29564",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Method replacement for object instance</strong></p>\n\n<p>You can replace methods of already created object instances. It allows you to create object instance with different (exceptional) functionality:</p>\n\n<pre><code>>>> class C(object):\n... def fun(self):\n... print \"C.a\", self\n...\n>>> inst = C()\n>>> inst.fun() # C.a method is executed\nC.a <__main__.C object at 0x00AE74D0>\n>>> instancemethod = type(C.fun)\n>>>\n>>> def fun2(self):\n... print \"fun2\", self\n...\n>>> inst.fun = instancemethod(fun2, inst, C) # Now we are replace C.a by fun2\n>>> inst.fun() # ... and fun2 is executed\nfun2 <__main__.C object at 0x00AE74D0>\n</code></pre>\n\n<p>As we can <code>C.a</code> was replaced by <code>fun2()</code> in <code>inst</code> instance (<code>self</code> didn't change).</p>\n\n<p>Alternatively we may use <code>new</code> module, but it's depreciated since Python 2.6:</p>\n\n<pre><code>>>> def fun3(self):\n... print \"fun3\", self\n...\n>>> import new\n>>> inst.fun = new.instancemethod(fun3, inst, C)\n>>> inst.fun()\nfun3 <__main__.C object at 0x00AE74D0>\n</code></pre>\n\n<p><strong>Node:</strong> This solution shouldn't be used as general replacement of inheritance mechanism! But it may be very handy in some specific situations (debugging, mocking).</p>\n\n<p><strong>Warning:</strong> This solution will not work for built-in types and for new style classes using slots.</p>\n"
},
{
"answer_id": 221874,
"author": "Jake",
"author_id": 10675,
"author_profile": "https://Stackoverflow.com/users/10675",
"pm_score": 5,
"selected": false,
"text": "<h3>Referencing a list comprehension as it is being built...</h3>\n<p>You can reference a list comprehension as it is being built by the symbol '_[1]'. For example, the following function unique-ifies a list of elements without changing their order by referencing its list comprehension.</p>\n<pre><code>def unique(my_list):\n return [x for x in my_list if x not in locals()['_[1]']]\n</code></pre>\n"
},
{
"answer_id": 224747,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://docs.python.org/library/stdtypes.html#set\" rel=\"nofollow noreferrer\"><strong>set/frozenset</strong></a></p>\n\n<p>Probably an easily overlooked python builtin is \"set/frozenset\".</p>\n\n<p>Useful when you have a list like this, [1,2,1,1,2,3,4] and only want the uniques like this [1,2,3,4].</p>\n\n<p>Using set() that's exactly what you get:</p>\n\n<pre><code>>>> x = [1,2,1,1,2,3,4] \n>>> \n>>> set(x) \nset([1, 2, 3, 4]) \n>>>\n>>> for i in set(x):\n... print i\n...\n1\n2\n3\n4\n</code></pre>\n\n<p>And of course to get the number of uniques in a list:</p>\n\n<pre><code>>>> len(set([1,2,1,1,2,3,4]))\n4\n</code></pre>\n\n<p>You can also find if a list is a subset of another list using set().issubset():</p>\n\n<pre><code>>>> set([1,2,3,4]).issubset([0,1,2,3,4,5])\nTrue\n</code></pre>\n\n<p>As of Python 2.7 and 3.0 you can use curly braces to create a set:</p>\n\n<pre><code>myset = {1,2,3,4}\n</code></pre>\n\n<p>as well as set comprehensions:</p>\n\n<pre><code>{x for x in stuff}\n</code></pre>\n\n<p>For more details:\n<a href=\"http://docs.python.org/library/stdtypes.html#set\" rel=\"nofollow noreferrer\">http://docs.python.org/library/stdtypes.html#set</a></p>\n"
},
{
"answer_id": 235492,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Functional support.</strong></p>\n\n<p>Generators and generator expressions, specifically.</p>\n\n<p>Ruby made this mainstream again, but Python can do it just as well. Not as ubiquitous in the libraries as in Ruby, which is too bad, but I like the syntax better, it's simpler.</p>\n\n<p>Because they're not as ubiquitous, I don't see as many examples out there on why they're useful, but they've allowed me to write cleaner, more efficient code.</p>\n"
},
{
"answer_id": 261833,
"author": "utku_karatas",
"author_id": 14716,
"author_profile": "https://Stackoverflow.com/users/14716",
"pm_score": 5,
"selected": false,
"text": "<p>While debugging complex data structures <em>pprint</em> module comes handy.</p>\n\n<p>Quoting from the docs..</p>\n\n<pre><code>>>> import pprint \n>>> stuff = sys.path[:]\n>>> stuff.insert(0, stuff)\n>>> pprint.pprint(stuff)\n[<Recursion on list with id=869440>,\n '',\n '/usr/local/lib/python1.5',\n '/usr/local/lib/python1.5/test',\n '/usr/local/lib/python1.5/sunos5',\n '/usr/local/lib/python1.5/sharedmodules',\n '/usr/local/lib/python1.5/tkinter']\n</code></pre>\n"
},
{
"answer_id": 299781,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<pre><code>>>> from functools import partial\n>>> bound_func = partial(range, 0, 10)\n>>> bound_func()\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> bound_func(2)\n[0, 2, 4, 6, 8]\n</code></pre>\n\n<p>not really a hidden feature but partial is extremely useful for having late evaluation of functions.</p>\n\n<p>you can bind as many or as few parameters in the initial call to partial as you want, and call it with any remaining parameters later (in this example i've bound the begin/end args to range, but call it the second time with a step arg)</p>\n\n<p>See <a href=\"http://www.python.org/doc//current/library/functools.html\" rel=\"nofollow noreferrer\">the documentation</a>.</p>\n"
},
{
"answer_id": 322868,
"author": "M. Utku ALTINKAYA",
"author_id": 40948,
"author_profile": "https://Stackoverflow.com/users/40948",
"pm_score": -1,
"selected": false,
"text": "<pre><code>is_ok() and \"Yes\" or \"No\"\n</code></pre>\n"
},
{
"answer_id": 326615,
"author": "Steen",
"author_id": 1448983,
"author_profile": "https://Stackoverflow.com/users/1448983",
"pm_score": 3,
"selected": false,
"text": "<p>...that <code>dict.get()</code> has a <a href=\"http://docs.python.org/library/stdtypes.html#dict.get\" rel=\"nofollow noreferrer\">default value</a> of None, thereby avoiding KeyErrors:</p>\n\n<pre><code>In [1]: test = { 1 : 'a' }\n\nIn [2]: test[2]\n---------------------------------------------------------------------------\n<type 'exceptions.KeyError'> Traceback (most recent call last)\n\n&lt;ipython console&gt; in <module>()\n\n<type 'exceptions.KeyError'>: 2\n\nIn [3]: test.get( 2 )\n\nIn [4]: test.get( 1 )\nOut[4]: 'a'\n\nIn [5]: test.get( 2 ) == None\nOut[5]: True\n</code></pre>\n\n<p>and even to specify this 'at the scene':</p>\n\n<pre><code>In [6]: test.get( 2, 'Some' ) == 'Some'\nOut[6]: True\n</code></pre>\n\n<p>And you can use <code>setdefault(</code>) to have a value set and returned if it doesn't exist:</p>\n\n<pre><code>>>> a = {}\n>>> b = a.setdefault('foo', 'bar')\n>>> a\n{'foo': 'bar'}\n>>> b\n'bar\n</code></pre>\n"
},
{
"answer_id": 326893,
"author": "FA.",
"author_id": 33281,
"author_profile": "https://Stackoverflow.com/users/33281",
"pm_score": 6,
"selected": false,
"text": "<p>You can easily transpose an array with zip.</p>\n\n<pre><code>a = [(1,2), (3,4), (5,6)]\nzip(*a)\n# [(1, 3, 5), (2, 4, 6)]\n</code></pre>\n"
},
{
"answer_id": 373949,
"author": "Abgan",
"author_id": 46308,
"author_profile": "https://Stackoverflow.com/users/46308",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Negative round</strong></p>\n\n<p>The <code>round()</code> function rounds a float number to given precision in decimal digits, but precision can be negative:</p>\n\n<pre><code>>>> str(round(1234.5678, -2))\n'1200.0'\n>>> str(round(1234.5678, 2))\n'1234.57'\n</code></pre>\n\n<p><em>Note:</em> <code>round()</code> always returns a float, <code>str()</code> used in the above example because floating point math is inexact, and under 2.x the second example can print as <code>1234.5700000000001</code>. Also see the <a href=\"http://docs.python.org/library/decimal.html#module-decimal\" rel=\"nofollow noreferrer\"><code>decimal</code></a> module.</p>\n"
},
{
"answer_id": 393927,
"author": "James Brady",
"author_id": 29903,
"author_profile": "https://Stackoverflow.com/users/29903",
"pm_score": 5,
"selected": false,
"text": "<p><strong>An interpreter within the interpreter</strong></p>\n\n<p>The standard library's <a href=\"http://docs.python.org/library/code.html\" rel=\"nofollow noreferrer\">code</a> module let's you include your own read-eval-print loop inside a program, or run a whole nested interpreter. E.g. (copied my example from <a href=\"https://stackoverflow.com/questions/393871/scripting-inside-a-python-application#393921\">here</a>)</p>\n\n<pre><code>$ python\nPython 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) \n[GCC 4.0.1 (Apple Inc. build 5465)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> shared_var = \"Set in main console\"\n>>> import code\n>>> ic = code.InteractiveConsole({ 'shared_var': shared_var })\n>>> try:\n... ic.interact(\"My custom console banner!\")\n... except SystemExit, e:\n... print \"Got SystemExit!\"\n... \nMy custom console banner!\n>>> shared_var\n'Set in main console'\n>>> shared_var = \"Set in sub-console\"\n>>> import sys\n>>> sys.exit()\nGot SystemExit!\n>>> shared_var\n'Set in main console'\n</code></pre>\n\n<p>This is extremely useful for situations where you want to accept scripted input from the user, or query the state of the VM in real-time.</p>\n\n<p><a href=\"http://turbogears.com/\" rel=\"nofollow noreferrer\">TurboGears</a> uses this to great effect by having a WebConsole from which you can query the state of you live web app.</p>\n"
},
{
"answer_id": 405085,
"author": "Kiv",
"author_id": 49559,
"author_profile": "https://Stackoverflow.com/users/49559",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Operator overloading for the <code>set</code> builtin:</strong></p>\n\n<pre><code>>>> a = set([1,2,3,4])\n>>> b = set([3,4,5,6])\n>>> a | b # Union\n{1, 2, 3, 4, 5, 6}\n>>> a & b # Intersection\n{3, 4}\n>>> a < b # Subset\nFalse\n>>> a - b # Difference\n{1, 2}\n>>> a ^ b # Symmetric Difference\n{1, 2, 5, 6}\n</code></pre>\n\n<p>More detail from the standard library reference: <a href=\"http://docs.python.org/py3k/library/stdtypes.html#set-types-set-frozenset\" rel=\"noreferrer\">Set Types</a></p>\n"
},
{
"answer_id": 405094,
"author": "Benjamin Peterson",
"author_id": 33795,
"author_profile": "https://Stackoverflow.com/users/33795",
"pm_score": 3,
"selected": false,
"text": "<p>You can override the mro of a class with a metaclass</p>\n\n<pre><code>>>> class A(object):\n... def a_method(self):\n... print(\"A\")\n... \n>>> class B(object):\n... def b_method(self):\n... print(\"B\")\n... \n>>> class MROMagicMeta(type):\n... def mro(cls):\n... return (cls, B, object)\n... \n>>> class C(A, metaclass=MROMagicMeta):\n... def c_method(self):\n... print(\"C\")\n... \n>>> cls = C()\n>>> cls.c_method()\nC\n>>> cls.a_method()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'C' object has no attribute 'a_method'\n>>> cls.b_method()\nB\n>>> type(cls).__bases__\n(<class '__main__.A'>,)\n>>> type(cls).__mro__\n(<class '__main__.C'>, <class '__main__.B'>, <class 'object'>)\n</code></pre>\n\n<p>It's probably hidden for a good reason. :)</p>\n"
},
{
"answer_id": 407695,
"author": "Christian Oudard",
"author_id": 3757,
"author_profile": "https://Stackoverflow.com/users/3757",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>reversed()</code> builtin. It makes iterating much cleaner in many cases.</p>\n\n<p>quick example:</p>\n\n<pre><code>for i in reversed([1, 2, 3]):\n print(i)\n</code></pre>\n\n<p>produces:</p>\n\n<pre><code>3\n2\n1\n</code></pre>\n\n<p>However, <code>reversed()</code> also works with arbitrary iterators, such as lines in a file, or generator expressions.</p>\n"
},
{
"answer_id": 407754,
"author": "sprintf",
"author_id": 50712,
"author_profile": "https://Stackoverflow.com/users/50712",
"pm_score": 3,
"selected": false,
"text": "<p><strong>The Zen of Python</strong></p>\n\n<pre><code>>>> import this\nThe Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!\n</code></pre>\n"
},
{
"answer_id": 435187,
"author": "Tom Viner",
"author_id": 15890,
"author_profile": "https://Stackoverflow.com/users/15890",
"pm_score": 3,
"selected": false,
"text": "<p><strong>pdb — The Python Debugger</strong></p>\n\n<p>As a programmer, one of the first things that you need for serious program development is a debugger. Python has one built-in which is available as a module called pdb (for \"Python DeBugger\", naturally!).</p>\n\n<p><a href=\"http://docs.python.org/library/pdb.html\" rel=\"nofollow noreferrer\">http://docs.python.org/library/pdb.html</a></p>\n"
},
{
"answer_id": 585473,
"author": "Mykola Kharechko",
"author_id": 69885,
"author_profile": "https://Stackoverflow.com/users/69885",
"pm_score": 3,
"selected": false,
"text": "<p>Objects of small intgers (-5 .. 256) never created twice:</p>\n\n<pre>\n<code>\n>>> a1 = -5; b1 = 256\n>>> a2 = -5; b2 = 256\n>>> id(a1) == id(a2), id(b1) == id(b2)\n(True, True)\n>>>\n>>> c1 = -6; d1 = 257\n>>> c2 = -6; d2 = 257\n>>> id(c1) == id(c2), id(d1) == id(d2)\n(False, False)\n>>>\n</code>\n</pre>\n\n<p>Edit:\nList objects never destroyed (only objects in lists). Python has array in which it keeps up to 80 empty lists. When you destroy list object - python puts it to that array and when you create new list - python gets last puted list from this array:</p>\n\n<pre>\n<code>\n>>> a = [1,2,3]; a_id = id(a)\n>>> b = [1,2,3]; b_id = id(b)\n>>> del a; del b\n>>> c = [1,2,3]; id(c) == b_id\nTrue\n>>> d = [1,2,3]; id(d) == a_id\nTrue\n>>>\n</code>\n</pre>\n"
},
{
"answer_id": 603391,
"author": "lprsd",
"author_id": 55562,
"author_profile": "https://Stackoverflow.com/users/55562",
"pm_score": 3,
"selected": false,
"text": "<p>Creating dictionary of two sequences that have related data</p>\n\n<pre><code>In [15]: t1 = (1, 2, 3)\n\nIn [16]: t2 = (4, 5, 6)\n\nIn [17]: dict (zip(t1,t2))\nOut[17]: {1: 4, 2: 5, 3: 6}\n</code></pre>\n"
},
{
"answer_id": 603408,
"author": "lprsd",
"author_id": 55562,
"author_profile": "https://Stackoverflow.com/users/55562",
"pm_score": 2,
"selected": false,
"text": "<p>Simulating the tertiary operator using and and or.</p>\n\n<p>and and or operators in python return the objects themselves rather than Booleans. Thus:</p>\n\n<pre><code>In [18]: a = True\n\nIn [19]: a and 3 or 4\nOut[19]: 3\n\nIn [20]: a = False\n\nIn [21]: a and 3 or 4\nOut[21]: 4\n</code></pre>\n\n<p>However, Py 2.5 seems to have added an explicit tertiary operator</p>\n\n<pre><code> In [22]: a = 5 if True else '6'\n\n In [23]: a\n Out[23]: 5\n</code></pre>\n\n<p>Well, this works if you are sure that your true clause does not evaluate to False. example:</p>\n\n<pre><code>>>> def foo(): \n... print \"foo\"\n... return 0\n...\n>>> def bar(): \n... print \"bar\"\n... return 1\n...\n>>> 1 and foo() or bar()\nfoo\nbar\n1\n</code></pre>\n\n<p>To get it right, you've got to just a little bit more: </p>\n\n<pre><code>>>> (1 and [foo()] or [bar()])[0]\nfoo\n0\n</code></pre>\n\n<p>However, this isn't as pretty. if your version of python supports it, use the conditional operator.</p>\n\n<pre><code>>>> foo() if True or bar()\nfoo\n0\n</code></pre>\n"
},
{
"answer_id": 632582,
"author": "Pratik Deoghare",
"author_id": 58737,
"author_profile": "https://Stackoverflow.com/users/58737",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://docs.python.org/library/inspect.html?highlight=inspect#retrieving-source-code\" rel=\"nofollow noreferrer\">inspect</a> module is also a cool feature.</p>\n"
},
{
"answer_id": 652687,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "<h3>The <code>spam</code> module in standard Python</h3>\n\n<p>It is used for testing purposes. </p>\n\n<p>I've picked it from <a href=\"http://starship.python.net/crew/theller/ctypes/tutorial.html\" rel=\"nofollow noreferrer\"><code>ctypes</code> tutorial</a>. Try it yourself:</p>\n\n<pre><code>>>> import __hello__\nHello world...\n>>> type(__hello__)\n<type 'module'>\n>>> from __phello__ import spam\nHello world...\nHello world...\n>>> type(spam)\n<type 'module'>\n>>> help(spam)\nHelp on module __phello__.spam in __phello__:\n\nNAME\n __phello__.spam\n\nFILE\n c:\\python26\\<frozen>\n</code></pre>\n"
},
{
"answer_id": 781998,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Memory Management</strong></p>\n\n<p>Python dynamically allocates memory and uses garbage collection to recover unused space. Once an object is out of scope, and no other variables reference it, it will be recovered. I do not have to worry about buffer overruns and slowly growing server processes. Memory management is also a feature of other dynamic languages but Python just does it so well.</p>\n\n<p>Of course, we must watch out for circular references and keeping references to objects which are no longer needed, but weak references help a lot here.</p>\n"
},
{
"answer_id": 804238,
"author": "Scott Kirkwood",
"author_id": 95818,
"author_profile": "https://Stackoverflow.com/users/95818",
"pm_score": 6,
"selected": false,
"text": "<h1>re can call functions!</h1>\n\n<p>The fact that you can call a function every time something matches a regular expression is very handy.\nHere I have a sample of replacing every \"Hello\" with \"Hi,\" and \"there\" with \"Fred\", etc.</p>\n\n<pre><code>import re\n\ndef Main(haystack):\n # List of from replacements, can be a regex\n finds = ('Hello', 'there', 'Bob')\n replaces = ('Hi,', 'Fred,', 'how are you?')\n\n def ReplaceFunction(matchobj):\n for found, rep in zip(matchobj.groups(), replaces):\n if found != None:\n return rep\n\n # log error\n return matchobj.group(0)\n\n named_groups = [ '(%s)' % find for find in finds ]\n ret = re.sub('|'.join(named_groups), ReplaceFunction, haystack)\n print ret\n\nif __name__ == '__main__':\n str = 'Hello there Bob'\n Main(str)\n # Prints 'Hi, Fred, how are you?'\n</code></pre>\n"
},
{
"answer_id": 938602,
"author": "Tom",
"author_id": 115846,
"author_profile": "https://Stackoverflow.com/users/115846",
"pm_score": 5,
"selected": false,
"text": "<p>I personally love the <strong>3 different quotes</strong></p>\n\n<pre><code>str = \"I'm a string 'but still I can use quotes' inside myself!\"\nstr = \"\"\" For some messy multi line strings.\nSuch as\n<html>\n<head> ... </head>\"\"\"\n</code></pre>\n\n<p>Also cool: not having to escape regular expressions, avoiding horrible backslash salad by using <strong>raw strings</strong>:</p>\n\n<pre><code>str2 = r\"\\n\" \nprint str2\n>> \\n\n</code></pre>\n"
},
{
"answer_id": 967971,
"author": "Ken Arnold",
"author_id": 69707,
"author_profile": "https://Stackoverflow.com/users/69707",
"pm_score": 4,
"selected": false,
"text": "<p>One word: <a href=\"http://ipython.scipy.org/moin/\" rel=\"nofollow noreferrer\">IPython</a></p>\n\n<p>Tab introspection, pretty-printing, <code>%debug</code>, history management, <code>pylab</code>, ... well worth the time to learn well.</p>\n"
},
{
"answer_id": 967998,
"author": "Ken Arnold",
"author_id": 69707,
"author_profile": "https://Stackoverflow.com/users/69707",
"pm_score": 3,
"selected": false,
"text": "<p>Reloading modules enables a \"live-coding\" style. But class instances don't update. Here's why, and how to get around it. Remember, everything, yes, <em>everything</em> is an object.</p>\n\n<pre><code>>>> from a_package import a_module\n>>> cls = a_module.SomeClass\n>>> obj = cls()\n>>> obj.method()\n(old method output)\n</code></pre>\n\n<p>Now you change the method in a_module.py and want to update your object.</p>\n\n<pre><code>>>> reload(a_module)\n>>> a_module.SomeClass is cls\nFalse # Because it just got freshly created by reload.\n>>> obj.method()\n(old method output)\n</code></pre>\n\n<p>Here's one way to update it (but consider it running with scissors):</p>\n\n<pre><code>>>> obj.__class__ is cls\nTrue # it's the old class object\n>>> obj.__class__ = a_module.SomeClass # pick up the new class\n>>> obj.method()\n(new method output)\n</code></pre>\n\n<p>This is \"running with scissors\" because the object's internal state may be different than what the new class expects. This works for really simple cases, but beyond that, <code>pickle</code> is your friend. It's still helpful to understand why this works, though.</p>\n"
},
{
"answer_id": 1013448,
"author": "Markus",
"author_id": 125185,
"author_profile": "https://Stackoverflow.com/users/125185",
"pm_score": 4,
"selected": false,
"text": "<p>Not very hidden, but functions have attributes:</p>\n\n<pre><code>def doNothing():\n pass\n\ndoNothing.monkeys = 4\nprint doNothing.monkeys\n4\n</code></pre>\n"
},
{
"answer_id": 1013470,
"author": "Markus",
"author_id": 125185,
"author_profile": "https://Stackoverflow.com/users/125185",
"pm_score": 3,
"selected": false,
"text": "<p>You can decorate functions with classes - replacing the function with a class instance:</p>\n\n<pre><code>class countCalls(object):\n \"\"\" decorator replaces a function with a \"countCalls\" instance\n which behaves like the original function, but keeps track of calls\n\n >>> @countCalls\n ... def doNothing():\n ... pass\n >>> doNothing()\n >>> doNothing()\n >>> print doNothing.timesCalled\n 2\n \"\"\"\n def __init__ (self, functionToTrack):\n self.functionToTrack = functionToTrack\n self.timesCalled = 0\n def __call__ (self, *args, **kwargs):\n self.timesCalled += 1\n return self.functionToTrack(*args, **kwargs)\n</code></pre>\n"
},
{
"answer_id": 1013517,
"author": "Markus",
"author_id": 125185,
"author_profile": "https://Stackoverflow.com/users/125185",
"pm_score": 2,
"selected": false,
"text": "<p>With a minute amount of work, the threading module becomes amazingly easy to use. This decorator changes a function so that it runs in its own thread, returning a placeholder class instance instead of its regular result. You can probe for the answer by checking placeolder.result or wait for it by calling placeholder.awaitResult()</p>\n\n<pre><code>def threadify(function):\n \"\"\"\n exceptionally simple threading decorator. Just:\n >>> @threadify\n ... def longOperation(result):\n ... time.sleep(3)\n ... return result\n >>> A= longOperation(\"A has finished\")\n >>> B= longOperation(\"B has finished\")\n\n A doesn't have a result yet:\n >>> print A.result\n None\n\n until we wait for it:\n >>> print A.awaitResult()\n A has finished\n\n we could also wait manually - half a second more should be enough for B:\n >>> time.sleep(0.5); print B.result\n B has finished\n \"\"\"\n class thr (threading.Thread,object):\n def __init__(self, *args, **kwargs):\n threading.Thread.__init__ ( self ) \n self.args, self.kwargs = args, kwargs\n self.result = None\n self.start()\n def awaitResult(self):\n self.join()\n return self.result \n def run(self):\n self.result=function(*self.args, **self.kwargs)\n return thr\n</code></pre>\n"
},
{
"answer_id": 1024693,
"author": "André",
"author_id": 9683,
"author_profile": "https://Stackoverflow.com/users/9683",
"pm_score": 8,
"selected": false,
"text": "<p>ROT13 is a valid encoding for source code, when you use the right coding declaration at the top of the code file:</p>\n\n<pre><code>#!/usr/bin/env python\n# -*- coding: rot13 -*-\n\ncevag \"Uryyb fgnpxbiresybj!\".rapbqr(\"rot13\")\n</code></pre>\n"
},
{
"answer_id": 1088213,
"author": "Steven Sproat",
"author_id": 108560,
"author_profile": "https://Stackoverflow.com/users/108560",
"pm_score": 2,
"selected": false,
"text": "<p>If you've renamed a class in your application where you're loading user-saved files via Pickle, and one of the renamed classes are stored in a user's old save, you will not be able to load in that pickled file.</p>\n\n<p>However, simply add in a reference to your class definition and everything's good:</p>\n\n<p>e.g., before:</p>\n\n<pre><code>class Bleh:\n pass\n</code></pre>\n\n<p>now, </p>\n\n<pre><code>class Blah:\n pass\n</code></pre>\n\n<p>so, your user's pickled saved file contains a reference to Bleh, which doesn't exist due to the rename. The fix?</p>\n\n<pre><code>Bleh = Blah\n</code></pre>\n\n<p>simple!</p>\n"
},
{
"answer_id": 1338523,
"author": "Greg",
"author_id": 105101,
"author_profile": "https://Stackoverflow.com/users/105101",
"pm_score": 2,
"selected": false,
"text": "<p>The fact that EVERYTHING is an object, and as such is extensible. I can add member variables as metadata to a function that I define:</p>\n\n<pre><code>>>> def addInts(x,y): \n... return x + y\n>>> addInts.params = ['integer','integer']\n>>> addInts.returnType = 'integer'\n</code></pre>\n\n<p>This can be very useful for writing dynamic unit tests, e.g.</p>\n"
},
{
"answer_id": 1399564,
"author": "Busted Keaton",
"author_id": 164711,
"author_profile": "https://Stackoverflow.com/users/164711",
"pm_score": 2,
"selected": false,
"text": "<p>The getattr built-in function :</p>\n\n<pre><code>>>> class C():\n def getMontys(self):\n self.montys = ['Cleese','Palin','Idle','Gilliam','Jones','Chapman']\n return self.montys\n\n\n>>> c = C()\n>>> getattr(c,'getMontys')()\n['Cleese', 'Palin', 'Idle', 'Gilliam', 'Jones', 'Chapman']\n>>> \n</code></pre>\n\n<p>Useful if you want to dispatch function depending on the context. See examples in Dive Into Python (<a href=\"http://diveintopython.net/power_of_introspection/getattr.html\" rel=\"nofollow noreferrer\">Here</a>)</p>\n"
},
{
"answer_id": 1592819,
"author": "six8",
"author_id": 185316,
"author_profile": "https://Stackoverflow.com/users/185316",
"pm_score": 2,
"selected": false,
"text": "<p>Simple way to test if a key is in a dict:</p>\n\n<pre><code>>>> 'key' in { 'key' : 1 }\nTrue\n\n>>> d = dict(key=1, key2=2)\n>>> if 'key' in d:\n... print 'Yup'\n... \nYup\n</code></pre>\n"
},
{
"answer_id": 1602751,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Classes as first-class objects (shown through a dynamic class definition)</strong></p>\n\n<p>Note the use of the closure as well. If this particular example looks like a \"right\" approach to a problem, carefully reconsider ... several times :)</p>\n\n<pre><code>def makeMeANewClass(parent, value):\n class IAmAnObjectToo(parent):\n def theValue(self):\n return value\n return IAmAnObjectToo\n\nKlass = makeMeANewClass(str, \"fred\")\no = Klass()\nprint isinstance(o, str) # => True\nprint o.theValue() # => fred\n</code></pre>\n"
},
{
"answer_id": 1602786,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p><strong><em>Exposing Mutable Buffers</em></strong></p>\n\n<p>Using the Python <a href=\"http://docs.python.org/c-api/buffer.html\" rel=\"noreferrer\">Buffer Protocol</a> to <em>expose mutable byte-oriented buffers</em> in Python (2.5/2.6).</p>\n\n<p>(Sorry, no code here. Requires use of low-level C API or existing adapter module).</p>\n"
},
{
"answer_id": 1631763,
"author": "Denis Otkidach",
"author_id": 168352,
"author_profile": "https://Stackoverflow.com/users/168352",
"pm_score": 4,
"selected": false,
"text": "<h2>Extending properties (defined as descriptor) in subclasses</h2>\n\n<p>Sometimes it's useful to extent (modify) value \"returned\" by descriptor in subclass. It can be easily done with <code>super()</code>:</p>\n\n<pre><code>class A(object):\n @property\n def prop(self):\n return {'a': 1}\n\nclass B(A):\n @property\n def prop(self):\n return dict(super(B, self).prop, b=2)\n</code></pre>\n\n<p>Store this in <code>test.py</code> and run <code>python -i test.py</code> (<strong>another hidden feature: <code>-i</code> option executed the script and allow you to continue in interactive mode</strong>):</p>\n\n<pre><code>>>> B().prop\n{'a': 1, 'b': 2}\n</code></pre>\n"
},
{
"answer_id": 1667256,
"author": "Amol",
"author_id": 91966,
"author_profile": "https://Stackoverflow.com/users/91966",
"pm_score": 3,
"selected": false,
"text": "<p>The pythonic idiom <code>x = ... if ... else ...</code> is far superior to <code>x = ... and ... or ...</code> and here is why:</p>\n\n<p>Although the statement </p>\n\n<pre><code>x = 3 if (y == 1) else 2\n</code></pre>\n\n<p>Is equivalent to</p>\n\n<pre><code>x = y == 1 and 3 or 2\n</code></pre>\n\n<p>if you use the <code>x = ... and ... or ...</code> idiom, some day you may get bitten by this tricky situation:</p>\n\n<pre><code>x = 0 if True else 1 # sets x equal to 0\n</code></pre>\n\n<p>and therefore is not equivalent to </p>\n\n<pre><code>x = True and 0 or 1 # sets x equal to 1\n</code></pre>\n\n<p>For more on the proper way to do this,\nsee <a href=\"https://stackoverflow.com/questions/101268/hidden-features-of-python/116480#116480\">Hidden features of Python</a>.</p>\n"
},
{
"answer_id": 1687543,
"author": "u0b34a0f6ae",
"author_id": 137317,
"author_profile": "https://Stackoverflow.com/users/137317",
"pm_score": 4,
"selected": false,
"text": "<p>Python <a href=\"http://bugs.python.org/issue6595\" rel=\"nofollow noreferrer\">can understand any kind of unicode digits</a>, not just the ASCII kind:</p>\n\n<pre><code>>>> s = u'10585'\n>>> s\nu'\\uff11\\uff10\\uff15\\uff18\\uff15'\n>>> print s\n10585\n>>> int(s)\n10585\n>>> float(s)\n10585.0\n</code></pre>\n"
},
{
"answer_id": 1734183,
"author": "Eryk Sun",
"author_id": 205580,
"author_profile": "https://Stackoverflow.com/users/205580",
"pm_score": 2,
"selected": false,
"text": "<p>Regarding Nick Johnson's implementation of a <a href=\"https://stackoverflow.com/questions/101268/hidden-features-of-python/102062#102062\">Property class</a> (just a demonstration of descriptors, of course, not a replacement for the built-in), I'd include a setter that raises an AttributeError:</p>\n\n<pre>\nclass Property(object):\n def __init__(self, fget):\n self.fget = fget\n\n def __get__(self, obj, type):\n if obj is None:\n return self\n return self.fget(obj)\n\n def __set__(self, obj, value):\n raise AttributeError, 'Read-only attribute'\n</pre>\n\n<p>Including the setter makes this a data descriptor as opposed to a method/non-data descriptor. A data descriptor has precedence over instance dictionaries. Now an instance can't have a different object assigned to the property name, and attempts to assign to the property will raise an attribute error.</p>\n"
},
{
"answer_id": 1823597,
"author": "Noctis Skytower",
"author_id": 216356,
"author_profile": "https://Stackoverflow.com/users/216356",
"pm_score": 5,
"selected": false,
"text": "<p>The unpacking syntax has been upgraded in the recent version as can be seen in the example.</p>\n\n<pre><code>>>> a, *b = range(5)\n>>> a, b\n(0, [1, 2, 3, 4])\n>>> *a, b = range(5)\n>>> a, b\n([0, 1, 2, 3], 4)\n>>> a, *b, c = range(5)\n>>> a, b, c\n(0, [1, 2, 3], 4)\n</code></pre>\n"
},
{
"answer_id": 1837623,
"author": "grayger",
"author_id": 433078,
"author_profile": "https://Stackoverflow.com/users/433078",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Manipulating Recursion Limit</strong></p>\n\n<p>Getting or setting the maximum depth of recursion with sys.getrecursionlimit() & sys.setrecursionlimit().</p>\n\n<p>We can limit it to prevent a stack overflow caused by infinite recursion.</p>\n"
},
{
"answer_id": 1853593,
"author": "jpsimons",
"author_id": 205934,
"author_profile": "https://Stackoverflow.com/users/205934",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Multiplying by a boolean</strong></p>\n\n<p>One thing I'm constantly doing in web development is optionally printing HTML parameters. We've all seen code like this in other languages:</p>\n\n<pre><code>class='<% isSelected ? \"selected\" : \"\" %>'\n</code></pre>\n\n<p>In Python, you can multiply by a boolean and it does exactly what you'd expect:</p>\n\n<pre><code>class='<% \"selected\" * isSelected %>'\n</code></pre>\n\n<p>This is because multiplication coerces the boolean to an integer (0 for False, 1 for True), and in python multiplying a string by an int <em>repeats</em> the string N times.</p>\n"
},
{
"answer_id": 1853633,
"author": "jpsimons",
"author_id": 205934,
"author_profile": "https://Stackoverflow.com/users/205934",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Mod works correctly with negative numbers</strong></p>\n\n<p>-1 % 5 is <strong><em>4</em></strong>, as it should be, not -1 as it is in other languages like JavaScript. This makes \"wraparound windows\" cleaner in Python, you just do this:</p>\n\n<pre><code>index = (index + increment) % WINDOW_SIZE\n</code></pre>\n"
},
{
"answer_id": 1958325,
"author": "Martin Thurau",
"author_id": 20247,
"author_profile": "https://Stackoverflow.com/users/20247",
"pm_score": 0,
"selected": false,
"text": "<p>You can construct a functions kwargs on demand:</p>\n\n<pre><code>kwargs = {}\nkwargs[str(\"%s__icontains\" % field)] = some_value\nsome_function(**kwargs)\n</code></pre>\n\n<p>The str() call is somehow needed, since python complains otherwise that it is no string. Don't know why ;)\nI use this for a dynamic filters within Djangos object model:</p>\n\n<pre><code>result = model_class.objects.filter(**kwargs)\n</code></pre>\n"
},
{
"answer_id": 1983078,
"author": "Xavier Martinez-Hidalgo",
"author_id": 25996,
"author_profile": "https://Stackoverflow.com/users/25996",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Guessing integer base</strong></p>\n\n<pre><code>>>> int('10', 0)\n10\n>>> int('0x10', 0)\n16\n>>> int('010', 0) # does not work on Python 3.x\n8\n>>> int('0o10', 0) # Python >=2.6 and Python 3.x\n8\n>>> int('0b10', 0) # Python >=2.6 and Python 3.x\n2\n</code></pre>\n"
},
{
"answer_id": 1983095,
"author": "Xavier Martinez-Hidalgo",
"author_id": 25996,
"author_profile": "https://Stackoverflow.com/users/25996",
"pm_score": 4,
"selected": false,
"text": "<p><strong>itertools</strong></p>\n\n<p>This module is often overlooked. The following example uses <code>itertools.chain()</code>\nto flatten a list:</p>\n\n<pre><code>>>> from itertools import *\n>>> l = [[1, 2], [3, 4]]\n>>> list(chain(*l))\n[1, 2, 3, 4]\n</code></pre>\n\n<p>See <a href=\"http://docs.python.org/library/itertools.html#recipes\" rel=\"nofollow noreferrer\">http://docs.python.org/library/itertools.html#recipes</a> for more applications.</p>\n"
},
{
"answer_id": 2060871,
"author": "Chinmay Kanchi",
"author_id": 148765,
"author_profile": "https://Stackoverflow.com/users/148765",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Monkeypatching objects</strong></p>\n\n<p>Every object in Python has a <code>__dict__</code> member, which stores the object's attributes. So, you can do something like this:</p>\n\n<pre><code>class Foo(object):\n def __init__(self, arg1, arg2, **kwargs):\n #do stuff with arg1 and arg2\n self.__dict__.update(kwargs)\n\nf = Foo('arg1', 'arg2', bar=20, baz=10)\n#now f is a Foo object with two extra attributes\n</code></pre>\n\n<p>This can be exploited to add both attributes and functions arbitrarily to objects. This can also be exploited to create a quick-and-dirty <code>struct</code> type.</p>\n\n<pre><code>class struct(object):\n def __init__(**kwargs):\n self.__dict__.update(kwargs)\n\ns = struct(foo=10, bar=11, baz=\"i'm a string!')\n</code></pre>\n"
},
{
"answer_id": 2060945,
"author": "Chinmay Kanchi",
"author_id": 148765,
"author_profile": "https://Stackoverflow.com/users/148765",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Creating enums</strong></p>\n\n<p>In Python, you can do this to quickly create an enumeration:</p>\n\n<pre><code>>>> FOO, BAR, BAZ = range(3)\n>>> FOO\n0\n</code></pre>\n\n<p>But the \"enums\" don't have to have integer values. You can even do this:</p>\n\n<pre><code>class Colors(object):\n RED, GREEN, BLUE, YELLOW = (255,0,0), (0,255,0), (0,0,255), (0,255,255)\n\n#now Colors.RED is a 3-tuple that returns the 24-bit 8bpp RGB \n#value for saturated red\n</code></pre>\n"
},
{
"answer_id": 2259080,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 4,
"selected": false,
"text": "<h2>Manipulating sys.modules</h2>\n\n<p>You can manipulate the modules cache directly, making modules available or unavailable as you wish:</p>\n\n<pre><code>>>> import sys\n>>> import ham\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nImportError: No module named ham\n\n# Make the 'ham' module available -- as a non-module object even!\n>>> sys.modules['ham'] = 'ham, eggs, saussages and spam.'\n>>> import ham\n>>> ham\n'ham, eggs, saussages and spam.'\n\n# Now remove it again.\n>>> sys.modules['ham'] = None\n>>> import ham\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nImportError: No module named ham\n</code></pre>\n\n<p>This works even for modules that <em>are</em> available, and to some extent for modules that <em>already are imported</em>:</p>\n\n<pre><code>>>> import os\n# Stop future imports of 'os'.\n>>> sys.modules['os'] = None\n>>> import os\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nImportError: No module named os\n# Our old imported module is still available.\n>>> os\n<module 'os' from '/usr/lib/python2.5/os.pyc'>\n</code></pre>\n\n<p>As the last line shows, changing sys.modules only affects future <code>import</code> statements, not past ones, so if you want to affect other modules it's important to make these changes <em>before</em> you give them a chance to try and import the modules -- so before you import them, typically. <code>None</code> is a special value in <code>sys.modules</code>, used for negative caching (indicating the module was not found the first time, so there's no point in looking again.) Any other value will be the result of the <code>import</code> operation -- even when it is not a module object. You can use this to replace modules with objects that behave exactly like you want. Deleting the entry from <code>sys.modules</code> entirely causes the next <code>import</code> to do a normal search for the module, even if it was already imported before.</p>\n"
},
{
"answer_id": 2259256,
"author": "Juanjo Conti",
"author_id": 157519,
"author_profile": "https://Stackoverflow.com/users/157519",
"pm_score": 2,
"selected": false,
"text": "<p>There are no secrets in Python ;)</p>\n"
},
{
"answer_id": 2482459,
"author": "evilpie",
"author_id": 297734,
"author_profile": "https://Stackoverflow.com/users/297734",
"pm_score": 4,
"selected": false,
"text": "<h2>Passing tuple to builtin functions</h2>\n\n<p>Much Python functions accept tuples, also it doesn't seem like. For example you want to test if your variable is a number, you could do: </p>\n\n<pre><code>if isinstance (number, float) or isinstance (number, int): \n print \"yaay\"\n</code></pre>\n\n<p>But if you pass us tuple this looks much cleaner: </p>\n\n<pre><code>if isinstance (number, (float, int)): \n print \"yaay\"\n</code></pre>\n"
},
{
"answer_id": 2582013,
"author": "haridsv",
"author_id": 95750,
"author_profile": "https://Stackoverflow.com/users/95750",
"pm_score": 2,
"selected": false,
"text": "<p>You can assign several variables to the same value</p>\n\n<pre><code>>>> foo = bar = baz = 1\n>>> foo, bar, baz\n(1, 1, 1)\n</code></pre>\n\n<p>Useful to initialize several variable to None, in a compact way.</p>\n"
},
{
"answer_id": 2582046,
"author": "haridsv",
"author_id": 95750,
"author_profile": "https://Stackoverflow.com/users/95750",
"pm_score": 3,
"selected": false,
"text": "<p>threading.enumerate() gives access to all Thread objects in the system and sys._current_frames() returns the current stack frames of all threads in the system, so combine these two and you get Java style stack dumps:</p>\n\n<pre><code>def dumpstacks(signal, frame):\n id2name = dict([(th.ident, th.name) for th in threading.enumerate()])\n code = []\n for threadId, stack in sys._current_frames().items():\n code.append(\"\\n# Thread: %s(%d)\" % (id2name[threadId], threadId))\n for filename, lineno, name, line in traceback.extract_stack(stack):\n code.append('File: \"%s\", line %d, in %s' % (filename, lineno, name))\n if line:\n code.append(\" %s\" % (line.strip()))\n print \"\\n\".join(code)\n\nimport signal\nsignal.signal(signal.SIGQUIT, dumpstacks)\n</code></pre>\n\n<p>Do this at the beginning of a multi-threaded python program and you get access to current state of threads at any time by sending a SIGQUIT. You may also choose signal.SIGUSR1 or signal.SIGUSR2.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application/2569696#2569696\">See</a></p>\n"
},
{
"answer_id": 2830047,
"author": "L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳",
"author_id": 80243,
"author_profile": "https://Stackoverflow.com/users/80243",
"pm_score": -1,
"selected": false,
"text": "<p><strong>Braces</strong></p>\n\n<pre><code>def g():\n print 'hi!'\n\ndef f(): (\n g()\n)\n\n>>> f()\nhi!\n</code></pre>\n"
},
{
"answer_id": 2898562,
"author": "L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳",
"author_id": 80243,
"author_profile": "https://Stackoverflow.com/users/80243",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Top Secret Attributes</strong></p>\n\n<pre><code>>>> class A(object): pass\n>>> a = A()\n>>> setattr(a, \"can't touch this\", 123)\n>>> dir(a)\n['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', \"can't touch this\"]\n>>> a.can't touch this # duh\n File \"<stdin>\", line 1\n a.can't touch this\n ^\nSyntaxError: EOL while scanning string literal\n>>> getattr(a, \"can't touch this\")\n123\n>>> setattr(a, \"__class__.__name__\", \":O\")\n>>> a.__class__.__name__\n'A'\n>>> getattr(a, \"__class__.__name__\")\n':O'\n</code></pre>\n"
},
{
"answer_id": 2916508,
"author": "Evgeny",
"author_id": 331701,
"author_profile": "https://Stackoverflow.com/users/331701",
"pm_score": 4,
"selected": false,
"text": "<p>Nice treatment of infinite recursion in dictionaries:</p>\n\n<pre><code>>>> a = {}\n>>> b = {}\n>>> a['b'] = b\n>>> b['a'] = a\n>>> print a\n{'b': {'a': {...}}}\n</code></pre>\n"
},
{
"answer_id": 3143595,
"author": "David Z",
"author_id": 56541,
"author_profile": "https://Stackoverflow.com/users/56541",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Multiple references to an iterator</strong></p>\n\n<p>You can create multiple references to the same iterator using list multiplication:</p>\n\n<pre><code>>>> i = (1,2,3,4,5,6,7,8,9,10) # or any iterable object\n>>> iterators = [iter(i)] * 2\n>>> iterators[0].next()\n1\n>>> iterators[1].next()\n2\n>>> iterators[0].next()\n3\n</code></pre>\n\n<p>This can be used to group an iterable into chunks, for example, as in this example from the <a href=\"http://docs.python.org/library/itertools.html\" rel=\"nofollow noreferrer\"><code>itertools</code> documentation</a></p>\n\n<pre><code>def grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return izip_longest(fillvalue=fillvalue, *args)\n</code></pre>\n"
},
{
"answer_id": 3242895,
"author": "John D. Cook",
"author_id": 25188,
"author_profile": "https://Stackoverflow.com/users/25188",
"pm_score": 4,
"selected": false,
"text": "<p>You can ask any object which module it came from by looking at its __ module__ property. This is useful, for example, if you're experimenting at the command line and have imported a lot of things.</p>\n\n<p>Along the same lines, you can ask a module where it came from by looking at its __ file__ property. This is useful when debugging path issues.</p>\n"
},
{
"answer_id": 3244390,
"author": "Marcin Swiderski",
"author_id": 391336,
"author_profile": "https://Stackoverflow.com/users/391336",
"pm_score": 4,
"selected": false,
"text": "<p>reversing an iterable using negative step</p>\n\n<pre><code>>>> s = \"Hello World\"\n>>> s[::-1]\n'dlroW olleH'\n>>> a = (1,2,3,4,5,6)\n>>> a[::-1]\n(6, 5, 4, 3, 2, 1)\n>>> a = [5,4,3,2,1]\n>>> a[::-1]\n[1, 2, 3, 4, 5]\n</code></pre>\n"
},
{
"answer_id": 3254039,
"author": "Giampaolo Rodolà",
"author_id": 376587,
"author_profile": "https://Stackoverflow.com/users/376587",
"pm_score": 5,
"selected": false,
"text": "<p>When using the interactive shell, \"_\" contains the value of the last printed item:</p>\n\n<pre><code>>>> range(10)\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> _\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>>\n</code></pre>\n"
},
{
"answer_id": 3265438,
"author": "Daniel Hepper",
"author_id": 211960,
"author_profile": "https://Stackoverflow.com/users/211960",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Slices & Mutability</strong> </p>\n\n<p>Copying lists</p>\n\n<pre><code>>>> x = [1,2,3]\n>>> y = x[:]\n>>> y.pop()\n3\n>>> y\n[1, 2]\n>>> x\n[1, 2, 3]\n</code></pre>\n\n<p>Replacing lists</p>\n\n<pre><code>>>> x = [1,2,3]\n>>> y = x\n>>> y[:] = [4,5,6]\n>>> x\n[4, 5, 6]\n</code></pre>\n"
},
{
"answer_id": 3267903,
"author": "Wayne Werner",
"author_id": 344286,
"author_profile": "https://Stackoverflow.com/users/344286",
"pm_score": 2,
"selected": false,
"text": "<p>Combine unpacking with the print function:</p>\n\n<pre><code># in 2.6 <= python < 3.0, 3.0 + the print function is native\nfrom __future__ import print_function \n\nmylist = ['foo', 'bar', 'some other value', 1,2,3,4] \nprint(*mylist)\n</code></pre>\n"
},
{
"answer_id": 3268128,
"author": "Wayne Werner",
"author_id": 344286,
"author_profile": "https://Stackoverflow.com/users/344286",
"pm_score": 6,
"selected": false,
"text": "<p>This answer has been moved into the question itself, as requested by many people.</p>\n"
},
{
"answer_id": 3277236,
"author": "Piotr Duda",
"author_id": 352850,
"author_profile": "https://Stackoverflow.com/users/352850",
"pm_score": 4,
"selected": false,
"text": "<p>From python 3.1 ( 2.7 ) dictionary and set comprehensions are supported :</p>\n\n<pre><code>{ a:a for a in range(10) }\n{ a for a in range(10) }\n</code></pre>\n"
},
{
"answer_id": 3280831,
"author": "Martin",
"author_id": 338547,
"author_profile": "https://Stackoverflow.com/users/338547",
"pm_score": 3,
"selected": false,
"text": "<p>Python 2.x ignores commas if found after the last element of the sequence:</p>\n\n<pre><code>>>> a_tuple_for_instance = (0,1,2,3,)\n>>> another_tuple = (0,1,2,3)\n>>> a_tuple_for_instance == another_tuple\nTrue\n</code></pre>\n\n<p>A trailing comma causes a single parenthesized element to be treated as a sequence:</p>\n\n<pre><code>>>> a_tuple_with_one_element = (8,)\n</code></pre>\n"
},
{
"answer_id": 3282681,
"author": "Don O'Donnell",
"author_id": 140894,
"author_profile": "https://Stackoverflow.com/users/140894",
"pm_score": 2,
"selected": false,
"text": "<pre><code>** Using sets to reference contents in sets of frozensets**\n</code></pre>\n\n<p>As you probably know, sets are mutable and thus not hashable, so it's necessary to use frozensets if you want to make a set of sets (or use sets as dictionary keys):</p>\n\n<pre><code>>>> fabc = frozenset('abc')\n>>> fxyz = frozenset('xyz')\n>>> mset = set((fabc, fxyz))\n>>> mset\n{frozenset({'a', 'c', 'b'}), frozenset({'y', 'x', 'z'})}\n</code></pre>\n\n<p>However, it's possible to test for membership and remove/discard members using just ordinary sets:</p>\n\n<pre><code>>>> abc = set('abc')\n>>> abc in mset\nTrue\n>>> mset.remove(abc)\n>>> mset\n{frozenset({'y', 'x', 'z'})}\n</code></pre>\n\n<p>To quote from the Python Standard Library docs:</p>\n\n<blockquote>\n <p>Note, the <code>elem</code> argument to the <code>__contains__()</code>, <code>remove()</code>, and <code>discard()</code>\n methods may be a set. To support searching for an equivalent frozenset, the \n <code>elem</code> set is temporarily mutated during the search and then restored. During \n the search, the <code>elem</code> set should not be read or mutated since it does not \n have a meaningful value. </p>\n</blockquote>\n\n<p>Unfortunately, and perhaps astonishingly, the same is not true of dictionaries:</p>\n\n<pre><code>>>> mdict = {fabc:1, fxyz:2}\n>>> fabc in mdict\nTrue\n>>> abc in mdict\nTraceback (most recent call last):\nFile \"<interactive input>\", line 1, in <module>\nTypeError: unhashable type: 'set'\n</code></pre>\n"
},
{
"answer_id": 3310122,
"author": "Remco Wendt",
"author_id": 216255,
"author_profile": "https://Stackoverflow.com/users/216255",
"pm_score": 5,
"selected": false,
"text": "<p>The <a href=\"http://docs.python.org/library/textwrap.html#textwrap.dedent\" rel=\"nofollow noreferrer\"><code>textwrap.dedent</code></a> utility function in python can come quite in handy testing that a multiline string returned is equal to the expected output without breaking the indentation of your unittests:</p>\n\n<pre><code>import unittest, textwrap\n\nclass XMLTests(unittest.TestCase):\n def test_returned_xml_value(self):\n returned_xml = call_to_function_that_returns_xml()\n expected_value = textwrap.dedent(\"\"\"\\\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n <root_node>\n <my_node>my_content</my_node>\n </root_node>\n \"\"\")\n\n self.assertEqual(expected_value, returned_xml)\n</code></pre>\n"
},
{
"answer_id": 3312925,
"author": "hughdbrown",
"author_id": 10293,
"author_profile": "https://Stackoverflow.com/users/10293",
"pm_score": 3,
"selected": false,
"text": "<p>Slices as lvalues. This Sieve of Eratosthenes produces a list that has either the prime number or 0. Elements are 0'd out with the slice assignment in the loop.</p>\n\n<pre><code>def eras(n):\n last = n + 1\n sieve = [0,0] + list(range(2, last))\n sqn = int(round(n ** 0.5))\n it = (i for i in xrange(2, sqn + 1) if sieve[i])\n for i in it:\n sieve[i*i:last:i] = [0] * (n//i - i + 1)\n return filter(None, sieve)\n</code></pre>\n\n<p>To work, the slice on the left must be assigned a list on the right of the same length.</p>\n"
},
{
"answer_id": 3326757,
"author": "David Z",
"author_id": 56541,
"author_profile": "https://Stackoverflow.com/users/56541",
"pm_score": 5,
"selected": false,
"text": "<h2>Zero-argument and variable-argument lambdas</h2>\n\n<p>Lambda functions are usually used for a quick transformation of one value into another, but they can also be used to wrap a value in a function:</p>\n\n<pre><code>>>> f = lambda: 'foo'\n>>> f()\n'foo'\n</code></pre>\n\n<p>They can also accept the usual <code>*args</code> and <code>**kwargs</code> syntax:</p>\n\n<pre><code>>>> g = lambda *args, **kwargs: args[0], kwargs['thing']\n>>> g(1, 2, 3, thing='stuff')\n(1, 'stuff')\n</code></pre>\n"
},
{
"answer_id": 3342952,
"author": "sa125",
"author_id": 187907,
"author_profile": "https://Stackoverflow.com/users/187907",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Multi line strings</strong></p>\n\n<p>One approach is to use backslashes:</p>\n\n<pre><code>>>> sql = \"select * from some_table \\\nwhere id > 10\"\n>>> print sql\nselect * from some_table where id > 10\n</code></pre>\n\n<p>Another is to use the triple-quote:</p>\n\n<pre><code>>>> sql = \"\"\"select * from some_table \nwhere id > 10\"\"\"\n>>> print sql\nselect * from some_table where id > 10\n</code></pre>\n\n<p>Problem with those is that they are not indented (look poor in your code). If you try to indent, it'll just print the white-spaces you put. </p>\n\n<p>A third solution, which I found about recently, is to divide your string into lines and surround with parentheses:</p>\n\n<pre><code>>>> sql = (\"select * from some_table \" # <-- no comma, whitespace at end\n \"where id > 10 \"\n \"order by name\") \n>>> print sql\nselect * from some_table where id > 10 order by name\n</code></pre>\n\n<p>note how there's no comma between lines (this is not a tuple), and you have to account for any trailing/leading white spaces that your string needs to have. All of these work with placeholders, by the way (such as <code>\"my name is %s\" % name</code>).</p>\n"
},
{
"answer_id": 3371415,
"author": "Tamás",
"author_id": 156771,
"author_profile": "https://Stackoverflow.com/users/156771",
"pm_score": 6,
"selected": false,
"text": "<h3>pow() can also calculate (x ** y) % z efficiently.</h3>\n\n<p>There is a lesser known third argument of the built-in <code>pow()</code> function that allows you to calculate x<sup>y</sup> modulo z more efficiently than simply doing <code>(x ** y) % z</code>:</p>\n\n<pre><code>>>> x, y, z = 1234567890, 2345678901, 17\n>>> pow(x, y, z) # almost instantaneous\n6\n</code></pre>\n\n<p>In comparison, <code>(x ** y) % z</code> didn't given a result in one minute on my machine for the same values.</p>\n"
},
{
"answer_id": 3535064,
"author": "Denilson Sá Maia",
"author_id": 124946,
"author_profile": "https://Stackoverflow.com/users/124946",
"pm_score": 3,
"selected": false,
"text": "<p>Backslashes inside raw strings can still escape quotes. See this:</p>\n\n<pre><code>>>> print repr(r\"aaa\\\"bbb\")\n'aaa\\\\\"bbb'\n</code></pre>\n\n<p>Note that both the backslash and the double-quote are present in the final string.</p>\n\n<p>As consequence, you can't end a raw string with a backslash:</p>\n\n<pre><code>>>> print repr(r\"C:\\\")\nSyntaxError: EOL while scanning string literal\n>>> print repr(r\"C:\\\"\")\n'C:\\\\\"'\n</code></pre>\n\n<p>This happens because raw strings were implemented to help writing regular expressions, and not to write Windows paths. Read a long discussion about this at <a href=\"http://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%E2%80%94-backslashes-in-windows-filenames/\" rel=\"nofollow noreferrer\">Gotcha — backslashes in Windows filenames</a>.</p>\n"
},
{
"answer_id": 3693838,
"author": "Ruslan Spivak",
"author_id": 301440,
"author_profile": "https://Stackoverflow.com/users/301440",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Sequence multiplication and reflected operands</strong></p>\n\n<pre><code>>>> 'xyz' * 3\n'xyzxyzxyz'\n\n>>> [1, 2] * 3\n[1, 2, 1, 2, 1, 2]\n\n>>> (1, 2) * 3\n(1, 2, 1, 2, 1, 2)\n</code></pre>\n\n<p>We get the same result with reflected (swapped) operands</p>\n\n<pre><code>>>> 3 * 'xyz'\n'xyzxyzxyz'\n</code></pre>\n\n<p>It works like this:</p>\n\n<pre><code>>>> s = 'xyz'\n>>> num = 3\n</code></pre>\n\n<p>To evaluate an expression <strong>s * num</strong> interpreter calls <strong>s.___mul___(num)</strong></p>\n\n<pre><code>>>> s * num\n'xyzxyzxyz'\n\n>>> s.__mul__(num)\n'xyzxyzxyz'\n</code></pre>\n\n<p>To evaluate an expression <strong>num * s</strong> interpreter calls <strong>num.___mul___(s)</strong></p>\n\n<pre><code>>>> num * s\n'xyzxyzxyz'\n\n>>> num.__mul__(s)\nNotImplemented\n</code></pre>\n\n<p>If the call returns <strong><em>NotImplemented</em></strong> then interpreter calls\na reflected operation <strong>s.___rmul___(num)</strong> if operands have different types</p>\n\n<pre><code>>>> s.__rmul__(num)\n'xyzxyzxyz'\n</code></pre>\n\n<p>See <a href=\"http://docs.python.org/reference/datamodel.html#object.__rmul__\" rel=\"nofollow noreferrer\">http://docs.python.org/reference/datamodel.html#object.<strong>rmul</strong></a></p>\n"
},
{
"answer_id": 3967144,
"author": "Tamás",
"author_id": 156771,
"author_profile": "https://Stackoverflow.com/users/156771",
"pm_score": 6,
"selected": false,
"text": "<h3>enumerate with different starting index</h3>\n\n<p><code>enumerate</code> has partly been covered in <a href=\"https://stackoverflow.com/questions/101268/hidden-features-of-python/117116#117116\">this answer</a>, but recently I've found an even more hidden feature of <code>enumerate</code> that I think deserves its own post instead of just a comment.</p>\n\n<p>Since Python 2.6, you can specify a starting index to <code>enumerate</code> in its second argument:</p>\n\n<pre><code>>>> l = [\"spam\", \"ham\", \"eggs\"]\n>>> list(enumerate(l))\n>>> [(0, \"spam\"), (1, \"ham\"), (2, \"eggs\")]\n>>> list(enumerate(l, 1))\n>>> [(1, \"spam\"), (2, \"ham\"), (3, \"eggs\")]\n</code></pre>\n\n<p>One place where I've found it utterly useful is when I am enumerating over entries of a symmetric matrix. Since the matrix is symmetric, I can save time by iterating over the upper triangle only, but in that case, I have to use <code>enumerate</code> with a different starting index in the inner <code>for</code> loop to keep track of the row and column indices properly:</p>\n\n<pre><code>for ri, row in enumerate(matrix):\n for ci, column in enumerate(matrix[ri:], ri):\n # ci now refers to the proper column index\n</code></pre>\n\n<p>Strangely enough, this behaviour of <code>enumerate</code> is not documented in <code>help(enumerate)</code>, only in the <a href=\"http://docs.python.org/library/functions.html#enumerate\" rel=\"nofollow noreferrer\">online documentation</a>.</p>\n"
},
{
"answer_id": 4501451,
"author": "Noufal Ibrahim",
"author_id": 229602,
"author_profile": "https://Stackoverflow.com/users/229602",
"pm_score": 4,
"selected": false,
"text": "<p>Not \"hidden\" but quite useful and not commonly used </p>\n\n<p>Creating string joining functions quickly like so</p>\n\n<pre><code> comma_join = \",\".join\n semi_join = \";\".join\n\n print comma_join([\"foo\",\"bar\",\"baz\"])\n 'foo,bar,baz\n</code></pre>\n\n<p>and</p>\n\n<p>Ability to create lists of strings more elegantly than the quote, comma mess. </p>\n\n<pre><code>l = [\"item1\", \"item2\", \"item3\"]\n</code></pre>\n\n<p>replaced by</p>\n\n<pre><code>l = \"item1 item2 item3\".split()\n</code></pre>\n"
},
{
"answer_id": 4544088,
"author": "asmeurer",
"author_id": 161801,
"author_profile": "https://Stackoverflow.com/users/161801",
"pm_score": 4,
"selected": false,
"text": "<p><strong>The Object Data Model</strong></p>\n\n<p>You can override <em>any</em> operator in the language for your own classes. See <a href=\"http://docs.python.org/reference/datamodel.html\" rel=\"nofollow\">this page</a> for a complete list. Some examples:</p>\n\n<ul>\n<li><p>You can override any operator (<code>* + - / // % ^ == < > <= >= .</code> etc.). All this is done by overriding <code>__mul__</code>, <code>__add__</code>, etc. in your objects. You can even override things like <code>__rmul__</code> to handle separately <code>your_object*something_else</code> and <code>something_else*your_object</code>. <code>.</code> is attribute access (<code>a.b</code>), and can be overridden to handle any arbitrary <code>b</code> by using <code>__getattr__</code>. Also included here is <code>a(…)</code> using <code>__call__</code>.</p></li>\n<li><p>You can create your own slice syntax (<code>a[stuff]</code>), which can be very complicated and quite different from the standard syntax used in lists (numpy has a good example of the power of this in their arrays) using any combination of <code>,</code>, <code>:</code>, and <code>…</code> that you like, using Slice objects. </p></li>\n<li><p>Handle specially what happens with many keywords in the language. Included are <code>del</code>, <code>in</code>, <code>import</code>, and <code>not</code>.</p></li>\n<li><p>Handle what happens when many built in functions are called with your object. The standard <code>__int__</code>, <code>__str__</code>, etc. go here, but so do <code>__len__</code>, <code>__reversed__</code>, <code>__abs__</code>, and the three argument <code>__pow__</code> (for modular exponentiation). </p></li>\n</ul>\n"
},
{
"answer_id": 4602518,
"author": "Adrien Plisson",
"author_id": 195823,
"author_profile": "https://Stackoverflow.com/users/195823",
"pm_score": 6,
"selected": false,
"text": "<p><strong>tuple unpacking in python 3</strong></p>\n\n<p>in python 3, you can use a syntax identical to optional arguments in function definition for tuple unpacking:</p>\n\n<pre><code>>>> first,second,*rest = (1,2,3,4,5,6,7,8)\n>>> first\n1\n>>> second\n2\n>>> rest\n[3, 4, 5, 6, 7, 8]\n</code></pre>\n\n<p>but a feature less known and more powerful allows you to have an unknown number of elements <strong>in the middle of the list</strong>:</p>\n\n<pre><code>>>> first,*rest,last = (1,2,3,4,5,6,7,8)\n>>> first\n1\n>>> rest\n[2, 3, 4, 5, 6, 7]\n>>> last\n8\n</code></pre>\n"
},
{
"answer_id": 4627428,
"author": "Ant",
"author_id": 465159,
"author_profile": "https://Stackoverflow.com/users/465159",
"pm_score": 2,
"selected": false,
"text": "<p><strong>insert vs append</strong></p>\n\n<p>not a feature, but may be interesting </p>\n\n<p>suppose you want to insert some data in a list, and then reverse it. the easiest thing is</p>\n\n<pre><code>count = 10 ** 5\nnums = []\nfor x in range(count):\n nums.append(x)\nnums.reverse()\n</code></pre>\n\n<p>then you think: what about inserting the numbers from the beginning, instead? so:</p>\n\n<pre><code>count = 10 ** 5 \nnums = [] \nfor x in range(count):\n nums.insert(0, x)\n</code></pre>\n\n<p>but it turns to be 100 times slower! if we set count = 10 ** 6, it will be 1,000 times slower; this is because insert is O(n^2), while append is O(n).</p>\n\n<p>the reason for that difference is that insert has to move each element in a list each time it's called; append just add at the end of the list that elements (sometimes it has to re-allocate everything, but it's still much more fast)</p>\n"
},
{
"answer_id": 4630680,
"author": "Apalala",
"author_id": 545637,
"author_profile": "https://Stackoverflow.com/users/545637",
"pm_score": 3,
"selected": false,
"text": "<h2>namedtuple is a tuple</h2>\n\n<pre><code>>>> node = namedtuple('node', \"a b\")\n>>> node(1,2) + node(5,6)\n(1, 2, 5, 6)\n>>> (node(1,2), node(5,6))\n(node(a=1, b=2), node(a=5, b=6))\n>>> \n</code></pre>\n\n<p>Some more experiments to respond to comments:</p>\n\n<pre><code>>>> from collections import namedtuple\n>>> from operator import *\n>>> mytuple = namedtuple('A', \"a b\")\n>>> yourtuple = namedtuple('Z', \"x y\")\n>>> mytuple(1,2) + yourtuple(5,6)\n(1, 2, 5, 6)\n>>> q = [mytuple(1,2), yourtuple(5,6)]\n>>> q\n[A(a=1, b=2), Z(x=5, y=6)]\n>>> reduce(operator.__add__, q)\n(1, 2, 5, 6)\n</code></pre>\n\n<p>So, <code>namedtuple</code> is an <em>interesting</em> subtype of <code>tuple</code>.</p>\n"
},
{
"answer_id": 4675525,
"author": "Apalala",
"author_id": 545637,
"author_profile": "https://Stackoverflow.com/users/545637",
"pm_score": 2,
"selected": false,
"text": "<p><strong>A module exports <em>EVERYTHING</em> in its namespace</strong></p>\n\n<p>Including names imported from other modules!</p>\n\n<pre><code># this is \"answer42.py\"\nfrom operator import *\nfrom inspect import *\n</code></pre>\n\n<p>Now test what's importable from the module.</p>\n\n<pre><code>>>> import answer42\n>>> answer42.__dict__.keys()\n['gt', 'imul', 'ge', 'setslice', 'ArgInfo', 'getfile', 'isCallable', 'getsourcelines', 'CO_OPTIMIZED', 'le', 're', 'isgenerator', 'ArgSpec', 'imp', 'lt', 'delslice', 'BlockFinder', 'getargspec', 'currentframe', 'CO_NOFREE', 'namedtuple', 'rshift', 'string', 'getframeinfo', '__file__', 'strseq', 'iconcat', 'getmro', 'mod', 'getcallargs', 'isub', 'getouterframes', 'isdatadescriptor', 'modulesbyfile', 'setitem', 'truth', 'Attribute', 'div', 'CO_NESTED', 'ixor', 'getargvalues', 'ismemberdescriptor', 'getsource', 'isMappingType', 'eq', 'index', 'xor', 'sub', 'getcomments', 'neg', 'getslice', 'isframe', '__builtins__', 'abs', 'getmembers', 'mul', 'getclasstree', 'irepeat', 'is_', 'getitem', 'indexOf', 'Traceback', 'findsource', 'ModuleInfo', 'ipow', 'TPFLAGS_IS_ABSTRACT', 'or_', 'joinseq', 'is_not', 'itruediv', 'getsourcefile', 'dis', 'os', 'iand', 'countOf', 'getinnerframes', 'pow', 'pos', 'and_', 'lshift', '__name__', 'sequenceIncludes', 'isabstract', 'isbuiltin', 'invert', 'contains', 'add', 'isSequenceType', 'irshift', 'types', 'tokenize', 'isfunction', 'not_', 'istraceback', 'getmoduleinfo', 'isgeneratorfunction', 'getargs', 'CO_GENERATOR', 'cleandoc', 'classify_class_attrs', 'EndOfBlock', 'walktree', '__doc__', 'getmodule', 'isNumberType', 'ilshift', 'ismethod', 'ifloordiv', 'formatargvalues', 'indentsize', 'getmodulename', 'inv', 'Arguments', 'iscode', 'CO_NEWLOCALS', 'formatargspec', 'iadd', 'getlineno', 'imod', 'CO_VARKEYWORDS', 'ne', 'idiv', '__package__', 'CO_VARARGS', 'attrgetter', 'methodcaller', 'truediv', 'repeat', 'trace', 'isclass', 'ior', 'ismethoddescriptor', 'sys', 'isroutine', 'delitem', 'stack', 'concat', 'getdoc', 'getabsfile', 'ismodule', 'linecache', 'floordiv', 'isgetsetdescriptor', 'itemgetter', 'getblock']\n>>> from answer42 import getmembers\n>>> getmembers\n<function getmembers at 0xb74b2924>\n>>> \n</code></pre>\n\n<p>That's a good reason not to <code>from x import *</code> and to define <code>__all__ =</code>.</p>\n"
},
{
"answer_id": 4775286,
"author": "Brendon Crawford",
"author_id": 552766,
"author_profile": "https://Stackoverflow.com/users/552766",
"pm_score": 3,
"selected": false,
"text": "<p>Operators can be called as functions:</p>\n\n<pre><code>from operator import add\nprint reduce(add, [1,2,3,4,5,6])\n</code></pre>\n"
},
{
"answer_id": 4775544,
"author": "Chmouel Boudjnah",
"author_id": 145125,
"author_profile": "https://Stackoverflow.com/users/145125",
"pm_score": 5,
"selected": false,
"text": "<p>The simplicity of :</p>\n\n<pre><code>>>> 'str' in 'string'\nTrue\n>>> 'no' in 'yes'\nFalse\n>>> \n</code></pre>\n\n<p>is something i love about Python, I have seen a lot of not very pythonic idiom like that instead :</p>\n\n<pre><code>if 'yes'.find(\"no\") == -1:\n pass\n</code></pre>\n"
},
{
"answer_id": 4779148,
"author": "FernandoEscher",
"author_id": 176376,
"author_profile": "https://Stackoverflow.com/users/176376",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Dynamically added attributes</strong> </p>\n\n<p>This might be useful if you think about adding some attributes to your classes just by calling them. This can be done by overriding the <a href=\"http://docs.python.org/reference/datamodel.html#object.__getattribute__\" rel=\"nofollow\" rel=\"nofollow\"><code>__getattribute__</code></a> member function which is called when the dot operand is used. So, let's see a dummy class for example:</p>\n\n<pre><code>class Dummy(object):\n def __getattribute__(self, name):\n f = lambda: 'Hello with %s'%name\n return f\n</code></pre>\n\n<p>When you instantiate a Dummy object and do a method call you’ll get the following:</p>\n\n<pre><code>>>> d = Dummy()\n>>> d.b()\n'Hello with b'\n</code></pre>\n\n<p>Finally, you can even set the attribute to your class so it can be dynamically defined. This could be useful if you work with Python web frameworks and want to do queries by parsing the attribute's name.</p>\n\n<p>I have a <a href=\"https://gist.github.com/792865\" rel=\"nofollow\" rel=\"nofollow\">gist</a> at github with this simple code and its equivalent on Ruby made by a friend.</p>\n\n<p>Take care!</p>\n"
},
{
"answer_id": 4958857,
"author": "Foo Bah",
"author_id": 590042,
"author_profile": "https://Stackoverflow.com/users/590042",
"pm_score": 3,
"selected": false,
"text": "<p>Changing function label at run time:</p>\n\n<pre><code>>>> class foo:\n... def normal_call(self): print \"normal_call\"\n... def call(self): \n... print \"first_call\"\n... self.call = self.normal_call\n\n>>> y = foo()\n>>> y.call()\nfirst_call\n>>> y.call()\nnormal_call\n>>> y.call()\nnormal_call\n...\n</code></pre>\n"
},
{
"answer_id": 5024259,
"author": "Abbafei",
"author_id": 541412,
"author_profile": "https://Stackoverflow.com/users/541412",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not sure where (or whether) this is in the Python docs, but for python 2.x (at least 2.5 and 2.6, which I just tried), the <code>print</code> statement can be called with parenthenses. This can be useful if you want to be able to easily port some Python 2.x code to Python 3.x. </p>\n\n<p>Example:\n<code>print('We want Moshiach Now')</code> should print <code>We want Moshiach Now</code> work in python 2.5, 2.6, and 3.x.</p>\n\n<p>Also, the <code>not</code> operator can be called with parenthenses in Python 2 and 3:\n<code>not False</code>\nand\n<code>not(False)</code>\nshould both return <code>True</code>.</p>\n\n<p>Parenthenses might also work with other statements and operators.</p>\n\n<p><strong>EDIT</strong>: NOT a good idea to put parenthenses around <code>not</code> operators (and probably any other operators), since it can make for surprising situations, like so (this happens because the parenthenses are just really around the <code>1</code>):</p>\n\n<pre><code>>>> (not 1) == 9\nFalse\n\n>>> not(1) == 9\nTrue\n</code></pre>\n\n<p>This also can work, for some values (I think where it is not a valid identifier name), like this:\n<code>not'val'</code> should return <code>False</code>, and <code>print'We want Moshiach Now'</code> should return <code>We want Moshiach Now</code>. (but <code>not552</code> would raise a NameError since it is a valid identifier name).</p>\n"
},
{
"answer_id": 5084257,
"author": "Ivan P",
"author_id": 477396,
"author_profile": "https://Stackoverflow.com/users/477396",
"pm_score": 2,
"selected": false,
"text": "<h3>Python has \"private\" variables</h3>\n\n<p>Variables that start, but not end, with a double underscore become private, and not just by convention. Actually __var turns into _Classname__var, where Classname is the class in which the variable was created. They are not inherited and cannot be overriden.</p>\n\n<pre><code>\n>>> class A:\n... def __init__(self):\n... self.__var = 5\n... def getvar(self):\n... return self.__var\n... \n>>> a = A()\n>>> a.__var\nTraceback (most recent call last):\n File \"\", line 1, in \nAttributeError: A instance has no attribute '__var'\n>>> a.getvar()\n5\n>>> dir(a)\n['_A__var', '__doc__', '__init__', '__module__', 'getvar']\n>>>\n</code></pre>\n"
},
{
"answer_id": 5202538,
"author": "armandino",
"author_id": 45112,
"author_profile": "https://Stackoverflow.com/users/45112",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to this mentioned earlier by <a href=\"https://stackoverflow.com/questions/101268/hidden-features-of-python/2582013#2582013\">haridsv</a>:</p>\n\n<pre><code>>>> foo = bar = baz = 1\n>>> foo, bar, baz\n(1, 1, 1)\n</code></pre>\n\n<p>it's also possible to do this:</p>\n\n<pre><code>>>> foo, bar, baz = 1, 2, 3\n>>> foo, bar, baz\n(1, 2, 3)\n</code></pre>\n"
},
{
"answer_id": 5202620,
"author": "dan_waterworth",
"author_id": 393783,
"author_profile": "https://Stackoverflow.com/users/393783",
"pm_score": 4,
"selected": false,
"text": "<p>The <code>re.Scanner</code> class. <a href=\"http://code.activestate.com/recipes/457664-hidden-scanner-functionality-in-re-module/\" rel=\"nofollow\">http://code.activestate.com/recipes/457664-hidden-scanner-functionality-in-re-module/</a></p>\n"
},
{
"answer_id": 5251054,
"author": "Luper Rouch",
"author_id": 17911,
"author_profile": "https://Stackoverflow.com/users/17911",
"pm_score": 2,
"selected": false,
"text": "<p>Not at all a hidden feature but still nice:</p>\n\n<pre><code>import os.path as op\n\nroot_dir = op.abspath(op.join(op.dirname(__file__), \"..\"))\n</code></pre>\n\n<p>Saves lots of characters when manipulating paths !</p>\n"
},
{
"answer_id": 5251200,
"author": "Kimvais",
"author_id": 180174,
"author_profile": "https://Stackoverflow.com/users/180174",
"pm_score": 4,
"selected": false,
"text": "<p>Arguably, this is not a <em>programming</em> feature per se, but so useful that I'll post it nevertheless.</p>\n\n<pre><code>$ python -m http.server\n</code></pre>\n\n<p>...followed by <code>$ wget http://<ipnumber>:8000/filename</code> somewhere else.</p>\n\n<p>If you are still running an older (2.x) version of Python:</p>\n\n<pre><code>$ python -m SimpleHTTPServer\n</code></pre>\n\n<p>You can also specify a port e.g. <code>python -m http.server 80</code> (so you can omit the port in the url if you have the root on the server side)</p>\n"
},
{
"answer_id": 5446831,
"author": "Kabie",
"author_id": 260985,
"author_profile": "https://Stackoverflow.com/users/260985",
"pm_score": 2,
"selected": false,
"text": "<p>Unicode identifier in Python3:</p>\n\n<pre><code>>>> 'Unicode字符_تكوين_Variable'.isidentifier()\nTrue\n>>> Unicode字符_تكوين_Variable='Python3 rules!'\n>>> Unicode字符_تكوين_Variable\n'Python3 rules!'\n</code></pre>\n"
},
{
"answer_id": 6123240,
"author": "Rabarberski",
"author_id": 50899,
"author_profile": "https://Stackoverflow.com/users/50899",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Multiply a string to get it repeated</strong> </p>\n\n<pre><code>print \"SO\"*5 \n</code></pre>\n\n<p>gives</p>\n\n<pre><code>SOSOSOSOSO\n</code></pre>\n"
},
{
"answer_id": 6143038,
"author": "inspectorG4dget",
"author_id": 198633,
"author_profile": "https://Stackoverflow.com/users/198633",
"pm_score": 0,
"selected": false,
"text": "<p><strong>commands.getoutput</strong></p>\n\n<p>If you want to get the output of a function which outputs directly to <code>stdout</code> or <code>stderr</code> as is the case with <code>os.system</code>, <a href=\"http://docs.python.org/library/commands.html\" rel=\"nofollow\"><code>commands.getoutput</code></a> comes to the rescue. The whole module is just made of awesome.</p>\n\n<pre><code>>>> print commands.getoutput('ls')\nmyFile1.txt myFile2.txt myFile3.txt myFile4.txt myFile5.txt\nmyFile6.txt myFile7.txt myFile8.txt myFile9.txt myFile10.txt\nmyFile11.txt myFile12.txt myFile13.txt myFile14.txt module.py\n</code></pre>\n"
},
{
"answer_id": 6153425,
"author": "Mojo_Jojo",
"author_id": 601163,
"author_profile": "https://Stackoverflow.com/users/601163",
"pm_score": 2,
"selected": false,
"text": "<p>Ever used xrange(INT) instead of range(INT) .... It's got less memory usage and doesn't really depend on the size of the integer. Yey!! Isn't that good?</p>\n"
},
{
"answer_id": 6338283,
"author": "Ken Arnold",
"author_id": 69707,
"author_profile": "https://Stackoverflow.com/users/69707",
"pm_score": 3,
"selected": false,
"text": "<h2><code>getattr</code> takes a third parameter</h2>\n\n<p><code>getattr(obj, attribute_name, default)</code> is like:</p>\n\n<pre><code>try:\n return obj.attribute\nexcept AttributeError:\n return default\n</code></pre>\n\n<p>except that <code>attribute_name</code> can be any string.</p>\n\n<p>This can be really useful for <a href=\"http://en.wikipedia.org/wiki/Duck_typing\" rel=\"noreferrer\">duck typing</a>. Maybe you have something like:</p>\n\n<pre><code>class MyThing:\n pass\nclass MyOtherThing:\n pass\nif isinstance(obj, (MyThing, MyOtherThing)):\n process(obj)\n</code></pre>\n\n<p>(btw, <code>isinstance(obj, (a,b))</code> means <code>isinstance(obj, a) or isinstance(obj, b)</code>.)</p>\n\n<p>When you make a new kind of thing, you'd need to add it to that tuple everywhere it occurs. (That construction also causes problems when reloading modules or importing the same file under two names. It happens more than people like to admit.) But instead you could say:</p>\n\n<pre><code>class MyThing:\n processable = True\nclass MyOtherThing:\n processable = True\nif getattr(obj, 'processable', False):\n process(obj)\n</code></pre>\n\n<p>Add inheritance and it gets even better: all of your examples of processable objects can inherit from</p>\n\n<pre><code>class Processable:\n processable = True\n</code></pre>\n\n<p>but you don't have to convince everybody to inherit from your base class, just to set an attribute.</p>\n"
},
{
"answer_id": 6403350,
"author": "jassinm",
"author_id": 239007,
"author_profile": "https://Stackoverflow.com/users/239007",
"pm_score": 1,
"selected": false,
"text": "<p>mapreduce using map and reduce functions</p>\n\n<p>create a simple sumproduct this way:</p>\n\n<pre><code>def sumprod(x,y):\n return reduce(lambda a,b:a+b, map(lambda a, b: a*b,x,y))\n</code></pre>\n\n<p>example:</p>\n\n<pre><code>In [2]: sumprod([1,2,3],[4,5,6])\nOut[2]: 32\n</code></pre>\n"
},
{
"answer_id": 6413158,
"author": "Douglas",
"author_id": 244261,
"author_profile": "https://Stackoverflow.com/users/244261",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Simple built-in benchmarking tool</strong></p>\n\n<p>The Python Standard Library comes with a very easy-to-use benchmarking module called \"timeit\". You can even use it from the command line to see which of several language constructs is the fastest.</p>\n\n<p>E.g.,</p>\n\n<pre><code>% python -m timeit 'r = range(0, 1000)' 'for i in r: pass'\n10000 loops, best of 3: 48.4 usec per loop\n\n% python -m timeit 'r = xrange(0, 1000)' 'for i in r: pass'\n10000 loops, best of 3: 37.4 usec per loop\n</code></pre>\n"
},
{
"answer_id": 6486393,
"author": "Elisha",
"author_id": 766068,
"author_profile": "https://Stackoverflow.com/users/766068",
"pm_score": 3,
"selected": false,
"text": "<p>infinite recursion in list</p>\n\n<pre><code>>>> a = [1,2]\n>>> a.append(a)\n>>> a\n[1, 2, [...]]\n>>> a[2]\n[1, 2, [...]]\n>>> a[2][2][2][2][2][2][2][2][2] == a\nTrue\n</code></pre>\n"
},
{
"answer_id": 6528965,
"author": "matchew",
"author_id": 638649,
"author_profile": "https://Stackoverflow.com/users/638649",
"pm_score": 2,
"selected": false,
"text": "<p>while not very pythonic you can write to a file using <a href=\"http://docs.python.org/reference/simple_stmts.html#the-print-statement\" rel=\"nofollow\"><code>print</code></a></p>\n\n<p><code>print>>outFile, 'I am Being Written'</code></p>\n\n<p><a href=\"http://docs.python.org/reference/simple_stmts.html#the-print-statement\" rel=\"nofollow\">Explanation</a>:</p>\n\n<blockquote>\n <p>This form is sometimes referred to as\n “<code>print</code> chevron.” In this form, the\n first expression after the >> must\n evaluate to a “file-like” object,\n specifically an object that has a\n <code>write()</code> method as described above.\n With this extended form, the\n subsequent expressions are printed to\n this file object. <strong>If the first\n expression evaluates to <code>None</code>, then\n <code>sys.stdout</code> is used as the file for\n output.</strong></p>\n</blockquote>\n"
},
{
"answer_id": 6574805,
"author": "Roman Bodnarchuk",
"author_id": 406693,
"author_profile": "https://Stackoverflow.com/users/406693",
"pm_score": 3,
"selected": false,
"text": "<p><strong><code>string-escape</code> and <code>unicode-escape</code> encodings</strong></p>\n\n<p>Lets say you have a string from outer source, that contains <code>\\n</code>, <code>\\t</code> and so on. How to transform them into new-line or tab? Just decode string using <code>string-escape</code> encoding! </p>\n\n<pre><code>>>> print s\nHello\\nStack\\toverflow\n>>> print s.decode('string-escape')\nHello\nStack overflow\n</code></pre>\n\n<p>Another problem. You have normal string with unicode literals like <code>\\u01245</code>. How to make it work? Just decode string using <code>unicode-escape</code> encoding!</p>\n\n<pre><code>>>> s = '\\u041f\\u0440\\u0438\\u0432\\u0456\\u0442, \\u0441\\u0432\\u0456\\u0442!'\n>>> print s\n\\u041f\\u0440\\u0438\\u0432\\u0456\\u0442, \\u0441\\u0432\\u0456\\u0442!\n>>> print unicode(s)\n\\u041f\\u0440\\u0438\\u0432\\u0456\\u0442, \\u0441\\u0432\\u0456\\u0442!\n>>> print unicode(s, 'unicode-escape')\nПривіт, світ!\n</code></pre>\n"
},
{
"answer_id": 6632253,
"author": "johnsyweb",
"author_id": 78845,
"author_profile": "https://Stackoverflow.com/users/78845",
"pm_score": 3,
"selected": false,
"text": "<h2>Flattening a <a href=\"http://www.python.org/doc//current/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange\"><code>list</code></a> with <a href=\"http://www.python.org/doc/current/library/functions.html#sum\"><code>sum()</code></a>.</h2>\n\n<p>The <a href=\"http://www.python.org/doc/current/library/functions.html#sum\"><code>sum()</code></a> built-in function can be used to <a href=\"http://www.python.org/doc//current/reference/datamodel.html#object.__add__\"><code>__add__</code></a> <a href=\"http://www.python.org/doc//current/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange\"><code>list</code></a>s together, providing a handy way to flatten a <a href=\"http://www.python.org/doc//current/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange\"><code>list</code></a> of <a href=\"http://www.python.org/doc//current/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange\"><code>list</code></a>s:</p>\n\n<pre><code>Python 2.7.1 (r271:86832, May 27 2011, 21:41:45) \n[GCC 4.2.1 (Apple Inc. build 5664)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> l = [[1, 2, 3], [4, 5], [6], [7, 8, 9]]\n>>> sum(l, [])\n[1, 2, 3, 4, 5, 6, 7, 8, 9]\n</code></pre>\n"
},
{
"answer_id": 6735488,
"author": "cerberos",
"author_id": 121725,
"author_profile": "https://Stackoverflow.com/users/121725",
"pm_score": 3,
"selected": false,
"text": "<h2>The Borg Pattern</h2>\n<p>This is a killer from <a href=\"https://stackoverflow.com/users/95810/alex-martelli\">Alex Martelli</a>. All instances of <code>Borg</code> share state. This removes the need to employ the singleton pattern (instances don't matter when state is shared) and is rather elegant (but is more complicated with new classes).</p>\n<p>The value of <code>foo</code> can be reassigned in any instance and all will be updated, you can even reassign the entire dict. Borg is the perfect name, read more <a href=\"http://code.activestate.com/recipes/66531/\" rel=\"noreferrer\">here</a>.</p>\n<pre><code>class Borg:\n __shared_state = {'foo': 'bar'}\n def __init__(self):\n self.__dict__ = self.__shared_state\n # rest of your class here\n</code></pre>\n<p>This is perfect for sharing an eventlet.GreenPool to control concurrency.</p>\n"
},
{
"answer_id": 6852190,
"author": "Abdelouahab",
"author_id": 861487,
"author_profile": "https://Stackoverflow.com/users/861487",
"pm_score": -1,
"selected": false,
"text": "<p>to activate the autocompletion in IDE that accepts it (like IDLE, Editra, IEP) instead of making:\n\"hi\". (and then you hit TAB), you can cheat in the IDE, just make\nhi\". (and you heat TAB) (as you can see, there is no single quote in the beginning) because it will only follows the latest punctuation, it's like when you add : and hit enter, it adds directly an indentation, dont know if it will make change, but it's a tip no more :)</p>\n"
},
{
"answer_id": 7076512,
"author": "mdeous",
"author_id": 293050,
"author_profile": "https://Stackoverflow.com/users/293050",
"pm_score": 3,
"selected": false,
"text": "<p>Here are 2 easter eggs:</p>\n\n<hr>\n\n<p>One in python itself:</p>\n\n<pre><code>>>> import __hello__\nHello world...\n</code></pre>\n\n<hr>\n\n<p>And another one in the <code>Werkzeug</code> module, which is a bit complicated to reveal, here it is:</p>\n\n<p>By looking at <code>Werkzeug</code>'s source code, in <code>werkzeug/__init__.py</code>, there is a line that should draw your attention:</p>\n\n<pre><code>'werkzeug._internal': ['_easteregg']\n</code></pre>\n\n<p>If you're a bit curious, this should lead you to have a look at the <code>werkzeug/_internal.py</code>, there, you'll find an <code>_easteregg()</code> function which takes a wsgi application in argument, it also contains some base64 encoded data and 2 nested functions, that seem to do something special if an argument named <code>macgybarchakku</code> is found in the query string.</p>\n\n<p>So, to reveal this easter egg, it seems you need to wrap an application in the <code>_easteregg()</code> function, let's go:</p>\n\n<pre><code>from werkzeug import Request, Response, run_simple\nfrom werkzeug import _easteregg\n\[email protected]\ndef application(request):\n return Response('Hello World!')\n\nrun_simple('localhost', 8080, _easteregg(application))\n</code></pre>\n\n<p>Now, if you run the app and visit <a href=\"http://localhost:8080/?macgybarchakku\" rel=\"noreferrer\">http://localhost:8080/?macgybarchakku</a>, you should see the easter egg.</p>\n"
},
{
"answer_id": 7305174,
"author": "giodamelio",
"author_id": 375847,
"author_profile": "https://Stackoverflow.com/users/375847",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a helpful function I use when debugging type errors</p>\n\n<pre><code>def typePrint(object):\n print(str(object) + \" - (\" + str(type(object)) + \")\")\n</code></pre>\n\n<p>It simply prints the input followed by the type, for example</p>\n\n<pre><code>>>> a = 101\n>>> typePrint(a)\n 101 - (<type 'int'>)\n</code></pre>\n"
},
{
"answer_id": 7560592,
"author": "bfontaine",
"author_id": 735926,
"author_profile": "https://Stackoverflow.com/users/735926",
"pm_score": -1,
"selected": false,
"text": "<pre><code>for line in open('foo'):\n print(line)\n</code></pre>\n\n<p>which is equivalent (but better) to:</p>\n\n<pre><code>f = open('foo', 'r')\nfor line in f.readlines():\n print(line)\nf.close()\n</code></pre>\n"
},
{
"answer_id": 7742520,
"author": "etuardu",
"author_id": 440172,
"author_profile": "https://Stackoverflow.com/users/440172",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Print multiline strings one screenful at a time</strong></p>\n\n<p>Not really useful feature hidden in the <code>site._Printer</code> class, whose the <code>license</code> object is an instance. The latter, when called, prints the Python license. One can create another object of the same type, passing a string -- e.g. the content of a file -- as the second argument, and call it:</p>\n\n<pre><code>type(license)(0,open('textfile.txt').read(),0)()\n</code></pre>\n\n<p>That would print the file content splitted by a certain number of lines at a time:</p>\n\n<pre><code>...\nfile row 21\nfile row 22\nfile row 23\n\nHit Return for more, or q (and Return) to quit:\n</code></pre>\n"
},
{
"answer_id": 7852572,
"author": "shadowland",
"author_id": 179256,
"author_profile": "https://Stackoverflow.com/users/179256",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Interactive Debugging of Scripts (and doctest strings)</strong></p>\n\n<p>I don't think this is as widely known as it could be, but add this line to any python script:</p>\n\n<p><code>import pdb; pdb.set_trace()</code></p>\n\n<p>will cause the PDB debugger to pop up with the run cursor at that point in the code. What's even less known, I think, is that you can use that same line in a doctest:</p>\n\n<pre><code>\"\"\"\n>>> 1 in (1,2,3) \nBecomes\n>>> import pdb; pdb.set_trace(); 1 in (1,2,3)\n\"\"\"\n</code></pre>\n\n<p>You can then use the debugger to checkout the doctest environment. You can't really step through a doctest because the lines are each run autonomously, but it's a great tool for debugging the doctest globs and environment.</p>\n"
},
{
"answer_id": 8420779,
"author": "Giampaolo Rodolà",
"author_id": 376587,
"author_profile": "https://Stackoverflow.com/users/376587",
"pm_score": 0,
"selected": false,
"text": "<p>In Python 2 you can generate a string representation of an expression by enclosing it with backticks: </p>\n\n<pre><code> >>> `sorted`\n'<built-in function sorted>'\n</code></pre>\n\n<p>This is gone in python 3.X.</p>\n"
},
{
"answer_id": 8442263,
"author": "sransara",
"author_id": 729485,
"author_profile": "https://Stackoverflow.com/users/729485",
"pm_score": 1,
"selected": false,
"text": "<p>Not a programming feature but is useful when using Python with <code>bash</code> or <code>shell scripts</code>.</p>\n\n<pre><code>python -c\"import os; print(os.getcwd());\"\n</code></pre>\n\n<p>See the <a href=\"http://docs.python.org/using/cmdline.html#cmdoption-unittest-discover-c\" rel=\"nofollow noreferrer\">python documentation here</a>. Additional things to note when writing <strong>longer Python scripts</strong> can be seen in <a href=\"https://stackoverflow.com/questions/3637020/long-programs-using-python-c-switch\">this discussion</a>.</p>\n"
},
{
"answer_id": 8625452,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 2,
"selected": false,
"text": "<p>Python have exceptions for very unexpected things:</p>\n\n<p><strong>Imports</strong></p>\n\n<p>This let you import an alternative if a lib is missing</p>\n\n<pre><code>try:\n import json\nexcept ImportError:\n import simplejson as json\n</code></pre>\n\n<p><strong>Iteration</strong></p>\n\n<p>For loops do this internally, and catch StopIteration:</p>\n\n<pre><code>iter([]).next()\nTraceback (most recent call last):\n File \"<pyshell#4>\", line 1, in <module>\n iter(a).next()\nStopIteration\n</code></pre>\n\n<p><strong>Assertion</strong></p>\n\n<pre><code>>>> try:\n... assert []\n... except AssertionError:\n... print \"This list should not be empty\"\nThis list should not be empty\n</code></pre>\n\n<p>While this is more verbose for one check, multiple checks mixing exceptions and boolean operators with the same error message can be shortened this way.</p>\n"
},
{
"answer_id": 8670760,
"author": "yoav.aviram",
"author_id": 25287,
"author_profile": "https://Stackoverflow.com/users/25287",
"pm_score": 3,
"selected": false,
"text": "<p>Rounding Integers:\nPython has the function round, which returns numbers of type double:</p>\n\n<pre><code> >>> print round(1123.456789, 4)\n1123.4568\n >>> print round(1123.456789, 2)\n1123.46\n >>> print round(1123.456789, 0)\n1123.0\n</code></pre>\n\n<p>This function has a wonderful magic property:</p>\n\n<pre><code> >>> print round(1123.456789, -1)\n1120.0\n >>> print round(1123.456789, -2)\n1100.0\n</code></pre>\n\n<p>If you need an integer as a result use int to convert type:</p>\n\n<pre><code> >>> print int(round(1123.456789, -2))\n1100\n >>> print int(round(8359980, -2))\n8360000\n</code></pre>\n\n<p>Thank you <a href=\"http://mail.python.org/pipermail/tutor/2003-August/024395.html\">Gregor</a>.</p>\n"
},
{
"answer_id": 8785858,
"author": "Srinivas Reddy Thatiparthy",
"author_id": 201393,
"author_profile": "https://Stackoverflow.com/users/201393",
"pm_score": 0,
"selected": false,
"text": "<p>some cool features with reduce and operator.</p>\n\n<pre><code>>>> from operator import add,mul\n>>> reduce(add,[1,2,3,4])\n10\n>>> reduce(mul,[1,2,3,4])\n24\n>>> reduce(add,[[1,2,3,4],[1,2,3,4]])\n[1, 2, 3, 4, 1, 2, 3, 4]\n>>> reduce(add,(1,2,3,4))\n10\n>>> reduce(mul,(1,2,3,4))\n24\n</code></pre>\n"
},
{
"answer_id": 8857541,
"author": "Perkins",
"author_id": 845159,
"author_profile": "https://Stackoverflow.com/users/845159",
"pm_score": 1,
"selected": false,
"text": "<p>Python's positional and keyword expansions can be used on the fly, not just from a stored list.</p>\n\n<pre><code>l=lambda x,y,z:x+y+z\na=1,2,3\nprint l(*a)\nprint l(*[a[0],2,3])\n</code></pre>\n\n<p>It is usually more useful with things like this:</p>\n\n<pre><code>a=[2,3]\nl(*(a+[3]))\n</code></pre>\n"
},
{
"answer_id": 8913428,
"author": "Justin",
"author_id": 601810,
"author_profile": "https://Stackoverflow.com/users/601810",
"pm_score": 3,
"selected": false,
"text": "<p>Dict Comprehensions</p>\n\n<pre><code>>>> {i: i**2 for i in range(5)}\n{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}\n</code></pre>\n\n<p><a href=\"http://docs.python.org/dev/reference/expressions.html?highlight=comprehensions#dictionary-displays\" rel=\"noreferrer\">Python documentation</a></p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/List_comprehension#Dictionary_comprehension\" rel=\"noreferrer\">Wikipedia Entry</a></p>\n"
},
{
"answer_id": 8913512,
"author": "Justin",
"author_id": 601810,
"author_profile": "https://Stackoverflow.com/users/601810",
"pm_score": 3,
"selected": false,
"text": "<p>Set Comprehensions</p>\n\n<pre><code>>>> {i**2 for i in range(5)} \nset([0, 1, 4, 16, 9])\n</code></pre>\n\n<p><a href=\"http://docs.python.org/dev/reference/expressions.html?highlight=comprehensions#set-displays\" rel=\"noreferrer\">Python documentation</a></p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/List_comprehension#Set_comprehension\" rel=\"noreferrer\">Wikipedia Entry</a></p>\n"
},
{
"answer_id": 8951143,
"author": "Primal Pappachan",
"author_id": 323404,
"author_profile": "https://Stackoverflow.com/users/323404",
"pm_score": 2,
"selected": false,
"text": "<p>Not really a hidden feature but something that might come in handy.</p>\n\n<p>for looping through items in a list pairwise</p>\n\n<pre><code>for x, y in zip(s, s[1:]):\n</code></pre>\n"
},
{
"answer_id": 9116759,
"author": "Giampaolo Rodolà",
"author_id": 376587,
"author_profile": "https://Stackoverflow.com/users/376587",
"pm_score": 2,
"selected": false,
"text": "<pre><code>>>> float('infinity')\ninf\n>>> float('NaN')\nnan\n</code></pre>\n\n<p>More info:</p>\n\n<ul>\n<li><a href=\"http://docs.python.org/library/functions.html#float\" rel=\"nofollow noreferrer\">http://docs.python.org/library/functions.html#float</a></li>\n<li><a href=\"http://www.python.org/dev/peps/pep-0754/\" rel=\"nofollow noreferrer\">http://www.python.org/dev/peps/pep-0754/</a></li>\n<li><a href=\"https://stackoverflow.com/questions/5438745/python-nan-and-inf-values\">python nan and inf values</a></li>\n</ul>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679/"
]
| What are the lesser-known but useful features of the Python programming language?
* Try to limit answers to Python core.
* One feature per answer.
* Give an example and short description of the feature, not just a link to documentation.
* Label the feature using a title as the first line.
Quick links to answers:
-----------------------
* [Argument Unpacking](https://stackoverflow.com/questions/101268/hidden-features-of-python#111176)
* [Braces](https://stackoverflow.com/questions/101268/hidden-features-of-python#112303)
* [Chaining Comparison Operators](https://stackoverflow.com/questions/101268/hidden-features-of-python#101945)
* [Decorators](https://stackoverflow.com/questions/101268/hidden-features-of-python#101447)
* [Default Argument Gotchas / Dangers of Mutable Default arguments](https://stackoverflow.com/questions/101268/hidden-features-of-python#113198)
* [Descriptors](https://stackoverflow.com/questions/101268/hidden-features-of-python#102062)
* [Dictionary default `.get` value](https://stackoverflow.com/questions/101268/hidden-features-of-python#111970)
* [Docstring Tests](https://stackoverflow.com/questions/101268/hidden-features-of-python#102065)
* [Ellipsis Slicing Syntax](https://stackoverflow.com/questions/101268/hidden-features-of-python/112316#112316)
* [Enumeration](https://stackoverflow.com/questions/101268/hidden-features-of-python#117116)
* [For/else](https://stackoverflow.com/questions/101268/hidden-features-of-python#114420)
* [Function as iter() argument](https://stackoverflow.com/questions/101268/hidden-features-of-python#102202)
* [Generator expressions](https://stackoverflow.com/questions/101268/hidden-features-of-python#101310)
* [`import this`](https://stackoverflow.com/questions/101268/hidden-features-of-python#101276)
* [In Place Value Swapping](https://stackoverflow.com/questions/101268/hidden-features-of-python#102037)
* [List stepping](https://stackoverflow.com/questions/101268/hidden-features-of-python#101840)
* [`__missing__` items](https://stackoverflow.com/questions/101268/hidden-features-of-python#112286)
* [Multi-line Regex](https://stackoverflow.com/questions/101268/hidden-features-of-python#101537)
* [Named string formatting](https://stackoverflow.com/questions/101268/hidden-features-of-python#113164)
* [Nested list/generator comprehensions](https://stackoverflow.com/questions/101268/hidden-features-of-python#101549)
* [New types at runtime](https://stackoverflow.com/questions/101268/hidden-features-of-python#108297)
* [`.pth` files](https://stackoverflow.com/questions/101268/hidden-features-of-python#113833)
* [ROT13 Encoding](https://stackoverflow.com/questions/101268/hidden-features-of-python#1024693)
* [Regex Debugging](https://stackoverflow.com/questions/101268/hidden-features-of-python#143636)
* [Sending to Generators](https://stackoverflow.com/questions/101268/hidden-features-of-python#101739)
* [Tab Completion in Interactive Interpreter](https://stackoverflow.com/questions/101268/hidden-features-of-python#168270)
* [Ternary Expression](https://stackoverflow.com/questions/101268/hidden-features-of-python#116480)
* [`try/except/else`](https://stackoverflow.com/questions/101268/hidden-features-of-python#114157)
* [Unpacking+`print()` function](https://stackoverflow.com/questions/101268/hidden-features-of-python#3267903)
* [`with` statement](https://stackoverflow.com/questions/101268/hidden-features-of-python#109182) | Chaining comparison operators:
------------------------------
```
>>> x = 5
>>> 1 < x < 10
True
>>> 10 < x < 20
False
>>> x < 10 < x*10 < 100
True
>>> 10 > x <= 9
True
>>> 5 == x > 4
True
```
In case you're thinking it's doing `1 < x`, which comes out as `True`, and then comparing `True < 10`, which is also `True`, then no, that's really not what happens (see the last example.) It's really translating into `1 < x and x < 10`, and `x < 10 and 10 < x * 10 and x*10 < 100`, but with less typing and each term is only evaluated once. |
101,270 | <p>I want to use Vim's quickfix features with the output from Visual Studio's devenv build process or msbuild.</p>
<p>I've created a batch file called build.bat which executes the devenv build like this:</p>
<pre><code>devenv MySln.sln /Build Debug
</code></pre>
<p>In vim I've pointed the :make command to that batch file:</p>
<pre><code>:set makeprg=build.bat
</code></pre>
<p>When I now run :make, the build executes successfully, however the errors don't get parsed out. So if I run :cl or :cn I just end up seeing all the output from devenv /Build. I should see only the errors.</p>
<p>I've tried a number of different errorformat settings that I've found on various sites around the net, but none of them have parsed out the errors correctly. Here's a few I've tried:</p>
<pre><code>set errorformat=%*\\d>%f(%l)\ :\ %t%[A-z]%#\ %m
set errorformat=\ %#%f(%l)\ :\ %#%t%[A-z]%#\ %m
set errorformat=%f(%l,%c):\ error\ %n:\ %f
</code></pre>
<p>And of course I've tried Vim's default.</p>
<p>Here's some example output from the build.bat:</p>
<pre><code>C:\TFS\KwB Projects\Thingy>devenv Thingy.sln /Build Debug
Microsoft (R) Visual Studio Version 9.0.30729.1.
Copyright (C) Microsoft Corp. All rights reserved.
------ Build started: Project: Thingy, Configuration: Debug Any CPU ------
c:\WINDOWS\Microsoft.NET\Framework\v3.5\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationCore.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationFramework.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.DataSetExtensions.dll" /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.Linq.dll" /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationProvider.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\WindowsBase.dll" /debug+ /debug:full /filealign:512 /optimize- /out:obj\Debug\Thingy.exe /resource:obj\Debug\Thingy.g.resources /resource:obj\Debug\Thingy.Properties.Resources.resources /target:winexe App.xaml.cs Controller\FieldFactory.cs Controller\UserInfo.cs Data\ThingGatewaySqlDirect.cs Data\ThingListFetcher.cs Data\UserListFetcher.cs Gui\FieldList.xaml.cs Interfaces\IList.cs Interfaces\IListFetcher.cs Model\ComboBoxField.cs Model\ListValue.cs Model\ThingType.cs Interfaces\IThingGateway.cs Model\Field.cs Model\TextBoxField.cs Model\Thing.cs Gui\MainWindow.xaml.cs Gui\ThingWindow.xaml.cs Interfaces\IField.cs Properties\AssemblyInfo.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs RequiredValidation.cs "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\FieldList.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\MainWindow.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\ThingWindow.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\App.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\GeneratedInternalTypeHelper.g.cs"
C:\TFS\KwB Projects\Thingy\Thingy\Controller\FieldFactory.cs(14,19): error CS0246: The type or namespace name 'IFieldNothing' could not be found (are you missing a using directive or an assembly reference?)
Compile complete -- 1 errors, 0 warnings
========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ==========
</code></pre>
<p><strong>UPDATE:</strong>
It looks like using msbuild instead of devenv is probably the right way to go (as per Jay's comment).</p>
<p>Using msbuild the makeprg would be:</p>
<pre><code>:set makeprg=msbuild\ /nologo\ /v:q
</code></pre>
<p>Sample output whould be:</p>
<pre><code>Controller\FieldFactory.cs(14,19): error CS0246: The type or namespace name 'IFieldNothing' could not be found (are you missing a using directive or an assembly reference?)
</code></pre>
<p>It looks like the tricky part here may lie in the fact that the path is relative to the .csproj file, not the .sln file which is the current directory in Vim and lies one directory above the .csproj file.</p>
<p><strong>ANSWER:</strong>
I figured it out...</p>
<pre><code>set errorformat=\ %#%f(%l\\\,%c):\ %m
</code></pre>
<p>This will capture the output for both devenv /Build and msbuild.
However, msbuild has one catch. By default, it's output doesn't include full paths. To fix this you have to add the following line to your csproj file's main PropertyGroup:</p>
<pre><code><GenerateFullPaths>True</GenerateFullPaths>
</code></pre>
| [
{
"answer_id": 102454,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 1,
"selected": false,
"text": "<p>Try running msbuild instead of devenv. This will open up a ton of power in how the build runs.</p>\n\n<p>Open a Visual Studio Command Prompt to get your path set up. Then do <code>msbuild MySln.sln /Configuration:Debug</code>.</p>\n\n<p>See <code>msbuild /?</code> for help.</p>\n"
},
{
"answer_id": 161090,
"author": "Simon Buchan",
"author_id": 20135,
"author_profile": "https://Stackoverflow.com/users/20135",
"pm_score": 3,
"selected": false,
"text": "<p><em>Copy from question to remove from 'unanswered' list</em></p>\n\n<pre><code>set errorformat=\\ %#%f(%l\\\\\\,%c):\\ %m\n</code></pre>\n\n<p>This will capture the output for both <code>devenv /Build</code> and msbuild. However, msbuild has one catch. By default, it's output doesn't include full paths. To fix this you have to add the following line to your csproj file's main PropertyGroup:</p>\n\n<pre><code><GenerateFullPaths>True</GenerateFullPaths>\n</code></pre>\n"
},
{
"answer_id": 3115121,
"author": "idbrii",
"author_id": 79125,
"author_profile": "https://Stackoverflow.com/users/79125",
"pm_score": 1,
"selected": false,
"text": "<p>I found this question when looking for errorformat for compiling c++ in Visual Studio. The above answers don't work for me (I'm not using MSBuild either).</p>\n\n<p>I figured out this from <a href=\"http://vim.wikia.com/wiki/Integrate_gvim_with_Visual_Studio\" rel=\"nofollow noreferrer\">this Vim Tip</a> and <code>:help errorformat</code>:</p>\n\n<pre><code>\" filename(line) : error|warning|fatal error C0000: message\nset errorformat=\\ %#%f(%l)\\ :\\ %#%t%[A-z]%#\\ %[A-Z\\ ]%#%n:\\ %m\n</code></pre>\n\n<p>Which will give you a quickfix looking like this:</p>\n\n<pre><code>stats.cpp|604 error 2039| 'getMedian' : is not a member of 'Stats'\n</code></pre>\n\n<p>(with error highlighted) from</p>\n\n<pre><code>c:\\p4\\main\\stats.cpp(604) : error C2039: 'getMedian' : is not a member of 'Stats'\n</code></pre>\n"
},
{
"answer_id": 3122220,
"author": "idbrii",
"author_id": 79125,
"author_profile": "https://Stackoverflow.com/users/79125",
"pm_score": 3,
"selected": false,
"text": "<p>I found an even better answer: use <code>:compiler</code> to use built-in <code>efm</code> settings.</p>\n\n<pre><code>\" Microsoft C#\ncompiler cs\n\" Microsoft Visual C++\ncompiler msvc\n\" mono\ncompiler mcs\n\" gcc\ncompiler gcc\n</code></pre>\n\n<p>Note: It also sets the default <code>makeprg</code>. See $VIMRUNTIME/compiler/</p>\n"
},
{
"answer_id": 3145327,
"author": "manifest",
"author_id": 236554,
"author_profile": "https://Stackoverflow.com/users/236554",
"pm_score": 0,
"selected": false,
"text": "<p>None of these errorformats worked in Visual studio 2009 v9.0.21022.8 professional edition. Using cygwin, had to call devenv from bash which made setting makeprg a little tricky (screw batch files). Also had to tweak my errorformat when devenv splits into multiple processes and proceeds error message with \"1>\" or \"2>\" etc:</p>\n\n<pre><code>set autowrite\n\"2>c:\\cygwin\\home\\user\\proj/blah.cpp(1657) : error C2065: 'blah' : undeclared identifier\n\nset errorformat=%.%#>\\ %#%f(%l)\\ :\\ %#%t%[A-z]%#\\ %[A-Z\\ ]%#%n:\\ %m\nlet prg=\"devenv\"\nlet makepath=$MAKEPATH\nlet &makeprg='cmd /c \"'.prg.' '.makepath.'\"'\n</code></pre>\n\n<p>My .bashrc sets the MAKEPATH environment variable using cygpath to convert to a DOS compatible path:</p>\n\n<pre><code>export MAKEPATH=\"$(cygpath -d \"proj/VC9/some.sln\") /build \\\"Debug\\\"\"\n</code></pre>\n\n<p>If you have vim 6.x you can use <a href=\"http://vim.wikia.com/wiki/Use_the_quickfix_window_to_list_all_errors\" rel=\"nofollow noreferrer\">:cw</a> which is SO much better than clist (try searching for errors among hundreds of warnings and you know what I mean). Looking at vim tweaks makes me want to vomit but I'm in vim heaven!!! Good bye visual studio! Thanks for the base to tweak pydave +1.</p>\n"
},
{
"answer_id": 3618197,
"author": "Tom Miller",
"author_id": 188810,
"author_profile": "https://Stackoverflow.com/users/188810",
"pm_score": 1,
"selected": false,
"text": "<p>As Simon Buchan mentioned you can use this in your project to generate the full paths in the output:</p>\n\n<pre><code><GenerateFullPaths>True</GenerateFullPaths>\n</code></pre>\n\n<p>But you can make it more portable by adding <code>/property:GenerateFullPaths=true</code> to you <code>makeprg</code> instead of adding the above to your project files.</p>\n\n<pre><code>:set makeprg=msbuild\\ /nologo\\ /v:q\\ /property:GenerateFullPaths=true\\\n</code></pre>\n"
},
{
"answer_id": 3621753,
"author": "Kevin Berridge",
"author_id": 4407,
"author_profile": "https://Stackoverflow.com/users/4407",
"pm_score": 6,
"selected": true,
"text": "<p>I have a blog post which walks through all the details of getting C# projects building in Vim, including the error format. You can find it here: <a href=\"http://kevin-berridge.blogspot.com/2008/09/vim-c-compiling.html\" rel=\"noreferrer\">http://kevin-berridge.blogspot.com/2008/09/vim-c-compiling.html</a></p>\n\n<p>In short you need the following:</p>\n\n<pre><code>:set errorformat=\\ %#%f(%l\\\\\\,%c):\\ %m\n:set makeprg=msbuild\\ /nologo\\ /v:q\\ /property:GenerateFullPaths=true\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4407/"
]
| I want to use Vim's quickfix features with the output from Visual Studio's devenv build process or msbuild.
I've created a batch file called build.bat which executes the devenv build like this:
```
devenv MySln.sln /Build Debug
```
In vim I've pointed the :make command to that batch file:
```
:set makeprg=build.bat
```
When I now run :make, the build executes successfully, however the errors don't get parsed out. So if I run :cl or :cn I just end up seeing all the output from devenv /Build. I should see only the errors.
I've tried a number of different errorformat settings that I've found on various sites around the net, but none of them have parsed out the errors correctly. Here's a few I've tried:
```
set errorformat=%*\\d>%f(%l)\ :\ %t%[A-z]%#\ %m
set errorformat=\ %#%f(%l)\ :\ %#%t%[A-z]%#\ %m
set errorformat=%f(%l,%c):\ error\ %n:\ %f
```
And of course I've tried Vim's default.
Here's some example output from the build.bat:
```
C:\TFS\KwB Projects\Thingy>devenv Thingy.sln /Build Debug
Microsoft (R) Visual Studio Version 9.0.30729.1.
Copyright (C) Microsoft Corp. All rights reserved.
------ Build started: Project: Thingy, Configuration: Debug Any CPU ------
c:\WINDOWS\Microsoft.NET\Framework\v3.5\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationCore.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationFramework.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.DataSetExtensions.dll" /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.Linq.dll" /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationProvider.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\WindowsBase.dll" /debug+ /debug:full /filealign:512 /optimize- /out:obj\Debug\Thingy.exe /resource:obj\Debug\Thingy.g.resources /resource:obj\Debug\Thingy.Properties.Resources.resources /target:winexe App.xaml.cs Controller\FieldFactory.cs Controller\UserInfo.cs Data\ThingGatewaySqlDirect.cs Data\ThingListFetcher.cs Data\UserListFetcher.cs Gui\FieldList.xaml.cs Interfaces\IList.cs Interfaces\IListFetcher.cs Model\ComboBoxField.cs Model\ListValue.cs Model\ThingType.cs Interfaces\IThingGateway.cs Model\Field.cs Model\TextBoxField.cs Model\Thing.cs Gui\MainWindow.xaml.cs Gui\ThingWindow.xaml.cs Interfaces\IField.cs Properties\AssemblyInfo.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs RequiredValidation.cs "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\FieldList.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\MainWindow.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\ThingWindow.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\App.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\GeneratedInternalTypeHelper.g.cs"
C:\TFS\KwB Projects\Thingy\Thingy\Controller\FieldFactory.cs(14,19): error CS0246: The type or namespace name 'IFieldNothing' could not be found (are you missing a using directive or an assembly reference?)
Compile complete -- 1 errors, 0 warnings
========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ==========
```
**UPDATE:**
It looks like using msbuild instead of devenv is probably the right way to go (as per Jay's comment).
Using msbuild the makeprg would be:
```
:set makeprg=msbuild\ /nologo\ /v:q
```
Sample output whould be:
```
Controller\FieldFactory.cs(14,19): error CS0246: The type or namespace name 'IFieldNothing' could not be found (are you missing a using directive or an assembly reference?)
```
It looks like the tricky part here may lie in the fact that the path is relative to the .csproj file, not the .sln file which is the current directory in Vim and lies one directory above the .csproj file.
**ANSWER:**
I figured it out...
```
set errorformat=\ %#%f(%l\\\,%c):\ %m
```
This will capture the output for both devenv /Build and msbuild.
However, msbuild has one catch. By default, it's output doesn't include full paths. To fix this you have to add the following line to your csproj file's main PropertyGroup:
```
<GenerateFullPaths>True</GenerateFullPaths>
``` | I have a blog post which walks through all the details of getting C# projects building in Vim, including the error format. You can find it here: <http://kevin-berridge.blogspot.com/2008/09/vim-c-compiling.html>
In short you need the following:
```
:set errorformat=\ %#%f(%l\\\,%c):\ %m
:set makeprg=msbuild\ /nologo\ /v:q\ /property:GenerateFullPaths=true
``` |
101,326 | <p>I've set up wildcard mapping on IIS 6, by adding "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll", and ensured "Verify that file exists" is not checked :</p>
<ul>
<li>on the "websites" directory in IIS</li>
<li>on the website</li>
</ul>
<p>However, after a iisreset, when I go to <a href="http://myserver/something.gif" rel="nofollow noreferrer">http://myserver/something.gif</a>, I still get IIS 404 error, not asp.net one.</p>
<p>Is there something I missed ?</p>
<p>Precisions:</p>
<ul>
<li>this is not for using ASP.NET MVC</li>
<li>i'd rather not use iis 404 custom error pages, as I have a httpmodule for logging errors (this is a low traffic internal site, so wildcard mapping performance penalty is not a problem ;))</li>
</ul>
| [
{
"answer_id": 101408,
"author": "WebDude",
"author_id": 15360,
"author_profile": "https://Stackoverflow.com/users/15360",
"pm_score": 0,
"selected": false,
"text": "<p>You can try use custom errors to do this.\nGo into Custom Errors in you Website properties and set the 404 to point to a URL in your site. Like /404.aspx is that exists.</p>\n\n<p>With aspnet_isapi, you want to use a HttpModule to handle your wildcards.\nlike <a href=\"http://urlrewriter.net/\" rel=\"nofollow noreferrer\">http://urlrewriter.net/</a></p>\n"
},
{
"answer_id": 101692,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 0,
"selected": false,
"text": "<p>You can't use wilcard mapping without using ASP.net Routing or URLrewriting or some url mapping mechanism.</p>\n\n<p>If you want to do 404, you have to configure it in web.config -> Custom errors.<br>\nThen you can redirect to other pages if you want.</p>\n\n<p>New in 3.5 SP1, you set the RedirectMode to \"responseRewrite\" to avoid a redirect to a custom error page and leave the URL in the browser untouched.</p>\n\n<p>Other way to do it, will be catching the error in global.aspx, and redirecting. Please comment on the answer if you need further instructions.</p>\n"
},
{
"answer_id": 103661,
"author": "Christopher G. Lewis",
"author_id": 13532,
"author_profile": "https://Stackoverflow.com/users/13532",
"pm_score": 3,
"selected": true,
"text": "<p>You need to add an HTTP Handler in your web config for gif files:</p>\n\n<pre><code> <system.web>\n <httpHandlers>\n <add path=\"*.gif\" verb=\"GET,HEAD\" type=\"System.Web.StaticFileHandler\" validate=\"true\"/>\n </httpHandlers>\n </system.web>\n</code></pre>\n\n<p>That forces .Net to handle the file, then you'll get the .Net error.</p>\n\n<h2>Server Error in '/' Application.</h2>\n\n<p>The resource cannot be found. \nDescription: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. </p>\n\n<p>Requested URL: /test.gif</p>\n\n<hr>\n\n<p>Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433 </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971/"
]
| I've set up wildcard mapping on IIS 6, by adding "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet\_isapi.dll", and ensured "Verify that file exists" is not checked :
* on the "websites" directory in IIS
* on the website
However, after a iisreset, when I go to <http://myserver/something.gif>, I still get IIS 404 error, not asp.net one.
Is there something I missed ?
Precisions:
* this is not for using ASP.NET MVC
* i'd rather not use iis 404 custom error pages, as I have a httpmodule for logging errors (this is a low traffic internal site, so wildcard mapping performance penalty is not a problem ;)) | You need to add an HTTP Handler in your web config for gif files:
```
<system.web>
<httpHandlers>
<add path="*.gif" verb="GET,HEAD" type="System.Web.StaticFileHandler" validate="true"/>
</httpHandlers>
</system.web>
```
That forces .Net to handle the file, then you'll get the .Net error.
Server Error in '/' Application.
--------------------------------
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /test.gif
---
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433 |
101,329 | <p>In particular, wouldn't there have to be some kind of function pointer in place anyway? </p>
| [
{
"answer_id": 101341,
"author": "yrp",
"author_id": 7228,
"author_profile": "https://Stackoverflow.com/users/7228",
"pm_score": 0,
"selected": false,
"text": "<p>There's no need for function pointers as it cant change during the runtime.</p>\n"
},
{
"answer_id": 101342,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 0,
"selected": false,
"text": "<p>Branches are generated directly to the compiled code for the methods; just like if you have functions that aren't in a class at all, branches are generated straight to them.</p>\n"
},
{
"answer_id": 101349,
"author": "m_pGladiator",
"author_id": 446104,
"author_profile": "https://Stackoverflow.com/users/446104",
"pm_score": 2,
"selected": false,
"text": "<p>The virtual methods are required when you want to use polymorphism. The <code>virtual</code> modifier puts the method in the VMT for late binding and then at runtime is decided which method from which class is executed. </p>\n\n<p>If the method is not virtual - it is decided at compile time from which class instance will it be executed.</p>\n\n<p>Function pointers are used mostly for callbacks.</p>\n"
},
{
"answer_id": 101352,
"author": "Arno",
"author_id": 13685,
"author_profile": "https://Stackoverflow.com/users/13685",
"pm_score": 0,
"selected": false,
"text": "<p>The compiler/linker links directly which methods will be invoked. No need for a vtable indirection. BTW, what does that have to do with \"stack vs. heap\"?</p>\n"
},
{
"answer_id": 101356,
"author": "JB.",
"author_id": 12274,
"author_profile": "https://Stackoverflow.com/users/12274",
"pm_score": 1,
"selected": false,
"text": "<p>If a class with a virtual function is implemented with a vtable, then a class with no virtual function is implemented without a vtable.</p>\n\n<p>A vtable contains the function pointers needed to dispatch a call to the appropriate method. If the method isn't virtual, the call goes to the class's known type, and no indirection is needed.</p>\n"
},
{
"answer_id": 101480,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 1,
"selected": false,
"text": "<p>For a non-virtual method the compiler can generate a normal function invocation (e.g., CALL to a particular address with this pointer passed as a parameter) or even inline it. For a virtual function, the compiler doesn't usually know at compile time at which address to invoke the code, therefore it generates code that looks up the address in the vtable at runtime and then invokes the method. True, even for virtual functions the compiler can sometimes correctly resolve the right code at compile time (e.g., methods on local variables invoked without a pointer/reference).</p>\n"
},
{
"answer_id": 101583,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 5,
"selected": true,
"text": "<p>Non virtual member functions are really just a syntactic sugar as they are almost like an ordinary function but with access checking and an implicit object parameter.</p>\n\n<pre><code>struct A \n{\n void foo ();\n void bar () const;\n};\n</code></pre>\n\n<p>is basically the same as:</p>\n\n<pre><code>struct A \n{\n};\n\nvoid foo (A * this);\nvoid bar (A const * this);\n</code></pre>\n\n<p>The vtable is needed so that we call the right function for our specific object instance. For example, if we have:</p>\n\n<pre><code>struct A \n{\n virtual void foo ();\n};\n</code></pre>\n\n<p>The implementation of 'foo' might approximate to something like:</p>\n\n<pre><code>void foo (A * this) {\n void (*realFoo)(A *) = lookupVtable (this->vtable, \"foo\");\n (realFoo)(this); // Make the call to the most derived version of 'foo'\n}\n</code></pre>\n"
},
{
"answer_id": 101648,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 4,
"selected": false,
"text": "<p>I think that the phrase "<em>classes with virtual functions are implemented with vtables</em>" is misleading you.</p>\n<p>The phrase makes it sound like classes with virtual functions are implemented "<em>in way A</em>" and classes without virtual functions are implemented "<em>in way B</em>".</p>\n<p>In reality, classes with virtual functions, <em><strong>in addition to</strong></em> being implemented as classes are, they also have a vtable. Another way to see it is that "'vtables' implement the 'virtual function' part of a class".</p>\n<h2>More details on how they both work:</h2>\n<p>All classes (with virtual or non-virtual methods) are structs. The <strong>only</strong> difference between a struct and a class in C++ is that, by default, members are public in structs and private in classes. Because of that, I'll use the term class here to refer to both structs and classes. Remember, they are almost synonyms!</p>\n<h3>Data Members</h3>\n<p>Classes are (as are structs) just blocks of contiguous memory where each member is stored in sequence. Note that some times there will be gaps between members for CPU architectural reasons, so the block can be larger than the sum of its parts.</p>\n<h3>Methods</h3>\n<p>Methods or "member functions" are an illusion. In reality, there is no such thing as a "member function". A function is always just a sequence of machine code instructions stored somewhere in memory. To make a call, the processor jumps to that position of memory and starts executing. You could say that all methods and functions are 'global', and any indication of the contrary is a convenient illusion enforced by the compiler.</p>\n<p>Obviously, a method acts like it belongs to a specific object, so clearly there is more going on. To tie a particular call of a method (a function) to a specific object, every member method has a hidden argument that is a pointer to the object in question. The member is <em>hidden</em> in that you don't add it to your C++ code yourself, but there is nothing magical about it -- it's very real. When you say this:</p>\n<pre><code>void CMyThingy::DoSomething(int arg);\n{\n // do something\n}\n</code></pre>\n<p>The compiler <em>really</em> does this:</p>\n<pre><code>void CMyThingy_DoSomething(CMyThingy* this, int arg)\n{\n /do something\n}\n</code></pre>\n<p>Finally, when you write this:</p>\n<pre><code>myObj.doSomething(aValue);\n</code></pre>\n<p>the compiler says:</p>\n<pre><code>CMyThingy_DoSomething(&myObj, aValue);\n</code></pre>\n<p>No need for function pointers anywhere! The compiler knows already which method you are calling so it calls it directly.</p>\n<p>Static methods are even simpler. They don't have a <em>this</em> pointer, so they are implemented exactly as you write them.</p>\n<p>That's is! The rest is just convenient syntax sugaring: The compiler knows which class a method belongs to, so it makes sure it doesn't let you call the function without specifying which one. It also uses that knowledge to translates <code>myItem</code> to <code>this->myItem</code> when it's unambiguous to do so.</p>\n<p><em>(yeah, that's right: member access in a method is <strong>always</strong> done indirectly via a pointer, even if you don't see one)</em></p>\n<p>(<strong>Edit</strong>: Removed last sentence and posted separately so it can be criticized separately)</p>\n"
},
{
"answer_id": 101710,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 1,
"selected": false,
"text": "<p><em>(I pulled this section from my original answer so that it can be criticized separately. It is a lot more concise and to the point of your question, so in a way it's a much better answer)</em></p>\n\n<p>No, there are no function pointers; instead, the compiler turns the problem <em>inside-out</em>.</p>\n\n<p>The compiler calls a global function with <em>a pointer to the object</em> instead of calling some <em>pointed-to function inside the object</em></p>\n\n<p>Why? Because it's usually a lot more efficient that way. Indirect calls are expensive instructions.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
| In particular, wouldn't there have to be some kind of function pointer in place anyway? | Non virtual member functions are really just a syntactic sugar as they are almost like an ordinary function but with access checking and an implicit object parameter.
```
struct A
{
void foo ();
void bar () const;
};
```
is basically the same as:
```
struct A
{
};
void foo (A * this);
void bar (A const * this);
```
The vtable is needed so that we call the right function for our specific object instance. For example, if we have:
```
struct A
{
virtual void foo ();
};
```
The implementation of 'foo' might approximate to something like:
```
void foo (A * this) {
void (*realFoo)(A *) = lookupVtable (this->vtable, "foo");
(realFoo)(this); // Make the call to the most derived version of 'foo'
}
``` |
101,338 | <p>Is it valid to have a 'choice' of 'group' elements when defining an XML Schema (XSD)</p>
<p>i.e. is the following valid</p>
<pre><code><xs:complexType name="HeaderType">
<xs:sequence>
<xs:element name="reservation-number" type="ReservationNumberType" minOccurs="1" maxOccurs="1" nillable="false" />
<xs:choice minOccurs="1" maxOccurs="1">
<xs:group ref="ReservationGroup" />
<xs:group ref="CancellationGroup"/>
</xs:choice>
</xs:sequence>
</xs:complexType>
</code></pre>
<p>Where an XML message can represent, for example, either a new reservation or a cancellation of an existing reservation.</p>
<p>If the message is for a reservation, then it must include all the elements defined in the ReservationGroup group.</p>
<p>If it is a cancellation, then it must include all the elements defined in the CancellationGroup group.</p>
<p>For some reason, my XML editor (Eclipse) does not like this, but does not indicate why. It shows there being an error on the line <xs:complexType name="HeaderType"> but does not say what the error is</p>
| [
{
"answer_id": 101410,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 1,
"selected": false,
"text": "<p>Whether this is valid depends on the content of the groups: if they're 'sequence' or 'choice' model groups, it's perfectly legal; 'all' model groups are more problematic and generally not allowed in this case.</p>\n"
},
{
"answer_id": 101772,
"author": "Dunderklumpen",
"author_id": 16239,
"author_profile": "https://Stackoverflow.com/users/16239",
"pm_score": 4,
"selected": true,
"text": "<p>I'm no XML expert, although I use it quite a lot. This isn't the way I'd generally do this sort of structure. I would prefer a separate complex types rather than a choice of two groups (see the very end of this answer).</p>\n\n<p>I suspect that the problem is that ReservationGroup and CancellationGroup start with the same element, in which case you will violate the Schema Component Constraint: Unique Particle Attribution (below).</p>\n\n<p><a href=\"http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/#cos-nonambig\" rel=\"noreferrer\" title=\"http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/#cos-nonambig\">http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/#cos-nonambig</a></p>\n\n<blockquote>\n <p><strong>Schema Component Constraint: Unique\n Particle Attribution</strong> </p>\n \n <p>A content model\n must be formed such that during\n ·validation· of an element information\n item sequence, the particle component\n contained directly, indirectly or\n ·implicitly· therein with which to\n attempt to ·validate· each item in the\n sequence in turn can be uniquely\n determined without examining the\n content or attributes of that item,\n and without any information about the\n items in the remainder of the\n sequence.</p>\n \n <p><strong>Note:</strong> This constraint\n reconstructs for XML Schema the\n equivalent constraints of [XML 1.0\n (Second Edition)] and SGML. Given the\n presence of element substitution\n groups and wildcards, the concise\n expression of this constraint is\n difficult, see Analysis of the Unique\n Particle Attribution Constraint\n (non-normative) (§H) for further\n discussion.</p>\n</blockquote>\n\n<p>For example, the two groups below are illegal in the same choice, because each of their first element is \"name\" which means that you cannot identify which group you are looking at. However is the first element of ReservationGroup is different from Cancellation group \n(resDate and cancDate maybe), then the that is valid.</p>\n\n<p><strong>Edit:</strong> I'd never come across this sort of problem before, and I think its fascinating that the definitions of the groups are totally legal, but if you put them together in a choice, that choice becomes illegal because of the definition of each group.</p>\n\n<p><strong>Groups that cannot form a legal choice</strong></p>\n\n<pre><code><xs:group name=\"ReservationGroup\">\n <xs:sequence>\n <xs:element name=\"date\"/>\n <xs:element name=\"name\"/>\n <xs:element name=\"address\"/>\n </xs:sequence>\n</xs:group>\n\n<xs:group name=\"CancellationGroup\">\n <xs:sequence>\n <xs:element name=\"date\"/>\n <xs:element name=\"name\"/>\n <xs:element name=\"address\"/>\n </xs:sequence>\n</xs:group>\n</code></pre>\n\n<p><strong>Groups that can form a legal choice</strong></p>\n\n<pre><code><xs:group name=\"ReservationGroup\">\n <xs:sequence>\n <xs:element name=\"resDate\"/>\n <xs:element name=\"name\"/>\n <xs:element name=\"address\"/>\n </xs:sequence>\n</xs:group>\n\n<xs:group name=\"CancellationGroup\">\n <xs:sequence>\n <xs:element name=\"cancDate\"/>\n <xs:element name=\"name\"/>\n <xs:element name=\"address\"/>\n </xs:sequence>\n</xs:group>\n</code></pre>\n\n<p>As I mentioned above, I'd do this sort of thing with complex types. Yes, it adds another element, but it seems the obvious way and I like obviousness.</p>\n\n<pre><code><xs:complexType name=\"HeaderType\">\n <xs:sequence>\n <xs:element name=\"reservation-number\" type=\"ReservationNumberType\" minOccurs=\"1\" maxOccurs=\"1\" nillable=\"false\" />\n <xs:choice minOccurs=\"1\" maxOccurs=\"1\">\n <xs:element name=\"reservation\" type=\"ReservationType\" />\n <xs:element name=\"cancellation\" type=\"CancellationType\" />\n </xs:choice>\n </xs:sequence>\n</xs:complexType>\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452/"
]
| Is it valid to have a 'choice' of 'group' elements when defining an XML Schema (XSD)
i.e. is the following valid
```
<xs:complexType name="HeaderType">
<xs:sequence>
<xs:element name="reservation-number" type="ReservationNumberType" minOccurs="1" maxOccurs="1" nillable="false" />
<xs:choice minOccurs="1" maxOccurs="1">
<xs:group ref="ReservationGroup" />
<xs:group ref="CancellationGroup"/>
</xs:choice>
</xs:sequence>
</xs:complexType>
```
Where an XML message can represent, for example, either a new reservation or a cancellation of an existing reservation.
If the message is for a reservation, then it must include all the elements defined in the ReservationGroup group.
If it is a cancellation, then it must include all the elements defined in the CancellationGroup group.
For some reason, my XML editor (Eclipse) does not like this, but does not indicate why. It shows there being an error on the line <xs:complexType name="HeaderType"> but does not say what the error is | I'm no XML expert, although I use it quite a lot. This isn't the way I'd generally do this sort of structure. I would prefer a separate complex types rather than a choice of two groups (see the very end of this answer).
I suspect that the problem is that ReservationGroup and CancellationGroup start with the same element, in which case you will violate the Schema Component Constraint: Unique Particle Attribution (below).
[http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/#cos-nonambig](http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/#cos-nonambig "http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/#cos-nonambig")
>
> **Schema Component Constraint: Unique
> Particle Attribution**
>
>
> A content model
> must be formed such that during
> ·validation· of an element information
> item sequence, the particle component
> contained directly, indirectly or
> ·implicitly· therein with which to
> attempt to ·validate· each item in the
> sequence in turn can be uniquely
> determined without examining the
> content or attributes of that item,
> and without any information about the
> items in the remainder of the
> sequence.
>
>
> **Note:** This constraint
> reconstructs for XML Schema the
> equivalent constraints of [XML 1.0
> (Second Edition)] and SGML. Given the
> presence of element substitution
> groups and wildcards, the concise
> expression of this constraint is
> difficult, see Analysis of the Unique
> Particle Attribution Constraint
> (non-normative) (§H) for further
> discussion.
>
>
>
For example, the two groups below are illegal in the same choice, because each of their first element is "name" which means that you cannot identify which group you are looking at. However is the first element of ReservationGroup is different from Cancellation group
(resDate and cancDate maybe), then the that is valid.
**Edit:** I'd never come across this sort of problem before, and I think its fascinating that the definitions of the groups are totally legal, but if you put them together in a choice, that choice becomes illegal because of the definition of each group.
**Groups that cannot form a legal choice**
```
<xs:group name="ReservationGroup">
<xs:sequence>
<xs:element name="date"/>
<xs:element name="name"/>
<xs:element name="address"/>
</xs:sequence>
</xs:group>
<xs:group name="CancellationGroup">
<xs:sequence>
<xs:element name="date"/>
<xs:element name="name"/>
<xs:element name="address"/>
</xs:sequence>
</xs:group>
```
**Groups that can form a legal choice**
```
<xs:group name="ReservationGroup">
<xs:sequence>
<xs:element name="resDate"/>
<xs:element name="name"/>
<xs:element name="address"/>
</xs:sequence>
</xs:group>
<xs:group name="CancellationGroup">
<xs:sequence>
<xs:element name="cancDate"/>
<xs:element name="name"/>
<xs:element name="address"/>
</xs:sequence>
</xs:group>
```
As I mentioned above, I'd do this sort of thing with complex types. Yes, it adds another element, but it seems the obvious way and I like obviousness.
```
<xs:complexType name="HeaderType">
<xs:sequence>
<xs:element name="reservation-number" type="ReservationNumberType" minOccurs="1" maxOccurs="1" nillable="false" />
<xs:choice minOccurs="1" maxOccurs="1">
<xs:element name="reservation" type="ReservationType" />
<xs:element name="cancellation" type="CancellationType" />
</xs:choice>
</xs:sequence>
</xs:complexType>
``` |
101,362 | <p>How do you generate passwords?</p>
<ul>
<li>Random Characters?</li>
<li>Passphrases?</li>
<li>High Ascii?</li>
</ul>
<p>Something like this?</p>
<pre><code>cat /dev/urandom | strings
</code></pre>
| [
{
"answer_id": 101368,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 4,
"selected": false,
"text": "<p>A short python script to generate passwords, originally from the python cookbook.</p>\n\n<pre><code>#!/usr/bin/env python\n\nfrom random import choice\nimport getopt\nimport string\nimport sys\n\ndef GenPasswd():\n chars = string.letters + string.digits\n for i in range(8):\n newpasswd = newpasswd + choice(chars)\n return newpasswd\n\ndef GenPasswd2(length=8, chars=string.letters + string.digits):\n return ''.join([choice(chars) for i in range(length)])\n\nclass Options(object):\n pass\n\ndef main(argv):\n (optionList,args) = getopt.getopt(argv[1:],\"r:l:\",[\"repeat=\",\"length=\"])\n\n options = Options()\n options.repeat = 1\n options.length = 8\n for (key,value) in optionList:\n if key == \"-r\" or key == \"--repeat\":\n options.repeat = int(value)\n elif key == \"-l\" or key == \"--length\":\n options.length = int(value)\n\n for i in xrange(options.repeat):\n print GenPasswd2(options.length)\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))\n</code></pre>\n"
},
{
"answer_id": 101369,
"author": "Matthias Kestenholz",
"author_id": 317346,
"author_profile": "https://Stackoverflow.com/users/317346",
"pm_score": 2,
"selected": false,
"text": "<p>The algorithm in <a href=\"http://www.adel.nursat.kz/apg/\" rel=\"nofollow noreferrer\">apg</a> is pretty cool. But I mostly use random characters from a list which I've defined myself. It is mostly numbers, upper- and lowercase letters and some punctuation marks. I've eliminated chars which are prone to getting mistaken for another character like '1', 'l', 'I', 'O', '0' etc.</p>\n"
},
{
"answer_id": 101371,
"author": "Luke Bennett",
"author_id": 17602,
"author_profile": "https://Stackoverflow.com/users/17602",
"pm_score": 2,
"selected": false,
"text": "<p>I use <a href=\"http://keepass.info/\" rel=\"nofollow noreferrer\">KeePass</a> to generate complex passwords.</p>\n"
},
{
"answer_id": 101377,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php\n print md5(rand(0, 99999));\n?>\n</code></pre>\n"
},
{
"answer_id": 101384,
"author": "px.",
"author_id": 18769,
"author_profile": "https://Stackoverflow.com/users/18769",
"pm_score": 1,
"selected": false,
"text": "<p>On a Mac I use <a href=\"http://www.net-security.org/software.php?id=612\" rel=\"nofollow noreferrer\">RPG</a>. </p>\n"
},
{
"answer_id": 101385,
"author": "Daniel",
"author_id": 416,
"author_profile": "https://Stackoverflow.com/users/416",
"pm_score": 1,
"selected": false,
"text": "<p>In PHP, by generating a random string of characters from the ASCII table. See <a href=\"https://stackoverflow.com/questions/48124/generating-pseudorandom-alpha-numeric-strings#48285\">Generating (pseudo)random alpha-numeric strings</a></p>\n"
},
{
"answer_id": 101392,
"author": "Turnkey",
"author_id": 13144,
"author_profile": "https://Stackoverflow.com/users/13144",
"pm_score": 3,
"selected": false,
"text": "<p>The open source <a href=\"http://keepass.info/\" rel=\"noreferrer\">Keepass</a> tool has some excellent capabilities for password generation, including enhanced randomization.</p>\n"
},
{
"answer_id": 101398,
"author": "Isaac Moses",
"author_id": 179,
"author_profile": "https://Stackoverflow.com/users/179",
"pm_score": 1,
"selected": false,
"text": "<p>I start with the initials of a sentence in a foreign language, with some convention for capitalizing some of them. Then, I insert in a particular part of the sentence a combination of numbers and symbols derived from the name of the application or website.</p>\n\n<p>This scheme generates a unique password for each application that I can re-derive each time in my head with no trouble (so no memorization), and there is zero chance of any part of it showing up in a dictionary.</p>\n"
},
{
"answer_id": 101399,
"author": "Erratic",
"author_id": 2246765,
"author_profile": "https://Stackoverflow.com/users/2246765",
"pm_score": 2,
"selected": false,
"text": "<p>I don't like random character passwords. They are difficult to remember.</p>\n\n<p>Generally my passwords fall into tiers based on how important that information is to me.</p>\n\n<p>My most secure passwords tend to use a combination of old BBS random generated passwords that I was too young and dumb to know how to change and memorized. Appending a few of those together with liberal use of the shift key works well. If I don't use those I find pass phrases better. Perhaps a phrase from some book that I enjoy, once again with some mixed case and special symbols put it. Often I'll use more than 1 phrase, or several words from one phrase, concatenated with several from another.</p>\n\n<p>On low priority sites my passwords are are pretty short, generally a combination of a few familiar tokens.</p>\n\n<p>The place I have the biggest problem is work, where we need to change our password every 30 days and can't repeat passwords. I just do like everyone else, come up with a password and append an ever increasing index to the end. Password rules like that are absurd.</p>\n"
},
{
"answer_id": 101417,
"author": "martinatime",
"author_id": 1353,
"author_profile": "https://Stackoverflow.com/users/1353",
"pm_score": 2,
"selected": false,
"text": "<p>I use <a href=\"https://www.grc.com/passwords.htm\" rel=\"nofollow noreferrer\">https://www.grc.com/passwords.htm</a> to generate long password strings for things like WPA keys. You could also use this (via screenscraping) to create salts for authentication password hashing if you have to implement some sort of registration site.</p>\n"
},
{
"answer_id": 101418,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 1,
"selected": false,
"text": "<p>You will have to code extra rules to check that your password is acceptable for the system you are writing it for. Some systems have policies like \"two digits and two uppercase letters minimum\" and so on. As you generate your password character by character, keep a count of the digits/alpha/uppercase as required, and wrap the password generation in a do..while that will repeat the password generation until (digitCount>1 && alphaCount>4 && upperCount>1), or whatever.</p>\n"
},
{
"answer_id": 101429,
"author": "Abhishek Mishra",
"author_id": 8786,
"author_profile": "https://Stackoverflow.com/users/8786",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.wohmart.com/ircd/pub/irc_tools/mkpasswd/mkpasswd+vms.c\" rel=\"nofollow noreferrer\">http://www.wohmart.com/ircd/pub/irc_tools/mkpasswd/mkpasswd+vms.c</a></p>\n\n<p><a href=\"http://www.obviex.com/Samples/Password.aspx\" rel=\"nofollow noreferrer\">http://www.obviex.com/Samples/Password.aspx</a></p>\n\n<p><a href=\"https://www.uwo.ca/its/network/security/passwd-suite/sample.c\" rel=\"nofollow noreferrer\">https://www.uwo.ca/its/network/security/passwd-suite/sample.c</a></p>\n\n<p>Even in Excel!\n<a href=\"https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1032050.html\" rel=\"nofollow noreferrer\">https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1032050.html</a></p>\n\n<p><a href=\"http://webnet77.com/cgi-bin/helpers/crypthelp.pl\" rel=\"nofollow noreferrer\">http://webnet77.com/cgi-bin/helpers/crypthelp.pl</a></p>\n"
},
{
"answer_id": 101432,
"author": "Thilo",
"author_id": 14955,
"author_profile": "https://Stackoverflow.com/users/14955",
"pm_score": 2,
"selected": false,
"text": "<p>For web sites I use <a href=\"http://supergenpass.com/\" rel=\"nofollow noreferrer\">SuperGenPass</a>, which derives a site-specific password from a master password and the domain name, using a hash function (based on MD5). No need to store that password anywhere (SuperGenPass itself is a bookmarklet, totally client-side), just remember your master password.</p>\n"
},
{
"answer_id": 101489,
"author": "mloughran",
"author_id": 18751,
"author_profile": "https://Stackoverflow.com/users/18751",
"pm_score": -1,
"selected": false,
"text": "<p>Pick a sequence out of</p>\n\n<pre><code>md5 random_file\n</code></pre>\n"
},
{
"answer_id": 101514,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 2,
"selected": false,
"text": "<p>In some circumstances, I use Perl's Crypt::PassGen module, which uses Markov chain analysis on a corpus of words (e.g. /usr/share/dict/words on any reasonably Unix system). This allows it to generate passwords that turn out to be reasonably pronounceable and thus remember.</p>\n\n<p>That said, at $work we are moving to hardware challenge/response token mechanisms.</p>\n"
},
{
"answer_id": 101529,
"author": "titanae",
"author_id": 2387,
"author_profile": "https://Stackoverflow.com/users/2387",
"pm_score": 1,
"selected": false,
"text": "<p>Password Monkey, iGoogle widget!</p>\n"
},
{
"answer_id": 101547,
"author": "Buzz",
"author_id": 13113,
"author_profile": "https://Stackoverflow.com/users/13113",
"pm_score": 2,
"selected": false,
"text": "<p>I used an unusual method of generating passwords recently. They didn't need to be super strong, and random passwords are just too hard to remember. My application had a huge table of cities in North America. To generate a password, I generated a random number, grabbed a randon city, and added another random number. </p>\n\n<p>boston9934</p>\n\n<p>The lengths of the numbers were random, (as was if they were appended, prepended, or both), so it wasn't too easy to brute force. </p>\n"
},
{
"answer_id": 101575,
"author": "Ron Tuffin",
"author_id": 939,
"author_profile": "https://Stackoverflow.com/users/939",
"pm_score": 3,
"selected": false,
"text": "<p>I use <a href=\"http://passwordsafe.sourceforge.net/\" rel=\"noreferrer\">password safe</a> to generate and store all my passwords, that way you don't have to remember super strong passwords (well except the one that unlocks your safe).</p>\n"
},
{
"answer_id": 101701,
"author": "Elias Yarrkov",
"author_id": 18814,
"author_profile": "https://Stackoverflow.com/users/18814",
"pm_score": 2,
"selected": false,
"text": "<p>Pick a strong master password how you like, then generate a password for each site with cryptohash(masterpasword+sitename). You will not lose your password for site A if your password for site B gets in the wrong hands (due to an evil admin, wlan sniffing or site compromise for example), yet you will only have to remember a single password.</p>\n"
},
{
"answer_id": 101715,
"author": "Linor",
"author_id": 3197,
"author_profile": "https://Stackoverflow.com/users/3197",
"pm_score": 2,
"selected": false,
"text": "<p>I think it largely depends on what you want to use the password for, and how sensitive the data is. If we need to generate a somewhat secure password for a client, we typically use an easy to remember sentence, and use the first letters of each word and add a number. Something like 'top secret password for use on stackoverflow' => 'tspfuos8'. </p>\n\n<p>Most of the time however, I use the 'pwgen' utility on Linux to create a password, you can specify the complexity and length, so it's quite flexible. </p>\n"
},
{
"answer_id": 101749,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The Firefox-addon Password Hasher is pretty awesome for generating passwords: <a href=\"http://wijjo.com/project/?c=passhash\" rel=\"nofollow noreferrer\" title=\"Password Hasher\">Password Hasher</a></p>\n\n<p>The website also features an online substitute for the addon:\n<a href=\"http://wijjo.com/passhash/passhash.html\" rel=\"nofollow noreferrer\" title=\"Online Password hasher\">Online Password Hasher</a></p>\n"
},
{
"answer_id": 101785,
"author": "skiphoppy",
"author_id": 18103,
"author_profile": "https://Stackoverflow.com/users/18103",
"pm_score": 1,
"selected": false,
"text": "<p>I generate random printable ASCII characters with a Perl program and then tweak the script if there's extra rules to help me generate a more \"secure\" password. I can keep the password on a post-it note and then destroy it after one or two days; my fingers will have memorized it, and my password will be completely unguessable.</p>\n\n<p>This is for my primary login password, something I use every day, and in fact many times a day as I sit down and unlock my screen. This makes it easy to memorize fast. Obviously passwords for other situations have to use a different mechanism.</p>\n"
},
{
"answer_id": 101793,
"author": "nullDev",
"author_id": 6621,
"author_profile": "https://Stackoverflow.com/users/6621",
"pm_score": 2,
"selected": false,
"text": "<p>Well, my technique is to use first letters of the words of my favorite songs. Need an example:\nEvery night in my dreams, I see you, I feel you...</p>\n\n<p>Give me:</p>\n\n<blockquote>\n <p>enimdisyify</p>\n</blockquote>\n\n<p>... and a little of insering numbers e.g. i=1, o=0 etc...</p>\n\n<blockquote>\n <p>en1md1sy1fy</p>\n</blockquote>\n\n<p>... capitalization? Always give importance to yourself :)</p>\n\n<p>And the final password is...</p>\n\n<blockquote>\n <p>en1Md1sy1fy</p>\n</blockquote>\n"
},
{
"answer_id": 101856,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 0,
"selected": false,
"text": "<p>I use the <a href=\"http://search.cpan.org/perldoc?Crypt::GeneratePassword\" rel=\"nofollow noreferrer\">Crypt::GeneratePassword</a> module.</p>\n"
},
{
"answer_id": 101972,
"author": "Piku",
"author_id": 18854,
"author_profile": "https://Stackoverflow.com/users/18854",
"pm_score": 0,
"selected": false,
"text": "<p>For websites it's a 'secret' word combined with something memorable for the site I'm registering with.</p>\n\n<p>For everything else I use a random generated password.</p>\n"
},
{
"answer_id": 102050,
"author": "Agoston Horvath",
"author_id": 18872,
"author_profile": "https://Stackoverflow.com/users/18872",
"pm_score": 2,
"selected": false,
"text": "<p>The standard UNIX utility called pwgen.\nAvailable in practically any unix distribution.</p>\n"
},
{
"answer_id": 102188,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/users/4/joel-spolsky\">Joel Spolsky</a> wrote a short article: <a href=\"http://joelonsoftware.com/items/2008/09/11b.html\" rel=\"nofollow noreferrer\">Password management finally possible</a></p>\n\n<blockquote>\n <p>…there's finally a good way to\n manage all your passwords. This system\n works no matter how many computers you\n use regularly; it works with Mac,\n Windows, and Linux; it's secure; it\n doesn't expose your passwords to any\n internet site (whether or not you\n trust it); it generates highly secure,\n random passwords for each and every\n site, it's fairly easy to use once you\n have it all set up, it maintains an\n automatic backup of your password file\n online, and it's free.</p>\n</blockquote>\n\n<p>He recommends using <a href=\"http://www.getdropbox.com/\" rel=\"nofollow noreferrer\">DropBox</a> and <a href=\"http://passwordsafe.sourceforge.net/\" rel=\"nofollow noreferrer\">PasswordSafe</a> or <a href=\"http://www.fpx.de/fp/Software/Gorilla/\" rel=\"nofollow noreferrer\">Password Gorilla</a>.</p>\n"
},
{
"answer_id": 102227,
"author": "aaronsw",
"author_id": 4300,
"author_profile": "https://Stackoverflow.com/users/4300",
"pm_score": 8,
"selected": true,
"text": "<p>Mac OS X's \"Keychain Access\" application gives you access to the nice OS X password generator. Hit command-N and click the key icon. You get to choose password style (memorable, numeric, alphanumeric, random, FIPS-181) and choose the length. It also warns you about weak passwords.</p>\n"
},
{
"answer_id": 102235,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 0,
"selected": false,
"text": "<p>I manually generate pretty hard-to-remember strings of symbols, numbers, and upper and lower case letters that usually look like <a href=\"http://en.wikipedia.org/wiki/Leet\" rel=\"nofollow noreferrer\">leetspeak</a>.</p>\n\n<p>Example: </p>\n\n<pre><code>&p0pul4rw3b$ite!\n</code></pre>\n\n<p>Then I store them as an email draft I can access from anywhere via web mail.</p>\n"
},
{
"answer_id": 102332,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/users/1/jeff-atwood\">Jeff Atwood</a> has suggested we all switch to pass phrases rather than passwords:</p>\n\n<ul>\n<li><a href=\"http://www.codinghorror.com/blog/archives/000342.html\" rel=\"nofollow noreferrer\">Passwords vs. Pass Phrases</a></li>\n<li><a href=\"http://www.codinghorror.com/blog/archives/000360.html\" rel=\"nofollow noreferrer\">Passphrase Evangelism</a></li>\n</ul>\n"
},
{
"answer_id": 102553,
"author": "Linulin",
"author_id": 12481,
"author_profile": "https://Stackoverflow.com/users/12481",
"pm_score": 0,
"selected": false,
"text": "<p><strong>makepasswd</strong> generates true random passwords by using the /dev/random feature of Linux, with the emphasis on security over pronounceability. It can also encrypt plaintext passwords given on the command line.</p>\n\n<p>Most notable options are</p>\n\n<pre>\n--crypt-md5 Produce encrypted passwords using the MD5 digest algorithm\n--string STRING Use the characters in STRING to generate random passwords\n</pre>\n\n<p>The former could be used to automatically generate /etc/passwd, /etc/cvspasswd, etc. entries. The latter is useful to add punctuation characters into your passwords, (by default generated password contains alphanumeric chars only).</p>\n\n<p>makepasswd was originally part of the mkircconf program used to centrally administer the Linux Internet Support Cooperative IRC network.</p>\n"
},
{
"answer_id": 102653,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>passwords:</p>\n\n<pre><code>$ gpg --gen-random 1 20 | gpg --enarmor | sed -n 5p\n</code></pre>\n\n<p>passphrases:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Diceware\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Diceware</a></p>\n"
},
{
"answer_id": 102671,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to generate passwords that are easier for users to remember, take a look at Markov chains. <a href=\"http://en.wikipedia.org/wiki/Markov_chain\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Markov_chain</a> </p>\n\n<p>This algorithm can produce nonsense words that can be pronounced, so they also become easier to remember and to relay over the phone. A little Google-fu can get you some code samples in just about any language.</p>\n\n<p>You would need to also obtain a good dictionary to filter out any passwords that come out as actual words.</p>\n\n<p>Of course, these are not going to be high-strength passwords, but are really good when you need some basic access control on something and you don't want to burden your users with hard to remember passwords.</p>\n"
},
{
"answer_id": 102695,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p>I usually use password safe to generate random passwords. For passwords I actually want to be able to remember without password safe, I usually take a word, and a number, and interleave the characters</p>\n\n<p>So you take a word.</p>\n\n<p>baseball</p>\n\n<p>and a number</p>\n\n<p>24681357</p>\n\n<p>and you get a password of </p>\n\n<p>b2a4s6e8b1a3l5l7</p>\n\n<p>It looks pretty random, and would probalby be hard to brute force. Also it's quite easy to type most of the time. You just type the word, and then move your cursor back to the second character, and type the number, and between each character press the right cursor key. Not only does this make it easier to type, it also makes it harder for key loggers to record what you are actually typing.</p>\n"
},
{
"answer_id": 289886,
"author": "Vatine",
"author_id": 34771,
"author_profile": "https://Stackoverflow.com/users/34771",
"pm_score": 2,
"selected": false,
"text": "<p>Mostly, I type <code>dd if=/dev/urandom bs=6 count=1 | mimencode</code> and save the result in a password safe.</p>\n"
},
{
"answer_id": 432077,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "<p>This Perl one-liner helps sometimes (<code>rand</code> isn't secure but it often doesn't matter):</p>\n\n<pre><code>$ perl -E\"say map { chr(33 + rand(126-33)) } 1..31\n</code></pre>\n\n<p>An example output:</p>\n\n<pre><code>ET<2:k|D:!z)nBPMv+yitM8x`r.(WwO\n</code></pre>\n"
},
{
"answer_id": 432097,
"author": "Evan Fosmark",
"author_id": 49701,
"author_profile": "https://Stackoverflow.com/users/49701",
"pm_score": 2,
"selected": false,
"text": "<pre><code>import random\n\nlength = 12\ncharset = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n\npassword = \"\"\nfor i in range(0, length):\n token += random.choice(charset)\n\nprint password\n</code></pre>\n"
},
{
"answer_id": 3992009,
"author": "Pontus",
"author_id": 333448,
"author_profile": "https://Stackoverflow.com/users/333448",
"pm_score": 0,
"selected": false,
"text": "<p>For fairly important stuff I like to use combinations of letters and numbers, like \"xme7UpOK\". These can be generated with this one-liner:</p>\n\n<pre><code>perl -le 'print map { (a..z,A..Z,0..9)[rand 62] } 1..8'\n</code></pre>\n\n<p>For less important stuff I like to have passwords that are easy to type, pronounce and remember, something like \"loskubov\" or \"gobdafol\". These can be generated like this:</p>\n\n<pre><code>perl -le '@l=(\"aeiou\", \"bdfgjklmnprstv\");\n print map {(split \"\",$l[$_])[rand length $l[$_]]} split \"\", \"10110101\"'\n</code></pre>\n\n<p>where \"10110101\" is the pattern for vowels and consonants.</p>\n"
},
{
"answer_id": 4396389,
"author": "Kyle",
"author_id": 490487,
"author_profile": "https://Stackoverflow.com/users/490487",
"pm_score": 2,
"selected": false,
"text": "<p>Having read and tried out some of the great answers here, I was still in search of a generation technique that would be easy to tweak and used very common Linux utils and resources.</p>\n\n<p>I really liked the <code>gpg --gen-random</code> answer but it felt a bit clunky?</p>\n\n<p>I found this gem after some further searching</p>\n\n<pre><code>echo $(</dev/urandom tr -dc A-Za-z0-9 | head -c8)\n</code></pre>\n"
},
{
"answer_id": 8298104,
"author": "dan_waterworth",
"author_id": 393783,
"author_profile": "https://Stackoverflow.com/users/393783",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$ echo `cat /etc/dictionaries-common/words | sort --random-sort | head -n 4`\nconsented upsurges whitewall balderdash\n</code></pre>\n\n<p>Quite inefficient, but it works.</p>\n"
},
{
"answer_id": 13134698,
"author": "Arul S",
"author_id": 1784895,
"author_profile": "https://Stackoverflow.com/users/1784895",
"pm_score": 5,
"selected": false,
"text": "<p>Use this & thumps up :)</p>\n\n<pre><code>cat /dev/urandom | tr -dc 'a-zA-Z0-9-!@#$%^&*()_+~' | fold -w 10 | head -n 1\n</code></pre>\n\n<p>Change the head count to generate number of passwords.</p>\n"
},
{
"answer_id": 13473730,
"author": "DNA",
"author_id": 699224,
"author_profile": "https://Stackoverflow.com/users/699224",
"pm_score": 3,
"selected": false,
"text": "<p>An slight variation on your suggestion:</p>\n\n<pre><code>head -c 32 /dev/random | base64\n</code></pre>\n\n<p>Optionally, you can trim the trailing <code>=</code> and use <code>echo</code> to get a newline:</p>\n\n<pre><code>echo $(head -c 32 /dev/random | base64 | head -c 32)\n</code></pre>\n\n<p>which gives you a more predictable output length password whilst still ensuring only printable characters.</p>\n"
},
{
"answer_id": 14484217,
"author": "Keith Thompson",
"author_id": 827263,
"author_profile": "https://Stackoverflow.com/users/827263",
"pm_score": 0,
"selected": false,
"text": "<p>I use a couple of Perl scripts I wrote myself, <a href=\"https://github.com/Keith-S-Thompson/random-passwords\" rel=\"nofollow\">available on Github</a>.</p>\n\n<p><code>gen-password</code> generates passwords like <code>7bp4ssi02d4i</code>, with options to specify the length and character set. (And as far as my bank knows, that's my mother's maiden name.)</p>\n\n<p><code>gen-passphrase</code> generates random passphrases like <code>porcine volume smiled insert</code>, using dictionary words, inspired by <a href=\"http://xkcd.com/936/\" rel=\"nofollow\">this XKCD cartoon</a>.</p>\n\n<p>Both get random data from <code>/dev/urandom</code> by default, but can be told to use <code>/dev/random</code> instead.</p>\n\n<p>I keep my passwords in an encrypted database, and I never use the same password on more than one site. I actually remember very few of them.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18769/"
]
| How do you generate passwords?
* Random Characters?
* Passphrases?
* High Ascii?
Something like this?
```
cat /dev/urandom | strings
``` | Mac OS X's "Keychain Access" application gives you access to the nice OS X password generator. Hit command-N and click the key icon. You get to choose password style (memorable, numeric, alphanumeric, random, FIPS-181) and choose the length. It also warns you about weak passwords. |
101,363 | <p>I'm using Castle Windsor for dependency injection in my test project. I'm trying to create an instance one of my 'Repository' classes. "It works fine on my machine", but when I run a nightly build in TFS, my tests are not able to load said classes.</p>
<pre><code>private static readonly WindsorContainer _container = new WindsorContainer(new XmlInterpreter());
public void MyTestInitialize()
{
var testRepository = (IBogusRepository)_container[typeof(IBogusRepository)];
}
</code></pre>
<p>xml configuration:</p>
<pre><code><castle>
<components>
<component id="primaryBogusRepository" type="Example2008.Repository.LALALALALA, Example2008.Repository" service="Example2008.Domain.Repository.IBogusRepository, Example2008.Domain" />
<component id="primaryProductRepository" type="Example2008.Repository.ProductRepository, Example2008.Repository" service="Example2008.Domain.Repository.IProductRepository, Example2008.Domain" />
</components>
</castle>
</code></pre>
<p>When I queue a new build it produces
the following message:</p>
<blockquote>
<p>Unable to create instance of class
Example2008.Test.ActiveProductRepositoryTest. Error:
System.Configuration.ConfigurationException:
The type name
Example2008.Repository.LALALALALA,
Example2008.Repository could not be
located.</p>
<p>Castle.Windsor.Installer.DefaultComponentInstaller.ObtainType(String
typeName)
Castle.Windsor.Installer.DefaultComponentInstaller.SetUpComponents(IConfiguration[]
configurations, IWindsorContainer
container)
Castle.Windsor.Installer.DefaultComponentInstaller.SetUp(IWindsorContainer
container, IConfigurationStore store)
Castle.Windsor.WindsorContainer.RunInstaller()
Castle.Windsor.WindsorContainer..ctor(IConfigurationInterpreter
interpreter)
Example2008.Test.ActiveProductRepositoryTest..cctor()
in d:\Code_Temp\Example Project
Nightly\Sources\Example2008.Test\ProductRepositoryTest.cs:
line 19</p>
</blockquote>
<p>From this message, it seems that my configuration is correct (it can see that I want to instantiate the concrete class 'LALALALALA', so the xml configuration has obviously been red correctly)</p>
<p>I think I have my dependencies set up correctly as well (because it works locally, even if I clean the solution and rebuild).</p>
<p>Any thoughts?</p>
<p>(using VS2008, TFS 2008.Net 3.5, Castle 1.03, by the way) </p>
| [
{
"answer_id": 101368,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 4,
"selected": false,
"text": "<p>A short python script to generate passwords, originally from the python cookbook.</p>\n\n<pre><code>#!/usr/bin/env python\n\nfrom random import choice\nimport getopt\nimport string\nimport sys\n\ndef GenPasswd():\n chars = string.letters + string.digits\n for i in range(8):\n newpasswd = newpasswd + choice(chars)\n return newpasswd\n\ndef GenPasswd2(length=8, chars=string.letters + string.digits):\n return ''.join([choice(chars) for i in range(length)])\n\nclass Options(object):\n pass\n\ndef main(argv):\n (optionList,args) = getopt.getopt(argv[1:],\"r:l:\",[\"repeat=\",\"length=\"])\n\n options = Options()\n options.repeat = 1\n options.length = 8\n for (key,value) in optionList:\n if key == \"-r\" or key == \"--repeat\":\n options.repeat = int(value)\n elif key == \"-l\" or key == \"--length\":\n options.length = int(value)\n\n for i in xrange(options.repeat):\n print GenPasswd2(options.length)\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))\n</code></pre>\n"
},
{
"answer_id": 101369,
"author": "Matthias Kestenholz",
"author_id": 317346,
"author_profile": "https://Stackoverflow.com/users/317346",
"pm_score": 2,
"selected": false,
"text": "<p>The algorithm in <a href=\"http://www.adel.nursat.kz/apg/\" rel=\"nofollow noreferrer\">apg</a> is pretty cool. But I mostly use random characters from a list which I've defined myself. It is mostly numbers, upper- and lowercase letters and some punctuation marks. I've eliminated chars which are prone to getting mistaken for another character like '1', 'l', 'I', 'O', '0' etc.</p>\n"
},
{
"answer_id": 101371,
"author": "Luke Bennett",
"author_id": 17602,
"author_profile": "https://Stackoverflow.com/users/17602",
"pm_score": 2,
"selected": false,
"text": "<p>I use <a href=\"http://keepass.info/\" rel=\"nofollow noreferrer\">KeePass</a> to generate complex passwords.</p>\n"
},
{
"answer_id": 101377,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php\n print md5(rand(0, 99999));\n?>\n</code></pre>\n"
},
{
"answer_id": 101384,
"author": "px.",
"author_id": 18769,
"author_profile": "https://Stackoverflow.com/users/18769",
"pm_score": 1,
"selected": false,
"text": "<p>On a Mac I use <a href=\"http://www.net-security.org/software.php?id=612\" rel=\"nofollow noreferrer\">RPG</a>. </p>\n"
},
{
"answer_id": 101385,
"author": "Daniel",
"author_id": 416,
"author_profile": "https://Stackoverflow.com/users/416",
"pm_score": 1,
"selected": false,
"text": "<p>In PHP, by generating a random string of characters from the ASCII table. See <a href=\"https://stackoverflow.com/questions/48124/generating-pseudorandom-alpha-numeric-strings#48285\">Generating (pseudo)random alpha-numeric strings</a></p>\n"
},
{
"answer_id": 101392,
"author": "Turnkey",
"author_id": 13144,
"author_profile": "https://Stackoverflow.com/users/13144",
"pm_score": 3,
"selected": false,
"text": "<p>The open source <a href=\"http://keepass.info/\" rel=\"noreferrer\">Keepass</a> tool has some excellent capabilities for password generation, including enhanced randomization.</p>\n"
},
{
"answer_id": 101398,
"author": "Isaac Moses",
"author_id": 179,
"author_profile": "https://Stackoverflow.com/users/179",
"pm_score": 1,
"selected": false,
"text": "<p>I start with the initials of a sentence in a foreign language, with some convention for capitalizing some of them. Then, I insert in a particular part of the sentence a combination of numbers and symbols derived from the name of the application or website.</p>\n\n<p>This scheme generates a unique password for each application that I can re-derive each time in my head with no trouble (so no memorization), and there is zero chance of any part of it showing up in a dictionary.</p>\n"
},
{
"answer_id": 101399,
"author": "Erratic",
"author_id": 2246765,
"author_profile": "https://Stackoverflow.com/users/2246765",
"pm_score": 2,
"selected": false,
"text": "<p>I don't like random character passwords. They are difficult to remember.</p>\n\n<p>Generally my passwords fall into tiers based on how important that information is to me.</p>\n\n<p>My most secure passwords tend to use a combination of old BBS random generated passwords that I was too young and dumb to know how to change and memorized. Appending a few of those together with liberal use of the shift key works well. If I don't use those I find pass phrases better. Perhaps a phrase from some book that I enjoy, once again with some mixed case and special symbols put it. Often I'll use more than 1 phrase, or several words from one phrase, concatenated with several from another.</p>\n\n<p>On low priority sites my passwords are are pretty short, generally a combination of a few familiar tokens.</p>\n\n<p>The place I have the biggest problem is work, where we need to change our password every 30 days and can't repeat passwords. I just do like everyone else, come up with a password and append an ever increasing index to the end. Password rules like that are absurd.</p>\n"
},
{
"answer_id": 101417,
"author": "martinatime",
"author_id": 1353,
"author_profile": "https://Stackoverflow.com/users/1353",
"pm_score": 2,
"selected": false,
"text": "<p>I use <a href=\"https://www.grc.com/passwords.htm\" rel=\"nofollow noreferrer\">https://www.grc.com/passwords.htm</a> to generate long password strings for things like WPA keys. You could also use this (via screenscraping) to create salts for authentication password hashing if you have to implement some sort of registration site.</p>\n"
},
{
"answer_id": 101418,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 1,
"selected": false,
"text": "<p>You will have to code extra rules to check that your password is acceptable for the system you are writing it for. Some systems have policies like \"two digits and two uppercase letters minimum\" and so on. As you generate your password character by character, keep a count of the digits/alpha/uppercase as required, and wrap the password generation in a do..while that will repeat the password generation until (digitCount>1 && alphaCount>4 && upperCount>1), or whatever.</p>\n"
},
{
"answer_id": 101429,
"author": "Abhishek Mishra",
"author_id": 8786,
"author_profile": "https://Stackoverflow.com/users/8786",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.wohmart.com/ircd/pub/irc_tools/mkpasswd/mkpasswd+vms.c\" rel=\"nofollow noreferrer\">http://www.wohmart.com/ircd/pub/irc_tools/mkpasswd/mkpasswd+vms.c</a></p>\n\n<p><a href=\"http://www.obviex.com/Samples/Password.aspx\" rel=\"nofollow noreferrer\">http://www.obviex.com/Samples/Password.aspx</a></p>\n\n<p><a href=\"https://www.uwo.ca/its/network/security/passwd-suite/sample.c\" rel=\"nofollow noreferrer\">https://www.uwo.ca/its/network/security/passwd-suite/sample.c</a></p>\n\n<p>Even in Excel!\n<a href=\"https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1032050.html\" rel=\"nofollow noreferrer\">https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1032050.html</a></p>\n\n<p><a href=\"http://webnet77.com/cgi-bin/helpers/crypthelp.pl\" rel=\"nofollow noreferrer\">http://webnet77.com/cgi-bin/helpers/crypthelp.pl</a></p>\n"
},
{
"answer_id": 101432,
"author": "Thilo",
"author_id": 14955,
"author_profile": "https://Stackoverflow.com/users/14955",
"pm_score": 2,
"selected": false,
"text": "<p>For web sites I use <a href=\"http://supergenpass.com/\" rel=\"nofollow noreferrer\">SuperGenPass</a>, which derives a site-specific password from a master password and the domain name, using a hash function (based on MD5). No need to store that password anywhere (SuperGenPass itself is a bookmarklet, totally client-side), just remember your master password.</p>\n"
},
{
"answer_id": 101489,
"author": "mloughran",
"author_id": 18751,
"author_profile": "https://Stackoverflow.com/users/18751",
"pm_score": -1,
"selected": false,
"text": "<p>Pick a sequence out of</p>\n\n<pre><code>md5 random_file\n</code></pre>\n"
},
{
"answer_id": 101514,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 2,
"selected": false,
"text": "<p>In some circumstances, I use Perl's Crypt::PassGen module, which uses Markov chain analysis on a corpus of words (e.g. /usr/share/dict/words on any reasonably Unix system). This allows it to generate passwords that turn out to be reasonably pronounceable and thus remember.</p>\n\n<p>That said, at $work we are moving to hardware challenge/response token mechanisms.</p>\n"
},
{
"answer_id": 101529,
"author": "titanae",
"author_id": 2387,
"author_profile": "https://Stackoverflow.com/users/2387",
"pm_score": 1,
"selected": false,
"text": "<p>Password Monkey, iGoogle widget!</p>\n"
},
{
"answer_id": 101547,
"author": "Buzz",
"author_id": 13113,
"author_profile": "https://Stackoverflow.com/users/13113",
"pm_score": 2,
"selected": false,
"text": "<p>I used an unusual method of generating passwords recently. They didn't need to be super strong, and random passwords are just too hard to remember. My application had a huge table of cities in North America. To generate a password, I generated a random number, grabbed a randon city, and added another random number. </p>\n\n<p>boston9934</p>\n\n<p>The lengths of the numbers were random, (as was if they were appended, prepended, or both), so it wasn't too easy to brute force. </p>\n"
},
{
"answer_id": 101575,
"author": "Ron Tuffin",
"author_id": 939,
"author_profile": "https://Stackoverflow.com/users/939",
"pm_score": 3,
"selected": false,
"text": "<p>I use <a href=\"http://passwordsafe.sourceforge.net/\" rel=\"noreferrer\">password safe</a> to generate and store all my passwords, that way you don't have to remember super strong passwords (well except the one that unlocks your safe).</p>\n"
},
{
"answer_id": 101701,
"author": "Elias Yarrkov",
"author_id": 18814,
"author_profile": "https://Stackoverflow.com/users/18814",
"pm_score": 2,
"selected": false,
"text": "<p>Pick a strong master password how you like, then generate a password for each site with cryptohash(masterpasword+sitename). You will not lose your password for site A if your password for site B gets in the wrong hands (due to an evil admin, wlan sniffing or site compromise for example), yet you will only have to remember a single password.</p>\n"
},
{
"answer_id": 101715,
"author": "Linor",
"author_id": 3197,
"author_profile": "https://Stackoverflow.com/users/3197",
"pm_score": 2,
"selected": false,
"text": "<p>I think it largely depends on what you want to use the password for, and how sensitive the data is. If we need to generate a somewhat secure password for a client, we typically use an easy to remember sentence, and use the first letters of each word and add a number. Something like 'top secret password for use on stackoverflow' => 'tspfuos8'. </p>\n\n<p>Most of the time however, I use the 'pwgen' utility on Linux to create a password, you can specify the complexity and length, so it's quite flexible. </p>\n"
},
{
"answer_id": 101749,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The Firefox-addon Password Hasher is pretty awesome for generating passwords: <a href=\"http://wijjo.com/project/?c=passhash\" rel=\"nofollow noreferrer\" title=\"Password Hasher\">Password Hasher</a></p>\n\n<p>The website also features an online substitute for the addon:\n<a href=\"http://wijjo.com/passhash/passhash.html\" rel=\"nofollow noreferrer\" title=\"Online Password hasher\">Online Password Hasher</a></p>\n"
},
{
"answer_id": 101785,
"author": "skiphoppy",
"author_id": 18103,
"author_profile": "https://Stackoverflow.com/users/18103",
"pm_score": 1,
"selected": false,
"text": "<p>I generate random printable ASCII characters with a Perl program and then tweak the script if there's extra rules to help me generate a more \"secure\" password. I can keep the password on a post-it note and then destroy it after one or two days; my fingers will have memorized it, and my password will be completely unguessable.</p>\n\n<p>This is for my primary login password, something I use every day, and in fact many times a day as I sit down and unlock my screen. This makes it easy to memorize fast. Obviously passwords for other situations have to use a different mechanism.</p>\n"
},
{
"answer_id": 101793,
"author": "nullDev",
"author_id": 6621,
"author_profile": "https://Stackoverflow.com/users/6621",
"pm_score": 2,
"selected": false,
"text": "<p>Well, my technique is to use first letters of the words of my favorite songs. Need an example:\nEvery night in my dreams, I see you, I feel you...</p>\n\n<p>Give me:</p>\n\n<blockquote>\n <p>enimdisyify</p>\n</blockquote>\n\n<p>... and a little of insering numbers e.g. i=1, o=0 etc...</p>\n\n<blockquote>\n <p>en1md1sy1fy</p>\n</blockquote>\n\n<p>... capitalization? Always give importance to yourself :)</p>\n\n<p>And the final password is...</p>\n\n<blockquote>\n <p>en1Md1sy1fy</p>\n</blockquote>\n"
},
{
"answer_id": 101856,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 0,
"selected": false,
"text": "<p>I use the <a href=\"http://search.cpan.org/perldoc?Crypt::GeneratePassword\" rel=\"nofollow noreferrer\">Crypt::GeneratePassword</a> module.</p>\n"
},
{
"answer_id": 101972,
"author": "Piku",
"author_id": 18854,
"author_profile": "https://Stackoverflow.com/users/18854",
"pm_score": 0,
"selected": false,
"text": "<p>For websites it's a 'secret' word combined with something memorable for the site I'm registering with.</p>\n\n<p>For everything else I use a random generated password.</p>\n"
},
{
"answer_id": 102050,
"author": "Agoston Horvath",
"author_id": 18872,
"author_profile": "https://Stackoverflow.com/users/18872",
"pm_score": 2,
"selected": false,
"text": "<p>The standard UNIX utility called pwgen.\nAvailable in practically any unix distribution.</p>\n"
},
{
"answer_id": 102188,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/users/4/joel-spolsky\">Joel Spolsky</a> wrote a short article: <a href=\"http://joelonsoftware.com/items/2008/09/11b.html\" rel=\"nofollow noreferrer\">Password management finally possible</a></p>\n\n<blockquote>\n <p>…there's finally a good way to\n manage all your passwords. This system\n works no matter how many computers you\n use regularly; it works with Mac,\n Windows, and Linux; it's secure; it\n doesn't expose your passwords to any\n internet site (whether or not you\n trust it); it generates highly secure,\n random passwords for each and every\n site, it's fairly easy to use once you\n have it all set up, it maintains an\n automatic backup of your password file\n online, and it's free.</p>\n</blockquote>\n\n<p>He recommends using <a href=\"http://www.getdropbox.com/\" rel=\"nofollow noreferrer\">DropBox</a> and <a href=\"http://passwordsafe.sourceforge.net/\" rel=\"nofollow noreferrer\">PasswordSafe</a> or <a href=\"http://www.fpx.de/fp/Software/Gorilla/\" rel=\"nofollow noreferrer\">Password Gorilla</a>.</p>\n"
},
{
"answer_id": 102227,
"author": "aaronsw",
"author_id": 4300,
"author_profile": "https://Stackoverflow.com/users/4300",
"pm_score": 8,
"selected": true,
"text": "<p>Mac OS X's \"Keychain Access\" application gives you access to the nice OS X password generator. Hit command-N and click the key icon. You get to choose password style (memorable, numeric, alphanumeric, random, FIPS-181) and choose the length. It also warns you about weak passwords.</p>\n"
},
{
"answer_id": 102235,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 0,
"selected": false,
"text": "<p>I manually generate pretty hard-to-remember strings of symbols, numbers, and upper and lower case letters that usually look like <a href=\"http://en.wikipedia.org/wiki/Leet\" rel=\"nofollow noreferrer\">leetspeak</a>.</p>\n\n<p>Example: </p>\n\n<pre><code>&p0pul4rw3b$ite!\n</code></pre>\n\n<p>Then I store them as an email draft I can access from anywhere via web mail.</p>\n"
},
{
"answer_id": 102332,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/users/1/jeff-atwood\">Jeff Atwood</a> has suggested we all switch to pass phrases rather than passwords:</p>\n\n<ul>\n<li><a href=\"http://www.codinghorror.com/blog/archives/000342.html\" rel=\"nofollow noreferrer\">Passwords vs. Pass Phrases</a></li>\n<li><a href=\"http://www.codinghorror.com/blog/archives/000360.html\" rel=\"nofollow noreferrer\">Passphrase Evangelism</a></li>\n</ul>\n"
},
{
"answer_id": 102553,
"author": "Linulin",
"author_id": 12481,
"author_profile": "https://Stackoverflow.com/users/12481",
"pm_score": 0,
"selected": false,
"text": "<p><strong>makepasswd</strong> generates true random passwords by using the /dev/random feature of Linux, with the emphasis on security over pronounceability. It can also encrypt plaintext passwords given on the command line.</p>\n\n<p>Most notable options are</p>\n\n<pre>\n--crypt-md5 Produce encrypted passwords using the MD5 digest algorithm\n--string STRING Use the characters in STRING to generate random passwords\n</pre>\n\n<p>The former could be used to automatically generate /etc/passwd, /etc/cvspasswd, etc. entries. The latter is useful to add punctuation characters into your passwords, (by default generated password contains alphanumeric chars only).</p>\n\n<p>makepasswd was originally part of the mkircconf program used to centrally administer the Linux Internet Support Cooperative IRC network.</p>\n"
},
{
"answer_id": 102653,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>passwords:</p>\n\n<pre><code>$ gpg --gen-random 1 20 | gpg --enarmor | sed -n 5p\n</code></pre>\n\n<p>passphrases:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Diceware\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Diceware</a></p>\n"
},
{
"answer_id": 102671,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to generate passwords that are easier for users to remember, take a look at Markov chains. <a href=\"http://en.wikipedia.org/wiki/Markov_chain\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Markov_chain</a> </p>\n\n<p>This algorithm can produce nonsense words that can be pronounced, so they also become easier to remember and to relay over the phone. A little Google-fu can get you some code samples in just about any language.</p>\n\n<p>You would need to also obtain a good dictionary to filter out any passwords that come out as actual words.</p>\n\n<p>Of course, these are not going to be high-strength passwords, but are really good when you need some basic access control on something and you don't want to burden your users with hard to remember passwords.</p>\n"
},
{
"answer_id": 102695,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p>I usually use password safe to generate random passwords. For passwords I actually want to be able to remember without password safe, I usually take a word, and a number, and interleave the characters</p>\n\n<p>So you take a word.</p>\n\n<p>baseball</p>\n\n<p>and a number</p>\n\n<p>24681357</p>\n\n<p>and you get a password of </p>\n\n<p>b2a4s6e8b1a3l5l7</p>\n\n<p>It looks pretty random, and would probalby be hard to brute force. Also it's quite easy to type most of the time. You just type the word, and then move your cursor back to the second character, and type the number, and between each character press the right cursor key. Not only does this make it easier to type, it also makes it harder for key loggers to record what you are actually typing.</p>\n"
},
{
"answer_id": 289886,
"author": "Vatine",
"author_id": 34771,
"author_profile": "https://Stackoverflow.com/users/34771",
"pm_score": 2,
"selected": false,
"text": "<p>Mostly, I type <code>dd if=/dev/urandom bs=6 count=1 | mimencode</code> and save the result in a password safe.</p>\n"
},
{
"answer_id": 432077,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "<p>This Perl one-liner helps sometimes (<code>rand</code> isn't secure but it often doesn't matter):</p>\n\n<pre><code>$ perl -E\"say map { chr(33 + rand(126-33)) } 1..31\n</code></pre>\n\n<p>An example output:</p>\n\n<pre><code>ET<2:k|D:!z)nBPMv+yitM8x`r.(WwO\n</code></pre>\n"
},
{
"answer_id": 432097,
"author": "Evan Fosmark",
"author_id": 49701,
"author_profile": "https://Stackoverflow.com/users/49701",
"pm_score": 2,
"selected": false,
"text": "<pre><code>import random\n\nlength = 12\ncharset = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n\npassword = \"\"\nfor i in range(0, length):\n token += random.choice(charset)\n\nprint password\n</code></pre>\n"
},
{
"answer_id": 3992009,
"author": "Pontus",
"author_id": 333448,
"author_profile": "https://Stackoverflow.com/users/333448",
"pm_score": 0,
"selected": false,
"text": "<p>For fairly important stuff I like to use combinations of letters and numbers, like \"xme7UpOK\". These can be generated with this one-liner:</p>\n\n<pre><code>perl -le 'print map { (a..z,A..Z,0..9)[rand 62] } 1..8'\n</code></pre>\n\n<p>For less important stuff I like to have passwords that are easy to type, pronounce and remember, something like \"loskubov\" or \"gobdafol\". These can be generated like this:</p>\n\n<pre><code>perl -le '@l=(\"aeiou\", \"bdfgjklmnprstv\");\n print map {(split \"\",$l[$_])[rand length $l[$_]]} split \"\", \"10110101\"'\n</code></pre>\n\n<p>where \"10110101\" is the pattern for vowels and consonants.</p>\n"
},
{
"answer_id": 4396389,
"author": "Kyle",
"author_id": 490487,
"author_profile": "https://Stackoverflow.com/users/490487",
"pm_score": 2,
"selected": false,
"text": "<p>Having read and tried out some of the great answers here, I was still in search of a generation technique that would be easy to tweak and used very common Linux utils and resources.</p>\n\n<p>I really liked the <code>gpg --gen-random</code> answer but it felt a bit clunky?</p>\n\n<p>I found this gem after some further searching</p>\n\n<pre><code>echo $(</dev/urandom tr -dc A-Za-z0-9 | head -c8)\n</code></pre>\n"
},
{
"answer_id": 8298104,
"author": "dan_waterworth",
"author_id": 393783,
"author_profile": "https://Stackoverflow.com/users/393783",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$ echo `cat /etc/dictionaries-common/words | sort --random-sort | head -n 4`\nconsented upsurges whitewall balderdash\n</code></pre>\n\n<p>Quite inefficient, but it works.</p>\n"
},
{
"answer_id": 13134698,
"author": "Arul S",
"author_id": 1784895,
"author_profile": "https://Stackoverflow.com/users/1784895",
"pm_score": 5,
"selected": false,
"text": "<p>Use this & thumps up :)</p>\n\n<pre><code>cat /dev/urandom | tr -dc 'a-zA-Z0-9-!@#$%^&*()_+~' | fold -w 10 | head -n 1\n</code></pre>\n\n<p>Change the head count to generate number of passwords.</p>\n"
},
{
"answer_id": 13473730,
"author": "DNA",
"author_id": 699224,
"author_profile": "https://Stackoverflow.com/users/699224",
"pm_score": 3,
"selected": false,
"text": "<p>An slight variation on your suggestion:</p>\n\n<pre><code>head -c 32 /dev/random | base64\n</code></pre>\n\n<p>Optionally, you can trim the trailing <code>=</code> and use <code>echo</code> to get a newline:</p>\n\n<pre><code>echo $(head -c 32 /dev/random | base64 | head -c 32)\n</code></pre>\n\n<p>which gives you a more predictable output length password whilst still ensuring only printable characters.</p>\n"
},
{
"answer_id": 14484217,
"author": "Keith Thompson",
"author_id": 827263,
"author_profile": "https://Stackoverflow.com/users/827263",
"pm_score": 0,
"selected": false,
"text": "<p>I use a couple of Perl scripts I wrote myself, <a href=\"https://github.com/Keith-S-Thompson/random-passwords\" rel=\"nofollow\">available on Github</a>.</p>\n\n<p><code>gen-password</code> generates passwords like <code>7bp4ssi02d4i</code>, with options to specify the length and character set. (And as far as my bank knows, that's my mother's maiden name.)</p>\n\n<p><code>gen-passphrase</code> generates random passphrases like <code>porcine volume smiled insert</code>, using dictionary words, inspired by <a href=\"http://xkcd.com/936/\" rel=\"nofollow\">this XKCD cartoon</a>.</p>\n\n<p>Both get random data from <code>/dev/urandom</code> by default, but can be told to use <code>/dev/random</code> instead.</p>\n\n<p>I keep my passwords in an encrypted database, and I never use the same password on more than one site. I actually remember very few of them.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12756/"
]
| I'm using Castle Windsor for dependency injection in my test project. I'm trying to create an instance one of my 'Repository' classes. "It works fine on my machine", but when I run a nightly build in TFS, my tests are not able to load said classes.
```
private static readonly WindsorContainer _container = new WindsorContainer(new XmlInterpreter());
public void MyTestInitialize()
{
var testRepository = (IBogusRepository)_container[typeof(IBogusRepository)];
}
```
xml configuration:
```
<castle>
<components>
<component id="primaryBogusRepository" type="Example2008.Repository.LALALALALA, Example2008.Repository" service="Example2008.Domain.Repository.IBogusRepository, Example2008.Domain" />
<component id="primaryProductRepository" type="Example2008.Repository.ProductRepository, Example2008.Repository" service="Example2008.Domain.Repository.IProductRepository, Example2008.Domain" />
</components>
</castle>
```
When I queue a new build it produces
the following message:
>
> Unable to create instance of class
> Example2008.Test.ActiveProductRepositoryTest. Error:
> System.Configuration.ConfigurationException:
> The type name
> Example2008.Repository.LALALALALA,
> Example2008.Repository could not be
> located.
>
>
> Castle.Windsor.Installer.DefaultComponentInstaller.ObtainType(String
> typeName)
> Castle.Windsor.Installer.DefaultComponentInstaller.SetUpComponents(IConfiguration[]
> configurations, IWindsorContainer
> container)
> Castle.Windsor.Installer.DefaultComponentInstaller.SetUp(IWindsorContainer
> container, IConfigurationStore store)
> Castle.Windsor.WindsorContainer.RunInstaller()
> Castle.Windsor.WindsorContainer..ctor(IConfigurationInterpreter
> interpreter)
> Example2008.Test.ActiveProductRepositoryTest..cctor()
> in d:\Code\_Temp\Example Project
> Nightly\Sources\Example2008.Test\ProductRepositoryTest.cs:
> line 19
>
>
>
From this message, it seems that my configuration is correct (it can see that I want to instantiate the concrete class 'LALALALALA', so the xml configuration has obviously been red correctly)
I think I have my dependencies set up correctly as well (because it works locally, even if I clean the solution and rebuild).
Any thoughts?
(using VS2008, TFS 2008.Net 3.5, Castle 1.03, by the way) | Mac OS X's "Keychain Access" application gives you access to the nice OS X password generator. Hit command-N and click the key icon. You get to choose password style (memorable, numeric, alphanumeric, random, FIPS-181) and choose the length. It also warns you about weak passwords. |
101,386 | <p>Does PHP have a method of having auto-generated class variables? I <em>think</em> I've seen something like this before but I'm not certain.</p>
<pre><code>public class TestClass {
private $data = array();
public function TestClass() {
$this->data['firstValue'] = "cheese";
}
}
</code></pre>
<p>The <code>$this->data</code> array is always an associative array but they keys change from class to class. Is there any viable way to access <code>$this->data['firstValue']</code> from <code>$this->firstValue</code> without having to define the link?</p>
<p>And if it is, are there any downsides to it?</p>
<p>Or is there a static method of defining the link in a way which won't explode if the <code>$this->data</code> array doesn't contain that key?</p>
| [
{
"answer_id": 101404,
"author": "Jan Hančič",
"author_id": 185527,
"author_profile": "https://Stackoverflow.com/users/185527",
"pm_score": 5,
"selected": true,
"text": "<p>See here: <a href=\"http://www.php.net/manual/en/language.oop5.overloading.php\" rel=\"noreferrer\">http://www.php.net/manual/en/language.oop5.overloading.php</a></p>\n\n<p>What you want is the \"__get\" method. There is an example for what you need on the link.</p>\n"
},
{
"answer_id": 131455,
"author": "David Stockton",
"author_id": 21897,
"author_profile": "https://Stackoverflow.com/users/21897",
"pm_score": 3,
"selected": false,
"text": "<p>Use the PHP5 \"magic\" <code>__get()</code> method. It would work like so:</p>\n\n<pre><code>public class TestClass {\n private $data = array();\n\n // Since you're using PHP5, you should be using PHP5 style constructors.\n public function __construct() {\n $this->data['firstValue'] = \"cheese\";\n }\n\n /**\n * This is the magic get function. Any class variable you try to access from \n * outside the class that is not public will go through this method. The variable\n * name will be passed in to the $param parameter. For this example, all \n * will be retrieved from the private $data array. If the variable doesn't exist\n * in the array, then the method will return null.\n *\n * @param string $param Class variable name\n *\n * @return mixed\n */\n public function __get($param) {\n if (isset($this->data[$param])) {\n return $this->data[$param];\n } else {\n return null;\n }\n }\n\n /**\n * This is the \"magic\" isset method. It is very important to implement this \n * method when using __get to change or retrieve data members from private or \n * protected members. If it is not implemented, code that checks to see if a\n * particular variable has been set will fail even though you'll be able to \n * retrieve a value for that variable.\n *\n * @param string $param Variable name to check\n * \n * @return boolean\n */\n public function __isset($param) {\n return isset($this->data[$param]);\n }\n\n /**\n * This method is required if you want to be able to set variables from outside\n * your class without providing explicit setter options. Similar to accessing\n * a variable using $foo = $object->firstValue, this method allows you to set \n * the value of a variable (any variable in this case, but it can be limited \n * by modifying this method) by doing something like:\n * $this->secondValue = 'foo';\n * \n * @param string $param Class variable name to set\n * @param mixed $value Value to set\n * \n * @return null\n */\n public function __set($param, $value) {\n $this->data[$param] = $value;\n }\n}\n</code></pre>\n\n<p>Using the magic <code>__get</code>, <code>__set</code>, and <code>__isset</code> constructors will allow you to control how you want variables to be set on a class while still storing all the values in a single array.</p>\n\n<p>Hope this helps :)</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870/"
]
| Does PHP have a method of having auto-generated class variables? I *think* I've seen something like this before but I'm not certain.
```
public class TestClass {
private $data = array();
public function TestClass() {
$this->data['firstValue'] = "cheese";
}
}
```
The `$this->data` array is always an associative array but they keys change from class to class. Is there any viable way to access `$this->data['firstValue']` from `$this->firstValue` without having to define the link?
And if it is, are there any downsides to it?
Or is there a static method of defining the link in a way which won't explode if the `$this->data` array doesn't contain that key? | See here: <http://www.php.net/manual/en/language.oop5.overloading.php>
What you want is the "\_\_get" method. There is an example for what you need on the link. |
101,439 | <p>What is the most efficient way given to raise an integer to the power of another integer in C?</p>
<pre><code>// 2^3
pow(2,3) == 8
// 5^5
pow(5,5) == 3125
</code></pre>
| [
{
"answer_id": 101473,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 3,
"selected": false,
"text": "<p>An extremely specialized case is, when you need say 2^(-x to the y), where x, is of course is negative and y is too large to do shifting on an int. You can still do 2^x in constant time by screwing with a float.</p>\n\n<pre><code>struct IeeeFloat\n{\n\n unsigned int base : 23;\n unsigned int exponent : 8;\n unsigned int signBit : 1;\n};\n\n\nunion IeeeFloatUnion\n{\n IeeeFloat brokenOut;\n float f;\n};\n\ninline float twoToThe(char exponent)\n{\n // notice how the range checking is already done on the exponent var \n static IeeeFloatUnion u;\n u.f = 2.0;\n // Change the exponent part of the float\n u.brokenOut.exponent += (exponent - 1);\n return (u.f);\n}\n</code></pre>\n\n<p>You can get more powers of 2 by using a double as the base type.\n(Thanks a lot to commenters for helping to square this post away).</p>\n\n<p>There's also the possibility that learning more about <a href=\"https://www.wikiwand.com/en/IEEE_754\" rel=\"nofollow noreferrer\">IEEE floats</a>, other special cases of exponentiation might present themselves.</p>\n"
},
{
"answer_id": 101613,
"author": "Elias Yarrkov",
"author_id": 18814,
"author_profile": "https://Stackoverflow.com/users/18814",
"pm_score": 10,
"selected": true,
"text": "<p>Exponentiation by squaring.</p>\n\n<pre><code>int ipow(int base, int exp)\n{\n int result = 1;\n for (;;)\n {\n if (exp & 1)\n result *= base;\n exp >>= 1;\n if (!exp)\n break;\n base *= base;\n }\n\n return result;\n}\n</code></pre>\n\n<p>This is the standard method for doing modular exponentiation for huge numbers in asymmetric cryptography.</p>\n"
},
{
"answer_id": 102319,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 3,
"selected": false,
"text": "<pre><code>int pow( int base, int exponent)\n\n{ // Does not work for negative exponents. (But that would be leaving the range of int) \n if (exponent == 0) return 1; // base case;\n int temp = pow(base, exponent/2);\n if (exponent % 2 == 0)\n return temp * temp; \n else\n return (base * temp * temp);\n}\n</code></pre>\n"
},
{
"answer_id": 108959,
"author": "Pramod",
"author_id": 1386292,
"author_profile": "https://Stackoverflow.com/users/1386292",
"pm_score": 6,
"selected": false,
"text": "<p>Note that <a href=\"https://en.wikipedia.org/wiki/Exponentiation_by_squaring\" rel=\"noreferrer\">exponentiation by squaring</a> is not the most optimal method. It is probably the best you can do as a general method that works for all exponent values, but for a specific exponent value there might be a better sequence that needs fewer multiplications.</p>\n\n<p>For instance, if you want to compute x^15, the method of exponentiation by squaring will give you:</p>\n\n<pre><code>x^15 = (x^7)*(x^7)*x \nx^7 = (x^3)*(x^3)*x \nx^3 = x*x*x\n</code></pre>\n\n<p>This is a total of 6 multiplications.</p>\n\n<p>It turns out this can be done using \"just\" 5 multiplications via <a href=\"https://en.wikipedia.org/wiki/Addition-chain_exponentiation\" rel=\"noreferrer\">addition-chain exponentiation</a>.</p>\n\n<pre><code>n*n = n^2\nn^2*n = n^3\nn^3*n^3 = n^6\nn^6*n^6 = n^12\nn^12*n^3 = n^15\n</code></pre>\n\n<p>There are no efficient algorithms to find this optimal sequence of multiplications. From <a href=\"https://en.wikipedia.org/wiki/Addition-chain_exponentiation\" rel=\"noreferrer\">Wikipedia</a>:</p>\n\n<blockquote>\n <p>The problem of finding the shortest addition chain cannot be solved by dynamic programming, because it does not satisfy the assumption of optimal substructure. That is, it is not sufficient to decompose the power into smaller powers, each of which is computed minimally, since the addition chains for the smaller powers may be related (to share computations). For example, in the shortest addition chain for a¹⁵ above, the subproblem for a⁶ must be computed as (a³)² since a³ is re-used (as opposed to, say, a⁶ = a²(a²)², which also requires three multiplies).</p>\n</blockquote>\n"
},
{
"answer_id": 163598,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 2,
"selected": false,
"text": "<p>Just as a follow up to comments on the efficiency of exponentiation by squaring.</p>\n\n<p>The advantage of that approach is that it runs in log(n) time. For example, if you were going to calculate something huge, such as x^1048575 (2^20 - 1), you only have to go thru the loop 20 times, not 1 million+ using the naive approach.</p>\n\n<p>Also, in terms of code complexity, it is simpler than trying to find the most optimal sequence of multiplications, a la Pramod's suggestion.</p>\n\n<p>Edit:</p>\n\n<p>I guess I should clarify before someone tags me for the potential for overflow. This approach assumes that you have some sort of hugeint library.</p>\n"
},
{
"answer_id": 5345369,
"author": "Jake",
"author_id": 498804,
"author_profile": "https://Stackoverflow.com/users/498804",
"pm_score": 5,
"selected": false,
"text": "<p>If you need to raise 2 to a power. The fastest way to do so is to bit shift by the power.</p>\n\n<pre><code>2 ** 3 == 1 << 3 == 8\n2 ** 30 == 1 << 30 == 1073741824 (A Gigabyte)\n</code></pre>\n"
},
{
"answer_id": 10517609,
"author": "user1067920",
"author_id": 1067920,
"author_profile": "https://Stackoverflow.com/users/1067920",
"pm_score": 4,
"selected": false,
"text": "<p>Here is the method in Java</p>\n\n<pre><code>private int ipow(int base, int exp)\n{\n int result = 1;\n while (exp != 0)\n {\n if ((exp & 1) == 1)\n result *= base;\n exp >>= 1;\n base *= base;\n }\n\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 10578794,
"author": "aditya",
"author_id": 1223316,
"author_profile": "https://Stackoverflow.com/users/1223316",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to get the value of an integer for 2 raised to the power of something it is always better to use the shift option:</p>\n\n<p><code>pow(2,5)</code> can be replaced by <code>1<<5</code></p>\n\n<p>This is much more efficient.</p>\n"
},
{
"answer_id": 20808031,
"author": "Vaibhav Fouzdar",
"author_id": 481275,
"author_profile": "https://Stackoverflow.com/users/481275",
"pm_score": 0,
"selected": false,
"text": "<p>One more implementation (in Java). May not be most efficient solution but # of iterations is same as that of Exponential solution.</p>\n\n<pre><code>public static long pow(long base, long exp){ \n if(exp ==0){\n return 1;\n }\n if(exp ==1){\n return base;\n }\n\n if(exp % 2 == 0){\n long half = pow(base, exp/2);\n return half * half;\n }else{\n long half = pow(base, (exp -1)/2);\n return base * half * half;\n } \n}\n</code></pre>\n"
},
{
"answer_id": 24299375,
"author": "Abhijit Gaikwad",
"author_id": 403872,
"author_profile": "https://Stackoverflow.com/users/403872",
"pm_score": 1,
"selected": false,
"text": "<p>more generic solution considering negative exponenet</p>\n\n<pre><code>private static int pow(int base, int exponent) {\n\n int result = 1;\n if (exponent == 0)\n return result; // base case;\n\n if (exponent < 0)\n return 1 / pow(base, -exponent);\n int temp = pow(base, exponent / 2);\n if (exponent % 2 == 0)\n return temp * temp;\n else\n return (base * temp * temp);\n}\n</code></pre>\n"
},
{
"answer_id": 28301482,
"author": "kyorilys",
"author_id": 1256388,
"author_profile": "https://Stackoverflow.com/users/1256388",
"pm_score": 0,
"selected": false,
"text": "<p>I use recursive, if the exp is even,5^10 =25^5.</p>\n\n<pre><code>int pow(float base,float exp){\n if (exp==0)return 1;\n else if(exp>0&&exp%2==0){\n return pow(base*base,exp/2);\n }else if (exp>0&&exp%2!=0){\n return base*pow(base,exp-1);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 29396800,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 2,
"selected": false,
"text": "<p>Late to the party: </p>\n\n<p>Below is a solution that also deals with <code>y < 0</code> as best as it can. </p>\n\n<ol>\n<li>It uses a result of <code>intmax_t</code> for maximum range. There is no provision for answers that do not fit in <code>intmax_t</code>. </li>\n<li><code>powjii(0, 0) --> 1</code> which is a <a href=\"https://stackoverflow.com/questions/19955968/why-is-math-pow0-0-1\">common result</a> for this case.</li>\n<li><p><code>pow(0,negative)</code>, another undefined result, returns <code>INTMAX_MAX</code></p>\n\n<pre><code>intmax_t powjii(int x, int y) {\n if (y < 0) {\n switch (x) {\n case 0:\n return INTMAX_MAX;\n case 1:\n return 1;\n case -1:\n return y % 2 ? -1 : 1;\n }\n return 0;\n }\n intmax_t z = 1;\n intmax_t base = x;\n for (;;) {\n if (y % 2) {\n z *= base;\n }\n y /= 2;\n if (y == 0) {\n break; \n }\n base *= base;\n }\n return z;\n}\n</code></pre></li>\n</ol>\n\n<p>This code uses a forever loop <code>for(;;)</code> to avoid the final <code>base *= base</code> common in other looped solutions. That multiplication is 1) not needed and 2) could be <code>int*int</code> overflow which is UB.</p>\n"
},
{
"answer_id": 31975558,
"author": "rank1",
"author_id": 1296250,
"author_profile": "https://Stackoverflow.com/users/1296250",
"pm_score": 0,
"selected": false,
"text": "<p>I have implemented algorithm that memorizes all computed powers and then uses them when need. So for example x^13 is equal to (x^2)^2^2 * x^2^2 * x where x^2^2 it taken from the table instead of computing it once again. This is basically implementation of @Pramod answer (but in C#). \nThe number of multiplication needed is Ceil(Log n)</p>\n\n<pre><code>public static int Power(int base, int exp)\n{\n int tab[] = new int[exp + 1];\n tab[0] = 1;\n tab[1] = base;\n return Power(base, exp, tab);\n}\n\npublic static int Power(int base, int exp, int tab[])\n {\n if(exp == 0) return 1;\n if(exp == 1) return base;\n int i = 1;\n while(i < exp/2)\n { \n if(tab[2 * i] <= 0)\n tab[2 * i] = tab[i] * tab[i];\n i = i << 1;\n }\n if(exp <= i)\n return tab[i];\n else return tab[i] * Power(base, exp - i, tab);\n}\n</code></pre>\n"
},
{
"answer_id": 34660211,
"author": "roottraveller",
"author_id": 5167682,
"author_profile": "https://Stackoverflow.com/users/5167682",
"pm_score": 3,
"selected": false,
"text": "<p><code>power()</code> function to work for <strong>Integers Only</strong> </p>\n\n<pre><code>int power(int base, unsigned int exp){\n\n if (exp == 0)\n return 1;\n int temp = power(base, exp/2);\n if (exp%2 == 0)\n return temp*temp;\n else\n return base*temp*temp;\n\n}\n</code></pre>\n\n<p><strong>Complexity = O(log(exp))</strong></p>\n\n<p><code>power()</code> function to work for <strong>negative exp and float base</strong>.</p>\n\n<pre><code>float power(float base, int exp) {\n\n if( exp == 0)\n return 1;\n float temp = power(base, exp/2); \n if (exp%2 == 0)\n return temp*temp;\n else {\n if(exp > 0)\n return base*temp*temp;\n else\n return (temp*temp)/base; //negative exponent computation \n }\n\n} \n</code></pre>\n\n<p><strong>Complexity = O(log(exp))</strong></p>\n"
},
{
"answer_id": 38984329,
"author": "MarcusJ",
"author_id": 1115761,
"author_profile": "https://Stackoverflow.com/users/1115761",
"pm_score": -1,
"selected": false,
"text": "<p>My case is a little different, I'm trying to create a mask from a power, but I thought I'd share the solution I found anyway.</p>\n\n<p>Obviously, it only works for powers of 2.</p>\n\n<pre><code>Mask1 = 1 << (Exponent - 1);\nMask2 = Mask1 - 1;\nreturn Mask1 + Mask2;\n</code></pre>\n"
},
{
"answer_id": 49712975,
"author": "Johannes Blaschke",
"author_id": 9550561,
"author_profile": "https://Stackoverflow.com/users/9550561",
"pm_score": -1,
"selected": false,
"text": "<p>In case you know the exponent (and it is an integer) at compile-time, you can use templates to unroll the loop. This can be made more efficient, but I wanted to demonstrate the basic principle here:</p>\n\n<pre><code>#include <iostream>\n\ntemplate<unsigned long N>\nunsigned long inline exp_unroll(unsigned base) {\n return base * exp_unroll<N-1>(base);\n}\n</code></pre>\n\n<p>We terminate the recursion using a template specialization:</p>\n\n<pre><code>template<>\nunsigned long inline exp_unroll<1>(unsigned base) {\n return base;\n}\n</code></pre>\n\n<p>The exponent needs to be known at runtime,</p>\n\n<pre><code>int main(int argc, char * argv[]) {\n std::cout << argv[1] <<\"**5= \" << exp_unroll<5>(atoi(argv[1])) << ;std::endl;\n}\n</code></pre>\n"
},
{
"answer_id": 55210943,
"author": "alx",
"author_id": 6872717,
"author_profile": "https://Stackoverflow.com/users/6872717",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to the answer by Elias, which causes Undefined Behaviour when implemented with signed integers, and incorrect values for high input when implemented with unsigned integers,</p>\n\n<p>here is a modified version of the Exponentiation by Squaring that also works with signed integer types, and doesn't give incorrect values:</p>\n\n<pre><code>#include <stdint.h>\n\n#define SQRT_INT64_MAX (INT64_C(0xB504F333))\n\nint64_t alx_pow_s64 (int64_t base, uint8_t exp)\n{\n int_fast64_t base_;\n int_fast64_t result;\n\n base_ = base;\n\n if (base_ == 1)\n return 1;\n if (!exp)\n return 1;\n if (!base_)\n return 0;\n\n result = 1;\n if (exp & 1)\n result *= base_;\n exp >>= 1;\n while (exp) {\n if (base_ > SQRT_INT64_MAX)\n return 0;\n base_ *= base_;\n if (exp & 1)\n result *= base_;\n exp >>= 1;\n }\n\n return result;\n}\n</code></pre>\n\n<p>Considerations for this function:</p>\n\n<pre><code>(1 ** N) == 1\n(N ** 0) == 1\n(0 ** 0) == 1\n(0 ** N) == 0\n</code></pre>\n\n<p>If any overflow or wrapping is going to take place, <code>return 0;</code></p>\n\n<p>I used <code>int64_t</code>, but any width (signed or unsigned) can be used with little modification. However, if you need to use a non-fixed-width integer type, you will need to change <code>SQRT_INT64_MAX</code> by <code>(int)sqrt(INT_MAX)</code> (in the case of using <code>int</code>) or something similar, which should be optimized, but it is uglier, and not a C constant expression. Also casting the result of <code>sqrt()</code> to an <code>int</code> is not very good because of floating point precission in case of a perfect square, but as I don't know of any implementation where <code>INT_MAX</code> -or the maximum of any type- is a perfect square, you can live with that.</p>\n"
},
{
"answer_id": 67377351,
"author": "ToxicAbe",
"author_id": 4233144,
"author_profile": "https://Stackoverflow.com/users/4233144",
"pm_score": 1,
"selected": false,
"text": "<p>The O(log N) solution in Swift...</p>\n<pre><code>// Time complexity is O(log N)\nfunc power(_ base: Int, _ exp: Int) -> Int { \n\n // 1. If the exponent is 1 then return the number (e.g a^1 == a)\n //Time complexity O(1)\n if exp == 1 { \n return base\n }\n\n // 2. Calculate the value of the number raised to half of the exponent. This will be used to calculate the final answer by squaring the result (e.g a^2n == (a^n)^2 == a^n * a^n). The idea is that we can do half the amount of work by obtaining a^n and multiplying the result by itself to get a^2n\n //Time complexity O(log N)\n let tempVal = power(base, exp/2) \n\n // 3. If the exponent was odd then decompose the result in such a way that it allows you to divide the exponent in two (e.g. a^(2n+1) == a^1 * a^2n == a^1 * a^n * a^n). If the eponent is even then the result must be the base raised to half the exponent squared (e.g. a^2n == a^n * a^n = (a^n)^2).\n //Time complexity O(1)\n return (exp % 2 == 1 ? base : 1) * tempVal * tempVal \n\n}\n</code></pre>\n"
},
{
"answer_id": 67410174,
"author": "user1095108",
"author_id": 1095108,
"author_profile": "https://Stackoverflow.com/users/1095108",
"pm_score": 1,
"selected": false,
"text": "<pre><code>int pow(int const x, unsigned const e) noexcept\n{\n return !e ? 1 : 1 == e ? x : (e % 2 ? x : 1) * pow(x * x, e / 2);\n //return !e ? 1 : 1 == e ? x : (((x ^ 1) & -(e % 2)) ^ 1) * pow(x * x, e / 2);\n}\n</code></pre>\n<p>Yes, it's recursive, but a good optimizing compiler will optimize recursion away.</p>\n"
},
{
"answer_id": 72904144,
"author": "anatolyg",
"author_id": 509868,
"author_profile": "https://Stackoverflow.com/users/509868",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a O(1) algorithm for calculating <code>x ** y</code>, inspired by <a href=\"https://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int/72904144#comment57067814_101439\">this comment</a>. It works for 32-bit signed <code>int</code>.</p>\n<p>For small values of <code>y</code>, it uses exponentiation by squaring. For large values of <code>y</code>, there are only a few values of <code>x</code> where the result doesn't overflow. This implementation uses a lookup table to read the result without calculating.</p>\n<p>On overflow, the C standard permits any behavior, including crash. However, I decided to do bound-checking on LUT indices to prevent memory access violation, which could be surprising and undesirable.</p>\n<p>Pseudo-code:</p>\n<pre><code>If `x` is between -2 and 2, use special-case formulas.\nOtherwise, if `y` is between 0 and 8, use special-case formulas.\nOtherwise:\n Set x = abs(x); remember if x was negative\n If x <= 10 and y <= 19:\n Load precomputed result from a lookup table\n Otherwise:\n Set result to 0 (overflow)\n If x was negative and y is odd, negate the result\n</code></pre>\n<p>C code:</p>\n<pre><code>#define POW9(x) x * x * x * x * x * x * x * x * x\n#define POW10(x) POW9(x) * x\n#define POW11(x) POW10(x) * x\n#define POW12(x) POW11(x) * x\n#define POW13(x) POW12(x) * x\n#define POW14(x) POW13(x) * x\n#define POW15(x) POW14(x) * x\n#define POW16(x) POW15(x) * x\n#define POW17(x) POW16(x) * x\n#define POW18(x) POW17(x) * x\n#define POW19(x) POW18(x) * x\n\nint mypow(int x, unsigned y)\n{\n static int table[8][11] = {\n {POW9(3), POW10(3), POW11(3), POW12(3), POW13(3), POW14(3), POW15(3), POW16(3), POW17(3), POW18(3), POW19(3)},\n {POW9(4), POW10(4), POW11(4), POW12(4), POW13(4), POW14(4), POW15(4), 0, 0, 0, 0},\n {POW9(5), POW10(5), POW11(5), POW12(5), POW13(5), 0, 0, 0, 0, 0, 0},\n {POW9(6), POW10(6), POW11(6), 0, 0, 0, 0, 0, 0, 0, 0},\n {POW9(7), POW10(7), POW11(7), 0, 0, 0, 0, 0, 0, 0, 0},\n {POW9(8), POW10(8), 0, 0, 0, 0, 0, 0, 0, 0, 0},\n {POW9(9), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n {POW9(10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}\n };\n\n int is_neg;\n int r;\n\n switch (x)\n {\n case 0:\n return y == 0 ? 1 : 0;\n case 1:\n return 1;\n case -1:\n return y % 2 == 0 ? 1 : -1;\n case 2:\n return 1 << y;\n case -2:\n return (y % 2 == 0 ? 1 : -1) << y;\n default:\n switch (y)\n {\n case 0:\n return 1;\n case 1:\n return x;\n case 2:\n return x * x;\n case 3:\n return x * x * x;\n case 4:\n r = x * x;\n return r * r;\n case 5:\n r = x * x;\n return r * r * x;\n case 6:\n r = x * x;\n return r * r * r;\n case 7:\n r = x * x;\n return r * r * r * x;\n case 8:\n r = x * x;\n r = r * r;\n return r * r;\n default:\n is_neg = x < 0;\n if (is_neg)\n x = -x;\n if (x <= 10 && y <= 19)\n r = table[x - 3][y - 9];\n else\n r = 0;\n if (is_neg && y % 2 == 1)\n r = -r;\n return r;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 73215238,
"author": "RARE Kpop Manifesto",
"author_id": 14672114,
"author_profile": "https://Stackoverflow.com/users/14672114",
"pm_score": -1,
"selected": false,
"text": "<p>I've noticed something strange about the standard exponential squaring algorithm with <code>gnu-GMP</code> :</p>\n<p>I implemented 2 nearly-identical functions - a power-modulo function using the most vanilla binary exponential squaring algorithm,</p>\n<ul>\n<li>labeled <strong><code>______2()</code></strong></li>\n</ul>\n<p>then another one basically the same concept, but re-mapped to dividing by 10 at each round instead of dividing by 2,</p>\n<ul>\n<li>labeled <strong><code>______10()</code></strong></li>\n</ul>\n<p>.</p>\n<pre><code> ( time ( jot - 1456 9999999999 6671 | pvE0 | \n\ngawk -Mbe '\nfunction ______10(_, __, ___, ____, _____, _______) {\n __ = +__\n ____ = (____+=_____=____^= \\\n (_ %=___=+___)<_)+____++^____—\n\n while (__) {\n if (_______= __%____) {\n if (__==_______) {\n return (_^__ *_____) %___\n }\n __-=_______\n _____ = (_^_______*_____) %___\n }\n __/=____\n _ = _^____%___\n }\n}\nfunction ______2(_, __, ___, ____, _____) {\n __=+__\n ____+=____=_____^=(_%=___=+___)<_\n while (__) {\n if (__ %____) {\n if (__<____) {\n return (_*_____) %___\n }\n _____ = (_____*_) %___\n --__\n }\n __/=____\n _= (_*_) %___\n }\n} \nBEGIN {\n OFMT = CONVFMT = "%.250g"\n\n __ = (___=_^= FS=OFS= "=")(_<_)\n\n _____ = __^(_=3)^--_ * ++_-(_+_)^_\n ______ = _^(_+_)-_ + _^!_\n\n _______ = int(______*_____)\n ________ = 10 ^ 5 + 1\n _________ = 8 ^ 4 * 2 - 1\n}\n</code></pre>\n<ul>\n<li><em><strong><code>GNU Awk 5.1.1, API: 3.1 (GNU MPFR 4.1.0, GNU MP 6.2.1)</code></strong></em></li>\n</ul>\n<p>.</p>\n<blockquote>\n<pre><code>($++NF = ______10(_=$___, NR %________ +_________,_______*(_-11))) ^!___'\n</code></pre>\n</blockquote>\n<pre><code> out9: 48.4MiB 0:00:08 [6.02MiB/s] [6.02MiB/s] [ <=> ]\n in0: 15.6MiB 0:00:08 [1.95MiB/s] [1.95MiB/s] [ <=> ]\n( jot - 1456 9999999999 6671 | pvE 0.1 in0 | gawk -Mbe ; ) \n\n8.31s user 0.06s system 103% cpu 8.058 total\nffa16aa937b7beca66a173ccbf8e1e12 stdin\n</code></pre>\n<blockquote>\n<pre><code>($++NF = ______2(_=$___, NR %________ +_________,_______*(_-11))) ^!___'\n</code></pre>\n</blockquote>\n<pre><code> out9: 48.4MiB 0:00:12 [3.78MiB/s] [3.78MiB/s] [<=> ]\n in0: 15.6MiB 0:00:12 [1.22MiB/s] [1.22MiB/s] [ <=> ]\n( jot - 1456 9999999999 6671 | pvE 0.1 in0 | gawk -Mbe ; ) \n\n13.05s user 0.07s system 102% cpu 12.821 total\nffa16aa937b7beca66a173ccbf8e1e12 stdin\n</code></pre>\n<p>For reasons extremely counter-intuitive and unknown to me, for a wide variety of inputs i threw at it, the div-10 variant is nearly always faster. It's the matching of hashes between the 2 that made it truly baffling, despite computers obviously not being built in and for a base-10 paradigm.</p>\n<p>Am I missing something critical or obvious in the code/approach that might be skewing the results in a confounding manner ? Thanks.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123/"
]
| What is the most efficient way given to raise an integer to the power of another integer in C?
```
// 2^3
pow(2,3) == 8
// 5^5
pow(5,5) == 3125
``` | Exponentiation by squaring.
```
int ipow(int base, int exp)
{
int result = 1;
for (;;)
{
if (exp & 1)
result *= base;
exp >>= 1;
if (!exp)
break;
base *= base;
}
return result;
}
```
This is the standard method for doing modular exponentiation for huge numbers in asymmetric cryptography. |
101,449 | <p>I'm guessing I need to implement an <code>NVelocityViewEngine</code> and <code>NVelocityView</code> - but before I do I wanted to check to see if anyone has already done this.</p>
<p>I can't see anything in the <a href="http://mvccontrib.googlecode.com/svn/trunk/" rel="nofollow noreferrer">trunk</a> for <a href="http://www.codeplex.com/MVCContrib" rel="nofollow noreferrer">MVCContrib</a>.</p>
<p>I've already seen the post below - I'm looking specifically for something which works with Preview 5:</p>
<ul>
<li><a href="http://www.chadmyers.com/Blog/archive/2007/11/28/testing-scottgu-alternate-view-engines-with-asp.net-mvc-nvelocity.aspx" rel="nofollow noreferrer">Testing ScottGu: Alternate View Engines with ASP.NET MVC (NVelocity)</a></li>
</ul>
<p>Otherwise I'll start writing one :)</p>
| [
{
"answer_id": 101473,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 3,
"selected": false,
"text": "<p>An extremely specialized case is, when you need say 2^(-x to the y), where x, is of course is negative and y is too large to do shifting on an int. You can still do 2^x in constant time by screwing with a float.</p>\n\n<pre><code>struct IeeeFloat\n{\n\n unsigned int base : 23;\n unsigned int exponent : 8;\n unsigned int signBit : 1;\n};\n\n\nunion IeeeFloatUnion\n{\n IeeeFloat brokenOut;\n float f;\n};\n\ninline float twoToThe(char exponent)\n{\n // notice how the range checking is already done on the exponent var \n static IeeeFloatUnion u;\n u.f = 2.0;\n // Change the exponent part of the float\n u.brokenOut.exponent += (exponent - 1);\n return (u.f);\n}\n</code></pre>\n\n<p>You can get more powers of 2 by using a double as the base type.\n(Thanks a lot to commenters for helping to square this post away).</p>\n\n<p>There's also the possibility that learning more about <a href=\"https://www.wikiwand.com/en/IEEE_754\" rel=\"nofollow noreferrer\">IEEE floats</a>, other special cases of exponentiation might present themselves.</p>\n"
},
{
"answer_id": 101613,
"author": "Elias Yarrkov",
"author_id": 18814,
"author_profile": "https://Stackoverflow.com/users/18814",
"pm_score": 10,
"selected": true,
"text": "<p>Exponentiation by squaring.</p>\n\n<pre><code>int ipow(int base, int exp)\n{\n int result = 1;\n for (;;)\n {\n if (exp & 1)\n result *= base;\n exp >>= 1;\n if (!exp)\n break;\n base *= base;\n }\n\n return result;\n}\n</code></pre>\n\n<p>This is the standard method for doing modular exponentiation for huge numbers in asymmetric cryptography.</p>\n"
},
{
"answer_id": 102319,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 3,
"selected": false,
"text": "<pre><code>int pow( int base, int exponent)\n\n{ // Does not work for negative exponents. (But that would be leaving the range of int) \n if (exponent == 0) return 1; // base case;\n int temp = pow(base, exponent/2);\n if (exponent % 2 == 0)\n return temp * temp; \n else\n return (base * temp * temp);\n}\n</code></pre>\n"
},
{
"answer_id": 108959,
"author": "Pramod",
"author_id": 1386292,
"author_profile": "https://Stackoverflow.com/users/1386292",
"pm_score": 6,
"selected": false,
"text": "<p>Note that <a href=\"https://en.wikipedia.org/wiki/Exponentiation_by_squaring\" rel=\"noreferrer\">exponentiation by squaring</a> is not the most optimal method. It is probably the best you can do as a general method that works for all exponent values, but for a specific exponent value there might be a better sequence that needs fewer multiplications.</p>\n\n<p>For instance, if you want to compute x^15, the method of exponentiation by squaring will give you:</p>\n\n<pre><code>x^15 = (x^7)*(x^7)*x \nx^7 = (x^3)*(x^3)*x \nx^3 = x*x*x\n</code></pre>\n\n<p>This is a total of 6 multiplications.</p>\n\n<p>It turns out this can be done using \"just\" 5 multiplications via <a href=\"https://en.wikipedia.org/wiki/Addition-chain_exponentiation\" rel=\"noreferrer\">addition-chain exponentiation</a>.</p>\n\n<pre><code>n*n = n^2\nn^2*n = n^3\nn^3*n^3 = n^6\nn^6*n^6 = n^12\nn^12*n^3 = n^15\n</code></pre>\n\n<p>There are no efficient algorithms to find this optimal sequence of multiplications. From <a href=\"https://en.wikipedia.org/wiki/Addition-chain_exponentiation\" rel=\"noreferrer\">Wikipedia</a>:</p>\n\n<blockquote>\n <p>The problem of finding the shortest addition chain cannot be solved by dynamic programming, because it does not satisfy the assumption of optimal substructure. That is, it is not sufficient to decompose the power into smaller powers, each of which is computed minimally, since the addition chains for the smaller powers may be related (to share computations). For example, in the shortest addition chain for a¹⁵ above, the subproblem for a⁶ must be computed as (a³)² since a³ is re-used (as opposed to, say, a⁶ = a²(a²)², which also requires three multiplies).</p>\n</blockquote>\n"
},
{
"answer_id": 163598,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 2,
"selected": false,
"text": "<p>Just as a follow up to comments on the efficiency of exponentiation by squaring.</p>\n\n<p>The advantage of that approach is that it runs in log(n) time. For example, if you were going to calculate something huge, such as x^1048575 (2^20 - 1), you only have to go thru the loop 20 times, not 1 million+ using the naive approach.</p>\n\n<p>Also, in terms of code complexity, it is simpler than trying to find the most optimal sequence of multiplications, a la Pramod's suggestion.</p>\n\n<p>Edit:</p>\n\n<p>I guess I should clarify before someone tags me for the potential for overflow. This approach assumes that you have some sort of hugeint library.</p>\n"
},
{
"answer_id": 5345369,
"author": "Jake",
"author_id": 498804,
"author_profile": "https://Stackoverflow.com/users/498804",
"pm_score": 5,
"selected": false,
"text": "<p>If you need to raise 2 to a power. The fastest way to do so is to bit shift by the power.</p>\n\n<pre><code>2 ** 3 == 1 << 3 == 8\n2 ** 30 == 1 << 30 == 1073741824 (A Gigabyte)\n</code></pre>\n"
},
{
"answer_id": 10517609,
"author": "user1067920",
"author_id": 1067920,
"author_profile": "https://Stackoverflow.com/users/1067920",
"pm_score": 4,
"selected": false,
"text": "<p>Here is the method in Java</p>\n\n<pre><code>private int ipow(int base, int exp)\n{\n int result = 1;\n while (exp != 0)\n {\n if ((exp & 1) == 1)\n result *= base;\n exp >>= 1;\n base *= base;\n }\n\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 10578794,
"author": "aditya",
"author_id": 1223316,
"author_profile": "https://Stackoverflow.com/users/1223316",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to get the value of an integer for 2 raised to the power of something it is always better to use the shift option:</p>\n\n<p><code>pow(2,5)</code> can be replaced by <code>1<<5</code></p>\n\n<p>This is much more efficient.</p>\n"
},
{
"answer_id": 20808031,
"author": "Vaibhav Fouzdar",
"author_id": 481275,
"author_profile": "https://Stackoverflow.com/users/481275",
"pm_score": 0,
"selected": false,
"text": "<p>One more implementation (in Java). May not be most efficient solution but # of iterations is same as that of Exponential solution.</p>\n\n<pre><code>public static long pow(long base, long exp){ \n if(exp ==0){\n return 1;\n }\n if(exp ==1){\n return base;\n }\n\n if(exp % 2 == 0){\n long half = pow(base, exp/2);\n return half * half;\n }else{\n long half = pow(base, (exp -1)/2);\n return base * half * half;\n } \n}\n</code></pre>\n"
},
{
"answer_id": 24299375,
"author": "Abhijit Gaikwad",
"author_id": 403872,
"author_profile": "https://Stackoverflow.com/users/403872",
"pm_score": 1,
"selected": false,
"text": "<p>more generic solution considering negative exponenet</p>\n\n<pre><code>private static int pow(int base, int exponent) {\n\n int result = 1;\n if (exponent == 0)\n return result; // base case;\n\n if (exponent < 0)\n return 1 / pow(base, -exponent);\n int temp = pow(base, exponent / 2);\n if (exponent % 2 == 0)\n return temp * temp;\n else\n return (base * temp * temp);\n}\n</code></pre>\n"
},
{
"answer_id": 28301482,
"author": "kyorilys",
"author_id": 1256388,
"author_profile": "https://Stackoverflow.com/users/1256388",
"pm_score": 0,
"selected": false,
"text": "<p>I use recursive, if the exp is even,5^10 =25^5.</p>\n\n<pre><code>int pow(float base,float exp){\n if (exp==0)return 1;\n else if(exp>0&&exp%2==0){\n return pow(base*base,exp/2);\n }else if (exp>0&&exp%2!=0){\n return base*pow(base,exp-1);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 29396800,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 2,
"selected": false,
"text": "<p>Late to the party: </p>\n\n<p>Below is a solution that also deals with <code>y < 0</code> as best as it can. </p>\n\n<ol>\n<li>It uses a result of <code>intmax_t</code> for maximum range. There is no provision for answers that do not fit in <code>intmax_t</code>. </li>\n<li><code>powjii(0, 0) --> 1</code> which is a <a href=\"https://stackoverflow.com/questions/19955968/why-is-math-pow0-0-1\">common result</a> for this case.</li>\n<li><p><code>pow(0,negative)</code>, another undefined result, returns <code>INTMAX_MAX</code></p>\n\n<pre><code>intmax_t powjii(int x, int y) {\n if (y < 0) {\n switch (x) {\n case 0:\n return INTMAX_MAX;\n case 1:\n return 1;\n case -1:\n return y % 2 ? -1 : 1;\n }\n return 0;\n }\n intmax_t z = 1;\n intmax_t base = x;\n for (;;) {\n if (y % 2) {\n z *= base;\n }\n y /= 2;\n if (y == 0) {\n break; \n }\n base *= base;\n }\n return z;\n}\n</code></pre></li>\n</ol>\n\n<p>This code uses a forever loop <code>for(;;)</code> to avoid the final <code>base *= base</code> common in other looped solutions. That multiplication is 1) not needed and 2) could be <code>int*int</code> overflow which is UB.</p>\n"
},
{
"answer_id": 31975558,
"author": "rank1",
"author_id": 1296250,
"author_profile": "https://Stackoverflow.com/users/1296250",
"pm_score": 0,
"selected": false,
"text": "<p>I have implemented algorithm that memorizes all computed powers and then uses them when need. So for example x^13 is equal to (x^2)^2^2 * x^2^2 * x where x^2^2 it taken from the table instead of computing it once again. This is basically implementation of @Pramod answer (but in C#). \nThe number of multiplication needed is Ceil(Log n)</p>\n\n<pre><code>public static int Power(int base, int exp)\n{\n int tab[] = new int[exp + 1];\n tab[0] = 1;\n tab[1] = base;\n return Power(base, exp, tab);\n}\n\npublic static int Power(int base, int exp, int tab[])\n {\n if(exp == 0) return 1;\n if(exp == 1) return base;\n int i = 1;\n while(i < exp/2)\n { \n if(tab[2 * i] <= 0)\n tab[2 * i] = tab[i] * tab[i];\n i = i << 1;\n }\n if(exp <= i)\n return tab[i];\n else return tab[i] * Power(base, exp - i, tab);\n}\n</code></pre>\n"
},
{
"answer_id": 34660211,
"author": "roottraveller",
"author_id": 5167682,
"author_profile": "https://Stackoverflow.com/users/5167682",
"pm_score": 3,
"selected": false,
"text": "<p><code>power()</code> function to work for <strong>Integers Only</strong> </p>\n\n<pre><code>int power(int base, unsigned int exp){\n\n if (exp == 0)\n return 1;\n int temp = power(base, exp/2);\n if (exp%2 == 0)\n return temp*temp;\n else\n return base*temp*temp;\n\n}\n</code></pre>\n\n<p><strong>Complexity = O(log(exp))</strong></p>\n\n<p><code>power()</code> function to work for <strong>negative exp and float base</strong>.</p>\n\n<pre><code>float power(float base, int exp) {\n\n if( exp == 0)\n return 1;\n float temp = power(base, exp/2); \n if (exp%2 == 0)\n return temp*temp;\n else {\n if(exp > 0)\n return base*temp*temp;\n else\n return (temp*temp)/base; //negative exponent computation \n }\n\n} \n</code></pre>\n\n<p><strong>Complexity = O(log(exp))</strong></p>\n"
},
{
"answer_id": 38984329,
"author": "MarcusJ",
"author_id": 1115761,
"author_profile": "https://Stackoverflow.com/users/1115761",
"pm_score": -1,
"selected": false,
"text": "<p>My case is a little different, I'm trying to create a mask from a power, but I thought I'd share the solution I found anyway.</p>\n\n<p>Obviously, it only works for powers of 2.</p>\n\n<pre><code>Mask1 = 1 << (Exponent - 1);\nMask2 = Mask1 - 1;\nreturn Mask1 + Mask2;\n</code></pre>\n"
},
{
"answer_id": 49712975,
"author": "Johannes Blaschke",
"author_id": 9550561,
"author_profile": "https://Stackoverflow.com/users/9550561",
"pm_score": -1,
"selected": false,
"text": "<p>In case you know the exponent (and it is an integer) at compile-time, you can use templates to unroll the loop. This can be made more efficient, but I wanted to demonstrate the basic principle here:</p>\n\n<pre><code>#include <iostream>\n\ntemplate<unsigned long N>\nunsigned long inline exp_unroll(unsigned base) {\n return base * exp_unroll<N-1>(base);\n}\n</code></pre>\n\n<p>We terminate the recursion using a template specialization:</p>\n\n<pre><code>template<>\nunsigned long inline exp_unroll<1>(unsigned base) {\n return base;\n}\n</code></pre>\n\n<p>The exponent needs to be known at runtime,</p>\n\n<pre><code>int main(int argc, char * argv[]) {\n std::cout << argv[1] <<\"**5= \" << exp_unroll<5>(atoi(argv[1])) << ;std::endl;\n}\n</code></pre>\n"
},
{
"answer_id": 55210943,
"author": "alx",
"author_id": 6872717,
"author_profile": "https://Stackoverflow.com/users/6872717",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to the answer by Elias, which causes Undefined Behaviour when implemented with signed integers, and incorrect values for high input when implemented with unsigned integers,</p>\n\n<p>here is a modified version of the Exponentiation by Squaring that also works with signed integer types, and doesn't give incorrect values:</p>\n\n<pre><code>#include <stdint.h>\n\n#define SQRT_INT64_MAX (INT64_C(0xB504F333))\n\nint64_t alx_pow_s64 (int64_t base, uint8_t exp)\n{\n int_fast64_t base_;\n int_fast64_t result;\n\n base_ = base;\n\n if (base_ == 1)\n return 1;\n if (!exp)\n return 1;\n if (!base_)\n return 0;\n\n result = 1;\n if (exp & 1)\n result *= base_;\n exp >>= 1;\n while (exp) {\n if (base_ > SQRT_INT64_MAX)\n return 0;\n base_ *= base_;\n if (exp & 1)\n result *= base_;\n exp >>= 1;\n }\n\n return result;\n}\n</code></pre>\n\n<p>Considerations for this function:</p>\n\n<pre><code>(1 ** N) == 1\n(N ** 0) == 1\n(0 ** 0) == 1\n(0 ** N) == 0\n</code></pre>\n\n<p>If any overflow or wrapping is going to take place, <code>return 0;</code></p>\n\n<p>I used <code>int64_t</code>, but any width (signed or unsigned) can be used with little modification. However, if you need to use a non-fixed-width integer type, you will need to change <code>SQRT_INT64_MAX</code> by <code>(int)sqrt(INT_MAX)</code> (in the case of using <code>int</code>) or something similar, which should be optimized, but it is uglier, and not a C constant expression. Also casting the result of <code>sqrt()</code> to an <code>int</code> is not very good because of floating point precission in case of a perfect square, but as I don't know of any implementation where <code>INT_MAX</code> -or the maximum of any type- is a perfect square, you can live with that.</p>\n"
},
{
"answer_id": 67377351,
"author": "ToxicAbe",
"author_id": 4233144,
"author_profile": "https://Stackoverflow.com/users/4233144",
"pm_score": 1,
"selected": false,
"text": "<p>The O(log N) solution in Swift...</p>\n<pre><code>// Time complexity is O(log N)\nfunc power(_ base: Int, _ exp: Int) -> Int { \n\n // 1. If the exponent is 1 then return the number (e.g a^1 == a)\n //Time complexity O(1)\n if exp == 1 { \n return base\n }\n\n // 2. Calculate the value of the number raised to half of the exponent. This will be used to calculate the final answer by squaring the result (e.g a^2n == (a^n)^2 == a^n * a^n). The idea is that we can do half the amount of work by obtaining a^n and multiplying the result by itself to get a^2n\n //Time complexity O(log N)\n let tempVal = power(base, exp/2) \n\n // 3. If the exponent was odd then decompose the result in such a way that it allows you to divide the exponent in two (e.g. a^(2n+1) == a^1 * a^2n == a^1 * a^n * a^n). If the eponent is even then the result must be the base raised to half the exponent squared (e.g. a^2n == a^n * a^n = (a^n)^2).\n //Time complexity O(1)\n return (exp % 2 == 1 ? base : 1) * tempVal * tempVal \n\n}\n</code></pre>\n"
},
{
"answer_id": 67410174,
"author": "user1095108",
"author_id": 1095108,
"author_profile": "https://Stackoverflow.com/users/1095108",
"pm_score": 1,
"selected": false,
"text": "<pre><code>int pow(int const x, unsigned const e) noexcept\n{\n return !e ? 1 : 1 == e ? x : (e % 2 ? x : 1) * pow(x * x, e / 2);\n //return !e ? 1 : 1 == e ? x : (((x ^ 1) & -(e % 2)) ^ 1) * pow(x * x, e / 2);\n}\n</code></pre>\n<p>Yes, it's recursive, but a good optimizing compiler will optimize recursion away.</p>\n"
},
{
"answer_id": 72904144,
"author": "anatolyg",
"author_id": 509868,
"author_profile": "https://Stackoverflow.com/users/509868",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a O(1) algorithm for calculating <code>x ** y</code>, inspired by <a href=\"https://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int/72904144#comment57067814_101439\">this comment</a>. It works for 32-bit signed <code>int</code>.</p>\n<p>For small values of <code>y</code>, it uses exponentiation by squaring. For large values of <code>y</code>, there are only a few values of <code>x</code> where the result doesn't overflow. This implementation uses a lookup table to read the result without calculating.</p>\n<p>On overflow, the C standard permits any behavior, including crash. However, I decided to do bound-checking on LUT indices to prevent memory access violation, which could be surprising and undesirable.</p>\n<p>Pseudo-code:</p>\n<pre><code>If `x` is between -2 and 2, use special-case formulas.\nOtherwise, if `y` is between 0 and 8, use special-case formulas.\nOtherwise:\n Set x = abs(x); remember if x was negative\n If x <= 10 and y <= 19:\n Load precomputed result from a lookup table\n Otherwise:\n Set result to 0 (overflow)\n If x was negative and y is odd, negate the result\n</code></pre>\n<p>C code:</p>\n<pre><code>#define POW9(x) x * x * x * x * x * x * x * x * x\n#define POW10(x) POW9(x) * x\n#define POW11(x) POW10(x) * x\n#define POW12(x) POW11(x) * x\n#define POW13(x) POW12(x) * x\n#define POW14(x) POW13(x) * x\n#define POW15(x) POW14(x) * x\n#define POW16(x) POW15(x) * x\n#define POW17(x) POW16(x) * x\n#define POW18(x) POW17(x) * x\n#define POW19(x) POW18(x) * x\n\nint mypow(int x, unsigned y)\n{\n static int table[8][11] = {\n {POW9(3), POW10(3), POW11(3), POW12(3), POW13(3), POW14(3), POW15(3), POW16(3), POW17(3), POW18(3), POW19(3)},\n {POW9(4), POW10(4), POW11(4), POW12(4), POW13(4), POW14(4), POW15(4), 0, 0, 0, 0},\n {POW9(5), POW10(5), POW11(5), POW12(5), POW13(5), 0, 0, 0, 0, 0, 0},\n {POW9(6), POW10(6), POW11(6), 0, 0, 0, 0, 0, 0, 0, 0},\n {POW9(7), POW10(7), POW11(7), 0, 0, 0, 0, 0, 0, 0, 0},\n {POW9(8), POW10(8), 0, 0, 0, 0, 0, 0, 0, 0, 0},\n {POW9(9), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n {POW9(10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}\n };\n\n int is_neg;\n int r;\n\n switch (x)\n {\n case 0:\n return y == 0 ? 1 : 0;\n case 1:\n return 1;\n case -1:\n return y % 2 == 0 ? 1 : -1;\n case 2:\n return 1 << y;\n case -2:\n return (y % 2 == 0 ? 1 : -1) << y;\n default:\n switch (y)\n {\n case 0:\n return 1;\n case 1:\n return x;\n case 2:\n return x * x;\n case 3:\n return x * x * x;\n case 4:\n r = x * x;\n return r * r;\n case 5:\n r = x * x;\n return r * r * x;\n case 6:\n r = x * x;\n return r * r * r;\n case 7:\n r = x * x;\n return r * r * r * x;\n case 8:\n r = x * x;\n r = r * r;\n return r * r;\n default:\n is_neg = x < 0;\n if (is_neg)\n x = -x;\n if (x <= 10 && y <= 19)\n r = table[x - 3][y - 9];\n else\n r = 0;\n if (is_neg && y % 2 == 1)\n r = -r;\n return r;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 73215238,
"author": "RARE Kpop Manifesto",
"author_id": 14672114,
"author_profile": "https://Stackoverflow.com/users/14672114",
"pm_score": -1,
"selected": false,
"text": "<p>I've noticed something strange about the standard exponential squaring algorithm with <code>gnu-GMP</code> :</p>\n<p>I implemented 2 nearly-identical functions - a power-modulo function using the most vanilla binary exponential squaring algorithm,</p>\n<ul>\n<li>labeled <strong><code>______2()</code></strong></li>\n</ul>\n<p>then another one basically the same concept, but re-mapped to dividing by 10 at each round instead of dividing by 2,</p>\n<ul>\n<li>labeled <strong><code>______10()</code></strong></li>\n</ul>\n<p>.</p>\n<pre><code> ( time ( jot - 1456 9999999999 6671 | pvE0 | \n\ngawk -Mbe '\nfunction ______10(_, __, ___, ____, _____, _______) {\n __ = +__\n ____ = (____+=_____=____^= \\\n (_ %=___=+___)<_)+____++^____—\n\n while (__) {\n if (_______= __%____) {\n if (__==_______) {\n return (_^__ *_____) %___\n }\n __-=_______\n _____ = (_^_______*_____) %___\n }\n __/=____\n _ = _^____%___\n }\n}\nfunction ______2(_, __, ___, ____, _____) {\n __=+__\n ____+=____=_____^=(_%=___=+___)<_\n while (__) {\n if (__ %____) {\n if (__<____) {\n return (_*_____) %___\n }\n _____ = (_____*_) %___\n --__\n }\n __/=____\n _= (_*_) %___\n }\n} \nBEGIN {\n OFMT = CONVFMT = "%.250g"\n\n __ = (___=_^= FS=OFS= "=")(_<_)\n\n _____ = __^(_=3)^--_ * ++_-(_+_)^_\n ______ = _^(_+_)-_ + _^!_\n\n _______ = int(______*_____)\n ________ = 10 ^ 5 + 1\n _________ = 8 ^ 4 * 2 - 1\n}\n</code></pre>\n<ul>\n<li><em><strong><code>GNU Awk 5.1.1, API: 3.1 (GNU MPFR 4.1.0, GNU MP 6.2.1)</code></strong></em></li>\n</ul>\n<p>.</p>\n<blockquote>\n<pre><code>($++NF = ______10(_=$___, NR %________ +_________,_______*(_-11))) ^!___'\n</code></pre>\n</blockquote>\n<pre><code> out9: 48.4MiB 0:00:08 [6.02MiB/s] [6.02MiB/s] [ <=> ]\n in0: 15.6MiB 0:00:08 [1.95MiB/s] [1.95MiB/s] [ <=> ]\n( jot - 1456 9999999999 6671 | pvE 0.1 in0 | gawk -Mbe ; ) \n\n8.31s user 0.06s system 103% cpu 8.058 total\nffa16aa937b7beca66a173ccbf8e1e12 stdin\n</code></pre>\n<blockquote>\n<pre><code>($++NF = ______2(_=$___, NR %________ +_________,_______*(_-11))) ^!___'\n</code></pre>\n</blockquote>\n<pre><code> out9: 48.4MiB 0:00:12 [3.78MiB/s] [3.78MiB/s] [<=> ]\n in0: 15.6MiB 0:00:12 [1.22MiB/s] [1.22MiB/s] [ <=> ]\n( jot - 1456 9999999999 6671 | pvE 0.1 in0 | gawk -Mbe ; ) \n\n13.05s user 0.07s system 102% cpu 12.821 total\nffa16aa937b7beca66a173ccbf8e1e12 stdin\n</code></pre>\n<p>For reasons extremely counter-intuitive and unknown to me, for a wide variety of inputs i threw at it, the div-10 variant is nearly always faster. It's the matching of hashes between the 2 that made it truly baffling, despite computers obviously not being built in and for a base-10 paradigm.</p>\n<p>Am I missing something critical or obvious in the code/approach that might be skewing the results in a confounding manner ? Thanks.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8542/"
]
| I'm guessing I need to implement an `NVelocityViewEngine` and `NVelocityView` - but before I do I wanted to check to see if anyone has already done this.
I can't see anything in the [trunk](http://mvccontrib.googlecode.com/svn/trunk/) for [MVCContrib](http://www.codeplex.com/MVCContrib).
I've already seen the post below - I'm looking specifically for something which works with Preview 5:
* [Testing ScottGu: Alternate View Engines with ASP.NET MVC (NVelocity)](http://www.chadmyers.com/Blog/archive/2007/11/28/testing-scottgu-alternate-view-engines-with-asp.net-mvc-nvelocity.aspx)
Otherwise I'll start writing one :) | Exponentiation by squaring.
```
int ipow(int base, int exp)
{
int result = 1;
for (;;)
{
if (exp & 1)
result *= base;
exp >>= 1;
if (!exp)
break;
base *= base;
}
return result;
}
```
This is the standard method for doing modular exponentiation for huge numbers in asymmetric cryptography. |
101,461 | <p>Most languages (Ruby included) allow number literals to be written in at least three bases: decimal, octal and hexadecimal. Numbers in decimal base is the usual thing and are written as (most) people naturally write numbers, 96 is written as <code>96</code>. Numbers prefixed by a zero are usually interpreted as octal based: 96 would be written as <code>0140</code>. Hexadecimal based numbers are usually prefixed by <code>0x</code>: 96 would be written as <code>0x60</code>.</p>
<p>The question is: can I write numbers as binary literals in Ruby? How?</p>
| [
{
"answer_id": 101479,
"author": "Thelema",
"author_id": 12874,
"author_profile": "https://Stackoverflow.com/users/12874",
"pm_score": 3,
"selected": false,
"text": "<p>From <a href=\"http://docs.huihoo.com/ruby/ruby-man-1.4/syntax.html#numeric\" rel=\"noreferrer\">this manual</a></p>\n\n<pre><code>0b01011\n</code></pre>\n\n<p>binary integer </p>\n"
},
{
"answer_id": 101482,
"author": "Purfideas",
"author_id": 4615,
"author_profile": "https://Stackoverflow.com/users/4615",
"pm_score": 7,
"selected": true,
"text": "<p>use 0b prefix</p>\n\n<pre><code>>> 0b100\n=> 4\n</code></pre>\n"
},
{
"answer_id": 102350,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 4,
"selected": false,
"text": "<p>For literals, the prefix is 0b. So </p>\n\n<pre><code>0b100 #=> 4\n</code></pre>\n\n<p>Be aware that the same exists to format strings:</p>\n\n<pre><code>\"%b\" % 4 #=> \"100\"\n</code></pre>\n"
},
{
"answer_id": 1267871,
"author": "Rob",
"author_id": 386102,
"author_profile": "https://Stackoverflow.com/users/386102",
"pm_score": 4,
"selected": false,
"text": "<p>and you can do:</p>\n\n<pre><code>>> easy_to_read_binary = 0b1110_0000_0000_0000\n=> 57344\n>> easy_to_read_binary.to_s(10)\n=> \"57344\"\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17801/"
]
| Most languages (Ruby included) allow number literals to be written in at least three bases: decimal, octal and hexadecimal. Numbers in decimal base is the usual thing and are written as (most) people naturally write numbers, 96 is written as `96`. Numbers prefixed by a zero are usually interpreted as octal based: 96 would be written as `0140`. Hexadecimal based numbers are usually prefixed by `0x`: 96 would be written as `0x60`.
The question is: can I write numbers as binary literals in Ruby? How? | use 0b prefix
```
>> 0b100
=> 4
``` |
101,463 | <p>I know how to change the schema of a table in SQL server 2005:</p>
<pre><code>ALTER SCHEMA NewSchama TRANSFER dbo.Table1
</code></pre>
<p>But how can i check and/or alter stored procedures that use the old schema name?</p>
<p>Sorry: I mean:
There are stored procedures that have the old schema name of the table in the sql of the stored procedure... How can i edit all the stored procedures that have the dbo.Table1 in the body of the procedure...</p>
| [
{
"answer_id": 101509,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 1,
"selected": true,
"text": "<p>Get a list of dependent objects by right-clicking on the table before you change the schema and then look at what is dependent on the table, make a list and then change those. There is, however, always a possibility that you'll miss something because it is possible to break the dependencies SQL server tracks.</p>\n\n<p>But the best way would be to script the database out into a file and then do a search for the table name, make a list of all of the sprocs where it needs to be changed and then add those to the script to change the schema of the table. </p>\n"
},
{
"answer_id": 102426,
"author": "CJM",
"author_id": 6898,
"author_profile": "https://Stackoverflow.com/users/6898",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li>Use Tasks>Generate Scripts in SSMS to provide a series of Create Proc scripts.</li>\n<li>Use Find & Replace (<kbd>Alt</kbd> - <kbd>H</kbd>) to change 'Create ' to 'Alter '</li>\n<li>Use <kbd>F</kbd> & <kbd>R</kbd> to change 'dbo.Table1' to 'dbo.Table2'</li>\n<li>Then Execute (<kbd>F5</kbd>) to modify all the affected SPs.</li>\n</ul>\n\n<p>Simple but effective.</p>\n"
},
{
"answer_id": 2388174,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>DECLARE @SearchObject VARCHAR(100)</p>\n\n<p>SET @SearchObject = 'searchable_table_name' -- change 'searchable_table_name' to the table name what you want to search</p>\n\n<p>SELECT sc.name [Search Object], so.name [Container Object],<br>\nCASE so.xtype\nWHEN 'U' THEN 'Table'\nWHEN 'P' THEN 'Stored Procedure'\nWHEN 'F' THEN 'User Defined Function'\nELSE 'Other' \nEND\nas [Container Object Type]</p>\n\n<p>FROM sysobjects so </p>\n\n<p>INNER JOIN syscolumns sc ON so.id = sc.id </p>\n\n<p>WHERE sc.name LIKE '%' + @SearchObject + '%' AND so.xtype IN ('U','P','F') -- U : Table , P : Stored Procedure, F: User defined functions(udf)</p>\n\n<p>ORDER BY [Container Object] ASC</p>\n\n<p>-- Display the stored procedures that contain the table name requested.</p>\n\n<p>Select text From syscomments Where text like '%from ' + @SearchObject + '%'</p>\n\n<p>(Select id From sysobjects Where type='P' and name = '') </p>\n\n<p>-- Display the content of a specific stored procedure (found from above)</p>\n\n<p>--Exec sp_helptext 'DeleteAssetByID'</p>\n"
},
{
"answer_id": 45588910,
"author": "Luqman Cheema",
"author_id": 4411751,
"author_profile": "https://Stackoverflow.com/users/4411751",
"pm_score": 0,
"selected": false,
"text": "<p>For example I have created a table Reports, by default dbo schema will be assigned to it, now if I want to change the schema of Reports table, firstly, I will create new schema named Reporting:</p>\n\n<pre><code>CREATE SCHEMA Reporting\n</code></pre>\n\n<p>then I will execute below script to change the schema of Reports table from dbo to Reporting:</p>\n\n<pre><code>ALTER SCHEMA Reporting TRANSFER dbo.Reports \n</code></pre>\n\n<p>OR for better understanding: </p>\n\n<pre><code>ALTER SCHEMA 'newSchema' TRANSFER 'oldSchema'.'table'\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13262/"
]
| I know how to change the schema of a table in SQL server 2005:
```
ALTER SCHEMA NewSchama TRANSFER dbo.Table1
```
But how can i check and/or alter stored procedures that use the old schema name?
Sorry: I mean:
There are stored procedures that have the old schema name of the table in the sql of the stored procedure... How can i edit all the stored procedures that have the dbo.Table1 in the body of the procedure... | Get a list of dependent objects by right-clicking on the table before you change the schema and then look at what is dependent on the table, make a list and then change those. There is, however, always a possibility that you'll miss something because it is possible to break the dependencies SQL server tracks.
But the best way would be to script the database out into a file and then do a search for the table name, make a list of all of the sprocs where it needs to be changed and then add those to the script to change the schema of the table. |
101,470 | <p>Does anybody know if there is a feasible way on Windows XP to programmatically create and configure a user account so that after logging in from the console (no terminal services) a specific app is launched and the user is "locked" to that app ?</p>
<p>The user should be prevented from doing anything else with the system (e.g.: no ctrl+alt+canc, no ctrl+shift+esc, no win+e, no nothing).</p>
<p>As an added optional bonus the user should be logged off when the launched app is closed and/or crashes.</p>
<p>Any existing free tool, language or any mixture of them that gets the job done would be fine (batch, VB-script, C, C++, whatever)</p>
| [
{
"answer_id": 104220,
"author": "kervin",
"author_id": 16549,
"author_profile": "https://Stackoverflow.com/users/16549",
"pm_score": 0,
"selected": false,
"text": "<p>I guess you're building a windows kiosk?</p>\n\n<p>Here's some background in replacing the windows login shell - <a href=\"http://blogs.msdn.com/embedded/archive/2005/03/30/403999.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/embedded/archive/2005/03/30/403999.aspx</a></p>\n\n<p>The above link talks about using IE as the replacement, but any program can be used.</p>\n\n<p>Also check out Windows Steady State - <a href=\"http://www.microsoft.com/windows/products/winfamily/sharedaccess/default.mspx\" rel=\"nofollow noreferrer\">http://www.microsoft.com/windows/products/winfamily/sharedaccess/default.mspx</a></p>\n"
},
{
"answer_id": 483553,
"author": "Chris Becke",
"author_id": 27491,
"author_profile": "https://Stackoverflow.com/users/27491",
"pm_score": 2,
"selected": false,
"text": "<p>SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\WinLogon has two values\nUserInit points to the application that is executed upon successful logon. The default app there, userinit.exe processes domain logon scripts (if any) and then launches the specified Shell= application.</p>\n\n<p>By creating or replacing those entries in HKEY_CURRENT_USER or in a HKEY_USERS hive you can replace the shell for a specific user.</p>\n\n<p>Once you ahve your own shell in place, you have very little to worry about, unless the \"kiosk user\" has access to a keyboard and can press ctrl-alt-del. This seems to be hardcoded to launch taskmgr.exe - rather than replacing the exe, you can set the following registry key</p>\n\n<pre><code>[SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\taskmgr.exe]\nDebugger=\"A path to an exe file that will be run instead of taskmgr.exe\"\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18780/"
]
| Does anybody know if there is a feasible way on Windows XP to programmatically create and configure a user account so that after logging in from the console (no terminal services) a specific app is launched and the user is "locked" to that app ?
The user should be prevented from doing anything else with the system (e.g.: no ctrl+alt+canc, no ctrl+shift+esc, no win+e, no nothing).
As an added optional bonus the user should be logged off when the launched app is closed and/or crashes.
Any existing free tool, language or any mixture of them that gets the job done would be fine (batch, VB-script, C, C++, whatever) | SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon has two values
UserInit points to the application that is executed upon successful logon. The default app there, userinit.exe processes domain logon scripts (if any) and then launches the specified Shell= application.
By creating or replacing those entries in HKEY\_CURRENT\_USER or in a HKEY\_USERS hive you can replace the shell for a specific user.
Once you ahve your own shell in place, you have very little to worry about, unless the "kiosk user" has access to a keyboard and can press ctrl-alt-del. This seems to be hardcoded to launch taskmgr.exe - rather than replacing the exe, you can set the following registry key
```
[SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\taskmgr.exe]
Debugger="A path to an exe file that will be run instead of taskmgr.exe"
``` |
101,487 | <p>I have some code which collects points (consed integers) from a loop which looks something like this:</p>
<pre><code>(loop
for x from 1 to 100
for y from 100 downto 1
collect `(,x . ,y))
</code></pre>
<p>My question is, is it correct to use <code>`(,x . ,y)</code> in this situation?</p>
<p>Edit: This sample is not about generating a table of 100x100 items, the code here just illustrate the use of two loop variables and the consing of their values. I have edited the loop to make this clear. The actual loop I use depends on several other functions (and is part of one itself) so it made more sense to replace the calls with literal integers and to pull the loop out of the function.</p>
| [
{
"answer_id": 101503,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 1,
"selected": false,
"text": "<p>Why not just</p>\n\n<pre><code>(cons x y)\n</code></pre>\n\n<p>By the way, I tried to run your code in CLISP and it didn't work as expected. Since I'm not a big fan of the loop macro here's how you might accomplish the same thing recursively:</p>\n\n<pre><code>(defun genint (stop)\n (if (= stop 1) '(1)\n (append (genint (- stop 1)) (list stop))))\n\n(defun genpairs (x y)\n (let ((row (mapcar #'(lambda (y)\n (cons x y))\n (genint y))))\n (if (= x 0) row\n (append (genpairs (- x 1) y)\n row))))\n\n(genpairs 100 100)\n</code></pre>\n"
},
{
"answer_id": 101504,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 4,
"selected": true,
"text": "<p>It would be much 'better' to just do (cons x y). </p>\n\n<p>But to <strong>answer the question</strong>, there is nothing wrong with doing that :) (except making it a tad slower).</p>\n"
},
{
"answer_id": 101641,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 3,
"selected": false,
"text": "<p>I think the answer here is resource utilization (following from <a href=\"https://stackoverflow.com/questions/101487/is-it-correct-to-use-the-backtick-comma-idiom-inside-a-loop#101504\">This post</a>)</p>\n\n<p>for example in clisp:</p>\n\n<pre><code>[1]> (time\n (progn\n (loop\n for x from 1 to 100000\n for y from 1 to 100000 do\n collect (cons x y))\n ()))\nWARNING: LOOP: missing forms after DO: permitted by CLtL2, forbidden by ANSI\n CL.\nReal time: 0.469 sec.\nRun time: 0.468 sec.\nSpace: 1609084 Bytes\nGC: 1, GC time: 0.015 sec.\nNIL\n[2]> (time\n (progn\n (loop\n for x from 1 to 100000\n for y from 1 to 100000 do\n collect `(,x . ,y)) ;`\n ()))\nWARNING: LOOP: missing forms after DO: permitted by CLtL2, forbidden by ANSI\n CL.\nReal time: 0.969 sec.\nRun time: 0.969 sec.\nSpace: 10409084 Bytes\nGC: 15, GC time: 0.172 sec.\nNIL\n[3]>\n</code></pre>\n"
},
{
"answer_id": 103205,
"author": "simon",
"author_id": 14143,
"author_profile": "https://Stackoverflow.com/users/14143",
"pm_score": 2,
"selected": false,
"text": "<p>dsm: there are a couple of odd things about your code <a href=\"https://stackoverflow.com/questions/101487/is-it-correct-to-use-the-backtick-comma-idiom-inside-a-loop#101641\">here</a>. Note that</p>\n\n<pre><code>(loop for x from 1 to 100000\n for y from 1 to 100000 do\n collect `(,x . ,y))\n</code></pre>\n\n<p>is equivalent to:</p>\n\n<pre><code>(loop for x from 1 to 100\n collecting (cons x x))\n</code></pre>\n\n<p>which probably isn't quite what you intended. Note three things: First, the way you've written it, x and y have the same role. You probably meant to nest loops. Second, your do after the y is incorrect, as there is not lisp form following it. Thirdly, you're right that you could use the backtick approach here but it makes your code harder to read and not idiomatic for no gain, so best avoided.</p>\n\n<p>Guessing at what you actually intended, you might do something like this (using loop):</p>\n\n<pre><code>(loop for x from 1 to 100 appending \n (loop for y from 1 to 100 collecting (cons x y)))\n</code></pre>\n\n<p>If you don't like the loop macro (like Kyle), you can use another iteration construct like</p>\n\n<pre><code>(let ((list nil)) \n (dotimes (n 100) ;; 0 based count, you will have to add 1 to get 1 .. 100\n (dotimes (m 100) \n (push (cons n m) list)))\n (nreverse list))\n</code></pre>\n\n<p>If you find yourself doing this sort of thing a lot, you should probably write a more general function for crossing lists, then pass it these lists of integers </p>\n\n<p>If you really have a problem with iteration, not just loop, you can do this sort of thing recursively (but note, this isn't scheme, your implementation may not guaranteed TCO). The function \"genint\" shown by Kyle <a href=\"https://stackoverflow.com/questions/101487/is-it-correct-to-use-the-backtick-comma-idiom-inside-a-loop#101503\">here</a> is a variant of a common (but not standard) function iota. However, appending to the list is a bad idea. An equivalent implementation like this:</p>\n\n<pre><code>(defun iota (n &optional (start 0))\n (let ((end (+ n start)))\n (labels ((next (n)\n (when (< n end) \n (cons n (next (1+ n))))))\n (next start))))\n</code></pre>\n\n<p>should be much more efficient, but still is not a tail call. Note I've set this up for the more usual 0-based, but given you an optional parameter to start at 1 or any other integer. Of course the above can be written something like:</p>\n\n<pre><code>(defun iota (n &optional (start 0))\n (loop repeat n \n for i from start collecting i))\n</code></pre>\n\n<p>Which has the advantage of not blowing the stack for large arguments. If your implementation supports tail call elimination, you can also avoid the recursion running out of place by doing something like this:</p>\n\n<pre><code>(defun iota (n &optional (start 0))\n (labels ((next (i list)\n (if (>= i (+ n start))\n nil\n (next (1+ i) (cons i list)))))\n (next start nil)))\n</code></pre>\n\n<p>Hope that helps! </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7780/"
]
| I have some code which collects points (consed integers) from a loop which looks something like this:
```
(loop
for x from 1 to 100
for y from 100 downto 1
collect `(,x . ,y))
```
My question is, is it correct to use ``(,x . ,y)` in this situation?
Edit: This sample is not about generating a table of 100x100 items, the code here just illustrate the use of two loop variables and the consing of their values. I have edited the loop to make this clear. The actual loop I use depends on several other functions (and is part of one itself) so it made more sense to replace the calls with literal integers and to pull the loop out of the function. | It would be much 'better' to just do (cons x y).
But to **answer the question**, there is nothing wrong with doing that :) (except making it a tad slower). |
101,532 | <p>When I run a Flex application in the debug flash player I get an exception pop up as soon as something unexpected happened. However when a customer uses the application he does not use the debug flash player. In this case he does not get an exception pop up, but he UI is not working.</p>
<p>So for supportability reasons, I would like to catch any exception that can happen anywhere in the Flex UI and present an error message in a Flex internal popup. By using Java I would just encapsulate the whole UI code in a try/catch block, but with MXML applications in Flex I do not know, where I could perform such a general try/catch.</p>
| [
{
"answer_id": 101953,
"author": "Richard Szalay",
"author_id": 3603,
"author_profile": "https://Stackoverflow.com/users/3603",
"pm_score": 7,
"selected": true,
"text": "<p>There is no way to be notified on uncaught exceptions in Flex 3. Adobe are aware of the problem but I don't know if they plan on creating a workaround.</p>\n\n<p>The only solution as it stands is to put try/catch in logical places and make sure you are listening to the ERROR (or FAULT for webservices) event for anything that dispatches them.</p>\n\n<p><strong>Edit:</strong> Furthermore, it's actually impossible to catch an error thrown from an event handler. I have logged a <a href=\"http://bugs.adobe.com/jira/browse/FP-1619\" rel=\"noreferrer\">bug</a> on the Adobe Bug System.</p>\n\n<p><strong>Update 2010-01-12:</strong> Global error handling is now supported in <a href=\"http://labs.adobe.com/technologies/flashplayer10/\" rel=\"noreferrer\">Flash 10.1</a> and <a href=\"http://labs.adobe.com/technologies/air2\" rel=\"noreferrer\">AIR 2.0</a> (both in beta), and is achieved by subscribing the <a href=\"http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/events/UncaughtErrorEvent.html\" rel=\"noreferrer\">UNCAUGHT_ERROR</a> event of <a href=\"http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/display/LoaderInfo.html#uncaughtErrorEvents\" rel=\"noreferrer\">LoaderInfo.uncaughtErrorEvents</a>. The following code is taken from the <a href=\"http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/display/LoaderInfo.html#uncaughtErrorEvents\" rel=\"noreferrer\">code sample on livedocs</a>:</p>\n\n<pre><code>public class UncaughtErrorEventExample extends Sprite\n{\n public function UncaughtErrorEventExample()\n {\n loaderInfo.uncaughtErrorEvents.addEventListener(\n UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);\n }\n\n private function uncaughtErrorHandler(event:UncaughtErrorEvent):void\n {\n if (event.error is Error)\n {\n var error:Error = event.error as Error;\n // do something with the error\n }\n else if (event.error is ErrorEvent)\n {\n var errorEvent:ErrorEvent = event.error as ErrorEvent;\n // do something with the error\n }\n else\n {\n // a non-Error, non-ErrorEvent type was thrown and uncaught\n }\n }\n</code></pre>\n"
},
{
"answer_id": 262166,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>There is a bug/feature request for this in the Adobe bug management system. Vote for it if it's important to you.</p>\n\n<p><a href=\"http://bugs.adobe.com/jira/browse/FP-444\" rel=\"noreferrer\">http://bugs.adobe.com/jira/browse/FP-444</a></p>\n"
},
{
"answer_id": 1636859,
"author": "Peter V. Mørch",
"author_id": 345716,
"author_profile": "https://Stackoverflow.com/users/345716",
"pm_score": 2,
"selected": false,
"text": "<p>Note that bug FP-444 (above) links to <a href=\"http://labs.adobe.com/technologies/flashplayer10/features.html#developer\" rel=\"nofollow noreferrer\">http://labs.adobe.com/technologies/flashplayer10/features.html#developer</a> that since Oct 2009 shows that this will be possible as of 10.1, which currently, Oct 28, 2009 is still unreleased - so I guess we'll see if that is true when it gets released</p>\n"
},
{
"answer_id": 2500361,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>It works in Flex 3.3.</p>\n\n<pre><code> if(loaderInfo.hasOwnProperty(\"uncaughtErrorEvents\")){\n IEventDispatcher(loaderInfo[\"uncaughtErrorEvents\"]).addEventListener(\"uncaughtError\", uncaughtErrorHandler);\n }\n</code></pre>\n"
},
{
"answer_id": 3020206,
"author": "aaaidan",
"author_id": 26331,
"author_profile": "https://Stackoverflow.com/users/26331",
"pm_score": 2,
"selected": false,
"text": "<p>Alternative to accepted answer, using try-catch. Slower, but more straightforward to read, I think.</p>\n\n<pre><code>try {\n loaderInfo.uncaughtErrorEvents.addEventListener(\"uncaughtError\", onUncaughtError);\n} catch (e:ReferenceError) {\n var spl:Array = Capabilities.version.split(\" \");\n var verSpl:Array = spl[1].split(\",\");\n\n if (int(verSpl[0]) >= 10 &&\n int(verSpl[1]) >= 1) {\n // This version is 10.1 or greater - we should have been able to listen for uncaught errors...\n d.warn(\"Unable to listen for uncaught error events, despite flash version: \" + Capabilities.version);\n }\n}\n</code></pre>\n\n<p>Of course, you'll need to be using an up-to-date 10.1 playerglobal.swc in order to compile this code successfully:\n<a href=\"http://labs.adobe.com/downloads/flashplayer10.html\" rel=\"nofollow noreferrer\">http://labs.adobe.com/downloads/flashplayer10.html</a></p>\n"
},
{
"answer_id": 4994963,
"author": "neave",
"author_id": 581853,
"author_profile": "https://Stackoverflow.com/users/581853",
"pm_score": 2,
"selected": false,
"text": "<p>I attached the event listener to the 'root', which worked for me:</p>\n\n<pre><code>sprite.root.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onUncaughtError);\n</code></pre>\n\n<p>In the debug Flash Player this will still error, but in the non-debug version the error will appear in Flash Player's dialog box - and then the handler will respond. To stop the dialog box from appearing, add:</p>\n\n<pre><code>event.preventDefault();\n</code></pre>\n\n<p>so:</p>\n\n<pre><code> private function onUncaughtError(event:UncaughtErrorEvent):void\n {\n event.preventDefault();\n // do something with this error\n }\n</code></pre>\n\n<p>I was using this in AIR, but I assume it works for standard AS3 projects too.</p>\n"
},
{
"answer_id": 5899108,
"author": "Rose",
"author_id": 466884,
"author_profile": "https://Stackoverflow.com/users/466884",
"pm_score": 2,
"selected": false,
"text": "<p>I'm using flex 4.\nI tried <code>loaderInfo.UncaughtErrorEvents,</code> but loaderInfo was not initialized so it gave me null reference error. Then i tried <code>root.loaderInfo.UncaughtErrorEvents</code> and the same story.\nI tried <code>sprite.root.UncaughtErrorEvents</code>, but there was no sprite object, I created one, but it didn't work. Finally I tried </p>\n\n<p>systemManager.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR,globalUnCaughtErrorHandler.hanleUnCaughtError);</p>\n\n<p>And guess what, it works like magic.\ncheck <a href=\"http://guya.net/blogstuff/geh/projects/GlobalErrFlex4.fxp\" rel=\"nofollow\">this</a></p>\n"
},
{
"answer_id": 6597046,
"author": "Jefferson",
"author_id": 831644,
"author_profile": "https://Stackoverflow.com/users/831644",
"pm_score": 2,
"selected": false,
"text": "<p>It works in Flex 3.5 and flash player 10:</p>\n<pre><code> <?xml version="1.0" encoding="utf-8"?>\n<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" addedToStage="application1_addedToStageHandler(event)">\n <mx:Script>\n <![CDATA[\n import mx.events.FlexEvent;\n \n protected function application1_addedToStageHandler(event:Event):void{ \n if(loaderInfo.hasOwnProperty("uncaughtErrorEvents")){\n IEventDispatcher(loaderInfo["uncaughtErrorEvents"]).addEventListener("uncaughtError", uncaughtErrorHandler);\n }\n \n sdk.text = "Flex " + mx_internal::VERSION;\n }\n \n private function uncaughtErrorHandler(e:*):void{\n e.preventDefault();\n \n var s:String;\n\n if (e.error is Error)\n {\n var error:Error = e.error as Error;\n s = "Uncaught Error: " + error.errorID + ", " + error.name + ", " + error.message;\n }\n else\n {\n var errorEvent:ErrorEvent = e.error as ErrorEvent;\n s = "Uncaught ErrorEvent: " + errorEvent.text;\n }\n \n msg.text = s;\n }\n \n private function unCaught():void\n {\n var foo:String = null;\n trace(foo.length);\n }\n ]]>\n </mx:Script>\n <mx:VBox>\n <mx:Label id="sdk" fontSize="18"/>\n <mx:Button y="50" label="UnCaught Error" click="unCaught();" />\n <mx:TextArea id="msg" width="180" height="70"/>\n </mx:VBox>\n</mx:Application>\n</code></pre>\n<p>Thanks</p>\n"
},
{
"answer_id": 28863039,
"author": "Pablo",
"author_id": 3242467,
"author_profile": "https://Stackoverflow.com/users/3242467",
"pm_score": 0,
"selected": false,
"text": "<p>Now you can, using loader info:</p>\n<p><a href=\"http://www.adobe.com/devnet/flex/articles/global-exception-handling.html\" rel=\"nofollow noreferrer\">http://www.adobe.com/devnet/flex/articles/global-exception-handling.html</a></p>\n<p>Checkout:</p>\n<pre><code>loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onUncaughtError);\n\nprivate function onUncaughtError(e:UncaughtErrorEvent):void\n{\n // Do something with your error.\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7524/"
]
| When I run a Flex application in the debug flash player I get an exception pop up as soon as something unexpected happened. However when a customer uses the application he does not use the debug flash player. In this case he does not get an exception pop up, but he UI is not working.
So for supportability reasons, I would like to catch any exception that can happen anywhere in the Flex UI and present an error message in a Flex internal popup. By using Java I would just encapsulate the whole UI code in a try/catch block, but with MXML applications in Flex I do not know, where I could perform such a general try/catch. | There is no way to be notified on uncaught exceptions in Flex 3. Adobe are aware of the problem but I don't know if they plan on creating a workaround.
The only solution as it stands is to put try/catch in logical places and make sure you are listening to the ERROR (or FAULT for webservices) event for anything that dispatches them.
**Edit:** Furthermore, it's actually impossible to catch an error thrown from an event handler. I have logged a [bug](http://bugs.adobe.com/jira/browse/FP-1619) on the Adobe Bug System.
**Update 2010-01-12:** Global error handling is now supported in [Flash 10.1](http://labs.adobe.com/technologies/flashplayer10/) and [AIR 2.0](http://labs.adobe.com/technologies/air2) (both in beta), and is achieved by subscribing the [UNCAUGHT\_ERROR](http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/events/UncaughtErrorEvent.html) event of [LoaderInfo.uncaughtErrorEvents](http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/display/LoaderInfo.html#uncaughtErrorEvents). The following code is taken from the [code sample on livedocs](http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/display/LoaderInfo.html#uncaughtErrorEvents):
```
public class UncaughtErrorEventExample extends Sprite
{
public function UncaughtErrorEventExample()
{
loaderInfo.uncaughtErrorEvents.addEventListener(
UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);
}
private function uncaughtErrorHandler(event:UncaughtErrorEvent):void
{
if (event.error is Error)
{
var error:Error = event.error as Error;
// do something with the error
}
else if (event.error is ErrorEvent)
{
var errorEvent:ErrorEvent = event.error as ErrorEvent;
// do something with the error
}
else
{
// a non-Error, non-ErrorEvent type was thrown and uncaught
}
}
``` |
101,533 | <p>I have created a C# class file by using a XSD-file as an input. One of my properties look like this:</p>
<pre><code> private System.DateTime timeField;
[System.Xml.Serialization.XmlElementAttribute(DataType="time")]
public System.DateTime Time {
get {
return this.timeField;
}
set {
this.timeField = value;
}
}
</code></pre>
<p>When serialized, the contents of the file now looks like this:</p>
<pre><code><Time>14:04:02.1661975+02:00</Time>
</code></pre>
<p>Is it possible, with XmlAttributes on the property, to have it render without the milliseconds and the GMT-value like this?</p>
<pre><code><Time>14:04:02</Time>
</code></pre>
<p>Is this possible, or do i need to hack together some sort of xsl/xpath-replace-magic after the class has been serialized?</p>
<p>It is not a solution to changing the object to String, because it is used like a DateTime in the rest of the application and allows us to create an xml-representation from an object by using the XmlSerializer.Serialize() method.</p>
<p>The reason I need to remove the extra info from the field is that the receiving system does not conform to the w3c-standards for the time datatype.</p>
| [
{
"answer_id": 101598,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 5,
"selected": true,
"text": "<p>You could create a string property that does the translation to/from your timeField field and put the serialization attribute on that instead the the real DateTime property that the rest of the application uses.</p>\n"
},
{
"answer_id": 101667,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 5,
"selected": false,
"text": "<p>Put [XmlIgnore] on the Time property.</p>\n\n<p>Then add a new property:</p>\n\n<pre><code>[XmlElement(DataType=\"string\",ElementName=\"Time\")]\npublic String TimeString\n{\n get { return this.timeField.ToString(\"yyyy-MM-dd\"); }\n set { this.timeField = DateTime.ParseExact(value, \"yyyy-MM-dd\", CultureInfo.InvariantCulture); }\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2257/"
]
| I have created a C# class file by using a XSD-file as an input. One of my properties look like this:
```
private System.DateTime timeField;
[System.Xml.Serialization.XmlElementAttribute(DataType="time")]
public System.DateTime Time {
get {
return this.timeField;
}
set {
this.timeField = value;
}
}
```
When serialized, the contents of the file now looks like this:
```
<Time>14:04:02.1661975+02:00</Time>
```
Is it possible, with XmlAttributes on the property, to have it render without the milliseconds and the GMT-value like this?
```
<Time>14:04:02</Time>
```
Is this possible, or do i need to hack together some sort of xsl/xpath-replace-magic after the class has been serialized?
It is not a solution to changing the object to String, because it is used like a DateTime in the rest of the application and allows us to create an xml-representation from an object by using the XmlSerializer.Serialize() method.
The reason I need to remove the extra info from the field is that the receiving system does not conform to the w3c-standards for the time datatype. | You could create a string property that does the translation to/from your timeField field and put the serialization attribute on that instead the the real DateTime property that the rest of the application uses. |
101,569 | <p>I need to write a module to detect similar documents. I have read many papers of fingerprints of documents techniques and others, but I do not know how to write code or implement such a solution. The algorithm should work for Chinese, Japanese, English and German language or be language independent. How can I accomplish this?</p>
| [
{
"answer_id": 101605,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 3,
"selected": false,
"text": "<p>You can use or at last study <a href=\"http://docs.python.org/lib/module-difflib.html\" rel=\"noreferrer\" title=\"difflib documentation\">difflib</a> from Python's stdlib to write your code.</p>\n\n<p>It is very flexible, and has algorithms to find differences between lists of strings, and to point these differences. Then you can use the <code>get_close_matches()</code> to find similar words:</p>\n\n<pre><code>>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])\n['apple', 'ape']\n</code></pre>\n\n<p>It is not the solution but maybe it is a start.</p>\n"
},
{
"answer_id": 101623,
"author": "SquareCog",
"author_id": 15962,
"author_profile": "https://Stackoverflow.com/users/15962",
"pm_score": 2,
"selected": false,
"text": "<p>You need to make your question more concrete. If you've already read the fingerprinting papers, you already know the principles at work, so describing common approaches here would not be beneficial. If you haven't, you should also check out papers on \"duplicate detection\" and various web spam detection related papers that have come out of Stanford, Google, Yahoo, and MS in recent years.</p>\n\n<p>Are you having specific problems with coding the described algorithms?</p>\n\n<p>Trouble getting started?</p>\n\n<p>The first thing I'd probably do is separate the tokenization (the process of extracting \"words\" or other sensible sequences) from the duplicate detection logic, so that it is easy to plug in different parsers for different languages and keep the duplicate detection piece the same.</p>\n"
},
{
"answer_id": 101625,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>If you're prepared to index the files that you want to search amongst, Xapian is an excellent engine, and provides Python bindings:</p>\n\n<p><a href=\"http://xapian.org/\" rel=\"nofollow noreferrer\">http://xapian.org/</a></p>\n\n<p><a href=\"http://xapian.org/docs/bindings/python/\" rel=\"nofollow noreferrer\">http://xapian.org/docs/bindings/python/</a></p>\n"
},
{
"answer_id": 101656,
"author": "Jeremiah Peschka",
"author_id": 11780,
"author_profile": "https://Stackoverflow.com/users/11780",
"pm_score": 3,
"selected": false,
"text": "<p>If these are pure text documents, or you have a method to extract the text from the documents, you can use a technique called shingling.</p>\n\n<p>You first compute a unique hash for each document. If these are the same, you are done.</p>\n\n<p>If not, you break each document down into smaller chunks. These are your 'shingles.'</p>\n\n<p>Once you have the shingles, you can then compute identity hashes for each shingle and compare the hashes of the shingles to determine if the documents are actually the same.</p>\n\n<p>The other technique you can use is to generate n-grams of the entire documents and compute the number of similar n-grams in each document and produce a weighted score for each document. Basically an n-gram is splitting a word into smaller chunks. 'apple' would become ' a', ' ap', 'app', 'ppl', 'ple', 'le '. (This is technically a 3-gram) This approach can become quite computationally expensive over a large number of documents or over two very large documents. Of course, common n-grams 'the', ' th, 'th ', etc need to be weighted to score them lower.</p>\n\n<p>I've posted about this on my blog and there are some links in the post to a few other articles on the subject <a href=\"http://facility9.com/2008/09/13/shingling-its-not-just-for-roofers/\" rel=\"noreferrer\">Shingling - it's not just for roofers</a>.</p>\n\n<p>Best of luck!</p>\n"
},
{
"answer_id": 102228,
"author": "Jiayao Yu",
"author_id": 10289,
"author_profile": "https://Stackoverflow.com/users/10289",
"pm_score": 0,
"selected": false,
"text": "<p>If you are trying to detect the documents that are talking about the same topic, you could try collecting the most frequently used words, throw away the <a href=\"http://en.wikipedia.org/wiki/Stop_words\" rel=\"nofollow noreferrer\">stop words</a> . Documents that have a similar distribution of the most frequently used words are probably talking about similar things. You may need to do some <a href=\"http://en.wikipedia.org/wiki/Stemming\" rel=\"nofollow noreferrer\">stemming</a> and extend the concept to <a href=\"http://en.wikipedia.org/wiki/N-gram\" rel=\"nofollow noreferrer\">n-grams</a> if you want higher accuracy. For more advanced techniques, look into machine learning.</p>\n"
},
{
"answer_id": 102807,
"author": "Ants Aasma",
"author_id": 107366,
"author_profile": "https://Stackoverflow.com/users/107366",
"pm_score": 2,
"selected": false,
"text": "<p>There is a rather good <a href=\"http://video.google.com/videoplay?docid=228784531481853811&ei=c73TSP-XF6bU2gKO2aSAAQ&q=techtalks+neuralnetworks&vt=lf\" rel=\"nofollow noreferrer\">talk on neural networks</a> on Google Techtalks that talks about using layered Boltzmann machines to generate feature vectors for documents that can then be used to measure document distance. The main issue is the requirement to have a large sample document set to train the network to discover relevant features.</p>\n"
},
{
"answer_id": 108649,
"author": "Jon Mills",
"author_id": 7486,
"author_profile": "https://Stackoverflow.com/users/7486",
"pm_score": 0,
"selected": false,
"text": "<p>I think Jeremy has hit the nail on the head - if you just want to detect if files are different, a hash algorithm like MD5 or SHA1 is a good way to go.</p>\n\n<p>Linus Torvalds' Git source control software uses SHA1 hashing in just this way - to check when files have been modified.</p>\n"
},
{
"answer_id": 108974,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 4,
"selected": false,
"text": "<p>Bayesian filters have exactly this purpose. That's the techno you'll find in most tools that identify spam.</p>\n\n<p>Example, to detect a language (from <a href=\"http://sebsauvage.net/python/snyppets/#bayesian\" rel=\"noreferrer\">http://sebsauvage.net/python/snyppets/#bayesian</a>) :</p>\n\n<pre><code>from reverend.thomas import Bayes\nguesser = Bayes()\nguesser.train('french','La souris est rentrée dans son trou.')\nguesser.train('english','my tailor is rich.')\nguesser.train('french','Je ne sais pas si je viendrai demain.')\nguesser.train('english','I do not plan to update my website soon.')\n\n>>> print guesser.guess('Jumping out of cliffs it not a good idea.')\n[('english', 0.99990000000000001), ('french', 9.9999999999988987e-005)]\n\n>>> print guesser.guess('Demain il fera très probablement chaud.')\n[('french', 0.99990000000000001), ('english', 9.9999999999988987e-005)]\n</code></pre>\n\n<p>But it works to detect any type you will train it for : technical text, songs, jokes, etc. As long as you can provide enought material to let the tool learn what does you document looks like.</p>\n"
},
{
"answer_id": 448554,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Similarity can be found easily without classification. Try this O(n2) but works fine.</p>\n\n<pre><code>def jaccard_similarity(doc1, doc2):\n a = sets(doc1.split())\n b = sets(doc2.split())\n similarity = float(len(a.intersection(b))*1.0/len(a.union(b))) #similarity belongs to [0,1] 1 means its exact replica.\n return similarity\n</code></pre>\n"
},
{
"answer_id": 2190011,
"author": "user225145",
"author_id": 225145,
"author_profile": "https://Stackoverflow.com/users/225145",
"pm_score": 0,
"selected": false,
"text": "<p>You might want to look into the DustBuster algorithm as outlined in <a href=\"http://portal.acm.org/citation.cfm?id=1135992\" rel=\"nofollow noreferrer\">this paper</a>.</p>\n\n<p>From the paper, they're able to detect duplicate pages without even examining the page contents. Of course examining the contents increases the efficacy, but using raw server logs is adequate for the method to detect duplicate pages.</p>\n\n<p>Similar to the recommendation of using MD5 or SHA1 hashes, the DustBuster method largely relies on comparing file size as it primary signal. As simple as it sounds, it's rather effective for an initial first pass.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17451/"
]
| I need to write a module to detect similar documents. I have read many papers of fingerprints of documents techniques and others, but I do not know how to write code or implement such a solution. The algorithm should work for Chinese, Japanese, English and German language or be language independent. How can I accomplish this? | Bayesian filters have exactly this purpose. That's the techno you'll find in most tools that identify spam.
Example, to detect a language (from <http://sebsauvage.net/python/snyppets/#bayesian>) :
```
from reverend.thomas import Bayes
guesser = Bayes()
guesser.train('french','La souris est rentrée dans son trou.')
guesser.train('english','my tailor is rich.')
guesser.train('french','Je ne sais pas si je viendrai demain.')
guesser.train('english','I do not plan to update my website soon.')
>>> print guesser.guess('Jumping out of cliffs it not a good idea.')
[('english', 0.99990000000000001), ('french', 9.9999999999988987e-005)]
>>> print guesser.guess('Demain il fera très probablement chaud.')
[('french', 0.99990000000000001), ('english', 9.9999999999988987e-005)]
```
But it works to detect any type you will train it for : technical text, songs, jokes, etc. As long as you can provide enought material to let the tool learn what does you document looks like. |
101,574 | <p>I want a list of hyperlinks on a basic html page, which point to files on our corporate intranet.</p>
<p>When a user clicks the link, I want the file to open.
They are excel spreadsheets, and this is an intranet environment, so I can count on everyone having Excel installed.</p>
<p>I've tried two things:</p>
<ol>
<li>The obvious and simple thing:</li>
</ol>
<pre class="lang-html prettyprint-override"><code><a href="file://server/directory/file.xlsx">Click me!</a>
</code></pre>
<ol start="2">
<li>A <a href="/questions/tagged/vbscript" class="post-tag" title="show questions tagged 'vbscript'" rel="tag">vbscript</a> option that I found in a Google search:</li>
</ol>
<pre class="lang-html prettyprint-override"><code><HTML>
<HEAD>
<SCRIPT LANGUAGE=VBScript>
Dim objExcel
Sub Btn1_onclick()
call OpenWorkbook("\\server\directory\file.xlsx")
End Sub
Sub OpenWorkbook(strLocation)
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = true
objExcel.Workbooks.Open strLocation
objExcel.UserControl = true
End Sub
</SCRIPT>
<TITLE>Launch Excel</Title>
</HEAD>
<BODY>
<INPUT TYPE=BUTTON NAME=Btn1 VALUE="Open Excel File">
</BODY>
</HTML>
</code></pre>
<p>I know this is a very basic question, but I would appreciate any help I can get.</p>
<p><strong><em>Edit: Any suggestions that work in both IE and Firefox?</em></strong></p>
| [
{
"answer_id": 101586,
"author": "diciu",
"author_id": 2811,
"author_profile": "https://Stackoverflow.com/users/2811",
"pm_score": 2,
"selected": false,
"text": "<p><code><a href=\"file://server/directory/file.xlsx\" target=\"_blank\"></code> if I remember correctly.</p>\n"
},
{
"answer_id": 101590,
"author": "typemismatch",
"author_id": 13714,
"author_profile": "https://Stackoverflow.com/users/13714",
"pm_score": -1,
"selected": false,
"text": "<p>Your first idea used to be the way but I've also noticed issues doing this using Firefox, try a straight http:// to the file - href='<a href=\"http://server/directory/file.xlsx\" rel=\"nofollow noreferrer\">http://server/directory/file.xlsx</a>'</p>\n"
},
{
"answer_id": 101592,
"author": "Jan Hančič",
"author_id": 185527,
"author_profile": "https://Stackoverflow.com/users/185527",
"pm_score": 0,
"selected": false,
"text": "<p>A simple link to the file is the obvious solution here. You just have to make shure that the link is valid and that it really points to a file ...</p>\n"
},
{
"answer_id": 101606,
"author": "Turnkey",
"author_id": 13144,
"author_profile": "https://Stackoverflow.com/users/13144",
"pm_score": 1,
"selected": false,
"text": "<p>If the file share is not open to everybody you will need to serve it up in the background from the file system via the web server.</p>\n\n<p>You can use something like <a href=\"https://web.archive.org/web/20081224053449/http://snippets.dzone.com/posts/show/3510\" rel=\"nofollow noreferrer\">this \"ASP.Net Serve File For Download\" example</a> (archived copy of <a href=\"http://snippets.dzone.com/posts/show/3510\" rel=\"nofollow noreferrer\">2</a>).</p>\n"
},
{
"answer_id": 101608,
"author": "Sam Reynolds",
"author_id": 9192,
"author_profile": "https://Stackoverflow.com/users/9192",
"pm_score": 1,
"selected": false,
"text": "<p>You may need an extra \"/\"</p>\n\n<pre><code><a href=\"file:///server/directory/file.xlsx\">Click me!</a>\n</code></pre>\n"
},
{
"answer_id": 101609,
"author": "Ken Ray",
"author_id": 12253,
"author_profile": "https://Stackoverflow.com/users/12253",
"pm_score": 1,
"selected": false,
"text": "<p>If your web server is IIS, you need to make sure that the new Office 2007 (I see the xlsx suffix) mime types are added to the list of mime types in IIS, otherwise it will refuse to serve the unknown file type.</p>\n\n<p>Here's one link to tell you how:</p>\n\n<p><a href=\"http://www.jameskovacs.com/blog/ConfiguringIIS6ToServeOffice2007FileFormats.aspx\" rel=\"nofollow noreferrer\">Configuring IIS 6 for Office 2007</a></p>\n"
},
{
"answer_id": 101660,
"author": "David Heggie",
"author_id": 4309,
"author_profile": "https://Stackoverflow.com/users/4309",
"pm_score": 5,
"selected": true,
"text": "<p>Try formatting the link like this (looks hellish, but it works in Firefox 3 under Vista for me) :</p>\n\n<pre><code><a href=\"file://///SERVER/directory/file.ext\">file.ext</a>\n</code></pre>\n"
},
{
"answer_id": 101714,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 0,
"selected": false,
"text": "<p>You're going to have to rely on each individual's machine having the correct file associations. If you try and open the application from JavaScript/VBScript in a web page, the spawned application is either going to itself be sandboxed (meaning decreased permissions) or there are going to be lots of security prompts.</p>\n\n<p>My suggestion is to look to SharePoint server for this one. This is something that we know they do and you can edit in place, but the question becomes how they manage to pull that off. My guess is direct integration with Office. Either way, this isn't something that the Internet is designed to do, because I'm assuming you want them to edit the original document and not simply create their own copy (which is what the default behavior of <code>file://</code> would be.</p>\n\n<p>So depending on you options, it might be possible to create a client side application that gets installed on all your client machines and then responds to a particular file handler that says go open this application on the file server. Then it wouldn't really matter who was doing it since all browsers would simply hand off the request to you. You would have to create your own handler like <code>fileserver://</code>.</p>\n"
},
{
"answer_id": 70994151,
"author": "Roger Dueck",
"author_id": 1488762,
"author_profile": "https://Stackoverflow.com/users/1488762",
"pm_score": 0,
"selected": false,
"text": "<p>This works in Firefox 96 in macOS 12, and should work in other browsers and in Windows too:</p>\n<pre><code><a href="smb://server/location">open file</a>\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
]
| I want a list of hyperlinks on a basic html page, which point to files on our corporate intranet.
When a user clicks the link, I want the file to open.
They are excel spreadsheets, and this is an intranet environment, so I can count on everyone having Excel installed.
I've tried two things:
1. The obvious and simple thing:
```html
<a href="file://server/directory/file.xlsx">Click me!</a>
```
2. A [vbscript](/questions/tagged/vbscript "show questions tagged 'vbscript'") option that I found in a Google search:
```html
<HTML>
<HEAD>
<SCRIPT LANGUAGE=VBScript>
Dim objExcel
Sub Btn1_onclick()
call OpenWorkbook("\\server\directory\file.xlsx")
End Sub
Sub OpenWorkbook(strLocation)
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = true
objExcel.Workbooks.Open strLocation
objExcel.UserControl = true
End Sub
</SCRIPT>
<TITLE>Launch Excel</Title>
</HEAD>
<BODY>
<INPUT TYPE=BUTTON NAME=Btn1 VALUE="Open Excel File">
</BODY>
</HTML>
```
I know this is a very basic question, but I would appreciate any help I can get.
***Edit: Any suggestions that work in both IE and Firefox?*** | Try formatting the link like this (looks hellish, but it works in Firefox 3 under Vista for me) :
```
<a href="file://///SERVER/directory/file.ext">file.ext</a>
``` |
101,597 | <p>Let's say I have the following HTML:</p>
<pre><code><table id="foo">
<th class="sortasc">Header</th>
</table>
<table id="bar">
<th class="sortasc">Header</th>
</table>
</code></pre>
<p>I know that I can do the following to get all of the <strong>th</strong> elements that have class="sortasc"</p>
<pre><code>$$('th.sortasc').each()
</code></pre>
<p>However that gives me the <strong>th</strong> elements from both table <em>foo</em> and table <em>bar</em>.</p>
<p>How can I tell it to give me just the th elements from table <em>foo</em>?</p>
| [
{
"answer_id": 101611,
"author": "Fuzzy76",
"author_id": 15932,
"author_profile": "https://Stackoverflow.com/users/15932",
"pm_score": 4,
"selected": true,
"text": "<p>table#foo th.sortasc</p>\n"
},
{
"answer_id": 101616,
"author": "pjesi",
"author_id": 1296737,
"author_profile": "https://Stackoverflow.com/users/1296737",
"pm_score": 0,
"selected": false,
"text": "<p>The CSS selector would be something like '#foo th.sortasc'. In jQuery that would be $('#foo th.sortasc').</p>\n"
},
{
"answer_id": 101762,
"author": "levik",
"author_id": 4465,
"author_profile": "https://Stackoverflow.com/users/4465",
"pm_score": 2,
"selected": false,
"text": "<p>This is how you'd do it with straight-up JS:</p>\n\n<pre><code>var table = document.getElementById('tableId');\nvar headers = table.getElementsByTagName('th');\nvar headersIWant = [];\nfor (var i = 0; i < headers.length; i++) {\n if ((' ' + headers[i].className + ' ').indexOf(' sortasc ') >= 0) {\n headersIWant.push(headers[i]);\n }\n}\nreturn headersIWant;\n</code></pre>\n"
},
{
"answer_id": 102666,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "<p>With a nested table, like:</p>\n\n<pre><code><table id=\"foo\">\n <th class=\"sortasc\">Header</th>\n <tr><td>\n <table id=\"nestedFoo\">\n <th class=\"sortasc\">Nested Header</th>\n </table>\n </td></tr>\n</table>\n</code></pre>\n\n<p>$('table#foo th.sortasc') will give you <em>all</em> the th's because you're using a <a href=\"http://www.w3.org/TR/CSS2/selector.html#descendant-selectors\" rel=\"nofollow noreferrer\">descendant selector</a>. If you only want foo's th's, then you should use the <a href=\"http://www.w3.org/TR/CSS2/selector.html#child-selectors\" rel=\"nofollow noreferrer\">child selector</a> - $('table#foo > th.sortasc').</p>\n\n<p>Note that the child selector is <a href=\"http://kimblim.dk/csstest/#ex1\" rel=\"nofollow noreferrer\">not supported</a> in CSS for IE6, though JQuery will still correctly do it from JavaScript.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
]
| Let's say I have the following HTML:
```
<table id="foo">
<th class="sortasc">Header</th>
</table>
<table id="bar">
<th class="sortasc">Header</th>
</table>
```
I know that I can do the following to get all of the **th** elements that have class="sortasc"
```
$$('th.sortasc').each()
```
However that gives me the **th** elements from both table *foo* and table *bar*.
How can I tell it to give me just the th elements from table *foo*? | table#foo th.sortasc |
101,693 | <p>I get an error everytime I upload my webapp to the provider. Because of the customErrors mode, all I see is the default "Runtime error" message, instructing me to turn off customErrors to view more about the error.</p>
<p>Exasperated, I've set my web.config to look like this:</p>
<pre><code><?xml version="1.0"?>
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
</code></pre>
<p>And still, all I get is the stupid remote errors page with no useful info on it.
What else can I do to turn customErrors OFF ?!</p>
| [
{
"answer_id": 101707,
"author": "Nick Craver",
"author_id": 13249,
"author_profile": "https://Stackoverflow.com/users/13249",
"pm_score": 3,
"selected": false,
"text": "<p>If you're still getting that page, it's likely that it's blowing up before getting past the Web.Config</p>\n\n<p>Make sure that ASP.Net has permissions it needs to things like the .Net Framework folders, the IIS Metabase, etc. Do you have any way of checking that ASP.Net is installed correctly and associated in IIS correctly?</p>\n\n<p>Edit: After Greg's comment it occured to me I assumed that what you posted was your entire very minimal web.config, is there more to it? If so can you post the entire web.config?</p>\n"
},
{
"answer_id": 101738,
"author": "Adam Vigh",
"author_id": 1613872,
"author_profile": "https://Stackoverflow.com/users/1613872",
"pm_score": 1,
"selected": false,
"text": "<p>Try restarting the application (creating an app_offline.htm than deleting it will do) and if you still get the same error message, make sure you've only declared customErrors once in the web.config, or anything like that. Errors in the web.config can have some weird impact on the application.</p>\n"
},
{
"answer_id": 103026,
"author": "Frederik Vig",
"author_id": 9819,
"author_profile": "https://Stackoverflow.com/users/9819",
"pm_score": 1,
"selected": false,
"text": "<p>Do you have any special character like æøå in your web.config? If so make sure that the encoding is set to utf-8.</p>\n"
},
{
"answer_id": 103166,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 1,
"selected": false,
"text": "<p>Is this web app set below any other apps in a website's directory tree? Check any parent web.config files for other settings, if any. Also, make your your directory is set as an application directory in IIS.</p>\n"
},
{
"answer_id": 103748,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using the MVC preview 4, you could be experiencing this because you're using the HandleErrorAttribute. The behavior changed in 5 so that it doesn't handle exceptions if you turn off custom errors.</p>\n"
},
{
"answer_id": 104129,
"author": "juan",
"author_id": 1782,
"author_profile": "https://Stackoverflow.com/users/1782",
"pm_score": 7,
"selected": false,
"text": "<p>\"Off\" is case-sensitive.</p>\n\n<p>Check if the \"O\" is in uppercase in your web.config file, I've suffered that a few times (as simple as it sounds)</p>\n"
},
{
"answer_id": 106366,
"author": "digitaljeebus",
"author_id": 19384,
"author_profile": "https://Stackoverflow.com/users/19384",
"pm_score": 3,
"selected": false,
"text": "<p>You can generally find more information regarding the error in the Event Viewer, if you have access to it. Your provider may also have prevented custom errors from being displayed at all, by either overriding it in their machine.config, or setting the retail attribute to true (<a href=\"http://msdn.microsoft.com/en-us/library/ms228298(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms228298(VS.80).aspx</a>). </p>\n"
},
{
"answer_id": 352626,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": true,
"text": "<p>This has been driving me insane for the past few days and couldn't get around it but have finally figured it out:</p>\n\n<p>In my machine.config file I had an entry under <code><system.web></code>:</p>\n\n<pre><code><deployment retail=\"true\" />\n</code></pre>\n\n<p>This seems to override any other customError settings that you have specified in a web.config file, so setting the above entry to:</p>\n\n<pre><code><deployment retail=\"false\" />\n</code></pre>\n\n<p>now means that I can once again see the detailed error messages that I need to.</p>\n\n<p>The <code>machine.config</code> is located at</p>\n\n<p><strong>32-bit</strong></p>\n\n<pre><code>%windir%\\Microsoft.NET\\Framework\\[version]\\config\\machine.config\n</code></pre>\n\n<p><strong>64-bit</strong></p>\n\n<pre><code>%windir%\\Microsoft.NET\\Framework64\\[version]\\config\\machine.config \n</code></pre>\n\n<p>Hope that helps someone out there and saves a few hours of hair-pulling.</p>\n"
},
{
"answer_id": 352644,
"author": "Neil Barnwell",
"author_id": 26414,
"author_profile": "https://Stackoverflow.com/users/26414",
"pm_score": 1,
"selected": false,
"text": "<p>You can also try bringing up the website in a browser on the server machine. I don't do a lot of ASP.NET development, but I remember the custom errors thing has a setting for only displaying full error text on the server, as a security measure.</p>\n"
},
{
"answer_id": 423873,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I tried most of the stuff described here. I was using VWD and the default web.config file contained:</p>\n\n<pre><code> <customErrors mode=\"RemoteOnly\" defaultRedirect=\"GenericErrorPage.htm\">\n <error statusCode=\"403\" redirect=\"NoAccess.htm\" />\n <error statusCode=\"404\" redirect=\"FileNotFound.htm\" />\n </customErrors>\n</code></pre>\n\n<p>I changed mode=\"RemoteOnly\" to mode=\"Off\". Still no joy.\nI then used IIS manager, properties, ASP.Net Tab, Edit configuration, then chose the CustomeErrors tab. This still showed RemoteOnly. I changed this to Off and finally I could see the detailed error messages.</p>\n\n<p>When I inspected the web.config I saw that there were two CustomErrors nodes in the system.web; and I have just noticed that the second entry (the one I was changing was inside a comment). So try not to use notepad to inspect web.config on a remote server.</p>\n\n<p>However, if you use the IIS edit configuration stuff it will complain about errors in the web.config. Then you can rule out all of the answers that say \"is there an XML syntax error in your web.config\"</p>\n"
},
{
"answer_id": 891429,
"author": "Cyberherbalist",
"author_id": 16964,
"author_profile": "https://Stackoverflow.com/users/16964",
"pm_score": 6,
"selected": false,
"text": "<p>In the interests of adding more situations to this question (because this is where I looked because I was having the exact same problem), here's my answer:</p>\n\n<p>In my case, I cut/pasted the text from the generic error saying in effect if you want to see what's wrong, put </p>\n\n<pre><code><system.web>\n <customErrors mode=\"Off\"/>\n</system.web>\n</code></pre>\n\n<p>So this should have fixed it, but of course not! My problem was that there was a <system.web> node several lines above (before a compilation and authentication node), and a closing tag </system.web> a few lines below that. Once I corrected this, OK, problem solved. What I should have done is copy/pasted only this line:</p>\n\n<pre><code><customErrors mode=\"Off\"/>\n</code></pre>\n\n<p>This is from the annals of Stupid Things I Keep Doing Over and Over Again, in the chapter entitled \"Copy and Paste Your Way to Destruction\".</p>\n"
},
{
"answer_id": 3744319,
"author": "Joseph D'Souza",
"author_id": 451708,
"author_profile": "https://Stackoverflow.com/users/451708",
"pm_score": 2,
"selected": false,
"text": "<p>Actually, what I figured out while hosting my web app is the the code you developed on your local Machine is of higher version than the hosting company offers you. If you have admin privileges you may be able to change the Microsoft ASP.NET version support under web hosting setting </p>\n"
},
{
"answer_id": 4616172,
"author": "Tjaart",
"author_id": 178931,
"author_profile": "https://Stackoverflow.com/users/178931",
"pm_score": 2,
"selected": false,
"text": "<p>We had this issue and it was due to the IIS user not having access to the machine config on the web server.</p>\n"
},
{
"answer_id": 4709366,
"author": "Michael Low",
"author_id": 308097,
"author_profile": "https://Stackoverflow.com/users/308097",
"pm_score": 3,
"selected": false,
"text": "<p>I also had this problem, but when using Apache and mod_mono. For anyone else in that situation, you need to restart Apache after changing web.config to force the new version to be read.</p>\n"
},
{
"answer_id": 7287631,
"author": "Roman",
"author_id": 223326,
"author_profile": "https://Stackoverflow.com/users/223326",
"pm_score": 1,
"selected": false,
"text": "<p>I have just dealt with similar issue. In my case the default site asp.net version was 1.1 while i was trying to start up a 2.0 web app. The error was pretty trivial, but it was not immediately clear why the custom errors would not go away, and runtime never wrote to event log. Obvious fix was to match the version in Asp.Net tab of IIS.</p>\n"
},
{
"answer_id": 7635270,
"author": "Ghlouw",
"author_id": 834988,
"author_profile": "https://Stackoverflow.com/users/834988",
"pm_score": 2,
"selected": false,
"text": "<p>We also ran into this error and in our case it was because the application pool user did not have permissions to the web.config file anymore. The reason it lost its permissions (everything was fine before) was because we had a backup of the site in a rar file and I dragged a backup version of the web.config from the rar into the site. This seems to have removed all permissions to the web.config file except for me, the logged on user. </p>\n\n<p>It took us a while to figure this out because I repeatedly checked permissions on the folder level, but never on the file level. </p>\n"
},
{
"answer_id": 7974132,
"author": "Rubens Farias",
"author_id": 113794,
"author_profile": "https://Stackoverflow.com/users/113794",
"pm_score": 3,
"selected": false,
"text": "<p>For Sharepoint 2010 applications, you should also edit <code>C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensions\\14\\TEMPLATE\\LAYOUTS\\web.config</code> and define <code><customErrors mode=\"Off\" /></code></p>\n"
},
{
"answer_id": 8725405,
"author": "SimonHL",
"author_id": 855606,
"author_profile": "https://Stackoverflow.com/users/855606",
"pm_score": 0,
"selected": false,
"text": "<p>I have had the same problem, and the cause was that IIS was running ASP.NET 1.1, and the site required .NET 2.0.</p>\n\n<p>The error message did nothing but throw me off track for several hours.</p>\n"
},
{
"answer_id": 18145438,
"author": "Levi",
"author_id": 1678383,
"author_profile": "https://Stackoverflow.com/users/1678383",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same issue but found resolve in a different way. </p>\n\n<p>-</p>\n\n<p>What I did was, I opened <strong>Advanced Settings</strong> for the <strong>Application Pool</strong> in <strong>IIS Manager</strong>.</p>\n\n<p>There I set <strong>Enable 32-Bit Applications</strong> to <strong>True</strong>. </p>\n"
},
{
"answer_id": 30345352,
"author": "Serj Sagan",
"author_id": 550975,
"author_profile": "https://Stackoverflow.com/users/550975",
"pm_score": 3,
"selected": false,
"text": "<p>The one answer that actually worked to fix this I found here: <a href=\"https://stackoverflow.com/a/18938991/550975\">https://stackoverflow.com/a/18938991/550975</a></p>\n\n<p>Just add this to your <code>web.config</code>:</p>\n\n<pre><code><configuration> \n <system.webServer> \n <httpErrors existingResponse=\"PassThrough\"/> \n </system.webServer> \n<configuration>\n</code></pre>\n"
},
{
"answer_id": 32457421,
"author": "Nayef",
"author_id": 559720,
"author_profile": "https://Stackoverflow.com/users/559720",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure you add \n \nright after the system.web</p>\n\n<p>I put it toward the end of the node and didn't work. </p>\n"
},
{
"answer_id": 33270763,
"author": "Eleanor Zimmermann",
"author_id": 2762457,
"author_profile": "https://Stackoverflow.com/users/2762457",
"pm_score": 1,
"selected": false,
"text": "<p>Also make sure you're editing web.config and not website.config, as I was doing.</p>\n"
},
{
"answer_id": 39451354,
"author": "Rich Hildebrand",
"author_id": 1854364,
"author_profile": "https://Stackoverflow.com/users/1854364",
"pm_score": 0,
"selected": false,
"text": "<p>If you are doing a config transform, you may also need to remove the following line from the relevant web.config file.</p>\n\n<pre><code><compilation xdt:Transform=\"RemoveAttributes(debug)\" />\n</code></pre>\n"
},
{
"answer_id": 40089265,
"author": "EM0",
"author_id": 1536933,
"author_profile": "https://Stackoverflow.com/users/1536933",
"pm_score": 0,
"selected": false,
"text": "<p>Having tried all the answers here, it turned out that my <code>Application_Error</code> method had this:</p>\n\n<pre><code>Server.ClearError();\nResponse.Redirect(\"/Home/Error\");\n</code></pre>\n\n<p>Removing these lines and setting fixed the problem. (The client still got redirected to the error page with <code>customErrors=\"On\"</code>).</p>\n"
},
{
"answer_id": 42647751,
"author": "Dongolo Jeno",
"author_id": 5525054,
"author_profile": "https://Stackoverflow.com/users/5525054",
"pm_score": 3,
"selected": false,
"text": "<p>My problem was that i had this defined in my web.config</p>\n\n<pre><code><httpErrors errorMode=\"Custom\" existingResponse=\"Replace\">\n <remove statusCode=\"404\" />\n <remove statusCode=\"500\" />\n <error statusCode=\"404\" responseMode=\"ExecuteURL\" path=\"/Error/NotFound\" />\n <error statusCode=\"500\" responseMode=\"ExecuteURL\" path=\"/Error/Internal\" />\n</httpErrors>\n</code></pre>\n"
},
{
"answer_id": 43383794,
"author": "Niraj Trivedi",
"author_id": 3839344,
"author_profile": "https://Stackoverflow.com/users/3839344",
"pm_score": 0,
"selected": false,
"text": "<p>I have had the same problem, and I went through the Event viewer application log where it clearly mention due to which exception this is happened. In my case exception was as below...</p>\n\n<p>Exception information :</p>\n\n<pre><code>Exception type: HttpException \nException message: The target principal name is incorrect. Cannot generate SSPI context.\nat System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app)\nat System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers)\nat System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context)\nat System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context)\nat System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext)\n\nThe target principal name is incorrect. Cannot generate SSPI context.\n</code></pre>\n\n<p>I have just updated my password in application pool and it works for me.</p>\n"
},
{
"answer_id": 44002045,
"author": "chriskuffner",
"author_id": 3179683,
"author_profile": "https://Stackoverflow.com/users/3179683",
"pm_score": 0,
"selected": false,
"text": "<p>It's also possible in some cases that web.config is not formatted correctly. In that case you have to go through it line by line before will work. Often, rewrite rules are the culprit here.</p>\n"
},
{
"answer_id": 52423459,
"author": "Ustin",
"author_id": 6935910,
"author_profile": "https://Stackoverflow.com/users/6935910",
"pm_score": 0,
"selected": false,
"text": "<p>That's really strange. I got this error and after rebooting of my server it disappeared.</p>\n"
},
{
"answer_id": 52549562,
"author": "andrew wisener",
"author_id": 6516243,
"author_profile": "https://Stackoverflow.com/users/6516243",
"pm_score": 0,
"selected": false,
"text": "<p>For me it was an error higher up in the web.config above the system.web.</p>\n\n<p>\n</p>\n\n<p>the file blah didn't exist so it was throwing an error at that point. Because it hadn't yet got to the System.Web section yet it was using the server default setting for CUstomErrors (On)</p>\n"
},
{
"answer_id": 64405451,
"author": "J. Gwinner",
"author_id": 5937168,
"author_profile": "https://Stackoverflow.com/users/5937168",
"pm_score": -1,
"selected": false,
"text": "<p>It may not be IIS!</p>\n<p>I went through all of the answers on this page, as well as several more. None of them solved our issue, BUT they are good things to check and WILL cause problems. SO check those first. If you're still pulling your hair out, and you're using PHP, check your PHP settings.</p>\n<p>What fixed it for me was to edit our php.ini file and specify:</p>\n<pre><code>display_errors: On\n</code></pre>\n<p>I also set:</p>\n<pre><code>display_startup_errors: On\n</code></pre>\n<p>just for good measure.</p>\n<p>That fixed the problem, and our real issue turned out to be a missed comma that was missed during dev to stage migration.</p>\n<p>I realize this page was linked to asp.net, which we were ALSO using, and this is not an asp.net issue, but when you search for these errors, this page comes up and has some good info for fixing most common problems; just not our specific issue. The config changes did fix it, and then we could concentrate on our asp.net files!</p>\n"
},
{
"answer_id": 69007785,
"author": "kaung htet naing",
"author_id": 1157593,
"author_profile": "https://Stackoverflow.com/users/1157593",
"pm_score": 0,
"selected": false,
"text": "<p>None of those above solutions work for me. my case is</p>\n<p>i have this in my web.config</p>\n<pre><code><log4net debug="true">\n</code></pre>\n<p>either remove all those or go and read errors logs in your application folder\\logs\neg.. C:\\Users\\YourName\\source\\repos\\YourProjectFolder\\logs</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3263/"
]
| I get an error everytime I upload my webapp to the provider. Because of the customErrors mode, all I see is the default "Runtime error" message, instructing me to turn off customErrors to view more about the error.
Exasperated, I've set my web.config to look like this:
```
<?xml version="1.0"?>
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
```
And still, all I get is the stupid remote errors page with no useful info on it.
What else can I do to turn customErrors OFF ?! | This has been driving me insane for the past few days and couldn't get around it but have finally figured it out:
In my machine.config file I had an entry under `<system.web>`:
```
<deployment retail="true" />
```
This seems to override any other customError settings that you have specified in a web.config file, so setting the above entry to:
```
<deployment retail="false" />
```
now means that I can once again see the detailed error messages that I need to.
The `machine.config` is located at
**32-bit**
```
%windir%\Microsoft.NET\Framework\[version]\config\machine.config
```
**64-bit**
```
%windir%\Microsoft.NET\Framework64\[version]\config\machine.config
```
Hope that helps someone out there and saves a few hours of hair-pulling. |
101,708 | <p>In VB.net I'm using the TcpClient to retrieve a string of data. I'm constantly checking the .Connected property to verify if the client is connected but even if the client disconnects this still returns true. What can I use as a workaround for this?</p>
<p>This is a stripped down version of my current code:</p>
<pre><code>Dim client as TcpClient = Nothing
client = listener.AcceptTcpClient
do while client.connected = true
dim stream as networkStream = client.GetStream()
dim bytes(1024) as byte
dim numCharRead as integer = stream.Read(bytes,0,bytes.length)
dim strRead as string = System.Text.Encoding.ASCII.GetString(bytes,0,i)
loop
</code></pre>
<p>I would have figured at least the GetStream() call would throw an exception if the client was disconnected but I've closed the other app and it still doesn't... </p>
<p>Thanks. </p>
<p><strong>EDIT</strong>
Polling the Client.Available was suggested but that doesn't solve the issue. If the client is not 'acutally' connected available just returns 0.</p>
<p>The key is that I'm trying to allow the connection to stay open and allow me to receive data multiple times over the same socket connection. </p>
| [
{
"answer_id": 101759,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": -1,
"selected": false,
"text": "<p>Instead of polling client.connected, maybe use of the NetworkStream's properties to see if there's no more data available?</p>\n\n<p>Anyhow, there's an <a href=\"http://www.ondotnet.com/pub/a/dotnet/2003/07/07/netstreams.html\" rel=\"nofollow noreferrer\">ONDotnet.com</a> article with TONS of info on listeners and whatnot. Should help you get past your issue...</p>\n"
},
{
"answer_id": 102581,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 4,
"selected": true,
"text": "<p>When NetworkStream.Read returns 0, then the connection has been closed. <a href=\"http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.read(VS.71).aspx\" rel=\"noreferrer\">Reference</a>:</p>\n\n<blockquote>\n <p>If no data is available for reading, the NetworkStream.Read method will block until data is available. To avoid blocking, you can use the DataAvailable property to determine if data is queued in the incoming network buffer for reading. If DataAvailable returns true, the Read operation will complete immediately. The Read operation will read as much data as is available, up to the number of bytes specified by the size parameter. <strong>If the remote host shuts down the connection, and all available data has been received, the Read method will complete immediately and return zero bytes.</strong></p>\n</blockquote>\n"
},
{
"answer_id": 3783019,
"author": "Sean P",
"author_id": 240405,
"author_profile": "https://Stackoverflow.com/users/240405",
"pm_score": 1,
"selected": false,
"text": "<p>Better answer:</p>\n<pre><code>if (client.Client.Poll(0, SelectMode.SelectRead))\n{\n byte[] checkConn = new byte[1];\n\n if (client.Client.Receive(checkConn, SocketFlags.Peek) == 0)\n throw new IOException();\n}\n</code></pre>\n"
},
{
"answer_id": 54497655,
"author": "MJ-",
"author_id": 11006514,
"author_profile": "https://Stackoverflow.com/users/11006514",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"https://i.stack.imgur.com/Jb0X2.png\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/Jb0X2.png</a></p>\n\n<p>LINK=<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.poll?view=netframework-4.0\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.poll?view=netframework-4.0</a></p>\n\n<p>You need to set up a timer that sends a msg to the other socket from time to time.</p>\n\n<p>Dim TC As New TimerCallback(AddressOf Ping)</p>\n\n<p>Tick = New Threading.Timer(TC, Nothing, 0, 30000)</p>\n\n<pre><code>Sub Ping()\n Send(\"Stil here?\")\nEnd Sub\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/77830/"
]
| In VB.net I'm using the TcpClient to retrieve a string of data. I'm constantly checking the .Connected property to verify if the client is connected but even if the client disconnects this still returns true. What can I use as a workaround for this?
This is a stripped down version of my current code:
```
Dim client as TcpClient = Nothing
client = listener.AcceptTcpClient
do while client.connected = true
dim stream as networkStream = client.GetStream()
dim bytes(1024) as byte
dim numCharRead as integer = stream.Read(bytes,0,bytes.length)
dim strRead as string = System.Text.Encoding.ASCII.GetString(bytes,0,i)
loop
```
I would have figured at least the GetStream() call would throw an exception if the client was disconnected but I've closed the other app and it still doesn't...
Thanks.
**EDIT**
Polling the Client.Available was suggested but that doesn't solve the issue. If the client is not 'acutally' connected available just returns 0.
The key is that I'm trying to allow the connection to stay open and allow me to receive data multiple times over the same socket connection. | When NetworkStream.Read returns 0, then the connection has been closed. [Reference](http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.read(VS.71).aspx):
>
> If no data is available for reading, the NetworkStream.Read method will block until data is available. To avoid blocking, you can use the DataAvailable property to determine if data is queued in the incoming network buffer for reading. If DataAvailable returns true, the Read operation will complete immediately. The Read operation will read as much data as is available, up to the number of bytes specified by the size parameter. **If the remote host shuts down the connection, and all available data has been received, the Read method will complete immediately and return zero bytes.**
>
>
> |
101,742 | <p>I have a Google App Engine app - <a href="http://mylovelyapp.appspot.com/" rel="noreferrer">http://mylovelyapp.appspot.com/</a>
It has a page - mylovelypage</p>
<p>For the moment, the page just does <code>self.response.out.write('OK')</code></p>
<p>If I run the following Python at my computer:</p>
<pre><code>import urllib2
f = urllib2.urlopen("http://mylovelyapp.appspot.com/mylovelypage")
s = f.read()
print s
f.close()
</code></pre>
<p>it prints "OK"</p>
<p>the problem is if I add <code>login:required</code> to this page in the app's yaml</p>
<p>then this prints out the HTML of the Google Accounts login page</p>
<p>I've tried "normal" authentication approaches. e.g.</p>
<pre><code>passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(None,
uri='http://mylovelyapp.appspot.com/mylovelypage',
user='[email protected]',
passwd='billybobspasswd')
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
</code></pre>
<p>But it makes no difference - I still get the login page's HTML back.</p>
<p>I've tried <a href="http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html" rel="noreferrer">Google's ClientLogin auth API</a>, but I can't get it to work.</p>
<pre><code>h = httplib2.Http()
auth_uri = 'https://www.google.com/accounts/ClientLogin'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
myrequest = "Email=%s&Passwd=%s&service=ah&source=DALELANE-0.0" % ("[email protected]", "billybobspassword")
response, content = h.request(auth_uri, 'POST', body=myrequest, headers=headers)
if response['status'] == '200':
authtok = re.search('Auth=(\S*)', content).group(1)
headers = {}
headers['Authorization'] = 'GoogleLogin auth=%s' % authtok.strip()
headers['Content-Length'] = '0'
response, content = h.request("http://mylovelyapp.appspot.com/mylovelypage",
'POST',
body="",
headers=headers)
while response['status'] == "302":
response, content = h.request(response['location'], 'POST', body="", headers=headers)
print content
</code></pre>
<p>I do seem to be able to get some token correctly, but attempts to use it in the header when I call 'mylovelypage' still just return me the login page's HTML. :-( </p>
<p>Can anyone help, please?</p>
<p>Could I use the <a href="http://code.google.com/p/gdata-python-client/" rel="noreferrer">GData client library</a> to do this sort of thing? From
what I've read, I think it should be able to access App Engine apps,
but I haven't been any more successful at getting the authentication working for App Engine stuff there either </p>
<p>Any pointers to samples, articles, or even just keywords I should be
searching for to get me started, would be very much appreciated.</p>
<p>Thanks!</p>
| [
{
"answer_id": 102158,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>I'm not a python expert or a app engine expert. But did you try following the sample appl at <a href=\"http://code.google.com/appengine/docs/gettingstarted/usingusers.html\" rel=\"nofollow noreferrer\">http://code.google.com/appengine/docs/gettingstarted/usingusers.html</a>. I created one at <a href=\"http://quizengine.appspot.com\" rel=\"nofollow noreferrer\">http://quizengine.appspot.com</a>, it seemed to work fine with Google authentication and everything.\nJust a suggestion, but look in to the getting started guide. Take it easy if the suggestion sounds naive. :)\nThanks.</p>\n"
},
{
"answer_id": 102162,
"author": "Sean O Donnell",
"author_id": 7813,
"author_profile": "https://Stackoverflow.com/users/7813",
"pm_score": 0,
"selected": false,
"text": "<p>Im not too familiar with AppEngine, or Googles web apis, but for a brute force approach you could write a script with something like mechanize (<a href=\"http://wwwsearch.sourceforge.net/mechanize/\" rel=\"nofollow noreferrer\">http://wwwsearch.sourceforge.net/mechanize/</a>) to simply walk through the login process before you begin doing the real work of the client.</p>\n"
},
{
"answer_id": 102509,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 6,
"selected": true,
"text": "<p>appcfg.py, the tool that uploads data to App Engine has to do exactly this to authenticate itself with the App Engine server. The relevant functionality is abstracted into appengine_rpc.py. In a nutshell, the solution is:</p>\n\n<ol>\n<li>Use the <a href=\"http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html\" rel=\"noreferrer\">Google ClientLogin API</a> to obtain an authentication token. appengine_rpc.py does this in <a href=\"http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#180\" rel=\"noreferrer\">_GetAuthToken</a></li>\n<li>Send the auth token to a special URL on your App Engine app. That page then returns a cookie and a 302 redirect. Ignore the redirect and store the cookie. appcfg.py does this in <a href=\"http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#228\" rel=\"noreferrer\">_GetAuthCookie</a></li>\n<li>Use the returned cookie in all future requests.</li>\n</ol>\n\n<p>You may also want to look at <a href=\"http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#253\" rel=\"noreferrer\">_Authenticate</a>, to see how appcfg handles the various return codes from ClientLogin, and <a href=\"http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#397\" rel=\"noreferrer\">_GetOpener</a>, to see how appcfg creates a urllib2 OpenerDirector that doesn't follow HTTP redirects. Or you could, in fact, just use the AbstractRpcServer and HttpRpcServer classes wholesale, since they do pretty much everything you need.</p>\n"
},
{
"answer_id": 103410,
"author": "dalelane",
"author_id": 477,
"author_profile": "https://Stackoverflow.com/users/477",
"pm_score": 5,
"selected": false,
"text": "<p>thanks to Arachnid for the answer - it worked as suggested</p>\n\n<p>here is a simplified copy of the code, in case it is helpful to the next person to try! </p>\n\n<pre><code>import os\nimport urllib\nimport urllib2\nimport cookielib\n\nusers_email_address = \"[email protected]\"\nusers_password = \"billybobspassword\"\n\ntarget_authenticated_google_app_engine_uri = 'http://mylovelyapp.appspot.com/mylovelypage'\nmy_app_name = \"yay-1.0\"\n\n\n\n# we use a cookie to authenticate with Google App Engine\n# by registering a cookie handler here, this will automatically store the \n# cookie returned when we use urllib2 to open http://currentcost.appspot.com/_ah/login\ncookiejar = cookielib.LWPCookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))\nurllib2.install_opener(opener)\n\n#\n# get an AuthToken from Google accounts\n#\nauth_uri = 'https://www.google.com/accounts/ClientLogin'\nauthreq_data = urllib.urlencode({ \"Email\": users_email_address,\n \"Passwd\": users_password,\n \"service\": \"ah\",\n \"source\": my_app_name,\n \"accountType\": \"HOSTED_OR_GOOGLE\" })\nauth_req = urllib2.Request(auth_uri, data=authreq_data)\nauth_resp = urllib2.urlopen(auth_req)\nauth_resp_body = auth_resp.read()\n# auth response includes several fields - we're interested in \n# the bit after Auth= \nauth_resp_dict = dict(x.split(\"=\")\n for x in auth_resp_body.split(\"\\n\") if x)\nauthtoken = auth_resp_dict[\"Auth\"]\n\n#\n# get a cookie\n# \n# the call to request a cookie will also automatically redirect us to the page\n# that we want to go to\n# the cookie jar will automatically provide the cookie when we reach the \n# redirected location\n\n# this is where I actually want to go to\nserv_uri = target_authenticated_google_app_engine_uri\n\nserv_args = {}\nserv_args['continue'] = serv_uri\nserv_args['auth'] = authtoken\n\nfull_serv_uri = \"http://mylovelyapp.appspot.com/_ah/login?%s\" % (urllib.urlencode(serv_args))\n\nserv_req = urllib2.Request(full_serv_uri)\nserv_resp = urllib2.urlopen(serv_req)\nserv_resp_body = serv_resp.read()\n\n# serv_resp_body should contain the contents of the \n# target_authenticated_google_app_engine_uri page - as we will have been \n# redirected to that page automatically \n#\n# to prove this, I'm just gonna print it out\nprint serv_resp_body\n</code></pre>\n"
},
{
"answer_id": 4813590,
"author": "ryan",
"author_id": 186123,
"author_profile": "https://Stackoverflow.com/users/186123",
"pm_score": 1,
"selected": false,
"text": "<p>for those who can't get ClientLogin to work, try app engine's <a href=\"http://code.google.com/appengine/docs/python/oauth/overview.html\" rel=\"nofollow\">OAuth support</a>.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/477/"
]
| I have a Google App Engine app - <http://mylovelyapp.appspot.com/>
It has a page - mylovelypage
For the moment, the page just does `self.response.out.write('OK')`
If I run the following Python at my computer:
```
import urllib2
f = urllib2.urlopen("http://mylovelyapp.appspot.com/mylovelypage")
s = f.read()
print s
f.close()
```
it prints "OK"
the problem is if I add `login:required` to this page in the app's yaml
then this prints out the HTML of the Google Accounts login page
I've tried "normal" authentication approaches. e.g.
```
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(None,
uri='http://mylovelyapp.appspot.com/mylovelypage',
user='[email protected]',
passwd='billybobspasswd')
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
```
But it makes no difference - I still get the login page's HTML back.
I've tried [Google's ClientLogin auth API](http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html), but I can't get it to work.
```
h = httplib2.Http()
auth_uri = 'https://www.google.com/accounts/ClientLogin'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
myrequest = "Email=%s&Passwd=%s&service=ah&source=DALELANE-0.0" % ("[email protected]", "billybobspassword")
response, content = h.request(auth_uri, 'POST', body=myrequest, headers=headers)
if response['status'] == '200':
authtok = re.search('Auth=(\S*)', content).group(1)
headers = {}
headers['Authorization'] = 'GoogleLogin auth=%s' % authtok.strip()
headers['Content-Length'] = '0'
response, content = h.request("http://mylovelyapp.appspot.com/mylovelypage",
'POST',
body="",
headers=headers)
while response['status'] == "302":
response, content = h.request(response['location'], 'POST', body="", headers=headers)
print content
```
I do seem to be able to get some token correctly, but attempts to use it in the header when I call 'mylovelypage' still just return me the login page's HTML. :-(
Can anyone help, please?
Could I use the [GData client library](http://code.google.com/p/gdata-python-client/) to do this sort of thing? From
what I've read, I think it should be able to access App Engine apps,
but I haven't been any more successful at getting the authentication working for App Engine stuff there either
Any pointers to samples, articles, or even just keywords I should be
searching for to get me started, would be very much appreciated.
Thanks! | appcfg.py, the tool that uploads data to App Engine has to do exactly this to authenticate itself with the App Engine server. The relevant functionality is abstracted into appengine\_rpc.py. In a nutshell, the solution is:
1. Use the [Google ClientLogin API](http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html) to obtain an authentication token. appengine\_rpc.py does this in [\_GetAuthToken](http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#180)
2. Send the auth token to a special URL on your App Engine app. That page then returns a cookie and a 302 redirect. Ignore the redirect and store the cookie. appcfg.py does this in [\_GetAuthCookie](http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#228)
3. Use the returned cookie in all future requests.
You may also want to look at [\_Authenticate](http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#253), to see how appcfg handles the various return codes from ClientLogin, and [\_GetOpener](http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appengine_rpc.py#397), to see how appcfg creates a urllib2 OpenerDirector that doesn't follow HTTP redirects. Or you could, in fact, just use the AbstractRpcServer and HttpRpcServer classes wholesale, since they do pretty much everything you need. |
101,752 | <p>I used <code>git pull</code> and had a merge conflict:</p>
<pre><code>unmerged: some_file.txt
You are in the middle of a conflicted merge.
</code></pre>
<p>How do I abandon my changes to the file and keep only the pulled changes?</p>
| [
{
"answer_id": 101773,
"author": "David Precious",
"author_id": 4040,
"author_profile": "https://Stackoverflow.com/users/4040",
"pm_score": 7,
"selected": false,
"text": "<p>I think it's <code>git reset</code> you need.</p>\n\n<p>Beware that <code>git revert</code> means something very different to, say, <code>svn revert</code> - in Subversion the revert will discard your (uncommitted) changes, returning the file to the current version from the repository, whereas <code>git revert</code> \"undoes\" a commit.</p>\n\n<p><code>git reset</code> should do the equivalent of <code>svn revert</code>, that is, discard your unwanted changes.</p>\n"
},
{
"answer_id": 102309,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 11,
"selected": false,
"text": "<p>Since your <code>pull</code> was unsuccessful then <code>HEAD</code> (not <code>HEAD^</code>) is the last \"valid\" commit on your branch:</p>\n\n<pre><code>git reset --hard HEAD\n</code></pre>\n\n<p>The other piece you want is to let their changes over-ride your changes. </p>\n\n<p>Older versions of git allowed you to use the \"theirs\" merge strategy:</p>\n\n<pre><code>git pull --strategy=theirs remote_branch\n</code></pre>\n\n<p>But this has since been removed, as explained in <a href=\"http://marc.info/?l=git&m=121637513604413&w=2\" rel=\"noreferrer\">this message by Junio Hamano</a> (the Git maintainer). As noted in <a href=\"http://marc.info/?l=git&m=121637513604413&w=2\" rel=\"noreferrer\">the link</a>, instead you would do this:</p>\n\n<pre><code>git fetch origin\ngit reset --hard origin\n</code></pre>\n"
},
{
"answer_id": 107860,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 6,
"selected": false,
"text": "<p>In this particular use case, you don't really want to abort the merge, just resolve the conflict in a particular way.</p>\n\n<p>There is no particular need to reset and perform a merge with a different strategy, either. The conflicts have been correctly highlighted by git and the requirement to accept the other sides changes is only for this one file.</p>\n\n<p>For an unmerged file in a conflict git makes available the common base, local and remote versions of the file in the index. (This is where they are read from for use in a 3-way diff tool by <code>git mergetool</code>.) You can use <code>git show</code> to view them.</p>\n\n<pre><code># common base:\ngit show :1:_widget.html.erb\n\n# 'ours'\ngit show :2:_widget.html.erb\n\n# 'theirs'\ngit show :3:_widget.html.erb\n</code></pre>\n\n<p>The simplest way to resolve the conflict to use the remote version verbatim is:</p>\n\n<pre><code>git show :3:_widget.html.erb >_widget.html.erb\ngit add _widget.html.erb\n</code></pre>\n\n<p>Or, with git >= 1.6.1:</p>\n\n<pre><code>git checkout --theirs _widget.html.erb\n</code></pre>\n"
},
{
"answer_id": 2534968,
"author": "Carl",
"author_id": 13760,
"author_profile": "https://Stackoverflow.com/users/13760",
"pm_score": 11,
"selected": false,
"text": "<p>If your git version is >= 1.6.1, you can use <code>git reset --merge</code>.</p>\n\n<p>Also, as @Michael Johnson mentions, if your git version is >= 1.7.4, you can also use <code>git merge --abort</code>.</p>\n\n<p>As always, make sure you have no uncommitted changes before you start a merge.</p>\n\n<p>From the <a href=\"https://www.kernel.org/pub/software/scm/git/docs/git-merge.html\" rel=\"noreferrer\">git merge man page</a></p>\n\n<p><code>git merge --abort</code> is equivalent to <code>git reset --merge</code> when <code>MERGE_HEAD</code> is present.</p>\n\n<p><code>MERGE_HEAD</code> is present when a merge is in progress.</p>\n\n<p>Also, regarding uncommitted changes when starting a merge:</p>\n\n<p>If you have changes you don't want to commit before starting a merge, just <code>git stash</code> them before the merge and <code>git stash pop</code> after finishing the merge or aborting it.</p>\n"
},
{
"answer_id": 3240453,
"author": "Alain O'Dea",
"author_id": 154527,
"author_profile": "https://Stackoverflow.com/users/154527",
"pm_score": 4,
"selected": false,
"text": "<p>An alternative, which preserves the state of the working copy is:</p>\n\n<pre><code>git stash\ngit merge --abort\ngit stash pop\n</code></pre>\n\n<p>I generally advise against this, because it is effectively like merging in Subversion as it throws away the branch relationships in the following commit.</p>\n"
},
{
"answer_id": 3269841,
"author": "Alain O'Dea",
"author_id": 154527,
"author_profile": "https://Stackoverflow.com/users/154527",
"pm_score": 4,
"selected": false,
"text": "<p>Since Git 1.6.1.3 <a href=\"http://git-scm.com/docs/git-checkout\" rel=\"noreferrer\"><code>git checkout</code></a> has been able to checkout from either side of a merge:</p>\n\n<pre><code>git checkout --theirs _widget.html.erb\n</code></pre>\n"
},
{
"answer_id": 13352008,
"author": "ignis",
"author_id": 778990,
"author_profile": "https://Stackoverflow.com/users/778990",
"pm_score": 9,
"selected": false,
"text": "<pre><code>git merge --abort\n</code></pre>\n\n<blockquote>\n <p>Abort the current conflict resolution process, and try to reconstruct\n the pre-merge state.</p>\n \n <p>If there were uncommitted worktree changes present when the merge\n started, <code>git merge --abort</code> will in some cases be unable to\n reconstruct these changes. It is therefore recommended to always\n commit or stash your changes before running git merge.</p>\n \n <p><code>git merge --abort</code> is equivalent to <code>git reset --merge</code> when\n <code>MERGE_HEAD</code> is present.</p>\n</blockquote>\n\n<p><a href=\"http://www.git-scm.com/docs/git-merge\" rel=\"noreferrer\">http://www.git-scm.com/docs/git-merge</a></p>\n"
},
{
"answer_id": 29412774,
"author": "Martin G",
"author_id": 3545094,
"author_profile": "https://Stackoverflow.com/users/3545094",
"pm_score": 6,
"selected": false,
"text": "<p>Comments suggest that <code>git reset --merge</code> is an alias for <code>git merge --abort</code>. It is worth noticing that <code>git merge --abort</code> is only equivalent to <code>git reset --merge</code> given that a <code>MERGE_HEAD</code> is present. This can be read in the git help for merge command.</p>\n\n<blockquote>\n <p>git merge --abort is equivalent to git reset --merge when MERGE_HEAD is present.</p>\n</blockquote>\n\n<p>After a failed merge, when there is no <code>MERGE_HEAD</code>, the failed merge can be undone with <code>git reset --merge</code>, but not necessarily with <code>git merge --abort</code>. <strong>They are not only old and new syntax for the same thing</strong>.</p>\n\n<p>Personally, I find <code>git reset --merge</code> much more powerful for scenarios similar to the described one, and failed merges in general.</p>\n"
},
{
"answer_id": 47026373,
"author": "Malcolm Boekhoff",
"author_id": 1388639,
"author_profile": "https://Stackoverflow.com/users/1388639",
"pm_score": 2,
"selected": false,
"text": "<p>I found the following worked for me (revert a single file to pre-merge state):</p>\n\n<pre><code>git reset *currentBranchIntoWhichYouMerged* -- *fileToBeReset*\n</code></pre>\n"
},
{
"answer_id": 49763085,
"author": "Nirav Mehta",
"author_id": 3875543,
"author_profile": "https://Stackoverflow.com/users/3875543",
"pm_score": 5,
"selected": false,
"text": "<p>If you end up with merge conflict and doesn't have anything to commit, but still a merge error is being displayed. After applying all the below mentioned commands, </p>\n\n<pre><code>git reset --hard HEAD\ngit pull --strategy=theirs remote_branch\ngit fetch origin\ngit reset --hard origin\n</code></pre>\n\n<p>Please remove </p>\n\n<blockquote>\n <p><strong><em>.git\\index.lock</em></strong></p>\n</blockquote>\n\n<p>File [cut paste to some other location in case of recovery] and then enter any of below command depending on which version you want.</p>\n\n<pre><code>git reset --hard HEAD\ngit reset --hard origin\n</code></pre>\n\n<p>Hope that helps!!!</p>\n"
},
{
"answer_id": 62588633,
"author": "Hanzla Habib",
"author_id": 3946527,
"author_profile": "https://Stackoverflow.com/users/3946527",
"pm_score": 6,
"selected": false,
"text": "<p>For git >= 1.6.1:</p>\n<pre><code>git merge --abort\n</code></pre>\n<p>For older versions of git, this will do the job:</p>\n<pre><code>git reset --merge\n</code></pre>\n<p>or</p>\n<pre><code>git reset --hard\n</code></pre>\n"
},
{
"answer_id": 65019148,
"author": "DARK_C0D3R",
"author_id": 8865579,
"author_profile": "https://Stackoverflow.com/users/8865579",
"pm_score": 6,
"selected": false,
"text": "<p>You can either abort the merge step:</p>\n<pre><code>git merge --abort\n</code></pre>\n<p>else you can keep your changes (on which branch you are)</p>\n<pre><code>git checkout --ours file1 file2 ...\n</code></pre>\n<p>otherwise you can keep other branch changes</p>\n<pre><code>git checkout --theirs file1 file2 ...\n</code></pre>\n"
},
{
"answer_id": 67916591,
"author": "sastorsl",
"author_id": 2045924,
"author_profile": "https://Stackoverflow.com/users/2045924",
"pm_score": 3,
"selected": false,
"text": "<p>To <em>avoid</em> getting into this sort of trouble one can expand on the <code>git merge --abort</code> approach and create a <strong>separate test branch <em>before</em> merging</strong>.</p>\n<p><strong>Case</strong>: You have a topic branch, it wasn't merged because you got distracted/something came up/you know but it <em>is</em> (or was) ready.</p>\n<p>Now <strong>is it possible</strong> to merge this into master?</p>\n<p>Work in a <strong><em>test</em></strong> branch to estimate / find a solution, then abandon the test branch and apply the solution in the topic branch.</p>\n<pre class=\"lang-sh prettyprint-override\"><code># Checkout the topic branch\ngit checkout topic-branch-1\n\n# Create a _test_ branch on top of this\ngit checkout -b test\n\n# Attempt to merge master\ngit merge master\n\n# If it fails you can abandon the merge\ngit merge --abort\ngit checkout -\ngit branch -D test # we don't care about this branch really...\n</code></pre>\n<p>Work on resolving the conflict.</p>\n<pre class=\"lang-sh prettyprint-override\"><code># Checkout the topic branch\ngit checkout topic-branch-1\n\n# Create a _test_ branch on top of this\ngit checkout -b test\n\n# Attempt to merge master\ngit merge master\n\n# resolve conflicts, run it through tests, etc\n# then\ngit commit <conflict-resolving>\n\n# You *could* now even create a separate test branch on top of master\n# and see if you are able to merge\ngit checkout master\ngit checkout -b master-test\ngit merge test\n</code></pre>\n<p>Finally checkout the topic branch again, apply the fix from the test branch and continue with the PR.\nLastly delete the test and master-test.</p>\n<p>Involved? Yes, but it won't mess with my topic or master branch until I'm good and ready.</p>\n"
},
{
"answer_id": 68576346,
"author": "Daniel",
"author_id": 11952668,
"author_profile": "https://Stackoverflow.com/users/11952668",
"pm_score": 4,
"selected": false,
"text": "<p>Might not be what the OP wanted, but for me I tried to merge a stable branch to a feature branch and there were too many conflicts.\nI didn't manage to reset the changes since the HEAD was changed by many commits, So the easy solution was to force checkout to a stable branch.\nyou can then checkout to the other branch and it will be as it was before the merge.</p>\n<p><code>git checkout -f master</code></p>\n<p><code>git checkout side-branch</code></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18666/"
]
| I used `git pull` and had a merge conflict:
```
unmerged: some_file.txt
You are in the middle of a conflicted merge.
```
How do I abandon my changes to the file and keep only the pulled changes? | Since your `pull` was unsuccessful then `HEAD` (not `HEAD^`) is the last "valid" commit on your branch:
```
git reset --hard HEAD
```
The other piece you want is to let their changes over-ride your changes.
Older versions of git allowed you to use the "theirs" merge strategy:
```
git pull --strategy=theirs remote_branch
```
But this has since been removed, as explained in [this message by Junio Hamano](http://marc.info/?l=git&m=121637513604413&w=2) (the Git maintainer). As noted in [the link](http://marc.info/?l=git&m=121637513604413&w=2), instead you would do this:
```
git fetch origin
git reset --hard origin
``` |
101,767 | <p>I'm trying to use cygwin as a build environment under Windows. I have some dependencies on 3rd party packages, for example, GTK+. </p>
<p>Normally when I build under Linux, in my Makefile I can add a call to pkg-config as an argument to gcc, so it comes out like so:</p>
<pre>
gcc example.c `pkg-config --libs --cflags gtk+-2.0`
</pre>
<p>This works fine under Linux, but in cygwin I get:</p>
<pre>
:Invalid argument
make: *** [example] Error 1
</pre>
<p>Right now, I am just manually running pkg-config and pasting the output into the Makefile, which is truly terrible. Is there a good way to workaround or fix for this issue?</p>
<p>Make isn't the culprit. I can copy and paste the command line that make uses to call gcc, and that by itself will run gcc, which halts with ": Invalid argument". </p>
<p>I wrote a small test program to print out command line arguments:</p>
<pre><code>for (i = 0; i < argc; i++)
printf("'%s'\n", argv[i]);
</code></pre>
<p>Notice the single quotes.</p>
<pre>
$ pkg-config --libs gtk+-2.0
-Lc:/mingw/lib -lgtk-win32-2.0 -lgdk-win32-2.0 -latk-1.0 -lgdk_pixbuf-2.0 -lpang
owin32-1.0 -lgdi32 -lpangocairo-1.0 -lpango-1.0 -lcairo -lgobject-2.0 -lgmodule-
2.0 -lglib-2.0 -lintl
</pre>
<p>Running through the test program:</p>
<pre>
$ ./t `pkg-config --libs gtk+-2.0`
'C:\cygwin\home\smo\pvm\src\t.exe'
'-Lc:/mingw/lib'
'-lgtk-win32-2.0'
'-lgdk-win32-2.0'
'-latk-1.0'
'-lgdk_pixbuf-2.0'
'-lpangowin32-1.0'
'-lgdi32'
'-lpangocairo-1.0'
'-lpango-1.0'
'-lcairo'
'-lgobject-2.0'
'-lgmodule-2.0'
'-lglib-2.0'
'-lintl'
'
</pre>
<p>Notice the one single quote on the last line. It looks like argc is one greater than it should be, and argv[argc - 1] is null. Running the same test on Linux does not have this result.</p>
<p>That said, is there, say, some way I could have the Makefile store the result of pkg-config into a variable, and then use that variable, rather than using the back-tick operator?</p>
| [
{
"answer_id": 102136,
"author": "Tobias Kunze",
"author_id": 6070,
"author_profile": "https://Stackoverflow.com/users/6070",
"pm_score": 2,
"selected": false,
"text": "<p>Are you sure that you're using the make provided by Cygwin? Use</p>\n\n<pre><code>which make\nmake --version\n</code></pre>\n\n<p>to check - this should return \"/usr/bin/make\" and \"GNU Make 3.8 [...]\" or something similar.</p>\n"
},
{
"answer_id": 102543,
"author": "Tobias Kunze",
"author_id": 6070,
"author_profile": "https://Stackoverflow.com/users/6070",
"pm_score": 2,
"selected": false,
"text": "<p>Hmmm... have you tried</p>\n\n<pre><code>make -d\n</code></pre>\n\n<p>That will give you some (lots) of debugging output.</p>\n"
},
{
"answer_id": 106420,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>That said, is there, say, some way I could have the Makefile store the result of pkg-config into a variable, and then use that variable, rather than using the back-tick operator?</p>\n</blockquote>\n\n<p>GTK_LIBS = $(shell pkg-config --libs gtk+-2.0)</p>\n"
},
{
"answer_id": 106475,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 1,
"selected": false,
"text": "<p>My guess would be that cygwin's gcc can't handle -Lc:/mingw/lib. Try translating that to a cygwin path.</p>\n\n<pre><code>GTK_LIBS = $(patsubst -Lc:/%,-L/cygdrive/c/%,$(shell pkg-config --libs gtk+-2.0))\n</code></pre>\n"
},
{
"answer_id": 106497,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 1,
"selected": false,
"text": "<p>The single quote at the end of the \"t\" output may be an artifact of CRLF translation. Is your pkg-config a cygwin app? The $(shell) solution I posted earlier may help with this, as GNU make seems to be fairly tolerant of different line ending styles.</p>\n"
},
{
"answer_id": 6498875,
"author": "allialliallialli",
"author_id": 818124,
"author_profile": "https://Stackoverflow.com/users/818124",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar issue and I found a fix here: <a href=\"http://www.demexp.org/dokuwiki/en:demexp_build_on_windows\" rel=\"nofollow\">http://www.demexp.org/dokuwiki/en:demexp_build_on_windows</a></p>\n\n<blockquote>\n <p>Take care to put /usr/bin before /cygwin/c/GTK/bin in your PATH so that you use /usr/bin/pkg-config. This is required because GTK's pkg-config post-processes paths, often transforming them in their Windows absolute paths equivalents. As a consequence, tools under cygwin may not understand those paths. </p>\n</blockquote>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16080/"
]
| I'm trying to use cygwin as a build environment under Windows. I have some dependencies on 3rd party packages, for example, GTK+.
Normally when I build under Linux, in my Makefile I can add a call to pkg-config as an argument to gcc, so it comes out like so:
```
gcc example.c `pkg-config --libs --cflags gtk+-2.0`
```
This works fine under Linux, but in cygwin I get:
```
:Invalid argument
make: *** [example] Error 1
```
Right now, I am just manually running pkg-config and pasting the output into the Makefile, which is truly terrible. Is there a good way to workaround or fix for this issue?
Make isn't the culprit. I can copy and paste the command line that make uses to call gcc, and that by itself will run gcc, which halts with ": Invalid argument".
I wrote a small test program to print out command line arguments:
```
for (i = 0; i < argc; i++)
printf("'%s'\n", argv[i]);
```
Notice the single quotes.
```
$ pkg-config --libs gtk+-2.0
-Lc:/mingw/lib -lgtk-win32-2.0 -lgdk-win32-2.0 -latk-1.0 -lgdk_pixbuf-2.0 -lpang
owin32-1.0 -lgdi32 -lpangocairo-1.0 -lpango-1.0 -lcairo -lgobject-2.0 -lgmodule-
2.0 -lglib-2.0 -lintl
```
Running through the test program:
```
$ ./t `pkg-config --libs gtk+-2.0`
'C:\cygwin\home\smo\pvm\src\t.exe'
'-Lc:/mingw/lib'
'-lgtk-win32-2.0'
'-lgdk-win32-2.0'
'-latk-1.0'
'-lgdk_pixbuf-2.0'
'-lpangowin32-1.0'
'-lgdi32'
'-lpangocairo-1.0'
'-lpango-1.0'
'-lcairo'
'-lgobject-2.0'
'-lgmodule-2.0'
'-lglib-2.0'
'-lintl'
'
```
Notice the one single quote on the last line. It looks like argc is one greater than it should be, and argv[argc - 1] is null. Running the same test on Linux does not have this result.
That said, is there, say, some way I could have the Makefile store the result of pkg-config into a variable, and then use that variable, rather than using the back-tick operator? | >
> That said, is there, say, some way I could have the Makefile store the result of pkg-config into a variable, and then use that variable, rather than using the back-tick operator?
>
>
>
GTK\_LIBS = $(shell pkg-config --libs gtk+-2.0) |
101,777 | <p>Let's say I have this code:</p>
<pre><code>if (md5($_POST[$foo['bar']]) == $somemd5) {
doSomethingWith(md5($_POST[$foo['bar']]);
}
</code></pre>
<p>I could shorten that down by doing:</p>
<pre><code>$value = md5($_POST[$foo['bar']];
if ($value == $somemd5) {
doSomethingWith($value);
}
</code></pre>
<p>But is there any pre-set variable that contains the first or second condition of the current if? Like for instance:</p>
<pre><code>if (md5($_POST[$foo['bar']]) == $somemd5) {
doSomethingWith($if1);
}
</code></pre>
<p>May be a unnecessary way of doing it, but I'm just wondering.</p>
| [
{
"answer_id": 101805,
"author": "smo",
"author_id": 16080,
"author_profile": "https://Stackoverflow.com/users/16080",
"pm_score": 4,
"selected": true,
"text": "<p>No, but since the assignment itself is an expression, you can use the assignment as the conditional expression for the if statement.</p>\n\n<pre>\nif (($value = md5(..)) == $somemd5) { ... }\n</pre>\n\n<p>In general, though, you'll want to avoid embedding assignments into conditional expressions:</p>\n\n<ul>\n<li>The code is denser and therefore harder to read, with more nested parentheses.</li>\n<li>Mixing = and == in the same expression is just asking for them to get mixed up.</li>\n</ul>\n"
},
{
"answer_id": 101817,
"author": "Zsolt Szeberenyi",
"author_id": 15440,
"author_profile": "https://Stackoverflow.com/users/15440",
"pm_score": 1,
"selected": false,
"text": "<p>Since the if is just using the result of an expression, you can't access parts of it.\nJust store the results of the functions in a variable, like you wrote in your second snippet.</p>\n"
},
{
"answer_id": 101867,
"author": "Paweł Hajdan",
"author_id": 9403,
"author_profile": "https://Stackoverflow.com/users/9403",
"pm_score": 1,
"selected": false,
"text": "<p>IMHO your 2nd example (quoting below in case someone edits the question) is just ok. You can obscure the code with some tricks, but for me this is the best. In more complicated cases this advise may not apply.</p>\n\n<blockquote>\n <p>$value = md5($_POST[foo['bar']];</p>\n \n <p>if ($value) == $somemd5) {</p>\n\n<pre><code> doSomethingWith($value);\n</code></pre>\n \n <p>}</p>\n</blockquote>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15214/"
]
| Let's say I have this code:
```
if (md5($_POST[$foo['bar']]) == $somemd5) {
doSomethingWith(md5($_POST[$foo['bar']]);
}
```
I could shorten that down by doing:
```
$value = md5($_POST[$foo['bar']];
if ($value == $somemd5) {
doSomethingWith($value);
}
```
But is there any pre-set variable that contains the first or second condition of the current if? Like for instance:
```
if (md5($_POST[$foo['bar']]) == $somemd5) {
doSomethingWith($if1);
}
```
May be a unnecessary way of doing it, but I'm just wondering. | No, but since the assignment itself is an expression, you can use the assignment as the conditional expression for the if statement.
```
if (($value = md5(..)) == $somemd5) { ... }
```
In general, though, you'll want to avoid embedding assignments into conditional expressions:
* The code is denser and therefore harder to read, with more nested parentheses.
* Mixing = and == in the same expression is just asking for them to get mixed up. |
101,783 | <p>Anyone happen to have a sample script for recursing a given directory in a filesystem with Powershell? Ultimately what I'm wanting to do is create a script that will generate NSIS file lists for me given a directory. Something very similar to what was done <a href="http://blogs.oracle.com/duffblog/2006/12/dynamic_file_list_with_nsis.html" rel="nofollow noreferrer">here</a> with a BASH script.</p>
| [
{
"answer_id": 106413,
"author": "halr9000",
"author_id": 6637,
"author_profile": "https://Stackoverflow.com/users/6637",
"pm_score": 2,
"selected": false,
"text": "<p>This is a \"paraphrase\" port of that bash script.</p>\n\n<pre><code>$path = \"c:\\path\\to\\program\"\n$installFiles = \"installfiles_list.txt\"\n$uninstFiles = \"uninstfiles_list.txt\"\n$files = get-childitem -path $path -recurse | where-object { ! $_.psIsContainer } # won't include dirs\n$filepath = $files | foreach-object { $_.FullName }\n$filepath | set-content $installFiles -encoding ASCII\n$filepath[($filepath.length-1)..0] | set-content $uninstFiles -encoding ASCII\n</code></pre>\n"
},
{
"answer_id": 151396,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 3,
"selected": true,
"text": "<p>As <a href=\"https://stackoverflow.com/questions/101783/recursing-the-file-system-with-powershell#106413\">halr9000</a> demonstrated, you can use the <code>-recurse</code> switch parameter of the <code>Get-ChildItem</code> cmdlet to retrieve all files and directories under a specified path.</p>\n\n<p>It looks like the bash script you linked to in your question saves out the directories as well, so here is a simple function to return both the files and directories in a single result object:</p>\n\n<pre><code>function Get-InstallFiles {\n param( [string]$path )\n\n $allItems = Get-ChildItem -path $path -recurse\n $directories = $allItems | ? { $_.PSIsContainer } | % { $_.FullName }\n $installFiles = $allItems | ? { -not $_.PSIsContainer } | % { $_.FullName }\n $uninstallFiles = $installFiles[-1..-$installFiles.Length]\n\n $result = New-Object PSObject\n $result | Add-Member NoteProperty Directories $directories\n $result | Add-Member NoteProperty InstallFiles $installFiles\n $result | Add-Member NoteProperty UninstallFiles $uninstallFiles\n return $result\n}\n</code></pre>\n\n<p>Here is how you could use it to create the same install/uninstall text files from halr9000's example, including uninstall directories:</p>\n\n<pre><code>$files = Get-InstallFiles 'C:\\some\\directory'\n$files.InstallFiles | Set-Content 'installfiles.txt'\n$files.UninstallFiles + $files.Directories | Set-Content 'uninstallfiles.txt'\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18831/"
]
| Anyone happen to have a sample script for recursing a given directory in a filesystem with Powershell? Ultimately what I'm wanting to do is create a script that will generate NSIS file lists for me given a directory. Something very similar to what was done [here](http://blogs.oracle.com/duffblog/2006/12/dynamic_file_list_with_nsis.html) with a BASH script. | As [halr9000](https://stackoverflow.com/questions/101783/recursing-the-file-system-with-powershell#106413) demonstrated, you can use the `-recurse` switch parameter of the `Get-ChildItem` cmdlet to retrieve all files and directories under a specified path.
It looks like the bash script you linked to in your question saves out the directories as well, so here is a simple function to return both the files and directories in a single result object:
```
function Get-InstallFiles {
param( [string]$path )
$allItems = Get-ChildItem -path $path -recurse
$directories = $allItems | ? { $_.PSIsContainer } | % { $_.FullName }
$installFiles = $allItems | ? { -not $_.PSIsContainer } | % { $_.FullName }
$uninstallFiles = $installFiles[-1..-$installFiles.Length]
$result = New-Object PSObject
$result | Add-Member NoteProperty Directories $directories
$result | Add-Member NoteProperty InstallFiles $installFiles
$result | Add-Member NoteProperty UninstallFiles $uninstallFiles
return $result
}
```
Here is how you could use it to create the same install/uninstall text files from halr9000's example, including uninstall directories:
```
$files = Get-InstallFiles 'C:\some\directory'
$files.InstallFiles | Set-Content 'installfiles.txt'
$files.UninstallFiles + $files.Directories | Set-Content 'uninstallfiles.txt'
``` |
101,806 | <p>I am working on an application that installs a system wide keyboard
hook. I do not want to install this hook when I am running a debug
build from inside the visual studio (or else it would hang the studio
and eventually the system), and I can avoid this by checking if the
DEBUG symbol is defined.</p>
<p>However, when I debug the <em>release</em> version of the application, is
there a way to detect that it has been started from inside visual
studio to avoid the same problem? It is very annoying to have to
restart the studio/the computer, just because I had been working on
the release build, and want to fix some bugs using the debugger having
forgotten to switch back to the debug build. </p>
<p>Currently I use something like this to check for this scenario:</p>
<pre><code>System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
string moduleName = currentProcess.MainModule.ModuleName;
bool launchedFromStudio = moduleName.Contains(".vshost");
</code></pre>
<p>I would call this the "brute force way", which works in my setting, but I would like to know whether there's another (better) way of detecting this scenario.</p>
| [
{
"answer_id": 101812,
"author": "TraumaPony",
"author_id": 18658,
"author_profile": "https://Stackoverflow.com/users/18658",
"pm_score": 7,
"selected": true,
"text": "<p>Try: <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.isattached.aspx\" rel=\"noreferrer\"><code>System.Diagnostics.Debugger.IsAttached</code></a></p>\n"
},
{
"answer_id": 101915,
"author": "William Casarin",
"author_id": 10486,
"author_profile": "https://Stackoverflow.com/users/10486",
"pm_score": 4,
"selected": false,
"text": "<p>For those working with Windows API, there's a function which allows you to see if any debugger is present using:</p>\n\n<pre><code>if( IsDebuggerPresent() )\n{\n ...\n}\n</code></pre>\n\n<p>Reference: <a href=\"http://msdn.microsoft.com/en-us/library/ms680345.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms680345.aspx</a></p>\n"
},
{
"answer_id": 12102885,
"author": "TonyT",
"author_id": 1621506,
"author_profile": "https://Stackoverflow.com/users/1621506",
"pm_score": 3,
"selected": false,
"text": "<p>Testing whether or not the module name of the current process contains the string \".vshost\" is the best way I have found to determine whether or not the application is running from within the VS IDE.</p>\n\n<p>Using the <strong>System.Diagnostics.Debugger.IsAttached</strong> property is also okay but it does not allow you to distinguish if you are running the EXE through the VS IDE's <strong><em>Run</em></strong> command or if you are running the debug build directly (e.g. using Windows Explorer or a Shortcut) and then attaching to it using the VS IDE.</p>\n\n<p>You see I once encountered a problem with a (COM related) <em>Data Execution Prevention</em> error that required me to run a <em>Post Build Event</em> that would execute <strong>editbin.exe</strong> with the <strong>/NXCOMPAT:NO</strong> parameter on the VS generated EXE.</p>\n\n<p>For some reason the EXE was not modified if you just hit <strong><em>F5</em></strong> and run the program and therefore <strong>AccessViolationExceptions</strong> would occur on DEP-violating code if run from within the VS IDE - which made it extremely difficult to debug. However, I found that if I run the generated EXE via a short cut and then attached the VS IDE debugger I could then test my code without AccessViolationExceptions occurring.</p>\n\n<p>So now I have created a function which uses the \"vshost\" method that I can use to warn about, or block, certain code from running if I am just doing my daily programming grind from within the VS IDE. </p>\n\n<p>This prevents those nasty AccessViolationExceptions from being raised and thereby fatally crashing the my application if I inadvertently attempt to run something that I know will cause me grief.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17378/"
]
| I am working on an application that installs a system wide keyboard
hook. I do not want to install this hook when I am running a debug
build from inside the visual studio (or else it would hang the studio
and eventually the system), and I can avoid this by checking if the
DEBUG symbol is defined.
However, when I debug the *release* version of the application, is
there a way to detect that it has been started from inside visual
studio to avoid the same problem? It is very annoying to have to
restart the studio/the computer, just because I had been working on
the release build, and want to fix some bugs using the debugger having
forgotten to switch back to the debug build.
Currently I use something like this to check for this scenario:
```
System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
string moduleName = currentProcess.MainModule.ModuleName;
bool launchedFromStudio = moduleName.Contains(".vshost");
```
I would call this the "brute force way", which works in my setting, but I would like to know whether there's another (better) way of detecting this scenario. | Try: [`System.Diagnostics.Debugger.IsAttached`](http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.isattached.aspx) |
101,818 | <p>When I run indent with various options I want against my source, it does what I want but also messes with the placement of *s in pointer types:</p>
<pre><code> -int send_pkt(tpkt_t* pkt, void* opt_data);
-void dump(tpkt_t* bp);
+int send_pkt(tpkt_t * pkt, void *opt_data);
+void dump(tpkt * bp);
</code></pre>
<p>I know my placement of *s next to the type not the variable is unconventional but how can I get indent to just leave them alone? Or is there another tool that will do what I want? I've looked in the man page, the info page, and visited a half a dozen pages that Google suggested and I can't find an option to do this. </p>
<p>I tried Artistic Style (a.k.a. AStyle) but can't seem to figure out how to make it indent in multiples of 4 but make every 8 a tab. That is:</p>
<pre><code>if ( ... ) {
<4spaces>if ( ... ) {
<tab>...some code here...
<4spaces>}
}
</code></pre>
| [
{
"answer_id": 101835,
"author": "Chris M.",
"author_id": 6747,
"author_profile": "https://Stackoverflow.com/users/6747",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Uncrustify</strong> </p>\n\n<p>Uncrustify has several options on how to indent your files. </p>\n\n<p>From the config file: </p>\n\n<pre>indent_with_tabs \n How to use tabs when indenting code \n 0=spaces only \n 1=indent with tabs, align with spaces \n 2=indent and align with tabs</pre>\n\n<p>You can find it <a href=\"http://uncrustify.sourceforge.net/\" rel=\"noreferrer\">here</a>.</p>\n\n<p><strong>BCPP</strong><br>\nFrom the website: <em>\"bcpp indents C/C++ source programs, replacing tabs with spaces or the reverse. Unlike indent, it does (by design) not attempt to wrap long statements.\"</em><br>\nFind it <a href=\"http://invisible-island.net/bcpp/\" rel=\"noreferrer\">here</a>.</p>\n\n<p><strong>UniversalIndentGUI</strong><br>\nIt's a tool which supports several beautifiers / formatters. It could lead you to even more alternatives.<br>\nFind it <a href=\"http://universalindent.sourceforge.net/\" rel=\"noreferrer\">here</a>.</p>\n\n<p><strong>Artistic Style</strong><br>\nYou could try <a href=\"http://astyle.sourceforge.net/\" rel=\"noreferrer\">Artistic Style aka AStyle</a> instead (even though it doesn't do what you need it to do, I'll leave it here in case someone else finds it useful).</p>\n"
},
{
"answer_id": 101886,
"author": "Paweł Hajdan",
"author_id": 9403,
"author_profile": "https://Stackoverflow.com/users/9403",
"pm_score": 2,
"selected": false,
"text": "<p>Hack around and change its behavior editing the code. It's GNU after all. ;-)</p>\n\n<p>As it's probably not the answer you wanted, here's another link: <a href=\"http://www.fnal.gov/docs/working-groups/c++wg/indenting.html\" rel=\"nofollow noreferrer\">http://www.fnal.gov/docs/working-groups/c++wg/indenting.html</a>.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7685/"
]
| When I run indent with various options I want against my source, it does what I want but also messes with the placement of \*s in pointer types:
```
-int send_pkt(tpkt_t* pkt, void* opt_data);
-void dump(tpkt_t* bp);
+int send_pkt(tpkt_t * pkt, void *opt_data);
+void dump(tpkt * bp);
```
I know my placement of \*s next to the type not the variable is unconventional but how can I get indent to just leave them alone? Or is there another tool that will do what I want? I've looked in the man page, the info page, and visited a half a dozen pages that Google suggested and I can't find an option to do this.
I tried Artistic Style (a.k.a. AStyle) but can't seem to figure out how to make it indent in multiples of 4 but make every 8 a tab. That is:
```
if ( ... ) {
<4spaces>if ( ... ) {
<tab>...some code here...
<4spaces>}
}
``` | **Uncrustify**
Uncrustify has several options on how to indent your files.
From the config file:
```
indent_with_tabs
How to use tabs when indenting code
0=spaces only
1=indent with tabs, align with spaces
2=indent and align with tabs
```
You can find it [here](http://uncrustify.sourceforge.net/).
**BCPP**
From the website: *"bcpp indents C/C++ source programs, replacing tabs with spaces or the reverse. Unlike indent, it does (by design) not attempt to wrap long statements."*
Find it [here](http://invisible-island.net/bcpp/).
**UniversalIndentGUI**
It's a tool which supports several beautifiers / formatters. It could lead you to even more alternatives.
Find it [here](http://universalindent.sourceforge.net/).
**Artistic Style**
You could try [Artistic Style aka AStyle](http://astyle.sourceforge.net/) instead (even though it doesn't do what you need it to do, I'll leave it here in case someone else finds it useful). |
101,825 | <p>That is, I'd like to have a tuple of values.</p>
<p>The use case on my mind:</p>
<pre><code>Dictionary<Pair<string, int>, object>
</code></pre>
<p>or</p>
<pre><code>Dictionary<Triple<string, int, int>, object>
</code></pre>
<p>Are there built-in types like Pair or Triple? Or what's the best way of implementing it?</p>
<p><strong>Update</strong> There are some general-purpose tuples implementations described in the answers, but for tuples used as keys in dictionaries you should additionaly verify correct calculation of the hash code. Some more info on that in another <a href="https://stackoverflow.com/questions/102690/how-does-c-figure-out-the-hash-code-for-an-object">question</a>.</p>
<p><strong>Update 2</strong> I guess it is also worth reminding, that when you use some value as a key in dictionary, it should be immutable.</p>
| [
{
"answer_id": 101841,
"author": "Grad van Horck",
"author_id": 12569,
"author_profile": "https://Stackoverflow.com/users/12569",
"pm_score": 2,
"selected": false,
"text": "<p>I usually just create my own struct, containing the values. It's often a bit more readable ;)</p>\n"
},
{
"answer_id": 101848,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>There aren't built ins, but a Pair<T,R> class is trivial to create. </p>\n"
},
{
"answer_id": 101854,
"author": "Adam Vigh",
"author_id": 1613872,
"author_profile": "https://Stackoverflow.com/users/1613872",
"pm_score": 3,
"selected": false,
"text": "<p>Pair and Triplet are existing classes in .net see msdn:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.triplet.aspx\" rel=\"nofollow noreferrer\">Triplet</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx\" rel=\"nofollow noreferrer\">Pair</a></p>\n\n<p>I recently came across them, while playing around with viewstate decoding</p>\n"
},
{
"answer_id": 101858,
"author": "Timothy Carter",
"author_id": 4660,
"author_profile": "https://Stackoverflow.com/users/4660",
"pm_score": 4,
"selected": false,
"text": "<pre><code>public struct Pair<T1, T2>\n{\n public T1 First;\n public T2 Second;\n}\n\npublic struct Triple<T1, T2, T3>\n{\n public T1 First;\n public T2 Second;\n public T3 Third;\n}\n</code></pre>\n"
},
{
"answer_id": 101860,
"author": "ballpointpeon",
"author_id": 8269,
"author_profile": "https://Stackoverflow.com/users/8269",
"pm_score": 0,
"selected": false,
"text": "<p>Aye, there's System.Web.UI.Pair and System.Web.UI.Triplet (which has an overloaded creator for Pair-type behaviour!)</p>\n"
},
{
"answer_id": 101861,
"author": "Jonas Lincoln",
"author_id": 17436,
"author_profile": "https://Stackoverflow.com/users/17436",
"pm_score": 0,
"selected": false,
"text": "<p>For the first case, I usually use</p>\n\n<pre><code>Dictionary<KeyValuePair<string, int>, object>\n</code></pre>\n"
},
{
"answer_id": 101863,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>There are not built-in classes for that. You can use <a href=\"http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx\" rel=\"nofollow noreferrer\">KeyValuePair</a> or roll out your own implementation.</p>\n"
},
{
"answer_id": 101866,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<p>You could use System.Collections.Generic.KeyValuePair as your Pair implementation.</p>\n\n<p>Or you could just implement your own, they aren't hard:</p>\n\n<pre><code>public class Triple<T, U, V>\n{\n public T First {get;set;}\n public U Second {get;set;}\n public V Third {get;set;}\n}\n</code></pre>\n\n<p>Of course, you may someday run into a problem that Triple(string, int, int) is not compatible with Triple(int, int, string). Maybe go with System.Xml.Linq.XElement instead.</p>\n"
},
{
"answer_id": 101882,
"author": "Michael L Perry",
"author_id": 7668,
"author_profile": "https://Stackoverflow.com/users/7668",
"pm_score": 4,
"selected": true,
"text": "<p>I have implemented a tuple library in C#. Visit <a href=\"http://www.adventuresinsoftware.com/generics/\" rel=\"noreferrer\">http://www.adventuresinsoftware.com/generics/</a> and click on the \"tuples\" link.</p>\n"
},
{
"answer_id": 101913,
"author": "TraumaPony",
"author_id": 18658,
"author_profile": "https://Stackoverflow.com/users/18658",
"pm_score": 0,
"selected": false,
"text": "<p>There are also the Tuple<> types in F#; you just need to reference FSharp.Core.dll.</p>\n"
},
{
"answer_id": 101926,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 2,
"selected": false,
"text": "<p><strong>KeyValuePair</strong> is the best class to extend if you don't want to create your own classes.</p>\n\n<pre><code>int id = 33;\nstring description = \"This is a custom solution\";\nDateTime created = DateTime.Now;\n\nKeyValuePair<int, KeyValuePair<string, DateTime>> triple =\n new KeyValuePair<int, KeyValuePair<string, DateTime>>();\ntriple.Key = id;\ntriple.Value.Key = description;\ntriple.Value.Value = created;\n</code></pre>\n\n<p>You can extend it to as many levels as you want.</p>\n\n<pre><code>KeyValuePair<KeyValuePair<KeyValuePair<string, string>, string, string> quadruple =\n new KeyValuePair<KeyValuePair<KeyValuePair<string, string>, string, string>();\n</code></pre>\n\n<p><strong>Note</strong>: The classes <strong>Triplet</strong> and <strong>Pair</strong> exists inside the <strong>System.Web</strong>-dll, so it's not very suitable for other solutions than ASP.NET.</p>\n"
},
{
"answer_id": 102744,
"author": "Maxime Labelle",
"author_id": 18865,
"author_profile": "https://Stackoverflow.com/users/18865",
"pm_score": 4,
"selected": false,
"text": "<h2><strong>Builtin Classes</strong></h2>\n\n<p>In certain specific cases, the .net framework already provides tuple-like classes that you may be able to leverage.</p>\n\n<p><strong><em>Pairs and Triples</em></strong></p>\n\n<p>The generic \n<strong><a href=\"http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx\" rel=\"nofollow noreferrer\">System.Collections.Generic.KeyValuePair</a></strong>\nclass could be used as an adhoc pair implementation. This is the class that the\ngeneric Dictionary uses internally.</p>\n\n<p>Alternatively, you may be able to make do with the\n<strong><a href=\"http://msdn.microsoft.com/en-us/library/system.collections.dictionaryentry.aspx\" rel=\"nofollow noreferrer\">System.Collections.DictionaryEntry</a></strong>\nstructure that acts as a rudimentary pair and has the advantage of\nbeing available in mscorlib. On the down side, however, is that this structure is not\nstrongly typed.</p>\n\n<p>Pairs and Triples are also available in the form of the\n<strong><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx\" rel=\"nofollow noreferrer\">System.Web.UI.Pair</a></strong> and\n<strong><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.triplet.aspx\" rel=\"nofollow noreferrer\">System.Web.UI.Triplet</a></strong> classes. Even though theses classes live in the the <em>System.Web</em> assembly\nthey might be perfectly suitable for winforms development. However, these classes are\nnot strongly typed either and might not be suitable in some scenarios, such as a general purposed framework or library.</p>\n\n<p><strong><em>Higher order tuples</em></strong></p>\n\n<p>For higher order tuples, short of rolling your own class, there may\nnot be a simple solution.</p>\n\n<p>If you have installed the \n<a href=\"http://research.microsoft.com/fsharp/fsharp.aspx\" rel=\"nofollow noreferrer\">F# language</a>, you could reference the <em>FSharp.Core.dll</em> that contains a set of generic immutable \n<strong><a href=\"http://research.microsoft.com/fsharp/manual/export-interop.aspx?0sr=a#Tuples\" rel=\"nofollow noreferrer\">Microsoft.Fsharp.Core.Tuple</a></strong> classes\nup to generic sextuples. However, even though an unmodified <em>FSharp.Code.dll</em>\ncan be redistributed, F# is a research language and a work in progress so\nthis solution is likely to be of interest only in academic circles.</p>\n\n<p>If you do not want to create your own class and are uncomfortable\nreferencing the F# library, one nifty trick could consist in extending the generic KeyValuePair class so that the Value member is itself a nested KeyValuePair. </p>\n\n<p>For instance, the following code illustrates how you could leverage the\nKeyValuePair in order to create a Triples:</p>\n\n<pre><code>int id = 33;\nstring description = \"This is a custom solution\";\nDateTime created = DateTime.Now;\n\nKeyValuePair<int, KeyValuePair<string, DateTime>> triple =\n new KeyValuePair<int, KeyValuePair<string, DateTime>>();\ntriple.Key = id;\ntriple.Value.Key = description;\ntriple.Value.Value = created;\n</code></pre>\n\n<p>This allows to extend the class to any arbitrary level as is required.</p>\n\n<pre><code>KeyValuePair<KeyValuePair<KeyValuePair<string, string>, string>, string> quadruple =\n new KeyValuePair<KeyValuePair<KeyValuePair<string, string>, string>, string>();\nKeyValuePair<KeyValuePair<KeyValuePair<KeyValuePair<string, string>, string>, string>, string> quintuple =\n new KeyValuePair<KeyValuePair<KeyValuePair<KeyValuePair<string, string>, string>, string>, string>();\n</code></pre>\n\n<h2><strong>Roll Your Own</strong></h2>\n\n<p>In other cases, you might need to resort to rolling your own\ntuple class, and this is not hard.</p>\n\n<p>You can create simple structures like so:</p>\n\n<pre><code>struct Pair<T, R>\n{\n private T first_;\n private R second_;\n\n public T First\n {\n get { return first_; }\n set { first_ = value; }\n }\n\n public R Second\n {\n get { return second_; }\n set { second_ = value; }\n }\n}\n</code></pre>\n\n<h2><strong>Frameworks and Libraries</strong></h2>\n\n<p>This problem has been tackled before and general purpose frameworks\ndo exist. Below is a link to one such framework:</p>\n\n<ul>\n<li><a href=\"http://www.adventuresinsoftware.com/generics/\" rel=\"nofollow noreferrer\">Tuple Library</a> by\n<a href=\"https://stackoverflow.com/users/7668/michael-l-perry\">Michael L Perry</a>.</li>\n</ul>\n"
},
{
"answer_id": 103348,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "<p>You can relatively easily create your own tuple classes, the only thing that potentially gets messy is your equality and hashcode overrides (essential if you're going to use them in dictionaries).</p>\n\n<p>It should be noted that .Net's own <code>KeyValuePair<TKey,TValue></code> struct has <a href=\"http://bizvprog.blogspot.com/2008/06/c-value-types-and-equality.html\" rel=\"nofollow noreferrer\">relatively slow equality and hashcode methods</a>.</p>\n\n<p>Assuming that isn't a concern for you there is still the problem that the code ends up being hard to figure out:</p>\n\n<pre><code>public Tuple<int, string, int> GetSomething() \n{\n //do stuff to get your multi-value return\n}\n\n//then call it:\nvar retVal = GetSomething();\n\n//problem is what does this mean?\nretVal.Item1 / retVal.Item3; \n//what are item 1 and 3?\n</code></pre>\n\n<p>In most of these cases I find it easier to create a specific record class (at least until C#4 makes this compiler-magic)</p>\n\n<pre><code>class CustomRetVal {\n int CurrentIndex { get; set; }\n string Message { get; set; }\n int CurrentTotal { get; set; }\n}\n\nvar retVal = GetSomething();\n\n//get % progress\nretVal.CurrentIndex / retVal.CurrentTotal;\n</code></pre>\n"
},
{
"answer_id": 1662395,
"author": "husayt",
"author_id": 15461,
"author_profile": "https://Stackoverflow.com/users/15461",
"pm_score": 1,
"selected": false,
"text": "<p>NGenerics - the popular .Net algorithms and data structures library, has recently introduced <strong>immutable</strong> data structures to the set. </p>\n\n<p>The first immutable ones to implement were <strong>pair</strong> and <strong>tuple</strong> classes. The code is well covered with tests and is quite elegant. You can check it <a href=\"http://code.google.com/p/ngenerics/source/browse/branches/immutable/Source/NGenerics/DataStructures/Immutable/\" rel=\"nofollow noreferrer\">here</a>. They are working on the other immutable alternatives at the moment and they should be ready shortly.</p>\n"
},
{
"answer_id": 2562496,
"author": "mafu",
"author_id": 39590,
"author_profile": "https://Stackoverflow.com/users/39590",
"pm_score": 2,
"selected": false,
"text": "<p>One simple solution has no been mentioned yet. You can also just use a <code>List<T></code>. It's built in, efficient and easy to use. Granted, it looks a bit weird at first, but it does its job perfectly, especially for a larger count of elements.</p>\n"
},
{
"answer_id": 3485762,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 4,
"selected": false,
"text": "<p>Fast-forward to 2010, .NET 4.0 now supports <a href=\"http://msdn.microsoft.com/en-us/library/dd383325.aspx\" rel=\"noreferrer\">n-tuples of arbitrary n</a>. These tuples implement structural equality and comparison as expected.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351099/"
]
| That is, I'd like to have a tuple of values.
The use case on my mind:
```
Dictionary<Pair<string, int>, object>
```
or
```
Dictionary<Triple<string, int, int>, object>
```
Are there built-in types like Pair or Triple? Or what's the best way of implementing it?
**Update** There are some general-purpose tuples implementations described in the answers, but for tuples used as keys in dictionaries you should additionaly verify correct calculation of the hash code. Some more info on that in another [question](https://stackoverflow.com/questions/102690/how-does-c-figure-out-the-hash-code-for-an-object).
**Update 2** I guess it is also worth reminding, that when you use some value as a key in dictionary, it should be immutable. | I have implemented a tuple library in C#. Visit <http://www.adventuresinsoftware.com/generics/> and click on the "tuples" link. |
101,850 | <p>Take this code:</p>
<pre><code><?php
if (isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
}
if ($action) {
echo $action;
}
else {
echo 'No variable';
}
?>
</code></pre>
<p>And then access the file with ?action=test
Is there any way of preventing $action from automatically being declared by the GET? Other than of course adding</p>
<pre><code>&& !isset($_GET['action'])
</code></pre>
<p>Why would I want the variable to be declared for me?</p>
| [
{
"answer_id": 101879,
"author": "owenmarshall",
"author_id": 9806,
"author_profile": "https://Stackoverflow.com/users/9806",
"pm_score": 6,
"selected": true,
"text": "<p>Check your php.ini for the <code>register_globals</code> setting. It is probably on, you want it off.</p>\n\n<blockquote>\n <p>Why would I want the variable to be declared for me?</p>\n</blockquote>\n\n<p><a href=\"http://us3.php.net/manual/en/security.globals.php\" rel=\"nofollow noreferrer\">You don't.</a> It's a horrible security risk. It makes the Environment, GET, POST, Cookie and Server variables global <a href=\"http://us3.php.net/manual/en/ini.core.php#ini.register-globals\" rel=\"nofollow noreferrer\">(PHP manual)</a>. These are a handful of <a href=\"http://us.php.net/manual/en/reserved.variables.php\" rel=\"nofollow noreferrer\">reserved variables</a> in PHP.</p>\n"
},
{
"answer_id": 101898,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": 2,
"selected": false,
"text": "<p>Looks like <code>register_globals</code> in your php.ini is the culprit. You should turn this off. It's also a huge security risk to have it on.</p>\n\n<p>If you're on shared hosting and can't modify php.ini, you can use <a href=\"http://php.net/ini_set\" rel=\"nofollow noreferrer\">ini_set()</a> to turn register_globals off.</p>\n"
},
{
"answer_id": 101904,
"author": "Nikki9696",
"author_id": 456669,
"author_profile": "https://Stackoverflow.com/users/456669",
"pm_score": 2,
"selected": false,
"text": "<p>Set register_globals to off, if I'm understanding your question.\nSee <a href=\"http://us2.php.net/manual/en/language.variables.predefined.php\" rel=\"nofollow noreferrer\">http://us2.php.net/manual/en/language.variables.predefined.php</a></p>\n"
},
{
"answer_id": 101908,
"author": "Johannes Hädrich",
"author_id": 18246,
"author_profile": "https://Stackoverflow.com/users/18246",
"pm_score": 1,
"selected": false,
"text": "<p>You can test, whether all variables are declared properly by turning the PHP log-level in PHP.INI to </p>\n\n<pre><code>error_reporting = E_ALL \n</code></pre>\n\n<p>Your code snippet now should generate a NOTICE. </p>\n"
},
{
"answer_id": 104297,
"author": "SeanDowney",
"author_id": 5261,
"author_profile": "https://Stackoverflow.com/users/5261",
"pm_score": 1,
"selected": false,
"text": "<p>At some point in php's history they made the controversial decision to turn off register_globals by default as it was a huge security hazard. It gives anyone the potential to inject variables in your code, create unthinkable consequences! This \"feature\" is even removed in php6</p>\n\n<p>If you notice that it's on contact your administrator to turn it off.</p>\n"
},
{
"answer_id": 104365,
"author": "Bob Fanger",
"author_id": 19165,
"author_profile": "https://Stackoverflow.com/users/19165",
"pm_score": 2,
"selected": false,
"text": "<p>if you don't have access to the <em>php.ini</em>, a <code>ini_set('register_globals', false)</code> in the php script won't work (variables are already declared) \nAn <em>.htacces</em>s with:</p>\n\n<pre><code>php_flag register_globals Off\n</code></pre>\n\n<p>can sometimes help.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15214/"
]
| Take this code:
```
<?php
if (isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
}
if ($action) {
echo $action;
}
else {
echo 'No variable';
}
?>
```
And then access the file with ?action=test
Is there any way of preventing $action from automatically being declared by the GET? Other than of course adding
```
&& !isset($_GET['action'])
```
Why would I want the variable to be declared for me? | Check your php.ini for the `register_globals` setting. It is probably on, you want it off.
>
> Why would I want the variable to be declared for me?
>
>
>
[You don't.](http://us3.php.net/manual/en/security.globals.php) It's a horrible security risk. It makes the Environment, GET, POST, Cookie and Server variables global [(PHP manual)](http://us3.php.net/manual/en/ini.core.php#ini.register-globals). These are a handful of [reserved variables](http://us.php.net/manual/en/reserved.variables.php) in PHP. |
101,868 | <p>Is there any easy to install/use (on unix) database migration tools like Rails Migrations? I really like the idea, but installing ruby/rails purely to manage my database migrations seems overkill.</p>
| [
{
"answer_id": 102353,
"author": "Otto",
"author_id": 9594,
"author_profile": "https://Stackoverflow.com/users/9594",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't personally done it, but it should be possible to use ActiveRecord::Migration without any of the other Rails stuff. Setting up the load path correctly would be the hard part, but really all you need is the <code>rake</code> tasks and the <code>db/migrate</code> directory plus whatever Rails gems they depend on, probably <code>activerecord</code>, <code>actviesupport</code> and maybe a couple others like <code>railties</code>. I'd try it and just see what classes are missing and add those in.</p>\n\n<p>At a previous company we built a tool that did essentially what ActiveRecord::Migration does, except it was written in Java as a Maven plugin. All it did was assemble text blobs of SQL scripts. It just needs to be smart about the filenames going in order and know how to update a versioning table.</p>\n"
},
{
"answer_id": 104903,
"author": "Ryan McGeary",
"author_id": 8985,
"author_profile": "https://Stackoverflow.com/users/8985",
"pm_score": 6,
"selected": true,
"text": "<p>Just use ActiveRecord and a simple Rakefile. For example, if you put your migrations in a <code>db/migrate</code> directory and have a <code>database.yml</code> file that has your db config, this simple Rakefile should work:</p>\n\n<p><strong>Rakefile:</strong></p>\n\n<pre><code>require 'active_record'\nrequire 'yaml'\n\ndesc \"Migrate the database through scripts in db/migrate. Target specific version with VERSION=x\"\ntask :migrate => :environment do\n ActiveRecord::Migrator.migrate('db/migrate', ENV[\"VERSION\"] ? ENV[\"VERSION\"].to_i : nil)\nend\n\ntask :environment do\n ActiveRecord::Base.establish_connection(YAML::load(File.open('database.yml')))\n ActiveRecord::Base.logger = Logger.new(STDOUT)\nend\n</code></pre>\n\n<p><strong>database.yml</strong>:</p>\n\n<pre><code>adapter: mysql\nencoding: utf8\ndatabase: test_database\nusername: root\npassword:\nhost: localhost\n</code></pre>\n\n<p>Afterwards, you'll be able to run <code>rake migrate</code> and have all the migration goodness without a surrounding rails app.</p>\n\n<p>Alternatively, I have a set of bash scripts that perform a very similar function to ActiveRecord migrations, but they only work with Oracle. I used to use them before switching to Ruby and Rails. They are somewhat complicated and I provide no support for them, but if you are interested, feel free to contact me.</p>\n"
},
{
"answer_id": 106831,
"author": "Otto",
"author_id": 9594,
"author_profile": "https://Stackoverflow.com/users/9594",
"pm_score": 2,
"selected": false,
"text": "<p>There's also a project called <a href=\"http://blog.carbonfive.com/2008/09/java/java-database-migrations\" rel=\"nofollow noreferrer\">Java Database Migrations</a>. To get the code check out the <a href=\"http://code.google.com/p/c5-db-migration/\" rel=\"nofollow noreferrer\">Google Code page for the project</a>.</p>\n"
},
{
"answer_id": 1966161,
"author": "RyanWilcox",
"author_id": 224334,
"author_profile": "https://Stackoverflow.com/users/224334",
"pm_score": 2,
"selected": false,
"text": "<p>I see this topic is really old, but I'll chip in for future googlers.</p>\n\n<p>I really like using Python's SQLAlchemy and <a href=\"http://code.google.com/p/sqlalchemy-migrate/\" rel=\"nofollow noreferrer\">SQLAlchemy-Migrate </a> to manage databases that I need to version control, if you don't want to go the ActiveRecord::Migrate route.</p>\n"
},
{
"answer_id": 5880936,
"author": "Bret Weinraub",
"author_id": 869942,
"author_profile": "https://Stackoverflow.com/users/869942",
"pm_score": 1,
"selected": false,
"text": "<p>This project is designed to allow active record migrations to be run without installing Rails:</p>\n\n<p><a href=\"https://github.com/bretweinraub/rails-free-DB-Migrate\" rel=\"nofollow\">https://github.com/bretweinraub/rails-free-DB-Migrate</a></p>\n\n<p>Install it (git clone it) and use it as a base for your project.</p>\n"
},
{
"answer_id": 8418127,
"author": "noahdiewald",
"author_id": 463399,
"author_profile": "https://Stackoverflow.com/users/463399",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a tool to do this written in Haskell:</p>\n\n<p><a href=\"http://hackage.haskell.org/package/dbmigrations\" rel=\"nofollow\">http://hackage.haskell.org/package/dbmigrations</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3839/"
]
| Is there any easy to install/use (on unix) database migration tools like Rails Migrations? I really like the idea, but installing ruby/rails purely to manage my database migrations seems overkill. | Just use ActiveRecord and a simple Rakefile. For example, if you put your migrations in a `db/migrate` directory and have a `database.yml` file that has your db config, this simple Rakefile should work:
**Rakefile:**
```
require 'active_record'
require 'yaml'
desc "Migrate the database through scripts in db/migrate. Target specific version with VERSION=x"
task :migrate => :environment do
ActiveRecord::Migrator.migrate('db/migrate', ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
end
task :environment do
ActiveRecord::Base.establish_connection(YAML::load(File.open('database.yml')))
ActiveRecord::Base.logger = Logger.new(STDOUT)
end
```
**database.yml**:
```
adapter: mysql
encoding: utf8
database: test_database
username: root
password:
host: localhost
```
Afterwards, you'll be able to run `rake migrate` and have all the migration goodness without a surrounding rails app.
Alternatively, I have a set of bash scripts that perform a very similar function to ActiveRecord migrations, but they only work with Oracle. I used to use them before switching to Ruby and Rails. They are somewhat complicated and I provide no support for them, but if you are interested, feel free to contact me. |
101,877 | <p>How can I add Page transitions effects like IE in Safari for web pages?</p>
| [
{
"answer_id": 101961,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 3,
"selected": true,
"text": "<p>You could check out this example: <a href=\"http://sachiniscool.blogspot.com/2006/01/implementing-page-transitions-in.html\" rel=\"nofollow noreferrer\">http://sachiniscool.blogspot.com/2006/01/implementing-page-transitions-in.html</a>. It describes how to emulate page transitions in Firefox using AJAX and CSS. The same method works for Safari as well. The code below is taken from that page and slightly formatted:</p>\n\n<pre><code>var xmlhttp;\nvar timerId = 0;\nvar op = 1;\n\nfunction getPageFx() {\n url = \"/transpage2.html\";\n if (window.XMLHttpRequest) {\n xmlhttp = new XMLHttpRequest()\n xmlhttp.onreadystatechange=xmlhttpChange\n xmlhttp.open(\"GET\",url,true)\n xmlhttp.send(null)\n } else getPageIE();\n}\n\nfunction xmlhttpChange() {\n// if xmlhttp shows \"loaded\"\n if (xmlhttp.readyState == 4) {\n // if \"OK\"\n if (xmlhttp.status == 200) {\n if (timerId != 0)\n window.clearTimeout(timerId);\n timerId = window.setTimeout(\"trans();\",100);\n } else {\n alert(xmlhttp.status)\n }\n }\n}\n\nfunction trans() {\n op -= .1;\n document.body.style.opacity = op;\n if(op < .4) {\n window.clearTimeout(timerId);\n timerId = 0; document.body.style.opacity = 1;\n document.open();\n document.write(xmlhttp.responseText);\n document.close();\n return;\n }\n timerId = window.setTimeout(\"trans();\",100);\n}\n\nfunction getPageIE() {\n window.location.href = \"transpage2.html\";\n}\n</code></pre>\n"
},
{
"answer_id": 101967,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 1,
"selected": false,
"text": "<p>Check out <a href=\"http://github.com/madrobby/scriptaculous/wikis\" rel=\"nofollow noreferrer\">Scriptaculous</a>. Avoid IE-Only JS if that's what you are referring to (no idea what kind of effect you mean).</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
]
| How can I add Page transitions effects like IE in Safari for web pages? | You could check out this example: <http://sachiniscool.blogspot.com/2006/01/implementing-page-transitions-in.html>. It describes how to emulate page transitions in Firefox using AJAX and CSS. The same method works for Safari as well. The code below is taken from that page and slightly formatted:
```
var xmlhttp;
var timerId = 0;
var op = 1;
function getPageFx() {
url = "/transpage2.html";
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest()
xmlhttp.onreadystatechange=xmlhttpChange
xmlhttp.open("GET",url,true)
xmlhttp.send(null)
} else getPageIE();
}
function xmlhttpChange() {
// if xmlhttp shows "loaded"
if (xmlhttp.readyState == 4) {
// if "OK"
if (xmlhttp.status == 200) {
if (timerId != 0)
window.clearTimeout(timerId);
timerId = window.setTimeout("trans();",100);
} else {
alert(xmlhttp.status)
}
}
}
function trans() {
op -= .1;
document.body.style.opacity = op;
if(op < .4) {
window.clearTimeout(timerId);
timerId = 0; document.body.style.opacity = 1;
document.open();
document.write(xmlhttp.responseText);
document.close();
return;
}
timerId = window.setTimeout("trans();",100);
}
function getPageIE() {
window.location.href = "transpage2.html";
}
``` |
101,880 | <ul>
<li>I start up my application which uses a Jetty server, using port 9000.</li>
<li>I then shut down my application with Ctrl-C</li>
<li>I check with "netstat -a" and see that the port 9000 is no longer being used.</li>
<li>I restart my application and get:</li>
</ul>
<blockquote>
<pre><code>[ERROR,9/19 15:31:08] java.net.BindException: Only one usage of each socket address (protocol/network address/port) is normally permitted
[TRACE,9/19 15:31:08] java.net.BindException: Only one usage of each socket address (protocol/network address/port) is normally permitted
[TRACE,9/19 15:31:08] at java.net.PlainSocketImpl.convertSocketExceptionToIOException(PlainSocketImpl.java:75)
[TRACE,9/19 15:31:08] at sun.nio.ch.Net.bind(Net.java:101)
[TRACE,9/19 15:31:08] at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:126)
[TRACE,9/19 15:31:08] at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:77)
[TRACE,9/19 15:31:08] at org.mortbay.jetty.nio.BlockingChannelConnector.open(BlockingChannelConnector.java:73)
[TRACE,9/19 15:31:08] at org.mortbay.jetty.AbstractConnector.doStart(AbstractConnector.java:285)
[TRACE,9/19 15:31:08] at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40)
[TRACE,9/19 15:31:08] at org.mortbay.jetty.Server.doStart(Server.java:233)
[TRACE,9/19 15:31:08] at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40)
[TRACE,9/19 15:31:08] at ...
</code></pre>
</blockquote>
<p>Is this a Java bug? Can I avoid it somehow before starting the Jetty server?</p>
<p><strong>Edit #1</strong> Here is our code for creating our BlockingChannelConnector, note the "setReuseAddress(true)":</p>
<blockquote>
<pre><code> connector.setReuseAddress( true );
connector.setPort( port );
connector.setStatsOn( true );
connector.setMaxIdleTime( 30000 );
connector.setLowResourceMaxIdleTime( 30000 );
connector.setAcceptQueueSize( maxRequests );
connector.setName( "Blocking-IO Connector, bound to host " + connector.getHost() );
</code></pre>
</blockquote>
<p>Could it have something to do with the idle time?</p>
<p><strong>Edit #2</strong> Next piece of the puzzle that may or may not help: when running the application in Debug Mode (Eclipse) the server starts up without a problem!!! But the problem described above occurs reproducibly when running the application in Run Mode or as a built jar file. Whiskey Tango Foxtrot?</p>
<p><strong>Edit #3 (4 days later)</strong> - still have the issue. Any thoughts?</p>
| [
{
"answer_id": 101906,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 1,
"selected": false,
"text": "<p>You might want call <code>setReuseAddress(true)</code> before calling <code>bind()</code> on your socket object. This is caused by a TCP connection persisting even after the socket is closed.</p>\n"
},
{
"answer_id": 101943,
"author": "user12786",
"author_id": 12786,
"author_profile": "https://Stackoverflow.com/users/12786",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure about Jetty, but I have noticed that sometimes Tomcat will not shut down cleanly on some of our Linux servers. In cases like that, Tomcat will restart but not be able to use the port in question because the previous instance is still bound to it. In such cases, we have to find the rogue process and explicitly kill -9 it before we restart Tomcat. I'm not sure if this is a java bug or specific to Tomcat or the JVM we're using.</p>\n"
},
{
"answer_id": 101951,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 2,
"selected": false,
"text": "<p>During your first invocation of your program, did it accept at least one incoming connection? If so then what you are most likely seeing is the socket linger in effect. </p>\n\n<p>For the best explanation dig up a copy of TCP/IP Illustrated by Stevens </p>\n\n<p><a href=\"https://i.stack.imgur.com/DNDVu.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DNDVu.gif\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://www.kohala.com/start/gifs/tcpipiv1.gif\" rel=\"nofollow noreferrer\">kohala.com</a>)</sub> </p>\n\n<p>But, as I understand it, because the application did not properly close the connection (that is BOTH client and server sent their FIN/ACK sequences) the socket you were listening on cannot be reused until the connection is considered dead, the so called 2MSL timeout. The value of 1 MSL can vary by operating system, but its usually a least a minute, and usually more like 5. </p>\n\n<p>The best advice I have heard to avoid this condition (apart from always closing all sockets properly on exit) is to set the SO_LINGER tcp option to 0 on your server socket during the listen() phase. As freespace pointed out, in java this is the setReuseAddress(true) method.</p>\n"
},
{
"answer_id": 105131,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 0,
"selected": false,
"text": "<p>I must say I also thought that it's the usual issue solved by setReuseAddress(true). However, the error message in that case is usually something along the lines that the JVM can't bind to the port. I've never seen the posted error message before. Googling for it seems to suggest that another process is listening on one or more (but not all) network interfaces, and you request your process to bind to all interfaces, whereas it can bind to some (those that the other process isn't listening to) but not all of them. Just guessing here though...</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
]
| * I start up my application which uses a Jetty server, using port 9000.
* I then shut down my application with Ctrl-C
* I check with "netstat -a" and see that the port 9000 is no longer being used.
* I restart my application and get:
>
>
> ```
> [ERROR,9/19 15:31:08] java.net.BindException: Only one usage of each socket address (protocol/network address/port) is normally permitted
> [TRACE,9/19 15:31:08] java.net.BindException: Only one usage of each socket address (protocol/network address/port) is normally permitted
> [TRACE,9/19 15:31:08] at java.net.PlainSocketImpl.convertSocketExceptionToIOException(PlainSocketImpl.java:75)
>
> [TRACE,9/19 15:31:08] at sun.nio.ch.Net.bind(Net.java:101)
> [TRACE,9/19 15:31:08] at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:126)
> [TRACE,9/19 15:31:08] at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:77)
> [TRACE,9/19 15:31:08] at org.mortbay.jetty.nio.BlockingChannelConnector.open(BlockingChannelConnector.java:73)
>
> [TRACE,9/19 15:31:08] at org.mortbay.jetty.AbstractConnector.doStart(AbstractConnector.java:285)
> [TRACE,9/19 15:31:08] at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40)
> [TRACE,9/19 15:31:08] at org.mortbay.jetty.Server.doStart(Server.java:233)
> [TRACE,9/19 15:31:08] at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40)
> [TRACE,9/19 15:31:08] at ...
>
> ```
>
>
Is this a Java bug? Can I avoid it somehow before starting the Jetty server?
**Edit #1** Here is our code for creating our BlockingChannelConnector, note the "setReuseAddress(true)":
>
>
> ```
> connector.setReuseAddress( true );
> connector.setPort( port );
> connector.setStatsOn( true );
> connector.setMaxIdleTime( 30000 );
> connector.setLowResourceMaxIdleTime( 30000 );
> connector.setAcceptQueueSize( maxRequests );
> connector.setName( "Blocking-IO Connector, bound to host " + connector.getHost() );
>
> ```
>
>
Could it have something to do with the idle time?
**Edit #2** Next piece of the puzzle that may or may not help: when running the application in Debug Mode (Eclipse) the server starts up without a problem!!! But the problem described above occurs reproducibly when running the application in Run Mode or as a built jar file. Whiskey Tango Foxtrot?
**Edit #3 (4 days later)** - still have the issue. Any thoughts? | During your first invocation of your program, did it accept at least one incoming connection? If so then what you are most likely seeing is the socket linger in effect.
For the best explanation dig up a copy of TCP/IP Illustrated by Stevens
[](https://i.stack.imgur.com/DNDVu.gif)
(source: [kohala.com](http://www.kohala.com/start/gifs/tcpipiv1.gif))
But, as I understand it, because the application did not properly close the connection (that is BOTH client and server sent their FIN/ACK sequences) the socket you were listening on cannot be reused until the connection is considered dead, the so called 2MSL timeout. The value of 1 MSL can vary by operating system, but its usually a least a minute, and usually more like 5.
The best advice I have heard to avoid this condition (apart from always closing all sockets properly on exit) is to set the SO\_LINGER tcp option to 0 on your server socket during the listen() phase. As freespace pointed out, in java this is the setReuseAddress(true) method. |
101,893 | <p>This concept is a new one for me -- I first came across it at the <a href="http://developer.yahoo.com/yui/articles/hosting/#configure" rel="nofollow noreferrer">YUI dependency configurator</a>. Basically, instead of having multiple requests for many files, the files are chained into one http request to cut down on page load time.</p>
<p>Anyone know how to implement this on a LAMP stack? (I saw a similar question was asked already, but it <a href="https://stackoverflow.com/questions/47937/combining-and-caching-multiple-javascript-files-in-aspnet">seems to be ASP specific</a>.</p>
<p>Thanks!</p>
<p>Update: Both answers are helpful...(my rep isn't high enough to comment yet so I'm adding some parting thoughts here). I also came <a href="http://www.artzstudio.com/2008/08/using-modconcat-to-speed-up-render-start/" rel="nofollow noreferrer">across another blog post</a> with PHP-specific examples that might be useful. David's build answer, though, is making me consider a different approach. Thanks, David!</p>
| [
{
"answer_id": 101941,
"author": "David McLaughlin",
"author_id": 3404,
"author_profile": "https://Stackoverflow.com/users/3404",
"pm_score": 4,
"selected": true,
"text": "<p>There are various ways, the two most obvious would be:</p>\n\n<ol>\n<li>Build a tool like YUI which builds a bespoke, unique version based on the components you ticked as required so that you can still serve the file as static. MooTools and jQuery UI all provide package-builders like this when you download their package to give you the most streamlined and effecient library possible. I'm sure a generic all purpose tool exists out there.</li>\n<li>Create a simple Perl/PHP/Python/Ruby script that serves a bunch of JavaScript files based on the request. So \"onerequest.js?load=ui&load=effects\" would go to a PHP script that loads in the files and serves them with the correct content-type. There are many examples of this but personally I'm not a fan. </li>\n</ol>\n\n<p>I prefer not to serve static files through any sort of script, but I also like to develop my code with 10 or so seperate small class files without the cost of 10 HTTP requests. So I came up with a custom build process that combines all the most common classes and functions and then minifies them into a single file like project.min.js and have a condition in all my views/templates that includes this file on production. </p>\n\n<p>Edit - The \"custom build process\" is actually an extremely simple perl script. It reads in each of the files that I've passed as arguments and writes them to a new file, optionally passing the entire thing through <a href=\"http://www.crockford.com/javascript/jsmin.html\" rel=\"noreferrer\">JSMIN</a> (available in all your favourite languages) automatically. </p>\n\n<p>At the command like it looks like:</p>\n\n<pre><code>perl build-project-master.pl core.js class1.js etc.js /path/to/live/js/file.js\n</code></pre>\n"
},
{
"answer_id": 101956,
"author": "Jamie",
"author_id": 8391,
"author_profile": "https://Stackoverflow.com/users/8391",
"pm_score": 3,
"selected": false,
"text": "<p>There is a good blog post on this @ <a href=\"http://www.hunlock.com/blogs/Supercharged_Javascript\" rel=\"noreferrer\">http://www.hunlock.com/blogs/Supercharged_Javascript</a>. </p>\n"
},
{
"answer_id": 110184,
"author": "Steve Clay",
"author_id": 3779,
"author_profile": "https://Stackoverflow.com/users/3779",
"pm_score": 2,
"selected": false,
"text": "<p>What you want is <a href=\"http://code.google.com/p/minify/\" rel=\"nofollow noreferrer\">Minify</a>. I just wrote a <a href=\"http://mrclay.org/index.php/2008/09/19/minify-21-on-mrclayorg/\" rel=\"nofollow noreferrer\">walkthrough</a> for setting it up.</p>\n"
},
{
"answer_id": 14414073,
"author": "Jonathan Berger",
"author_id": 518222,
"author_profile": "https://Stackoverflow.com/users/518222",
"pm_score": 0,
"selected": false,
"text": "<p>Capistrano is a fairly popular Ruby-based web deployment tool. If you're considering it or already using it, there's a great gem that will figure out CSS and Javascript dependencies, merge, and minify the files.</p>\n\n<p><code>gem install juicer</code></p>\n\n<p>From the <a href=\"https://github.com/cjohansen/juicer\" rel=\"nofollow\">Juicer GitHub page</a>, it can figure out which files depend on each other and merge them together, reducing the number of http requests per page view, thus improving performance.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13243/"
]
| This concept is a new one for me -- I first came across it at the [YUI dependency configurator](http://developer.yahoo.com/yui/articles/hosting/#configure). Basically, instead of having multiple requests for many files, the files are chained into one http request to cut down on page load time.
Anyone know how to implement this on a LAMP stack? (I saw a similar question was asked already, but it [seems to be ASP specific](https://stackoverflow.com/questions/47937/combining-and-caching-multiple-javascript-files-in-aspnet).
Thanks!
Update: Both answers are helpful...(my rep isn't high enough to comment yet so I'm adding some parting thoughts here). I also came [across another blog post](http://www.artzstudio.com/2008/08/using-modconcat-to-speed-up-render-start/) with PHP-specific examples that might be useful. David's build answer, though, is making me consider a different approach. Thanks, David! | There are various ways, the two most obvious would be:
1. Build a tool like YUI which builds a bespoke, unique version based on the components you ticked as required so that you can still serve the file as static. MooTools and jQuery UI all provide package-builders like this when you download their package to give you the most streamlined and effecient library possible. I'm sure a generic all purpose tool exists out there.
2. Create a simple Perl/PHP/Python/Ruby script that serves a bunch of JavaScript files based on the request. So "onerequest.js?load=ui&load=effects" would go to a PHP script that loads in the files and serves them with the correct content-type. There are many examples of this but personally I'm not a fan.
I prefer not to serve static files through any sort of script, but I also like to develop my code with 10 or so seperate small class files without the cost of 10 HTTP requests. So I came up with a custom build process that combines all the most common classes and functions and then minifies them into a single file like project.min.js and have a condition in all my views/templates that includes this file on production.
Edit - The "custom build process" is actually an extremely simple perl script. It reads in each of the files that I've passed as arguments and writes them to a new file, optionally passing the entire thing through [JSMIN](http://www.crockford.com/javascript/jsmin.html) (available in all your favourite languages) automatically.
At the command like it looks like:
```
perl build-project-master.pl core.js class1.js etc.js /path/to/live/js/file.js
``` |
101,935 | <p>Is there a way (without installing any libraries) of validating XML using a custom DTD in PHP?</p>
| [
{
"answer_id": 101962,
"author": "owenmarshall",
"author_id": 9806,
"author_profile": "https://Stackoverflow.com/users/9806",
"pm_score": 4,
"selected": true,
"text": "<p>Take a look at <a href=\"http://us3.php.net/dom\" rel=\"noreferrer\">PHP's DOM</a>, especially <a href=\"http://us3.php.net/manual/en/domdocument.schemavalidate.php\" rel=\"noreferrer\">DOMDocument::schemaValidate</a> and <a href=\"http://us3.php.net/manual/en/domdocument.validate.php\" rel=\"noreferrer\">DOMDocument::validate</a>.</p>\n\n<p>The example for DOMDocument::validate is fairly simple:</p>\n\n<pre><code><?php\n$dom = new DOMDocument;\n$dom->Load('book.xml');\nif ($dom->validate()) {\n echo \"This document is valid!\\n\";\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 5183358,
"author": "PayamRWD",
"author_id": 526385,
"author_profile": "https://Stackoverflow.com/users/526385",
"pm_score": 1,
"selected": false,
"text": "<h2>Trying to complete \"owenmarshall\" answer:</h2>\n\n<p><strong>in xml-validator.php:</strong></p>\n\n<p>add html, header, body, ...</p>\n\n<pre><code><?php\n\n$dom = new DOMDocument; <br/>\n$dom->Load('template-format.xml');<br/>\nif ($dom->validate()) { <br/>\n echo \"This document is valid!\\n\"; <br/>\n}\n\n?>\n</code></pre>\n\n<p><strong>template-format.xml:</strong></p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<!-- DTD to Validate against (format example) -->\n\n<!DOCTYPE template-format [ <br/>\n <!ELEMENT template-format (template)> <br/>\n <!ELEMENT template (background-color, color, font-size, header-image)> <br/>\n <!ELEMENT background-color (#PCDATA)> <br/>\n <!ELEMENT color (#PCDATA)> <br/>\n <!ELEMENT font-size (#PCDATA)> <br/>\n <!ELEMENT header-image (#PCDATA)> <br/>\n]>\n\n<!-- XML example -->\n\n<template-format>\n\n<template>\n\n<background-color>&lt;/background-color> <br/>\n<color>&lt;/color> <br/>\n<font-size>&lt;/font-size> <br/>\n<header-image>&lt;/header-image> <br/>\n\n</template> \n\n</template-format>\n</code></pre>\n"
},
{
"answer_id": 6532933,
"author": "Søren Jacobi",
"author_id": 822761,
"author_profile": "https://Stackoverflow.com/users/822761",
"pm_score": 2,
"selected": false,
"text": "<p>If you have the dtd in a string, you can validate against it by using a <a href=\"http://php.net/manual/en/wrappers.data.php\" rel=\"nofollow\">data wrapper</a> for the dtd: </p>\n\n<pre><code>$xml = '<?xml version=\"1.0\"?>\n <!DOCTYPE note SYSTEM \"note.dtd\">\n <note>\n <to>Tove</to>\n <from>Jani</from>\n <heading>Reminder</heading>\n <body>Don\\'t forget me this weekend!</body>\n </note>';\n\n$dtd = '<!ELEMENT note (to,from,heading,body)>\n <!ELEMENT to (#PCDATA)>\n <!ELEMENT from (#PCDATA)>\n <!ELEMENT heading (#PCDATA)>\n <!ELEMENT body (#PCDATA)>';\n\n\n$root = 'note';\n\n$systemId = 'data://text/plain;base64,'.base64_encode($dtd);\n\n$old = new DOMDocument;\n$old->loadXML($xml);\n\n$creator = new DOMImplementation;\n$doctype = $creator->createDocumentType($root, null, $systemId);\n$new = $creator->createDocument(null, null, $doctype);\n$new->encoding = \"utf-8\";\n\n$oldNode = $old->getElementsByTagName($root)->item(0);\n$newNode = $new->importNode($oldNode, true);\n$new->appendChild($newNode);\n\nif (@$new->validate()) {\n echo \"Valid\";\n} else {\n echo \"Not valid\";\n}\n</code></pre>\n"
},
{
"answer_id": 7389297,
"author": "Peter",
"author_id": 227491,
"author_profile": "https://Stackoverflow.com/users/227491",
"pm_score": 2,
"selected": false,
"text": "<p>My interpretation of the original question is that we have an \"on board\" XML file that we want to validate against an \"on board\" DTD file. So here's how I would implement the \"interpolate a local DTD inside the DOCTYPE element\" idea expressed in comments by both Soren and PayamRWD:</p>\n\n<p><PRE>\npublic function validate($xml_realpath, $dtd_realpath=null) {\n $xml_lines = file($xml_realpath);\n $doc = new DOMDocument;\n if ($dtd_realpath) {\n // Inject DTD inside DOCTYPE line:\n $dtd_lines = file($dtd_realpath);\n $new_lines = array();\n foreach ($xml_lines as $x) {\n // Assume DOCTYPE SYSTEM \"blah blah\" format:\n if (preg_match('/DOCTYPE/', $x)) {\n $y = preg_replace('/SYSTEM \"(.*)\"/', \" [\\n\" . implode(\"\\n\", $dtd_lines) . \"\\n]\", $x);\n $new_lines[] = $y;\n } else {\n $new_lines[] = $x;\n }\n }\n $doc->loadXML(implode(\"\\n\", $new_lines));\n } else {\n $doc->loadXML(implode(\"\\n\", $xml_lines));\n }\n // Enable user error handling\n libxml_use_internal_errors(true);\n if (@$doc->validate()) {\n echo \"Valid!\\n\";\n } else {\n echo \"Not valid:\\n\";\n $errors = libxml_get_errors();\n foreach ($errors as $error) {\n print_r($error, true);\n }\n }\n}\n</PRE></p>\n\n<p>Note that error handling has been suppressed for brevity, and there may be a better/more general way to handle the interpolation. But I <em>have</em> actually used this code with real data, and it works with PHP version 5.2.17.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18856/"
]
| Is there a way (without installing any libraries) of validating XML using a custom DTD in PHP? | Take a look at [PHP's DOM](http://us3.php.net/dom), especially [DOMDocument::schemaValidate](http://us3.php.net/manual/en/domdocument.schemavalidate.php) and [DOMDocument::validate](http://us3.php.net/manual/en/domdocument.validate.php).
The example for DOMDocument::validate is fairly simple:
```
<?php
$dom = new DOMDocument;
$dom->Load('book.xml');
if ($dom->validate()) {
echo "This document is valid!\n";
}
?>
``` |
101,958 | <p>I recently discovered that our company has a set of coding guidelines (hidden away in a document management system where no one can find it). It generally seems pretty sensible, and keeps away from the usual religious wars about where to put '{'s and whether to use hard tabs. However, it does suggest that "lines SHOULD NOT contain embedded multiple spaces". By which it means don't do this sort of thing:</p>
<pre><code>foo = 1;
foobar = 2;
bar = 3;
</code></pre>
<p>Or this:</p>
<pre><code>if ( test_one ) return 1;
else if ( longer_test ) return 2;
else if ( shorter ) return 3;
else return 4;
</code></pre>
<p>Or this:</p>
<pre><code>thing foo_table[] =
{
{ "aaaaa", 0 },
{ "aa", 1 },
// ...
}
</code></pre>
<p>The justification for this is that changes to one line often require every line to be edited. That makes it more effort to change, and harder to understand diffs.</p>
<p>I'm torn. On the one hand, lining up like this can make repetitive code much easier to read. On the other hand, it does make diffs harder to read.</p>
<p>What's your view on this?</p>
| [
{
"answer_id": 101970,
"author": "Sarien",
"author_id": 1994377,
"author_profile": "https://Stackoverflow.com/users/1994377",
"pm_score": 2,
"selected": false,
"text": "<p>With a good editor their point is just not true. :)</p>\n\n<p>(See \"visual block\" mode for vim.)</p>\n\n<p>P.S.: Ok, you still have to change every line but it's fast and simple.</p>\n"
},
{
"answer_id": 101983,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>I'm torn. On the one hand, lining up\n like this can make repetitive code\n much easier to read. On the other\n hand, it does make diffs harder to\n read.</p>\n</blockquote>\n\n<p>Well, since making code understandable is more important than making diffs understandable, you should not be torn.</p>\n\n<p>IMHO lining up similar lines does greatly improve readability. Moreover, it allows easier cut-n-pasting with editors that permit vertical selection.</p>\n"
},
{
"answer_id": 101984,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": false,
"text": "<p>2008: Since I supervise daily merges of source code,... I can only recommend against it.</p>\n<p>It is pretty, but if you do merges on a regular basis, the benefit of 'easier to read' is quickly far less than the effort involved in merging that code.</p>\n<p>Since that format can not be automated in a easy way, the first developer who does not follow it will trigger non-trivial merges.</p>\n<p>Do not forget that <strong>in source code merge, one can not ask the diff tool to ignore spaces</strong> :<br />\nOtherwise, "" and " " will look the same during the diff, meaning no merge necessary... the compiler (and the coder who added the space between the String double quotes) would not agree with that!</p>\n<p>2020: as noted in <a href=\"https://stackoverflow.com/questions/101958/code-formatting-is-lining-up-similar-lines-ok/101984#comment111213382_101984\">the comments</a> by <a href=\"https://stackoverflow.com/users/10529638/marco\">Marco</a></p>\n<blockquote>\n<p>most code mergers should be able to handle ignoring whitespace and aligning equals is now an auto format option in most IDE.</p>\n</blockquote>\n<p>I still prefer languages which come with their own formatting options, like <a href=\"https://golang.org/\" rel=\"nofollow noreferrer\">Go</a> and its <a href=\"https://golang.org/cmd/gofmt/\" rel=\"nofollow noreferrer\"><code>gofmt</code> command</a>.<br />\nEven <a href=\"https://www.rust-lang.org/\" rel=\"nofollow noreferrer\">Rust</a> has its <a href=\"https://github.com/rust-lang/rustfmt\" rel=\"nofollow noreferrer\"><code>rustfmt</code></a> now.</p>\n"
},
{
"answer_id": 101987,
"author": "Nick Craver",
"author_id": 13249,
"author_profile": "https://Stackoverflow.com/users/13249",
"pm_score": 0,
"selected": false,
"text": "<p>We had a similar issue with diffs at multiple contracts... We found that tabs worked best for everyone. Set your editor to maintain tabs and every developer can choose his own tab length as well.</p>\n\n<p>Example: I like 2 space tabs to code is very compact on the left, but the default is 4, so although it looks very different as far as indents, etc. go on our various screens, the diffs are identical and doesn't cause issues with source control.</p>\n"
},
{
"answer_id": 101993,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": 4,
"selected": false,
"text": "<p>I never do this. As you said, it sometimes requires modifying every line to adjust spacing. In some cases (like your conditionals above) it would be perfectly readable and much easier to maintain if you did away with the spacing and put the blocks on separate lines from the conditionals.</p>\n\n<p>Also, if you have decent syntax highlighting in your editor, this kind of spacing shouldn't really be necessary.</p>\n"
},
{
"answer_id": 102001,
"author": "Rylee Corradini",
"author_id": 7542,
"author_profile": "https://Stackoverflow.com/users/7542",
"pm_score": 3,
"selected": false,
"text": "<p>Personally I prefer the greater code readability at the expense of slightly harder-to-read diffs. It seems to me that in the long run an improvement to code maintainability -- especially as developers come and go -- is worth the tradeoff.</p>\n"
},
{
"answer_id": 102002,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": -1,
"selected": false,
"text": "<p>This is PRECISELY the reason the good Lord gave as Tabs -- adding a character in the middle of the line doesn't screw up alignment.</p>\n"
},
{
"answer_id": 102016,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>I like the first and last, but not the middle so much.</p>\n"
},
{
"answer_id": 102035,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 1,
"selected": false,
"text": "<p>If you're planning to use an automated code standard validation (i.e. CheckStyle, ReShaper or anything like that) those extra spaces will make it quite difficult to write and enforce the rules</p>\n"
},
{
"answer_id": 102048,
"author": "Onorio Catenacci",
"author_id": 2820,
"author_profile": "https://Stackoverflow.com/users/2820",
"pm_score": 4,
"selected": false,
"text": "<p>There is some discussion of this in the ever-useful <em><a href=\"http://cc2e.com/\" rel=\"noreferrer\">Code Complete</a></em> by Steve McConnell. If you don't own a copy of this seminal book, do yourself a favor and buy one. Anyway, the discussion is on pages 426 and 427 in the first edition which is the edition I've got an hand. </p>\n\n<hr>\n\n<p>Edit:</p>\n\n<p>McConnell suggests aligning the equal signs in a group of assignment statements to indicate that they're related. He also cautions against aligning all equal signs in a group of assignments because it can visually imply relationship where there is none. For example, this would be appropriate:</p>\n\n<pre><code>Employee.Name = \"Andrew Nelson\"\nEmployee.Bdate = \"1/1/56\"\nEmployee.Rank = \"Senator\"\nCurrentEmployeeRecord = 0\n\nFor CurrentEmployeeRecord From LBound(EmployeeArray) To UBound(EmployeeArray) \n. . .\n</code></pre>\n\n<p>While this would not </p>\n\n<pre><code>Employee.Name = \"Andrew Nelson\"\nEmployee.Bdate = \"1/1/56\"\nEmployee.Rank = \"Senator\"\nCurrentEmployeeRecord = 0\n\nFor CurrentEmployeeRecord From LBound(EmployeeArray) To UBound(EmployeeArray) \n. . .\n</code></pre>\n\n<p>I trust that the difference is apparent. There is also some discussion of aligning continuation lines.</p>\n"
},
{
"answer_id": 102268,
"author": "Agoston Horvath",
"author_id": 18872,
"author_profile": "https://Stackoverflow.com/users/18872",
"pm_score": 1,
"selected": false,
"text": "<p>You can set your diff tool to ignore whitespace (GNU diff: -w).\nThis way, your diffs will skip those lines and only show the real changes. Very handy!</p>\n"
},
{
"answer_id": 103232,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 4,
"selected": false,
"text": "<p>I never do this, and I always recommend against it. I don't care about diffs being harder to read. I do care that it takes time to do this in the first place, and it takes additional time whenever the lines have to be realigned. Editing code that has this format style is infuriating, because it often turns into a huge time sink, and I end up spending more time formatting than making real changes.</p>\n\n<p>I also dispute the readability benefit. This formatting style creates columns in the file. However, we do not <em>read</em> in column style, top to bottom. We read left to right. The columns distract from the standard reading style, and pull the eyes downward. The columns also become extremely ugly if they aren't all perfectly aligned. This applies to extraneous whitespace, but also to multiple (possibly unrelated) column groups which have different spacing, but fall one after the other in the file.</p>\n\n<p>By the way, I find it really bizarre that your coding standard doesn't specify tabbing or brace placement. Mixing different tabbing styles and brace placements will damage readability far more than using (or not using) column-style formatting.</p>\n"
},
{
"answer_id": 252608,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 2,
"selected": false,
"text": "<p>I try to follow two guidelines:</p>\n\n<ol>\n<li><p>Use tabs instead of spaces whenever possible to minimize the need to reformat.</p></li>\n<li><p>If you're concerned about the effect on revision control, make your <em>functional</em> changes first, check them in, then make <em>only cosmetic</em> changes.</p></li>\n</ol>\n\n<p>Public flogging is permissible if bugs are introduced in the \"cosmetic\" change. :-)</p>\n\n<hr>\n\n<p><strong>2020-04-19 Update:</strong> My, how things change in a dozen years! If I were to answer this question today, it would probably be something like, \"Ask your editor to format your code for you and/or tell your diff tool to ignore whitespace when you're making cosmetic changes.</p>\n\n<p>Today, when I review code for readability and think the clarity would be improved by formatting it differently, I always end the suggestion with, \"...unless the editor does it this way automatically. Don't fight your tools. They always win.\"</p>\n"
},
{
"answer_id": 536943,
"author": "Aaron Digulla",
"author_id": 34088,
"author_profile": "https://Stackoverflow.com/users/34088",
"pm_score": 2,
"selected": false,
"text": "<p>My stance is that this is an editor problem: While we use fancy tools to look at web pages and when writing texts in a word processor, our code editors are still stuck in the ASCII ages. They are as dumb as we can make them and then, we try to overcome the limitations of the editor by writing fancy code formatters.</p>\n\n<p>The root cause is that your compiler can't ignore formatting statements in the code which say \"hey, this is a table\" and that IDEs can't create a visually pleasing representation of the source code on the fly (i.e. <em>without</em> actually changing one byte of the code).</p>\n\n<p>One solution would be to use tabs but our editors can't automatically align tabs in consecutive rows (which would make so many thing so much more easy). And to add injury to insult, if you mess with the tab width (basically anything != 8), you can read <em>your</em> source code but no code from anyone else, say, the example code which comes with the libraries you use. And lastly, our diff tools have no option \"ignore whitespace except when it counts\" and the compilers can't produce diffs, either.</p>\n\n<p>Eclipse can at least format assignments in a tabular manner which will make big sets of global constants much more readable. But that's just a drop of water in the desert.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/101958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1105/"
]
| I recently discovered that our company has a set of coding guidelines (hidden away in a document management system where no one can find it). It generally seems pretty sensible, and keeps away from the usual religious wars about where to put '{'s and whether to use hard tabs. However, it does suggest that "lines SHOULD NOT contain embedded multiple spaces". By which it means don't do this sort of thing:
```
foo = 1;
foobar = 2;
bar = 3;
```
Or this:
```
if ( test_one ) return 1;
else if ( longer_test ) return 2;
else if ( shorter ) return 3;
else return 4;
```
Or this:
```
thing foo_table[] =
{
{ "aaaaa", 0 },
{ "aa", 1 },
// ...
}
```
The justification for this is that changes to one line often require every line to be edited. That makes it more effort to change, and harder to understand diffs.
I'm torn. On the one hand, lining up like this can make repetitive code much easier to read. On the other hand, it does make diffs harder to read.
What's your view on this? | >
> I'm torn. On the one hand, lining up
> like this can make repetitive code
> much easier to read. On the other
> hand, it does make diffs harder to
> read.
>
>
>
Well, since making code understandable is more important than making diffs understandable, you should not be torn.
IMHO lining up similar lines does greatly improve readability. Moreover, it allows easier cut-n-pasting with editors that permit vertical selection. |
102,019 | <p>We've got a product which utilizes multiple SQL Server 2005 databases with triggers. We're looking for a sustainable solution for deploying and upgrading the database schemas on customer servers.</p>
<p>Currently, we're using Red Gate's SQL Packager, which appears to be the wrong tool for this particular job. Not only does SQL Packager appear to be geared toward individual databases, but the particular (old) version we own has some issues with SQL Server 2005. (Our version of SQL Packager worked fine with SQL Server 2000, even though we had to do a lot of workarounds to make it handle multiple databases with triggers.) </p>
<p>Can someone suggest a product which can create an EXE or a .NET project to do the following things?</p>
<pre><code>* Create a main database with some default data.
* Create an audit trail database.
* Put triggers on the main database so audit data will automatically be inserted into the audit trail database.
* Create a secondary database that has nothing to do with the main database and audit trail database.
</code></pre>
<p>And then, when a customer needs to update their database schema, the product can look at the changes between the original set of databases and the updated set of databases on our server. Then the product can create an EXE or .NET project which can, on the customer's server...</p>
<pre><code>* Temporarily drop triggers on the main database so alterations can be made.
* Alter database schemas, triggers, stored procedures, etc. on any of the original databases, while leaving the customer's data alone.
* Put the triggers back on the main database.
</code></pre>
<p>Basically, we're looking for a product similar to SQL Packager, but one which will handle multiple databases easily. If no such product exists, we'll have to make our own.</p>
<p>Thanks in advance for your suggestions!</p>
| [
{
"answer_id": 102816,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 1,
"selected": false,
"text": "<p>I was looking for this product myself, knowing that RedGate solution worked fine for \"one\" DB; unfortunately I have been unable to find such tool :(</p>\n\n<p>In the end, I had to roll my own solution to do something \"similar\". It was a <em>pain in the…</em> but it worked. </p>\n\n<p>My scenario was way simpler than yours, as we didn't have triggers and T-SQL. </p>\n\n<p>Later, I decided to take a different approach:</p>\n\n<p>Every DB change had a SCRIPT. Numbered. 001_Create_Table_xXX.SQL, 002_AlterTable_whatever.SQL, etc.</p>\n\n<p>No matter how small the change is, there's got to be a script. The new version of the updater does this:</p>\n\n<ol>\n<li>Makes a BKP of the customerDB (just in case)</li>\n<li>Starts executing scripts in Alphabetical order. (001, 002...)</li>\n<li>If a script fails, it drops the BD. Logs the Script error, Script Number, etc. and restores the customer's DB.</li>\n<li>If it finishes, it makes another backup of the customer's DB (after the \"migration\") and updates a table where we store the DB version; this table is checked by the app to make sure that the DB and the app are in sync.</li>\n<li>Shows a nice success msg.</li>\n</ol>\n\n<p>This turned out to be a little bit more \"manual\" but it has been really working with little effort for three years now. \nThe secret lies in keeping a few testing DBs to test the \"upgrade\" before deploying. But apart from a few isolated Dbs where some scripts failed because of data inconsistency, this worked fine.</p>\n\n<p>Since your scenario is a bit more complex, I don't know if this kind of approach can be ok with you. </p>\n"
},
{
"answer_id": 989716,
"author": "Brent Ozar",
"author_id": 26837,
"author_profile": "https://Stackoverflow.com/users/26837",
"pm_score": 0,
"selected": false,
"text": "<p>As of this writing (June 2009) there's still no product on the market that'll do all this for multiple databases. I work for Quest Software, makers of Change Director for SQL Server, another database change automation system. Ours doesn't handle multiple databases like you're after, and I've seen the others out there. No dice.</p>\n\n<p>I wouldn't hold out hope for it either, given the directions I've seen in SQL Server management. Things are going more toward packaged applications being contained in a single database, and most of the code is focusing on that.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18871/"
]
| We've got a product which utilizes multiple SQL Server 2005 databases with triggers. We're looking for a sustainable solution for deploying and upgrading the database schemas on customer servers.
Currently, we're using Red Gate's SQL Packager, which appears to be the wrong tool for this particular job. Not only does SQL Packager appear to be geared toward individual databases, but the particular (old) version we own has some issues with SQL Server 2005. (Our version of SQL Packager worked fine with SQL Server 2000, even though we had to do a lot of workarounds to make it handle multiple databases with triggers.)
Can someone suggest a product which can create an EXE or a .NET project to do the following things?
```
* Create a main database with some default data.
* Create an audit trail database.
* Put triggers on the main database so audit data will automatically be inserted into the audit trail database.
* Create a secondary database that has nothing to do with the main database and audit trail database.
```
And then, when a customer needs to update their database schema, the product can look at the changes between the original set of databases and the updated set of databases on our server. Then the product can create an EXE or .NET project which can, on the customer's server...
```
* Temporarily drop triggers on the main database so alterations can be made.
* Alter database schemas, triggers, stored procedures, etc. on any of the original databases, while leaving the customer's data alone.
* Put the triggers back on the main database.
```
Basically, we're looking for a product similar to SQL Packager, but one which will handle multiple databases easily. If no such product exists, we'll have to make our own.
Thanks in advance for your suggestions! | I was looking for this product myself, knowing that RedGate solution worked fine for "one" DB; unfortunately I have been unable to find such tool :(
In the end, I had to roll my own solution to do something "similar". It was a *pain in the…* but it worked.
My scenario was way simpler than yours, as we didn't have triggers and T-SQL.
Later, I decided to take a different approach:
Every DB change had a SCRIPT. Numbered. 001\_Create\_Table\_xXX.SQL, 002\_AlterTable\_whatever.SQL, etc.
No matter how small the change is, there's got to be a script. The new version of the updater does this:
1. Makes a BKP of the customerDB (just in case)
2. Starts executing scripts in Alphabetical order. (001, 002...)
3. If a script fails, it drops the BD. Logs the Script error, Script Number, etc. and restores the customer's DB.
4. If it finishes, it makes another backup of the customer's DB (after the "migration") and updates a table where we store the DB version; this table is checked by the app to make sure that the DB and the app are in sync.
5. Shows a nice success msg.
This turned out to be a little bit more "manual" but it has been really working with little effort for three years now.
The secret lies in keeping a few testing DBs to test the "upgrade" before deploying. But apart from a few isolated Dbs where some scripts failed because of data inconsistency, this worked fine.
Since your scenario is a bit more complex, I don't know if this kind of approach can be ok with you. |
102,049 | <p>For example:</p>
<pre><code>me$ FOO="BAR * BAR"
me$ echo $FOO
BAR file1 file2 file3 file4 BAR
</code></pre>
<p>and using the <code>\</code> escape character:</p>
<pre><code>me$ FOO="BAR \* BAR"
me$ echo $FOO
BAR \* BAR
</code></pre>
<p>I'm obviously doing something stupid.</p>
<p>How do I get the output <code>BAR * BAR</code>?</p>
| [
{
"answer_id": 102073,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": false,
"text": "<pre><code>FOO='BAR * BAR'\necho \"$FOO\"\n</code></pre>\n"
},
{
"answer_id": 102074,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 2,
"selected": false,
"text": "<pre><code>echo \"$FOO\"\n</code></pre>\n"
},
{
"answer_id": 102075,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 8,
"selected": true,
"text": "<p>Quoting when setting <code>$FOO</code> is not enough. You need to quote the variable reference as well:</p>\n\n<pre><code>me$ FOO=\"BAR * BAR\"\nme$ echo \"$FOO\"\nBAR * BAR\n</code></pre>\n"
},
{
"answer_id": 102241,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 2,
"selected": false,
"text": "<p>It may be worth getting into the habit of using <code>printf</code> rather then <code>echo</code> on the command line.</p>\n\n<p>In this example it doesn't give much benefit but it can be more useful with more complex output.</p>\n\n<pre><code>FOO=\"BAR * BAR\"\nprintf %s \"$FOO\"\n</code></pre>\n"
},
{
"answer_id": 104023,
"author": "mithu",
"author_id": 16618,
"author_profile": "https://Stackoverflow.com/users/16618",
"pm_score": 7,
"selected": false,
"text": "<p><strong>SHORT ANSWER</strong></p>\n\n<p>Like others have said - you should always quote the variables to prevent strange behaviour. So use <em>echo \"$foo\"</em> in instead of just <em>echo $foo</em>.</p>\n\n<p><strong>LONG ANSWER</strong></p>\n\n<p>I do think this example warrants further explanation because there is more going on than it might seem on the face of it.</p>\n\n<p>I can see where your confusion comes in because after you ran your first example you probably thought to yourself that the shell is obviously doing:</p>\n\n<ol>\n<li>Parameter expansion</li>\n<li>Filename expansion</li>\n</ol>\n\n<p>So from your first example:</p>\n\n<pre><code>me$ FOO=\"BAR * BAR\"\nme$ echo $FOO\n</code></pre>\n\n<p>After parameter expansion is equivalent to:</p>\n\n<pre><code>me$ echo BAR * BAR\n</code></pre>\n\n<p>And after filename expansion is equivalent to:</p>\n\n<pre><code>me$ echo BAR file1 file2 file3 file4 BAR\n</code></pre>\n\n<p>And if you just type <code>echo BAR * BAR</code> into the command line you will see that they are equivalent.</p>\n\n<p>So you probably thought to yourself \"if I escape the *, I can prevent the filename expansion\"</p>\n\n<p>So from your second example:</p>\n\n<pre><code>me$ FOO=\"BAR \\* BAR\"\nme$ echo $FOO\n</code></pre>\n\n<p>After parameter expansion should be equivalent to:</p>\n\n<pre><code>me$ echo BAR \\* BAR\n</code></pre>\n\n<p>And after filename expansion should be equivalent to:</p>\n\n<pre><code>me$ echo BAR \\* BAR\n</code></pre>\n\n<p>And if you try typing \"echo BAR \\* BAR\" directly into the command line it will indeed print \"BAR * BAR\" because the filename expansion is prevented by the escape.</p>\n\n<p>So why did using $foo not work?</p>\n\n<p>It's because there is a third expansion that takes place - Quote Removal. From the bash manual quote removal is:</p>\n\n<blockquote>\n <p>After the preceding expansions, all\n unquoted occurrences of the characters\n ‘\\’, ‘'’, and ‘\"’ that did not result\n from one of the above expansions are\n removed.</p>\n</blockquote>\n\n<p>So what happens is when you type the command directly into the command line, the escape character is not the result of a previous expansion so BASH removes it before sending it to the echo command, but in the 2nd example, the \"\\*\" was the result of a previous Parameter expansion, so it is NOT removed. As a result, echo receives \"\\*\" and that's what it prints.</p>\n\n<p>Note the difference between the first example - \"*\" is not included in the characters that will be removed by Quote Removal.</p>\n\n<p>I hope this makes sense. In the end the conclusion in the same - just use quotes. I just thought I'd explain why escaping, which logically should work if only Parameter and Filename expansion are at play, didn't work.</p>\n\n<p>For a full explanation of BASH expansions, refer to:</p>\n\n<p><a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Shell-Expansions\" rel=\"noreferrer\">http://www.gnu.org/software/bash/manual/bashref.html#Shell-Expansions</a></p>\n"
},
{
"answer_id": 13484149,
"author": "Alex Just Alex",
"author_id": 1840401,
"author_profile": "https://Stackoverflow.com/users/1840401",
"pm_score": 6,
"selected": false,
"text": "<p>I'll add a bit to this old thread.</p>\n\n<p>Usually you would use</p>\n\n<pre><code>$ echo \"$FOO\"\n</code></pre>\n\n<p>However, I've had problems even with this syntax. Consider the following script.</p>\n\n<pre><code>#!/bin/bash\ncurl_opts=\"-s --noproxy * -O\"\ncurl $curl_opts \"$1\"\n</code></pre>\n\n<p>The <code>*</code> needs to be passed verbatim to <code>curl</code>, but the same problems will arise. The above example won't work (it will expand to filenames in the current directory) and neither will <code>\\*</code>. You also can't quote <code>$curl_opts</code> because it will be recognized as a single (invalid) option to <code>curl</code>.</p>\n\n<pre><code>curl: option -s --noproxy * -O: is unknown\ncurl: try 'curl --help' or 'curl --manual' for more information\n</code></pre>\n\n<p>Therefore I would recommend the use of the <code>bash</code> variable <code>$GLOBIGNORE</code> to prevent filename expansion altogether if applied to the global pattern, or use the <code>set -f</code> built-in flag.</p>\n\n<pre><code>#!/bin/bash\nGLOBIGNORE=\"*\"\ncurl_opts=\"-s --noproxy * -O\"\ncurl $curl_opts \"$1\" ## no filename expansion\n</code></pre>\n\n<p>Applying to your original example:</p>\n\n<pre><code>me$ FOO=\"BAR * BAR\"\n\nme$ echo $FOO\nBAR file1 file2 file3 file4 BAR\n\nme$ set -f\nme$ echo $FOO\nBAR * BAR\n\nme$ set +f\nme$ GLOBIGNORE=*\nme$ echo $FOO\nBAR * BAR\n</code></pre>\n"
},
{
"answer_id": 65161851,
"author": "INS",
"author_id": 13136,
"author_profile": "https://Stackoverflow.com/users/13136",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't want to bother with weird expansions from bash you can do this</p>\n<pre><code>me$ FOO="BAR \\x2A BAR" # 2A is hex code for *\nme$ echo -e $FOO\nBAR * BAR\nme$ \n</code></pre>\n<p>Explanation here why using -e option of echo makes life easier:</p>\n<p>Relevant quote from man here:</p>\n<pre><code>SYNOPSIS\n echo [SHORT-OPTION]... [STRING]...\n echo LONG-OPTION\n\nDESCRIPTION\n Echo the STRING(s) to standard output.\n\n -n do not output the trailing newline\n\n -e enable interpretation of backslash escapes\n\n -E disable interpretation of backslash escapes (default)\n\n --help display this help and exit\n\n --version\n output version information and exit\n\n If -e is in effect, the following sequences are recognized:\n\n \\\\ backslash\n\n ...\n\n \\0NNN byte with octal value NNN (1 to 3 digits)\n\n \\xHH byte with hexadecimal value HH (1 to 2 digits)\n</code></pre>\n<p>For the hex code you can check man ascii page (first line in octal, second decimal, third hex):</p>\n<pre><code> 051 41 29 ) 151 105 69 i\n 052 42 2A * 152 106 6A j\n 053 43 2B + 153 107 6B k\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2108/"
]
| For example:
```
me$ FOO="BAR * BAR"
me$ echo $FOO
BAR file1 file2 file3 file4 BAR
```
and using the `\` escape character:
```
me$ FOO="BAR \* BAR"
me$ echo $FOO
BAR \* BAR
```
I'm obviously doing something stupid.
How do I get the output `BAR * BAR`? | Quoting when setting `$FOO` is not enough. You need to quote the variable reference as well:
```
me$ FOO="BAR * BAR"
me$ echo "$FOO"
BAR * BAR
``` |
102,055 | <p>I am trying to make a div, that when you click it turns into an input box, and focuses it. I am using prototype to achieve this. This works in both Chrome and Firefox, but not in IE. IE refuses to focus the newly added input field, even if I set a 1 second timeout.</p>
<p>Basically the code works like this:</p>
<pre><code>var viewElement = new Element("div").update("text");
var editElement = new Element("input", {"type":"text"});
root.update(viewElement);
// pseudo shortcut for the sake of information:
viewElementOnClick = function(event) {
root.update(editElement);
editElement.focus();
}
</code></pre>
<p>The above example is a shortened version of the actual code, the actual code works fine except the focus bit in IE.</p>
<p>Are there limitations on the focus function in IE? Do I need to place the input in a form?</p>
| [
{
"answer_id": 102097,
"author": "x0n",
"author_id": 6920,
"author_profile": "https://Stackoverflow.com/users/6920",
"pm_score": 0,
"selected": false,
"text": "<p>What version IE? What's your DocType set to? is it strict, standards or quirks mode? Any javascript errors appearing (check the status bar bottom left for a little yellow warning sign) ? Enable error announcing for all errors via Tools > Options > Advanced. </p>\n\n<p>Oisin</p>\n"
},
{
"answer_id": 102152,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 3,
"selected": true,
"text": "<p>My guess is that IE hasn't updated the DOM yet when you make the call to focus(). Sometimes browsers will wait until a script has finished executing before updating the DOM.</p>\n\n<p>I would try doing the update, then doing </p>\n\n<pre><code>setTimeout(\"setFocus\", 0);\n\nfunction setFocus()\n{\n editElement.focus();\n}\n</code></pre>\n\n<p>Your other option would be to have both items present in the DOM at all times and just swap the style.display on them depending on what you need hidden/shown at a given time.</p>\n"
},
{
"answer_id": 142957,
"author": "Fczbkk",
"author_id": 22920,
"author_profile": "https://Stackoverflow.com/users/22920",
"pm_score": 0,
"selected": false,
"text": "<p>The question is already answered by <a href=\"https://stackoverflow.com/questions/102055/adding-an-input-field-to-the-dom-and-focusing-it-in-ie#102152\">17 of 26</a>. I just want to point out, that Prototype has native mechanism for this: <strong><a href=\"http://www.prototypejs.org/api/function/defer\" rel=\"nofollow noreferrer\">Function.defer()</a></strong></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355/"
]
| I am trying to make a div, that when you click it turns into an input box, and focuses it. I am using prototype to achieve this. This works in both Chrome and Firefox, but not in IE. IE refuses to focus the newly added input field, even if I set a 1 second timeout.
Basically the code works like this:
```
var viewElement = new Element("div").update("text");
var editElement = new Element("input", {"type":"text"});
root.update(viewElement);
// pseudo shortcut for the sake of information:
viewElementOnClick = function(event) {
root.update(editElement);
editElement.focus();
}
```
The above example is a shortened version of the actual code, the actual code works fine except the focus bit in IE.
Are there limitations on the focus function in IE? Do I need to place the input in a form? | My guess is that IE hasn't updated the DOM yet when you make the call to focus(). Sometimes browsers will wait until a script has finished executing before updating the DOM.
I would try doing the update, then doing
```
setTimeout("setFocus", 0);
function setFocus()
{
editElement.focus();
}
```
Your other option would be to have both items present in the DOM at all times and just swap the style.display on them depending on what you need hidden/shown at a given time. |
102,057 | <p>I've got a Fitnesse RowFixture that returns a list of business objects. The object has a field which is a float representing a percentage between 0 and 1. The <em>consumer</em> of the business object will be a web page or report that comes from a designer, so the formatting of the percentage will be up to the designer rather than the business object. </p>
<p>It would be nicer if the page could emulate the designer when converting the number to a percentage, i.e. instead of displaying 0.5, it should display 50%. But I'd rather not pollute the business object with the display code. Is there a way to specify a format string in the RowFixture?</p>
| [
{
"answer_id": 105012,
"author": "Tom Carr",
"author_id": 14954,
"author_profile": "https://Stackoverflow.com/users/14954",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure what the \"polution\" is. Either the requirement is that your Business Object returns a value expressed as a percentage, in which case your business object should offer that -OR- you are testing the true value of the response as float, which you have now. </p>\n\n<p>Trying to get fitnesse to massage the value for readability seems a bit odd.</p>\n"
},
{
"answer_id": 105997,
"author": "Josh",
"author_id": 11702,
"author_profile": "https://Stackoverflow.com/users/11702",
"pm_score": 3,
"selected": true,
"text": "<p>You certainly don't want to modify your Business Logic just to make your tests look better. Good news however, there is a way to accomplish this that is not difficult, but not as easy as passing in a format specifier.</p>\n\n<p>Try to think of your Fit Fixture as a service boundary between FitNesse and your application code. You want to define a contract that doesn't necessarily have to change if the implementation details of your <strong>SUT</strong> (<strong>S</strong>ystem <strong>U</strong>nder <strong>T</strong>est) change.</p>\n\n<p>Lets look at a simplified version of your Business Object:</p>\n\n<pre><code>public class BusinessObject\n{\n public float Percent { get; private set; }\n}\n</code></pre>\n\n<p>Becuase of the way that a RowFixture works we need to define a simple object that will work as the contract. Ordinarily we would use an interface, but that isn't going to serve our purpose here so a simple <strong>DTO</strong> (<strong>D</strong>ata <strong>T</strong>ransfer <strong>O</strong>bject) will suffice.</p>\n\n<p>Something Like This:</p>\n\n<pre><code>public class ReturnRowDTO\n{\n public String Percent { get; set; }\n}\n</code></pre>\n\n<p>Now we can define a RowFixture that will return a list of our custom DTO objects. We also need to create a way to convert BusinessObjects to ReturnRowDTOs. We end up with a Fixture that looks something like this.</p>\n\n<pre><code>public class ExampleRowFixture: fit.RowFixture\n {\n private ISomeService _someService;\n\n public override object[] Query()\n {\n BusinessObject[] list = _someService.GetBusinessObjects();\n\n return Array.ConvertAll(list, new Converter<BusinessObject, ReturnRowDTO>(ConvertBusinessObjectToDTO));\n }\n\n public override Type GetTargetClass()\n {\n return typeof (ReturnRowDTO);\n }\n\n public ReturnRowDTO ConvertBusinessObjectToDTO(BusinessObject businessObject)\n {\n return new ReturnRowDTO() {Percent = businessObject.Percent.ToString(\"%\")};\n }\n }\n</code></pre>\n\n<p>You can now change your underlying BusinessObjects around without breaking your actual Fit Tests. Hope this helps.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6902/"
]
| I've got a Fitnesse RowFixture that returns a list of business objects. The object has a field which is a float representing a percentage between 0 and 1. The *consumer* of the business object will be a web page or report that comes from a designer, so the formatting of the percentage will be up to the designer rather than the business object.
It would be nicer if the page could emulate the designer when converting the number to a percentage, i.e. instead of displaying 0.5, it should display 50%. But I'd rather not pollute the business object with the display code. Is there a way to specify a format string in the RowFixture? | You certainly don't want to modify your Business Logic just to make your tests look better. Good news however, there is a way to accomplish this that is not difficult, but not as easy as passing in a format specifier.
Try to think of your Fit Fixture as a service boundary between FitNesse and your application code. You want to define a contract that doesn't necessarily have to change if the implementation details of your **SUT** (**S**ystem **U**nder **T**est) change.
Lets look at a simplified version of your Business Object:
```
public class BusinessObject
{
public float Percent { get; private set; }
}
```
Becuase of the way that a RowFixture works we need to define a simple object that will work as the contract. Ordinarily we would use an interface, but that isn't going to serve our purpose here so a simple **DTO** (**D**ata **T**ransfer **O**bject) will suffice.
Something Like This:
```
public class ReturnRowDTO
{
public String Percent { get; set; }
}
```
Now we can define a RowFixture that will return a list of our custom DTO objects. We also need to create a way to convert BusinessObjects to ReturnRowDTOs. We end up with a Fixture that looks something like this.
```
public class ExampleRowFixture: fit.RowFixture
{
private ISomeService _someService;
public override object[] Query()
{
BusinessObject[] list = _someService.GetBusinessObjects();
return Array.ConvertAll(list, new Converter<BusinessObject, ReturnRowDTO>(ConvertBusinessObjectToDTO));
}
public override Type GetTargetClass()
{
return typeof (ReturnRowDTO);
}
public ReturnRowDTO ConvertBusinessObjectToDTO(BusinessObject businessObject)
{
return new ReturnRowDTO() {Percent = businessObject.Percent.ToString("%")};
}
}
```
You can now change your underlying BusinessObjects around without breaking your actual Fit Tests. Hope this helps. |
102,058 | <p>The server.xml which controls the startup of Apache Tomcat's servlet container contains a debug attribute for nearly every major component. The debug attribute is more or less verbose depending upon the number you give it, zero being least and 99 being most verbose. How does the debug level affect Tomcat's speed when servicing large numbers of users? I assume zero is fast and 99 is relatively slower, but is this true. If there are no errors being thrown, does it matter?</p>
| [
{
"answer_id": 105012,
"author": "Tom Carr",
"author_id": 14954,
"author_profile": "https://Stackoverflow.com/users/14954",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure what the \"polution\" is. Either the requirement is that your Business Object returns a value expressed as a percentage, in which case your business object should offer that -OR- you are testing the true value of the response as float, which you have now. </p>\n\n<p>Trying to get fitnesse to massage the value for readability seems a bit odd.</p>\n"
},
{
"answer_id": 105997,
"author": "Josh",
"author_id": 11702,
"author_profile": "https://Stackoverflow.com/users/11702",
"pm_score": 3,
"selected": true,
"text": "<p>You certainly don't want to modify your Business Logic just to make your tests look better. Good news however, there is a way to accomplish this that is not difficult, but not as easy as passing in a format specifier.</p>\n\n<p>Try to think of your Fit Fixture as a service boundary between FitNesse and your application code. You want to define a contract that doesn't necessarily have to change if the implementation details of your <strong>SUT</strong> (<strong>S</strong>ystem <strong>U</strong>nder <strong>T</strong>est) change.</p>\n\n<p>Lets look at a simplified version of your Business Object:</p>\n\n<pre><code>public class BusinessObject\n{\n public float Percent { get; private set; }\n}\n</code></pre>\n\n<p>Becuase of the way that a RowFixture works we need to define a simple object that will work as the contract. Ordinarily we would use an interface, but that isn't going to serve our purpose here so a simple <strong>DTO</strong> (<strong>D</strong>ata <strong>T</strong>ransfer <strong>O</strong>bject) will suffice.</p>\n\n<p>Something Like This:</p>\n\n<pre><code>public class ReturnRowDTO\n{\n public String Percent { get; set; }\n}\n</code></pre>\n\n<p>Now we can define a RowFixture that will return a list of our custom DTO objects. We also need to create a way to convert BusinessObjects to ReturnRowDTOs. We end up with a Fixture that looks something like this.</p>\n\n<pre><code>public class ExampleRowFixture: fit.RowFixture\n {\n private ISomeService _someService;\n\n public override object[] Query()\n {\n BusinessObject[] list = _someService.GetBusinessObjects();\n\n return Array.ConvertAll(list, new Converter<BusinessObject, ReturnRowDTO>(ConvertBusinessObjectToDTO));\n }\n\n public override Type GetTargetClass()\n {\n return typeof (ReturnRowDTO);\n }\n\n public ReturnRowDTO ConvertBusinessObjectToDTO(BusinessObject businessObject)\n {\n return new ReturnRowDTO() {Percent = businessObject.Percent.ToString(\"%\")};\n }\n }\n</code></pre>\n\n<p>You can now change your underlying BusinessObjects around without breaking your actual Fit Tests. Hope this helps.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13930/"
]
| The server.xml which controls the startup of Apache Tomcat's servlet container contains a debug attribute for nearly every major component. The debug attribute is more or less verbose depending upon the number you give it, zero being least and 99 being most verbose. How does the debug level affect Tomcat's speed when servicing large numbers of users? I assume zero is fast and 99 is relatively slower, but is this true. If there are no errors being thrown, does it matter? | You certainly don't want to modify your Business Logic just to make your tests look better. Good news however, there is a way to accomplish this that is not difficult, but not as easy as passing in a format specifier.
Try to think of your Fit Fixture as a service boundary between FitNesse and your application code. You want to define a contract that doesn't necessarily have to change if the implementation details of your **SUT** (**S**ystem **U**nder **T**est) change.
Lets look at a simplified version of your Business Object:
```
public class BusinessObject
{
public float Percent { get; private set; }
}
```
Becuase of the way that a RowFixture works we need to define a simple object that will work as the contract. Ordinarily we would use an interface, but that isn't going to serve our purpose here so a simple **DTO** (**D**ata **T**ransfer **O**bject) will suffice.
Something Like This:
```
public class ReturnRowDTO
{
public String Percent { get; set; }
}
```
Now we can define a RowFixture that will return a list of our custom DTO objects. We also need to create a way to convert BusinessObjects to ReturnRowDTOs. We end up with a Fixture that looks something like this.
```
public class ExampleRowFixture: fit.RowFixture
{
private ISomeService _someService;
public override object[] Query()
{
BusinessObject[] list = _someService.GetBusinessObjects();
return Array.ConvertAll(list, new Converter<BusinessObject, ReturnRowDTO>(ConvertBusinessObjectToDTO));
}
public override Type GetTargetClass()
{
return typeof (ReturnRowDTO);
}
public ReturnRowDTO ConvertBusinessObjectToDTO(BusinessObject businessObject)
{
return new ReturnRowDTO() {Percent = businessObject.Percent.ToString("%")};
}
}
```
You can now change your underlying BusinessObjects around without breaking your actual Fit Tests. Hope this helps. |
102,059 | <p>With previous versions of flash, entering the full screen mode increased the height and width of the stage to the dimensions of the screen. Now that hardware scaling has arrived, the height and width are set to the dimensions of the video (plus borders if the aspect ratio is different).</p>
<p>That's fine, unless you have controls placed over the video. Before, you could control their size; but now they're blown up by the same scale as the video, and pixellated horribly. Controls are ugly and subtitles are unreadable.</p>
<p>It's possible for the user to turn off hardware scaling, but all that achieves is to turn off anti-aliasing. The controls are still blown up to ugliness.</p>
<p>Is there a way to get the old scaling behaviour back?</p>
| [
{
"answer_id": 106667,
"author": "Brent",
"author_id": 10680,
"author_profile": "https://Stackoverflow.com/users/10680",
"pm_score": -1,
"selected": false,
"text": "<pre><code>stage.align = StageAlign.TOP_LEFT; \nstage.scaleMode = StageScaleMode.NO_SCALE;\nstage.addEventListener(Event.RESIZE, onStageResize);\n\nfunction onStageResize(event:Event):void {\n //do whatever you want to re-position your controls and scale the video\n // here's an example\n myFLVPlayback.width = stage.stageWidth;\n myFLVPlayback.height = stage.stageHeight - controls.height;\n controls.y = stage.stageHeight - controls.height;\n}\n</code></pre>\n\n<p>Or, and I'm not entirely sure about this, you might try to do some 9 slice scaling on the FLVPlayback, but I don't know if that'll work.</p>\n\n<p>9-slice scaling tutorial: <a href=\"http://www.sephiroth.it/tutorials/flashPHP/scale9/\" rel=\"nofollow noreferrer\">http://www.sephiroth.it/tutorials/flashPHP/scale9/</a></p>\n"
},
{
"answer_id": 113828,
"author": "Simon",
"author_id": 15371,
"author_profile": "https://Stackoverflow.com/users/15371",
"pm_score": 2,
"selected": true,
"text": "<p>I've eventually found the answer to this. The problem is that the FLVPlayback component is now using the stage.fullScreenSourceRect property to enter a hardware-scaled full screen mode. When it does that, it stretches the rendered area given by stage.fullScreenSourceRect to fill the screen, rather than increasing the size of the stage or any components.</p>\n\n<p>To stop it, you have to create a subclass of FLVPlayback that uses a subclass of UIManager, and override the function that's setting stage.fullScreenSourceRect. On the down side, you lose hardware scaling; but on the up side, your player doesn't look like it's been drawn by a three-year-old in crayons.</p>\n\n<p>CustomFLVPlayback.as:</p>\n\n<pre><code>import fl.video.*;\nuse namespace flvplayback_internal;\n\npublic class CustomFLVPlayback\n{\n public function CustomFLVPlayback()\n {\n super();\n uiMgr = new CustomUIManager(this);\n }\n}\n</code></pre>\n\n<p>CustomUIManager.as:</p>\n\n<pre><code>import fl.video.*;\nimport flash.display.StageDisplayState;\n\npublic class CustomUIManager\n{\n public function CustomUIManager(vc:FLVPlayback)\n {\n super(vc);\n }\n\n public override function enterFullScreenDisplayState():void\n {\n if (!_fullScreen && _vc.stage != null)\n {\n try\n {\n _vc.stage.displayState = StageDisplayState.FULL_SCREEN;\n } catch (se:SecurityError) {\n }\n }\n }\n}\n</code></pre>\n\n<p>We add the FLVPlayback to our movie using actionscript, so we just have to replace</p>\n\n<pre><code>var myFLVPLayback:FLVPlayback = new FLVPlayback();\n</code></pre>\n\n<p>with</p>\n\n<pre><code>var myFLVPLayback:CustomFLVPlayback = new CustomFLVPlayback();\n</code></pre>\n\n<p>I don't know whether there's a way to make the custom class available in the component library.</p>\n"
},
{
"answer_id": 189958,
"author": "aaaidan",
"author_id": 26331,
"author_profile": "https://Stackoverflow.com/users/26331",
"pm_score": 2,
"selected": false,
"text": "<p>Here's another way to solve it, which is simpler and it seems to work quite well for me.</p>\n\n<p><code><pre>myFLVPlayback.<a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html#fullScreenTakeOver\" rel=\"nofollow noreferrer\">fullScreenTakeOver</a> = false;</pre></code></p>\n\n<p>The <code>fullScreenTakeOver</code> property was introduced in Flash Player 9 <strong>update 3</strong>. The docs are all a bit vague, but there's a bit more info here:</p>\n\n<p><a href=\"http://www.adobe.com/devnet/flash/articles/flvplayback_fplayer9u3_02.html\" rel=\"nofollow noreferrer\">Using the <code>FLVPlayback</code> component with Flash Player 9 Update 3</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
]
| With previous versions of flash, entering the full screen mode increased the height and width of the stage to the dimensions of the screen. Now that hardware scaling has arrived, the height and width are set to the dimensions of the video (plus borders if the aspect ratio is different).
That's fine, unless you have controls placed over the video. Before, you could control their size; but now they're blown up by the same scale as the video, and pixellated horribly. Controls are ugly and subtitles are unreadable.
It's possible for the user to turn off hardware scaling, but all that achieves is to turn off anti-aliasing. The controls are still blown up to ugliness.
Is there a way to get the old scaling behaviour back? | I've eventually found the answer to this. The problem is that the FLVPlayback component is now using the stage.fullScreenSourceRect property to enter a hardware-scaled full screen mode. When it does that, it stretches the rendered area given by stage.fullScreenSourceRect to fill the screen, rather than increasing the size of the stage or any components.
To stop it, you have to create a subclass of FLVPlayback that uses a subclass of UIManager, and override the function that's setting stage.fullScreenSourceRect. On the down side, you lose hardware scaling; but on the up side, your player doesn't look like it's been drawn by a three-year-old in crayons.
CustomFLVPlayback.as:
```
import fl.video.*;
use namespace flvplayback_internal;
public class CustomFLVPlayback
{
public function CustomFLVPlayback()
{
super();
uiMgr = new CustomUIManager(this);
}
}
```
CustomUIManager.as:
```
import fl.video.*;
import flash.display.StageDisplayState;
public class CustomUIManager
{
public function CustomUIManager(vc:FLVPlayback)
{
super(vc);
}
public override function enterFullScreenDisplayState():void
{
if (!_fullScreen && _vc.stage != null)
{
try
{
_vc.stage.displayState = StageDisplayState.FULL_SCREEN;
} catch (se:SecurityError) {
}
}
}
}
```
We add the FLVPlayback to our movie using actionscript, so we just have to replace
```
var myFLVPLayback:FLVPlayback = new FLVPlayback();
```
with
```
var myFLVPLayback:CustomFLVPlayback = new CustomFLVPlayback();
```
I don't know whether there's a way to make the custom class available in the component library. |
102,072 | <p>A friend of mine was explaining how they do ping-pong pairing with TDD at his workplace and he said that they take an "adversarial" approach. That is, when the test writing person hands the keyboard over to the implementer, the implementer tries to do the bare simplest (and sometimes wrong thing) to make the test pass.</p>
<p>For example, if they're testing a GetName() method and the test checks for "Sally", the implementation of the GetName method would simply be:</p>
<pre><code>public string GetName(){
return "Sally";
}
</code></pre>
<p>Which would, of course, pass the test (naively).</p>
<p>He explains that this helps eliminate naive tests that check for specific canned values rather than testing the actual behavior or expected state of components. It also helps drive the creation of more tests and ultimately better design and fewer bugs.</p>
<p>It sounded good, but in a short session with him, it seemed like it took a lot longer to get through a single round of tests than otherwise and I didn't feel that a lot of extra value was gained.</p>
<p>Do you use this approach, and if so, have you seen it pay off?</p>
| [
{
"answer_id": 102236,
"author": "Heath Borders",
"author_id": 9636,
"author_profile": "https://Stackoverflow.com/users/9636",
"pm_score": 1,
"selected": false,
"text": "<p>I've used this approach. It doesn't work with all pairs; some people are just naturally resistant and won't give it an honest chance. However, it helps you do TDD and XP properly. You want to try and add features to your codebase slowly. You don't want to write a huge monolithic test that will take lots of code to satisfy. You want a bunch of simple tests. You also want to make sure you're passing the keyboard back and forth between your pairs regularly so that both pairs are engaged. With adversarial pairing, you're doing both. Simple tests lead to simple implementations, the code is built slowly, and both people are involved throughout the whole process.</p>\n"
},
{
"answer_id": 102348,
"author": "James A Wilson",
"author_id": 13892,
"author_profile": "https://Stackoverflow.com/users/13892",
"pm_score": -1,
"selected": true,
"text": "<p>It is based on the team's personality. Every team has a personality that is the sum of its members. You have to be careful not to practice passive-aggressive implementations done with an air of superiority. Some developers are frustrated by implementations like </p>\n\n<blockquote>\n <p><code>return \"Sally\";</code></p>\n</blockquote>\n\n<p>This frustration will lead to an unsuccessful team. I was among the frustrated and did not see it pay off. I think a better approach is more oral communication making suggestions about how a test might be better implemented.</p>\n"
},
{
"answer_id": 105819,
"author": "adrianh",
"author_id": 13165,
"author_profile": "https://Stackoverflow.com/users/13165",
"pm_score": 0,
"selected": false,
"text": "<p>I like it some of the time - but don't use that style the entire time. Acts as a nice change of pace at times. I don't think I'd like to use the style all of the time.</p>\n\n<p>I've found it a useful tool with beginners to introduce how the tests can drive the implementation though.</p>\n"
},
{
"answer_id": 168988,
"author": "Craig Angus",
"author_id": 15352,
"author_profile": "https://Stackoverflow.com/users/15352",
"pm_score": 2,
"selected": false,
"text": "<p>It can be very effective.</p>\n\n<p>It forces you to think more about what test you have to write to get the other programmer to write the correct functionality you require.</p>\n\n<p>You build up the code piece by piece passing the keyboard frequently</p>\n\n<p>It can be quite tiring and time consuming but I have found that its rare I have had to come back and fix a bug in any code that has been written like this </p>\n"
},
{
"answer_id": 55129930,
"author": "jamie",
"author_id": 337881,
"author_profile": "https://Stackoverflow.com/users/337881",
"pm_score": 0,
"selected": false,
"text": "<p>(First, off, Adversarial TDD should be fun. It should be an opportunity for teaching. It shouldn't be an opportunity for human dominance rituals. If there isn't the space for a bit of humor then leave the team. Sorry. Life is to short to waste in a negative environment.) </p>\n\n<p>The problem here is badly named tests. If the test looked like this:</p>\n\n<pre><code>foo = new Thing(\"Sally\")\nassertEquals(\"Sally\", foo.getName())\n</code></pre>\n\n<p>Then I bet it was named \"<code>testGetNameReturnsNameField</code>\". This is a bad name, but not immediately obviously so. The proper name for this test is \"<code>testGetNameReturnsSally</code>\". That is what it does. Any other name is lulling you into a false sense of security. So the test is badly named. The problem is not the code. The problem is not even the test. The problem is the name of the test.</p>\n\n<p>If, instead, the tester had named the test \"<code>testGetNameReturnsSally</code>\", then it would have been immediately obvious that this is probably not testing what we want.</p>\n\n<p>It is therefore the duty of the implementor to demonstrate the poor choice of the tester. It is also the duty of the implementor to write only what the tests demand of them. </p>\n\n<p>So many bugs in production occur not because the code did less than expected, but because it did more. Yes, there were unit tests for all the expected cases, but there were not tests for all the special edge cases that the code did because the programmer thought \"I better just do this too, we'll probably need that\" and then forgot about it. That is why TDD works better than test-after. That is why we throw code away after a spike. The code might do all the things you want, but it probably does somethings you thought you needed, and then forgot about.</p>\n\n<p>Force the test writer to test what they really want. Only write code to make tests pass and no more.</p>\n\n<p>RandomStringUtils is your friend.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10862/"
]
| A friend of mine was explaining how they do ping-pong pairing with TDD at his workplace and he said that they take an "adversarial" approach. That is, when the test writing person hands the keyboard over to the implementer, the implementer tries to do the bare simplest (and sometimes wrong thing) to make the test pass.
For example, if they're testing a GetName() method and the test checks for "Sally", the implementation of the GetName method would simply be:
```
public string GetName(){
return "Sally";
}
```
Which would, of course, pass the test (naively).
He explains that this helps eliminate naive tests that check for specific canned values rather than testing the actual behavior or expected state of components. It also helps drive the creation of more tests and ultimately better design and fewer bugs.
It sounded good, but in a short session with him, it seemed like it took a lot longer to get through a single round of tests than otherwise and I didn't feel that a lot of extra value was gained.
Do you use this approach, and if so, have you seen it pay off? | It is based on the team's personality. Every team has a personality that is the sum of its members. You have to be careful not to practice passive-aggressive implementations done with an air of superiority. Some developers are frustrated by implementations like
>
> `return "Sally";`
>
>
>
This frustration will lead to an unsuccessful team. I was among the frustrated and did not see it pay off. I think a better approach is more oral communication making suggestions about how a test might be better implemented. |
102,083 | <p>Preferably free tools if possible.</p>
<p>Also, the option of searching for multiple regular expressions and each replacing with different strings would be a bonus.</p>
| [
{
"answer_id": 102110,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 2,
"selected": false,
"text": "<p>Under Windows, I used to like <a href=\"http://www.wingrep.com\" rel=\"nofollow noreferrer\">WinGrep</a></p>\n\n<p>Under Ubuntu, I use Regexxer.</p>\n"
},
{
"answer_id": 102118,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 1,
"selected": false,
"text": "<p>I'd go for bash + find + sed.</p>\n"
},
{
"answer_id": 102120,
"author": "levik",
"author_id": 4465,
"author_profile": "https://Stackoverflow.com/users/4465",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.textpad.com/\" rel=\"noreferrer\">Textpad</a> does a good job of it on Windows. And it's a very good editor as well.</p>\n"
},
{
"answer_id": 102125,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>For Mac OS X, TextWrangler does the job. </p>\n"
},
{
"answer_id": 102131,
"author": "Oliver Giesen",
"author_id": 9784,
"author_profile": "https://Stackoverflow.com/users/9784",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.jedit.org\" rel=\"nofollow noreferrer\">jEdit</a>'s regex search&replace in files is pretty decent. Slightly overkill if you only use it for that, though. It also doesn't support the multi-expression-replace you asked for.</p>\n"
},
{
"answer_id": 102141,
"author": "Alex Fort",
"author_id": 12624,
"author_profile": "https://Stackoverflow.com/users/12624",
"pm_score": 6,
"selected": true,
"text": "<p>Perl. </p>\n\n<p>Seriously, it makes sysadmin stuff so much easier. Here's an example:</p>\n\n<pre><code>perl -pi -e 's/something/somethingelse/g' *.log\n</code></pre>\n"
},
{
"answer_id": 102155,
"author": "Craig Trader",
"author_id": 12895,
"author_profile": "https://Stackoverflow.com/users/12895",
"pm_score": 3,
"selected": false,
"text": "<p>Unsurprisingly, Perl does a fine job of handling this, in conjunction with a decent shell:</p>\n\n<pre><code>for file in @filelist ; do\n perl -p -i -e \"s/pattern/result/g\" $file\ndone\n</code></pre>\n\n<p>This has the same effect (but is more efficient, and without the race condition) as:</p>\n\n<pre><code>for file in @filelist ; do\n cat $file | sed \"s/pattern/result/\" > /tmp/newfile\n mv /tmp/newfile $file\ndone\n</code></pre>\n"
},
{
"answer_id": 102173,
"author": "lindelof",
"author_id": 1428,
"author_profile": "https://Stackoverflow.com/users/1428",
"pm_score": 3,
"selected": false,
"text": "<p>Emacs's directory editor has the `dired-do-query-replace-regexp' function to search for and replace a regexp over a set of marked files.</p>\n"
},
{
"answer_id": 102247,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 1,
"selected": false,
"text": "<p>Vim for the rescue (and president ;-) ). Try: </p>\n\n<pre><code>vim -c \"argdo! s:foo:bar:gci\" <list_of_files>\n</code></pre>\n\n<p>(I do love Vim's -c switch, it's magic.\nOr if you had already in Vim, and opened the files, e.g.:</p>\n\n<pre><code>vim <list_of_files>\n</code></pre>\n\n<p>Just issue:</p>\n\n<pre><code>:bufdo! s:foo:bar:gci\n</code></pre>\n\n<p>Of course <code>sed</code> and <code>perl</code> is capable as well.\nHTH.</p>\n"
},
{
"answer_id": 102730,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 5,
"selected": false,
"text": "<p><code>sed</code> is quick and easy:</p>\n\n<pre><code>sed -e \"s/pattern/result/\" <file list>\n</code></pre>\n\n<p>You can also join it with <code>find</code>:</p>\n\n<pre><code>find <other find args> -exec sed -e \"s/pattern/result/\" \"{}\" \";\"\n</code></pre>\n"
},
{
"answer_id": 202208,
"author": "Huppie",
"author_id": 1830,
"author_profile": "https://Stackoverflow.com/users/1830",
"pm_score": 2,
"selected": false,
"text": "<p>For find-and-replace on multiple files on Windows I found <a href=\"http://www.codeplex.com/RxFind\" rel=\"nofollow noreferrer\">rxFind</a> to be very helpful.</p>\n"
},
{
"answer_id": 962841,
"author": "Martin R-L",
"author_id": 46343,
"author_profile": "https://Stackoverflow.com/users/46343",
"pm_score": 0,
"selected": false,
"text": "<p>I've found the tool <a href=\"http://rxfind.codeplex.com/\" rel=\"nofollow noreferrer\">RxFind</a> useful (free OSS).</p>\n"
},
{
"answer_id": 962858,
"author": "Templar",
"author_id": 799,
"author_profile": "https://Stackoverflow.com/users/799",
"pm_score": 2,
"selected": false,
"text": "<p>My personal favorite is <a href=\"http://www.powergrep.com/\" rel=\"nofollow noreferrer\">PowerGrep</a> by JGSoft. It interfaces with <a href=\"http://www.regexbuddy.com/\" rel=\"nofollow noreferrer\">RegexBuddy</a> which can help you to create and test the regular expression, automatically backs up all changes (and provides undo capabilities), provides the ability to parse multiple directories (with filename patterns), and even supports file formats such as Microsoft Word, Excel, and PDF.</p>\n\n<p><img src=\"https://www.powergrep.com/screens/powergrep320.png\" alt=\"PowerGrep Screenshot\"></p>\n"
},
{
"answer_id": 989066,
"author": "jhw",
"author_id": 2070346,
"author_profile": "https://Stackoverflow.com/users/2070346",
"pm_score": 1,
"selected": false,
"text": "<p>I have the luxury of Unix and Ubuntu; In both, I use <strong>gawk</strong> for anything that requires line-by-line search and replace, especially for line-by-line for substring(s).\nRecently, this was the fastest for processing 1100 changes against millions of lines in hundreds of files (one directory)\nOn Ubuntu I am a fan of regexxer</p>\n\n<pre><code> sudo apt-get install regexxer\n</code></pre>\n"
},
{
"answer_id": 9828300,
"author": "Ciantic",
"author_id": 183544,
"author_profile": "https://Stackoverflow.com/users/183544",
"pm_score": 2,
"selected": false,
"text": "<p>In Windows there is free alternative that works the best: Notepad++</p>\n\n<p>Go to \"Search\" -> \"Find in Files\". One may give directory, file pattern, set regular expressions then preview the matches and finally replace all files recursively.</p>\n"
},
{
"answer_id": 14488152,
"author": "user2005187",
"author_id": 2005187,
"author_profile": "https://Stackoverflow.com/users/2005187",
"pm_score": 3,
"selected": false,
"text": "<p>I've written a free command line tool for Windows to do this. It's called <a href=\"https://sites.google.com/site/regexreplace/\" rel=\"noreferrer\">rxrepl</a>, it supports unicode and file search. Some may find it useful.</p>\n"
},
{
"answer_id": 14565274,
"author": "Patrick Steil",
"author_id": 1877610,
"author_profile": "https://Stackoverflow.com/users/1877610",
"pm_score": 2,
"selected": false,
"text": "<p>I love this tool:</p>\n\n<p><a href=\"http://www.abareplace.com/\" rel=\"nofollow\">http://www.abareplace.com/</a></p>\n\n<p>Gives you an \"as you type\" preview of your regular expression... FANTASTIC for those not well versed in RE's... and it is super fast at changing hundreds or thousands of files at a time...</p>\n\n<p>And then let's you UNDO your changes as well... </p>\n\n<p>Very nice...</p>\n\n<p>Patrick Steil - \n<a href=\"http://www.podiotools.com\" rel=\"nofollow\">http://www.podiotools.com</a></p>\n"
},
{
"answer_id": 31349564,
"author": "ThorSummoner",
"author_id": 1695680,
"author_profile": "https://Stackoverflow.com/users/1695680",
"pm_score": 1,
"selected": false,
"text": "<p>if 'textpad' is a valid answer, I would suggest <a href=\"http://www.sublimetext.com/\" rel=\"nofollow\">Sublime Text</a> hands down.</p>\n\n<p>Multi-cursor edits are an even more efficient way to make replacements in general I find, but its \"<a href=\"http://docs.sublimetext.info/en/latest/search_and_replace/search_and_replace_files.html\" rel=\"nofollow\">Find in Files</a>\" is top tier for bulk regex/plain find replacements.</p>\n"
},
{
"answer_id": 36531046,
"author": "victe",
"author_id": 3480746,
"author_profile": "https://Stackoverflow.com/users/3480746",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://brackets.io\" rel=\"nofollow\">Brackets</a> (source code, deb/Ubuntu, OSx and Windows) has a good visualization of results, permitting select them individually to apply substitution. You can search by standard text, case sensitive or not, and regex.\nVery important: you can exclude patterns of files and directories in the search.</p>\n"
},
{
"answer_id": 52634458,
"author": "user742070",
"author_id": 742070,
"author_profile": "https://Stackoverflow.com/users/742070",
"pm_score": 0,
"selected": false,
"text": "<p>For at least 25 years, I've been using Emacs for large-scale replacements across large numbers of files. Run <code>etags</code> to specify any set of files to search through:</p>\n\n<pre><code>$ etags file1.txt file2.md dir1/*.yml dir2/*.json dir3/*.md\n</code></pre>\n\n<p>Then open Emacs and run <code>tags-query-replace</code>, which prompts for regex and replacement:</p>\n\n<pre><code>\\b\\(foo\\)\\b\n\\1bar\n</code></pre>\n"
},
{
"answer_id": 61918048,
"author": "CodePrinz",
"author_id": 11514530,
"author_profile": "https://Stackoverflow.com/users/11514530",
"pm_score": 1,
"selected": false,
"text": "<p>If you are a Programmer: A lot of IDEs should do a good Job as well.</p>\n\n<p>For me <a href=\"https://www.jetbrains.com/de-de/pycharm/\" rel=\"nofollow noreferrer\">PyCharm</a> worked quite nice:</p>\n\n<ul>\n<li><em>Edit > Find > Replace in Path</em> or <strong>Strg + Shift + R</strong></li>\n<li>Check <em>Regex</em> at the top</li>\n</ul>\n\n<p>It has a live preview.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13967/"
]
| Preferably free tools if possible.
Also, the option of searching for multiple regular expressions and each replacing with different strings would be a bonus. | Perl.
Seriously, it makes sysadmin stuff so much easier. Here's an example:
```
perl -pi -e 's/something/somethingelse/g' *.log
``` |
102,084 | <p>I have learned quite a bit browsing through <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden Features
of C#</a> and was surprised when I couldn't find something
similar for VB.NET.</p>
<p>So what are some of its hidden or lesser known features?</p>
| [
{
"answer_id": 102111,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": false,
"text": "<ul>\n<li>AndAlso/OrElse logical operators</li>\n</ul>\n\n<p>(EDIT: Learn more here: <a href=\"https://stackoverflow.com/questions/55013/should-i-always-use-the-andalso-and-orelse-operators\">Should I always use the AndAlso and OrElse operators?</a>)</p>\n"
},
{
"answer_id": 102112,
"author": "Jasha87",
"author_id": 18874,
"author_profile": "https://Stackoverflow.com/users/18874",
"pm_score": 5,
"selected": false,
"text": "<p>One major time saver I use all the time is the <strong>With</strong> keyword:</p>\n\n<pre><code>With ReallyLongClassName\n .Property1 = Value1\n .Property2 = Value2\n ...\nEnd With\n</code></pre>\n\n<p>I just don't like typing more than I have to!</p>\n"
},
{
"answer_id": 102113,
"author": "Sam Erwin",
"author_id": 18224,
"author_profile": "https://Stackoverflow.com/users/18224",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know how hidden you'd call it, but the <a href=\"http://msdn.microsoft.com/en-us/library/bb513985.aspx\" rel=\"nofollow noreferrer\" title=\"If Operator (Visual Basic)\"><code>If</code></a> operator could count.</p>\n\n<p>It's very similar, in a way, to the <code>?:</code> (ternary) or the <code>??</code> operator in a lot of C-like languages. However, it's important to note that it does evaluate all of the parameters, so it's important to not pass in anything that may cause an exception (unless you want it to) or anything that may cause unintended side-effects.</p>\n\n<p>Usage:</p>\n\n<pre><code>Dim result = If(condition, valueWhenTrue, valueWhenFalse)\nDim value = If(obj, valueWhenObjNull)\n</code></pre>\n"
},
{
"answer_id": 102139,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<ul>\n<li>Child namespaces are in scope after importing their parent. For exampe, rather than having to import System.IO or say System.IO.File to use the File class, you can just say IO.File. That's a simple example: there are places where the feature really comes in handy, and C# doesn't do it.</li>\n</ul>\n"
},
{
"answer_id": 102146,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<h1><code>If</code> conditional and coalesce operator</h1>\n\n<blockquote>\n <p>I don't know how hidden you'd call it, but the Iif([expression],[value if true],[value if false]) As Object function could count.</p>\n</blockquote>\n\n<p>It's not so much hidden as <strong>deprecated</strong>! VB 9 has the <code>If</code> operator which is much better and works exactly as C#'s conditional and coalesce operator (depending on what you want):</p>\n\n<pre><code>Dim x = If(a = b, c, d)\n\nDim hello As String = Nothing\nDim y = If(hello, \"World\")\n</code></pre>\n\n<hr>\n\n<p>Edited to show another example:</p>\n\n<p>This will work with <code>If()</code>, but cause an exception with <code>IIf()</code></p>\n\n<pre><code>Dim x = If(b<>0,a/b,0)\n</code></pre>\n"
},
{
"answer_id": 102160,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 7,
"selected": false,
"text": "<p>The <code>Exception When</code> clause is largely unknown.</p>\n\n<p>Consider this:</p>\n\n<pre><code>Public Sub Login(host as string, user as String, password as string, _\n Optional bRetry as Boolean = False)\nTry\n ssh.Connect(host, user, password)\nCatch ex as TimeoutException When Not bRetry\n ''//Try again, but only once.\n Login(host, user, password, True)\nCatch ex as TimeoutException\n ''//Log exception\nEnd Try\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 102178,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 5,
"selected": false,
"text": "<p>Object initialization is in there too!</p>\n\n<pre><code>Dim x as New MyClass With {.Prop1 = foo, .Prop2 = bar}\n</code></pre>\n"
},
{
"answer_id": 102190,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>I used to be very fond of optional function parameters, but I use them less now that I have to go back and forth between C# and VB a lot. When will C# support them? C++ and even C had them (of a sort)!</p>\n"
},
{
"answer_id": 102212,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 4,
"selected": false,
"text": "<p>Import aliases are also largely unknown:</p>\n\n<pre><code>Import winf = System.Windows.Forms\n\n''Later\nDim x as winf.Form\n</code></pre>\n"
},
{
"answer_id": 102217,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": false,
"text": "<h1>Custom <code>Enum</code>s</h1>\n\n<p>One of the real <em>hidden</em> features of VB is the <code>completionlist</code> XML documentation tag that can be used to create own <code>Enum</code>-like types with extended functionality. This feature doesn't work in C#, though.</p>\n\n<p>One example from a recent code of mine:</p>\n\n<pre><code>'\n''' <completionlist cref=\"RuleTemplates\"/>\nPublic Class Rule\n Private ReadOnly m_Expression As String\n Private ReadOnly m_Options As RegexOptions\n\n Public Sub New(ByVal expression As String)\n Me.New(expression, RegexOptions.None)\n End Sub\n\n Public Sub New(ByVal expression As String, ByVal options As RegexOptions)\n m_Expression = expression\n m_options = options\n End Sub\n\n Public ReadOnly Property Expression() As String\n Get\n Return m_Expression\n End Get\n End Property\n\n Public ReadOnly Property Options() As RegexOptions\n Get\n Return m_Options\n End Get\n End Property\nEnd Class\n\nPublic NotInheritable Class RuleTemplates\n Public Shared ReadOnly Whitespace As New Rule(\"\\s+\")\n Public Shared ReadOnly Identifier As New Rule(\"\\w+\")\n Public Shared ReadOnly [String] As New Rule(\"\"\"([^\"\"]|\"\"\"\")*\"\"\")\nEnd Class\n</code></pre>\n\n<p>Now, when assigning a value to a variable declared as <code>Rule</code>, the IDE offers an IntelliSense list of possible values from <code>RuleTemplates</code>.</p>\n\n<h2>/EDIT:</h2>\n\n<p>Since this is a feature that relies on the IDE, it's hard to show how this looks when you use it but I'll just use a screenshot:</p>\n\n<p><a href=\"http://page.mi.fu-berlin.de/krudolph/stuff/completionlist.png\">Completion list in action http://page.mi.fu-berlin.de/krudolph/stuff/completionlist.png</a></p>\n\n<p>In fact, the IntelliSense is 100% identical to what you get when using an <code>Enum</code>.</p>\n"
},
{
"answer_id": 102229,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 4,
"selected": false,
"text": "<p>The Using statement is new as of VB 8, C# had it from the start. It calls dispose automagically for you.</p>\n\n<p>E.g.</p>\n\n<pre><code>Using lockThis as New MyLocker(objToLock)\n\nEnd Using\n</code></pre>\n"
},
{
"answer_id": 102244,
"author": "chrissie1",
"author_id": 2936,
"author_profile": "https://Stackoverflow.com/users/2936",
"pm_score": 2,
"selected": false,
"text": "<p>Aliassing namespaces</p>\n\n<pre><code>Imports Lan = Langauge\n</code></pre>\n\n<p>Although not unique to VB.Net it is often forgotten when running into namespace conflicts.</p>\n"
},
{
"answer_id": 102251,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 2,
"selected": false,
"text": "<p>It is also important to remember that VB.NET projects, by default, have a root namespace that is part of the project’s properties. By default this root namespace will have the same name as the project. When using the Namespace block structure, Names are actually appended to that root namespace. For example: if the project is named MyProject, then we could declare a variable as: </p>\n\n<pre><code>Private obj As MyProject.MyNamespace.MyClass\n</code></pre>\n\n<p>To change the root namespace, use the Project -> Properties menu option. The root namespace can be cleared as well, meaning that all Namespace blocks become the root level for the code they contain. </p>\n"
},
{
"answer_id": 102267,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 4,
"selected": false,
"text": "<p>This is built-in, and a definite advantage over C#. The ability to implement an interface Method without having to use the same name.</p>\n\n<p>Such as:</p>\n\n<pre><code>Public Sub GetISCSIAdmInfo(ByRef xDoc As System.Xml.XmlDocument) Implements IUnix.GetISCSIInfo\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 102321,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 6,
"selected": false,
"text": "<p>Oh! and don't forget <a href=\"http://msdn.microsoft.com/en-us/library/bb384629.aspx\" rel=\"nofollow noreferrer\">XML Literals</a>.</p>\n\n<pre><code>Dim contact2 = _\n <contact>\n <name>Patrick Hines</name>\n <%= From p In phoneNumbers2 _\n Select <phone type=<%= p.Type %>><%= p.Number %></phone> _\n %>\n </contact>\n</code></pre>\n"
},
{
"answer_id": 102369,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": false,
"text": "<h1>Typedefs</h1>\n\n<p>VB knows a primitive kind of <code>typedef</code> via <code>Import</code> aliases:</p>\n\n<pre><code>Imports S = System.String\n\nDim x As S = \"Hello\"\n</code></pre>\n\n<p>This is more useful when used in conjunction with generic types:</p>\n\n<pre><code>Imports StringPair = System.Collections.Generic.KeyValuePair(Of String, String)\n</code></pre>\n"
},
{
"answer_id": 102408,
"author": "Booji Boy",
"author_id": 1433,
"author_profile": "https://Stackoverflow.com/users/1433",
"pm_score": 2,
"selected": false,
"text": "<p>You can use REM to comment out a line instead of '\n. Not super useful, but helps important comments standout w/o using \"!!!!!!!\" or whatever. </p>\n"
},
{
"answer_id": 102435,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 4,
"selected": false,
"text": "<p>If you need a variable name to match that of a keyword, enclose it with brackets. Not nec. the best practice though - but it can be used wisely.</p>\n\n<p>e.g. </p>\n\n<pre><code>Class CodeException\nPublic [Error] as String\n''...\nEnd Class\n\n''later\nDim e as new CodeException\ne.Error = \"Invalid Syntax\"\n</code></pre>\n\n<p>e.g. Example from comments(@Pondidum):</p>\n\n<pre><code>Class Timer\nPublic Sub Start()\n''...\nEnd Sub\n\nPublic Sub [Stop]()\n''...\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 102471,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 3,
"selected": false,
"text": "<p>Title Case in VB.Net can be achieved by an old VB6 fxn:</p>\n\n<pre><code>StrConv(stringToTitleCase, VbStrConv.ProperCase,0) ''0 is localeID\n</code></pre>\n"
},
{
"answer_id": 103285,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<h1><code>DirectCast</code></h1>\n\n<p><code>DirectCast</code> is a marvel. On the surface, it works similar to the <code>CType</code> operator in that it converts an object from one type into another. However, it works by a much stricter set of rules. <code>CType</code>'s actual behaviour is therefore often opaque and it's not at all evident which kind of conversion is executed.</p>\n\n<p><code>DirectCast</code> only supports two distinct operations:</p>\n\n<ul>\n<li>Unboxing of a value type, and</li>\n<li>upcasting in the class hierarchy.</li>\n</ul>\n\n<p>Any other cast will not work (e.g. trying to unbox an <code>Integer</code> to a <code>Double</code>) and will result in a compile time/runtime error (depending on the situation and what can be detected by static type checking). I therefore use <code>DirectCast</code> whenever possible, as this captures my intent best: depending on the situation, I either want to unbox a value of known type or perform an upcast. End of story.</p>\n\n<p>Using <code>CType</code>, on the other hand, leaves the reader of the code wondering what the programmer really intended because it resolves to all kinds of different operations, including calling user-defined code.</p>\n\n<p>Why is this a hidden feature? The VB team has published a guideline<sup>1</sup> that discourages the use of <code>DirectCast</code> (even though it's actually faster!) in order to make the code more uniform. I argue that this is a bad guideline that should be reversed: <strong>Whenever possible, favour <code>DirectCast</code> over the more general <code>CType</code> operator.</strong> It makes the code much clearer. <code>CType</code>, on the other hand, should only be called if this is indeed intended, i.e. when a narrowing <code>CType</code> operator (cf. <a href=\"http://msdn.microsoft.com/en-us/library/yf7b9sy7(VS.80).aspx\" rel=\"nofollow noreferrer\">operator overloading</a>) should be called.</p>\n\n<hr>\n\n<p><sup>1)</sup> I'm unable to come up with a link to the guideline but I've found <a href=\"http://www.panopticoncentral.net/archive/2003/07/10/149.aspx\" rel=\"nofollow noreferrer\">Paul Vick's take on it</a> (chief developer of the VB team):</p>\n\n<blockquote>\n <p>In the real world, you're hardly ever going to notice the difference, so you might as well go with the more flexible conversion operators like CType, CInt, etc.</p>\n</blockquote>\n\n<hr>\n\n<p>(EDIT by Zack: Learn more here: <a href=\"https://stackoverflow.com/questions/40764/how-should-i-cast-in-vbnet\">How should I cast in VB.NET?</a>)</p>\n"
},
{
"answer_id": 103589,
"author": "Technobabble",
"author_id": 19063,
"author_profile": "https://Stackoverflow.com/users/19063",
"pm_score": 4,
"selected": false,
"text": "<p>Consider the following event declaration</p>\n\n<pre><code>Public Event SomethingHappened As EventHandler\n</code></pre>\n\n<p>In C#, you can check for event subscribers by using the following syntax:</p>\n\n<pre><code>if(SomethingHappened != null)\n{\n ...\n}\n</code></pre>\n\n<p>However, the VB.NET compiler does not support this. It actually creates a hidden private member field which is not visible in IntelliSense:</p>\n\n<pre><code>If Not SomethingHappenedEvent Is Nothing OrElse SomethingHappenedEvent.GetInvocationList.Length = 0 Then\n...\nEnd If\n</code></pre>\n\n<p>More Information:</p>\n\n<p><a href=\"http://jelle.druyts.net/2003/05/09/BehindTheScenesOfEventsInVBNET.aspx\" rel=\"nofollow noreferrer\">http://jelle.druyts.net/2003/05/09/BehindTheScenesOfEventsInVBNET.aspx</a>\n<a href=\"http://blogs.msdn.com/vbteam/archive/2009/09/25/testing-events-for-nothing-null-doug-rothaus.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/vbteam/archive/2009/09/25/testing-events-for-nothing-null-doug-rothaus.aspx</a></p>\n"
},
{
"answer_id": 103836,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<h1>Custom Events</h1>\n\n<p>Though seldom useful, event handling can be heavily customized:</p>\n\n<pre><code>Public Class ApplePie\n Private ReadOnly m_BakedEvent As New List(Of EventHandler)()\n\n Custom Event Baked As EventHandler\n AddHandler(ByVal value As EventHandler)\n Console.WriteLine(\"Adding a new subscriber: {0}\", value.Method)\n m_BakedEvent.Add(value)\n End AddHandler\n\n RemoveHandler(ByVal value As EventHandler)\n Console.WriteLine(\"Removing subscriber: {0}\", value.Method)\n m_BakedEvent.Remove(value)\n End RemoveHandler\n\n RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)\n Console.WriteLine(\"{0} is raising an event.\", sender)\n For Each ev In m_BakedEvent\n ev.Invoke(sender, e)\n Next\n End RaiseEvent\n End Event\n\n Public Sub Bake()\n ''// 1. Add ingredients\n ''// 2. Stir\n ''// 3. Put into oven (heated, not pre-heated!)\n ''// 4. Bake\n RaiseEvent Baked(Me, EventArgs.Empty)\n ''// 5. Digest\n End Sub\nEnd Class\n</code></pre>\n\n<p>This can then be tested in the following fashion:</p>\n\n<pre><code>Module Module1\n Public Sub Foo(ByVal sender As Object, ByVal e As EventArgs)\n Console.WriteLine(\"Hmm, freshly baked apple pie.\")\n End Sub\n\n Sub Main()\n Dim pie As New ApplePie()\n AddHandler pie.Baked, AddressOf Foo\n pie.Bake()\n RemoveHandler pie.Baked, AddressOf Foo\n End Sub\nEnd Module\n</code></pre>\n"
},
{
"answer_id": 167834,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Static members in methods.</strong></p>\n\n<p>For example:</p>\n\n<pre><code>Function CleanString(byval input As String) As String\n Static pattern As New RegEx(\"...\")\n\n return pattern.Replace(input, \"\")\nEnd Function\n</code></pre>\n\n<p>In the above function, the pattern regular expression will only ever be created once no matter how many times the function is called. </p>\n\n<p>Another use is to keep an instance of \"random\" around:</p>\n\n<pre><code>Function GetNextRandom() As Integer\n Static r As New Random(getSeed())\n\n Return r.Next()\nEnd Function \n</code></pre>\n\n<p>Also, this isn't the same as simply declaring it as a Shared member of the class; items declared this way are guaranteed to be thread-safe as well. It doesn't matter in this scenario since the expression will never change, but there are others where it might.</p>\n"
},
{
"answer_id": 190868,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 5,
"selected": false,
"text": "<p>I really like the <strong>\"My\" Namespace</strong> which was introduced in Visual Basic 2005. <em>My</em> is a shortcut to several groups of information and functionality. It provides quick and intuitive access to the following types of information:</p>\n\n<ul>\n<li><strong>My.Computer</strong>: Access to information related to the computer such as file system, network, devices, system information, etc. It provides access to a number of very important resources including My.Computer.Network, My.Computer.FileSystem, and My.Computer.Printers.</li>\n<li><strong>My.Application</strong>: Access to information related to the particular application such as name, version, current directory, etc.</li>\n<li><strong>My.User</strong>: Access to information related to the current authenticated user.</li>\n<li><strong>My.Resources</strong>: Access to resources used by the application residing in resource files in a strongly typed manner.</li>\n<li><strong>My.Settings</strong>: Access to configuration settings of the application in a strongly typed manner.</li>\n</ul>\n"
},
{
"answer_id": 198134,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>may be this link should help</p>\n\n<p><a href=\"http://blogs.msdn.com/vbteam/archive/2007/11/20/hidden-gems-in-visual-basic-2008-amanda-silver.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/vbteam/archive/2007/11/20/hidden-gems-in-visual-basic-2008-amanda-silver.aspx</a></p>\n"
},
{
"answer_id": 324153,
"author": "dr. evil",
"author_id": 40322,
"author_profile": "https://Stackoverflow.com/users/40322",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Optional Parameters</strong></p>\n\n<p>Optionals are so much easier than creating a new overloads, such as :</p>\n\n<pre><code>Function CloseTheSystem(Optional ByVal msg AS String = \"Shutting down the system...\")\n Console.Writeline(msg)\n ''//do stuff\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 337653,
"author": "Rich",
"author_id": 39691,
"author_profile": "https://Stackoverflow.com/users/39691",
"pm_score": 4,
"selected": false,
"text": "<p>Passing parameters by name and, so reordering them</p>\n\n<pre><code>Sub MyFunc(Optional msg as String= \"\", Optional displayOrder As integer = 0)\n\n 'Do stuff\n\nEnd function\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Module Module1\n\n Sub Main()\n\n MyFunc() 'No params specified\n\n End Sub\n\nEnd Module\n</code></pre>\n\n<p>Can also be called using the \":=\" parameter specification in any order:</p>\n\n<pre><code>MyFunc(displayOrder:=10, msg:=\"mystring\")\n</code></pre>\n"
},
{
"answer_id": 381331,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Properties with parameters</strong> </p>\n\n<p>I have been doing some C# programming, and discovered a feature that was missing that VB.Net had, but was not mentioned here.</p>\n\n<p>An example of how to do this (as well as the c# limitation) can be seen at: <a href=\"https://stackoverflow.com/questions/236530/using-the-typical-get-set-properties-in-c-with-parameters\">Using the typical get set properties in C#... with parameters</a></p>\n\n<p>I have excerpted the code from that answer:</p>\n\n<pre><code>Private Shared m_Dictionary As IDictionary(Of String, Object) = _\n New Dictionary(Of String, Object)\n\nPublic Shared Property DictionaryElement(ByVal Key As String) As Object\n Get\n If m_Dictionary.ContainsKey(Key) Then\n Return m_Dictionary(Key)\n Else\n Return [String].Empty\n End If\n End Get\n Set(ByVal value As Object)\n If m_Dictionary.ContainsKey(Key) Then\n m_Dictionary(Key) = value\n Else\n m_Dictionary.Add(Key, value)\n End If\n\n End Set\nEnd Property\n</code></pre>\n"
},
{
"answer_id": 394200,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 5,
"selected": false,
"text": "<p>This is a nice one. The Select Case statement within VB.Net is very powerful. </p>\n\n<p>Sure there is the standard</p>\n\n<pre><code>Select Case Role\n Case \"Admin\"\n ''//Do X\n Case \"Tester\"\n ''//Do Y\n Case \"Developer\"\n ''//Do Z\n Case Else\n ''//Exception case\nEnd Select\n</code></pre>\n\n<p>But there is more...</p>\n\n<p>You can do ranges:</p>\n\n<pre><code>Select Case Amount\n Case Is < 0\n ''//What!!\n Case 0 To 15\n Shipping = 2.0\n Case 16 To 59\n Shipping = 5.87\n Case Is > 59\n Shipping = 12.50\n Case Else\n Shipping = 9.99\n End Select\n</code></pre>\n\n<p>And even more...</p>\n\n<p>You can (although may not be a good idea) do boolean checks on multiple variables:</p>\n\n<pre><code>Select Case True\n Case a = b\n ''//Do X\n Case a = c\n ''//Do Y\n Case b = c\n ''//Do Z\n Case Else\n ''//Exception case\n End Select\n</code></pre>\n"
},
{
"answer_id": 500642,
"author": "Parsa",
"author_id": 60996,
"author_profile": "https://Stackoverflow.com/users/60996",
"pm_score": 2,
"selected": false,
"text": "<p>It's not possible to Explicitly implement interface members in VB, but it's possible to implement them with a different name.</p>\n\n<pre><code>Interface I1\n Sub Foo()\n Sub TheFoo()\nEnd Interface\n\nInterface I2\n Sub Foo()\n Sub TheFoo()\nEnd Interface\n\nClass C\n Implements I1, I2\n\n Public Sub IAmFoo1() Implements I1.Foo\n ' Something happens here'\n End Sub\n\n Public Sub IAmFoo2() Implements I2.Foo\n ' Another thing happens here'\n End Sub\n\n Public Sub TheF() Implements I1.TheFoo, I2.TheFoo\n ' You shouldn't yell!'\n End Sub\nEnd Class\n</code></pre>\n\n<p><a href=\"https://connect.microsoft.com/VisualStudio/feedback/details/454529/allow-implicit-interface-implementation-in-vb-like-in-c\" rel=\"nofollow noreferrer\" title=\"Allow implicit interface implementation in VB like in C#\"><strong>Please vote for this feature at Microsoft Connect</strong></a>.</p>\n"
},
{
"answer_id": 500655,
"author": "Parsa",
"author_id": 60996,
"author_profile": "https://Stackoverflow.com/users/60996",
"pm_score": 4,
"selected": false,
"text": "<p>You can have 2 lines of code in just one line. hence:</p>\n\n<pre><code>Dim x As New Something : x.CallAMethod\n</code></pre>\n"
},
{
"answer_id": 500667,
"author": "Parsa",
"author_id": 60996,
"author_profile": "https://Stackoverflow.com/users/60996",
"pm_score": 3,
"selected": false,
"text": "<p>You can have an If in one line.</p>\n\n<pre><code>If True Then DoSomething()\n</code></pre>\n"
},
{
"answer_id": 500669,
"author": "Parsa",
"author_id": 60996,
"author_profile": "https://Stackoverflow.com/users/60996",
"pm_score": 2,
"selected": false,
"text": "<p>VB also offers the OnError statement. But it's not much of use these days.\n<code></p>\n\n<pre><code>On Error Resume Next\n' Or'\nOn Error GoTo someline\n</code></pre>\n\n<p></code></p>\n"
},
{
"answer_id": 500677,
"author": "Parsa",
"author_id": 60996,
"author_profile": "https://Stackoverflow.com/users/60996",
"pm_score": 6,
"selected": false,
"text": "<p>Have you noticed the Like comparison operator?</p>\n\n<p><code>\n Dim b As Boolean = \"file.txt\" Like \"*.txt\"\n</code></p>\n\n<p>More from <a href=\"http://msdn.microsoft.com/en-us/library/swf8kaxw.aspx\" rel=\"noreferrer\">MSDN</a></p>\n\n<pre><code>Dim testCheck As Boolean\n\n' The following statement returns True (does \"F\" satisfy \"F\"?)'\ntestCheck = \"F\" Like \"F\"\n\n' The following statement returns False for Option Compare Binary'\n' and True for Option Compare Text (does \"F\" satisfy \"f\"?)'\ntestCheck = \"F\" Like \"f\"\n\n' The following statement returns False (does \"F\" satisfy \"FFF\"?)'\ntestCheck = \"F\" Like \"FFF\"\n\n' The following statement returns True (does \"aBBBa\" have an \"a\" at the'\n' beginning, an \"a\" at the end, and any number of characters in '\n' between?)'\ntestCheck = \"aBBBa\" Like \"a*a\"\n\n' The following statement returns True (does \"F\" occur in the set of'\n' characters from \"A\" through \"Z\"?)'\ntestCheck = \"F\" Like \"[A-Z]\"\n\n' The following statement returns False (does \"F\" NOT occur in the '\n' set of characters from \"A\" through \"Z\"?)'\ntestCheck = \"F\" Like \"[!A-Z]\"\n\n' The following statement returns True (does \"a2a\" begin and end with'\n' an \"a\" and have any single-digit number in between?)'\ntestCheck = \"a2a\" Like \"a#a\"\n\n' The following statement returns True (does \"aM5b\" begin with an \"a\",'\n' followed by any character from the set \"L\" through \"P\", followed'\n' by any single-digit number, and end with any character NOT in'\n' the character set \"c\" through \"e\"?)'\ntestCheck = \"aM5b\" Like \"a[L-P]#[!c-e]\"\n\n' The following statement returns True (does \"BAT123khg\" begin with a'\n' \"B\", followed by any single character, followed by a \"T\", and end'\n' with zero or more characters of any type?)'\ntestCheck = \"BAT123khg\" Like \"B?T*\"\n\n' The following statement returns False (does \"CAT123khg\" begin with'\n' a \"B\", followed by any single character, followed by a \"T\", and'\n' end with zero or more characters of any type?)'\ntestCheck = \"CAT123khg\" Like \"B?T*\"\n</code></pre>\n"
},
{
"answer_id": 500686,
"author": "Parsa",
"author_id": 60996,
"author_profile": "https://Stackoverflow.com/users/60996",
"pm_score": 1,
"selected": false,
"text": "<p>Someday Basic users didn't introduce any variable. They introduced them just by using them. VB's Option Explicit was introduced just to make sure you wouldn't introduce any variable mistakenly by bad typing. You can always turn it to Off, experience the days we worked with Basic.</p>\n"
},
{
"answer_id": 500690,
"author": "Parsa",
"author_id": 60996,
"author_profile": "https://Stackoverflow.com/users/60996",
"pm_score": 3,
"selected": false,
"text": "<p>In VB8 and the former vesions, if you didn't specify any type for the variable you introduce, the Object type was automaticly detected. In VB9 (2008), the <code>Dim</code> would act like C#'s <code>var</code> keyword if the Option Infer is set to On (which is, by default)</p>\n"
},
{
"answer_id": 646188,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 4,
"selected": false,
"text": "<p>I just found an article talking about the \"!\" operator, also know as the \"dictionary lookup operator\". Here's an excerpt from the article at: <a href=\"http://panopticoncentral.net/articles/902.aspx\" rel=\"nofollow noreferrer\">http://panopticoncentral.net/articles/902.aspx</a></p>\n\n<blockquote>\n <p>The technical name for the ! operator\n is the \"dictionary lookup operator.\" A\n dictionary is any collection type that\n is indexed by a key rather than a\n number, just like the way that the\n entries in an English dictionary are\n indexed by the word you want the\n definition of. The most common example\n of a dictionary type is the\n System.Collections.Hashtable, which\n allows you to add (key, value) pairs\n into the hashtable and then retrieve\n values using the keys. For example,\n the following code adds three entries\n to a hashtable, and looks one of them\n up using the key \"Pork\".</p>\n</blockquote>\n\n<pre><code>Dim Table As Hashtable = New Hashtable\nTable(\"Orange\") = \"A fruit\"\nTable(\"Broccoli\") = \"A vegetable\"\nTable(\"Pork\") = \"A meat\" \nConsole.WriteLine(Table(\"Pork\"))\n</code></pre>\n\n<blockquote>\n <p>The ! operator can be used to look up\n values from any dictionary type that\n indexes its values using strings. The\n identifier after the ! is used as the\n key in the lookup operation. So the\n above code could instead have been\n written:</p>\n</blockquote>\n\n<pre><code>Dim Table As Hashtable = New Hashtable\nTable!Orange = \"A fruit\"\nTable!Broccoli = \"A vegetable\"\nTable!Pork = \"A meat\"\nConsole.WriteLine(Table!Pork)\n</code></pre>\n\n<blockquote>\n <p>The second example is completely\n equivalent to the first, but just\n looks a lot nicer, at least to my\n eyes. I find that there are a lot of\n places where ! can be used, especially\n when it comes to XML and the web,\n where there are just tons of\n collections that are indexed by\n string. One unfortunate limitation is\n that the thing following the ! still\n has to be a valid identifier, so if\n the string you want to use as a key\n has some invalid identifier character\n in it, you can't use the ! operator.\n (You can't, for example, say\n \"Table!AB$CD = 5\" because $ isn't\n legal in identifiers.) In VB6 and\n before, you could use brackets to\n escape invalid identifiers (i.e.\n \"Table![AB$CD]\"), but when we started\n using brackets to escape keywords, we\n lost the ability to do that. In most\n cases, however, this isn't too much of\n a limitation.</p>\n \n <p>To get really technical, x!y works if\n x has a default property that takes a\n String or Object as a parameter. In\n that case, x!y is changed into\n x.DefaultProperty(\"y\"). An interesting\n side note is that there is a special\n rule in the lexical grammar of the\n language to make this all work. The !\n character is also used as a type\n character in the language, and type\n characters are eaten before operators.\n So without a special rule, x!y would\n be scanned as \"x! y\" instead of \"x !\n y\". Fortunately, since there is no\n place in the language where two\n identifiers in a row are valid, we\n just introduced the rule that if the\n next character after the ! is the\n start of an identifier, we consider\n the ! to be an operator and not a type\n character.</p>\n</blockquote>\n"
},
{
"answer_id": 692685,
"author": "Parsa",
"author_id": 60996,
"author_profile": "https://Stackoverflow.com/users/60996",
"pm_score": 2,
"selected": false,
"text": "<p>MyClass keyword provides a way to refer to the class instance members as originally implemented, ignoring any derived class overrides.</p>\n"
},
{
"answer_id": 884441,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Select Case in place of multiple If/ElseIf/Else statements.</p>\n\n<p>Assume simple geometry objects in this example:</p>\n\n<pre><code>Function GetToString(obj as SimpleGeomertyClass) as String\n Select Case True\n Case TypeOf obj is PointClass\n Return String.Format(\"Point: Position = {0}\", _\n DirectCast(obj,Point).ToString)\n Case TypeOf obj is LineClass\n Dim Line = DirectCast(obj,LineClass)\n Return String.Format(\"Line: StartPosition = {0}, EndPosition = {1}\", _\n Line.StartPoint.ToString,Line.EndPoint.ToString)\n Case TypeOf obj is CircleClass\n Dim Line = DirectCast(obj,CircleClass)\n Return String.Format(\"Circle: CenterPosition = {0}, Radius = {1}\", _\n Circle.CenterPoint.ToString,Circle.Radius)\n Case Else\n Return String.Format(\"Unhandled Type {0}\",TypeName(obj))\n End Select\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 940097,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Stack/group multiple using statements together:</strong></p>\n\n<pre><code>Dim sql As String = \"StoredProcedureName\"\nUsing cn As SqlConnection = getOpenConnection(), _\n cmd As New SqlCommand(sql, cn), _\n rdr As SqlDataReader = cmd.ExecuteReader()\n\n While rdr.Read()\n\n ''// Do Something\n\n End While\n\nEnd Using\n</code></pre>\n\n<p>To be fair, you can do it in C#, too. But a lot of people don't know about this in either language.</p>\n"
},
{
"answer_id": 940420,
"author": "cjk",
"author_id": 52201,
"author_profile": "https://Stackoverflow.com/users/52201",
"pm_score": 5,
"selected": false,
"text": "<p>The best and easy CSV parser:</p>\n\n<pre><code>Microsoft.VisualBasic.FileIO.TextFieldParser\n</code></pre>\n\n<p>By adding a reference to Microsoft.VisualBasic, this can be used in any other .Net language, e.g. C#</p>\n"
},
{
"answer_id": 1027703,
"author": "Dan F",
"author_id": 11569,
"author_profile": "https://Stackoverflow.com/users/11569",
"pm_score": 3,
"selected": false,
"text": "<p>Similar to <a href=\"https://stackoverflow.com/questions/102084/hidden-features-of-vb-net/500677#500677\">Parsa's</a> answer, the <a href=\"http://msdn.microsoft.com/en-us/library/swf8kaxw.aspx\" rel=\"nofollow noreferrer\">like operator</a> has <strong>lots</strong> of things it can match on over and above simple wildcards. I nearly fell of my chair when reading the MSDN doco on it :-) </p>\n"
},
{
"answer_id": 1058767,
"author": "danlash",
"author_id": 13072,
"author_profile": "https://Stackoverflow.com/users/13072",
"pm_score": 4,
"selected": false,
"text": "<p>DateTime can be initialized by surrounding your date with # </p>\n\n<pre><code>Dim independanceDay As DateTime = #7/4/1776#\n</code></pre>\n\n<p>You can also use type inference along with this syntax</p>\n\n<pre><code>Dim independanceDay = #7/4/1776#\n</code></pre>\n\n<p>That's a lot nicer than using the constructor</p>\n\n<pre><code>Dim independanceDay as DateTime = New DateTime(1776, 7, 4)\n</code></pre>\n"
},
{
"answer_id": 1120271,
"author": "Shimmy Weitzhandler",
"author_id": 75500,
"author_profile": "https://Stackoverflow.com/users/75500",
"pm_score": 5,
"selected": false,
"text": "<p>In vb there is a different between these operators:</p>\n\n<p><code>/</code> is <code>Double</code><br>\n<code>\\</code> is <code>Integer</code> ignoring the remainder</p>\n\n<pre><code>Sub Main()\n Dim x = 9 / 5 \n Dim y = 9 \\ 5 \n Console.WriteLine(\"item x of '{0}' equals to {1}\", x.GetType.FullName, x)\n Console.WriteLine(\"item y of '{0}' equals to {1}\", y.GetType.FullName, y)\n\n 'Results:\n 'item x of 'System.Double' equals to 1.8\n 'item y of 'System.Int32' equals to 1\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 1120393,
"author": "Shimmy Weitzhandler",
"author_id": 75500,
"author_profile": "https://Stackoverflow.com/users/75500",
"pm_score": 3,
"selected": false,
"text": "<p>If you never knew about the following you really won't believe it's true, this is really something that C# lacks big time:</p>\n\n<p>(It's called XML literals)</p>\n\n<pre><code>Imports <xmlns:xs=\"System\">\n\nModule Module1\n\n Sub Main()\n Dim xml =\n <root>\n <customer id=\"345\">\n <name>John</name>\n <age>17</age>\n </customer>\n <customer id=\"365\">\n <name>Doe</name>\n <age>99</age>\n </customer>\n </root>\n\n Dim id = 1\n Dim name = \"Beth\"\n DoIt(\n <param>\n <customer>\n <id><%= id %></id>\n <name><%= name %></name>\n </customer>\n </param>\n )\n\n Dim names = xml...<name>\n For Each n In names\n Console.WriteLine(n.Value)\n Next\n\n For Each customer In xml.<customer>\n Console.WriteLine(\"{0}: {1}\", customer.@id, customer.<age>.Value)\n Next\n\n Console.Read()\n End Sub\n\n Private Sub CreateClass()\n Dim CustomerSchema =\n XDocument.Load(CurDir() & \"\\customer.xsd\")\n\n Dim fields =\n From field In CustomerSchema...<xs:element>\n Where field.@type IsNot Nothing\n Select\n Name = field.@name,\n Type = field.@type\n\n Dim customer = \n <customer> Public Class Customer \n<%= From field In fields Select <f> \nPrivate m_<%= field.Name %> As <%= GetVBPropType(field.Type) %></f>.Value %>\n\n <%= From field In fields Select <p> \nPublic Property <%= field.Name %> As <%= GetVBPropType(field.Type) %>\n Get \nReturn m_<%= field.Name %> \nEnd Get\n Set(ByVal value As <%= GetVBPropType(field.Type) %>)\n m_<%= field.Name %> = value \nEnd Set\n End Property</p>.Value %> \nEnd Class</customer>\n\n My.Computer.FileSystem.WriteAllText(\"Customer.vb\",\n customer.Value,\n False,\n System.Text.Encoding.ASCII)\n\n End Sub\n\n Private Function GetVBPropType(ByVal xmlType As String) As String\n Select Case xmlType\n Case \"xs:string\"\n Return \"String\"\n Case \"xs:int\"\n Return \"Integer\"\n Case \"xs:decimal\"\n Return \"Decimal\"\n Case \"xs:boolean\"\n Return \"Boolean\"\n Case \"xs:dateTime\", \"xs:date\"\n Return \"Date\"\n Case Else\n Return \"'TODO: Define Type\"\n End Select\n End Function\n\n Private Sub DoIt(ByVal param As XElement)\n Dim customers =\n From customer In param...<customer>\n Select New Customer With\n {\n .ID = customer.<id>.Value,\n .FirstName = customer.<name>.Value\n }\n\n For Each c In customers\n Console.WriteLine(c.ToString())\n Next\n End Sub\n\n Private Class Customer\n Public ID As Integer\n Public FirstName As String\n Public Overrides Function ToString() As String\n Return <string>\nID : <%= Me.ID %>\nName : <%= Me.FirstName %>\n </string>.Value\n End Function\n\n End Class\nEnd Module\n'Results:\n\nID : 1\nName : Beth\nJohn\nDoe\n345: 17\n365: 99\n</code></pre>\n\n<p>Take a look at <a href=\"http://blogs.msdn.com/bethmassi/archive/2007/10/26/xml-literals-tips-tricks.aspx\" rel=\"nofollow noreferrer\">XML Literals Tips/Tricks</a> by Beth Massi.</p>\n"
},
{
"answer_id": 1120501,
"author": "Shimmy Weitzhandler",
"author_id": 75500,
"author_profile": "https://Stackoverflow.com/users/75500",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Sub Main()\n Select Case \"value to check\"\n 'Check for multiple items at once:'\n Case \"a\", \"b\", \"asdf\" \n Console.WriteLine(\"Nope...\")\n Case \"value to check\"\n Console.WriteLine(\"Oh yeah! thass what im talkin about!\")\n Case Else\n Console.WriteLine(\"Nah :'(\")\n End Select\n\n\n Dim jonny = False\n Dim charlie = True\n Dim values = New String() {\"asdff\", \"asdfasdf\"}\n Select Case \"asdfasdf\"\n 'You can perform boolean checks that has nothing to do with your var.,\n 'not that I would recommend that, but it exists.'\n Case values.Contains(\"ddddddddddddddddddddddd\")\n Case True\n Case \"No sense\"\n Case Else\n End Select\n\n Dim x = 56\n Select Case x\n Case Is > 56\n Case Is <= 5\n Case Is <> 45\n Case Else\n End Select\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 1120520,
"author": "Shimmy Weitzhandler",
"author_id": 75500,
"author_profile": "https://Stackoverflow.com/users/75500",
"pm_score": 2,
"selected": false,
"text": "<p>Unlike in C#, in VB you can rely on the default values for non-nullable items:</p>\n\n<pre><code>Sub Main()\n 'Auto assigned to def value'\n Dim i As Integer '0'\n Dim dt As DateTime '#12:00:00 AM#'\n Dim a As Date '#12:00:00 AM#'\n Dim b As Boolean 'False'\n\n Dim s = i.ToString 'valid\nEnd Sub\n</code></pre>\n\n<p>Whereas in C#, this will be a compiler error:</p>\n\n<pre><code>int x;\nvar y = x.ToString(); //Use of unassigned value\n</code></pre>\n"
},
{
"answer_id": 1120579,
"author": "Shimmy Weitzhandler",
"author_id": 75500,
"author_profile": "https://Stackoverflow.com/users/75500",
"pm_score": 3,
"selected": false,
"text": "<pre><code>IIf(False, MsgBox(\"msg1\"), MsgBox(\"msg2\"))\n</code></pre>\n\n<p>What is the result? two message boxes!!!!\nThis happens cuz the IIf function evaluates both parameters when reaching the function.</p>\n\n<p>VB has a new If operator (just like C# ?: operator):</p>\n\n<pre><code>If(False, MsgBox(\"msg1\"), MsgBox(\"msg2\"))\n</code></pre>\n\n<p>Will show only second msgbox.</p>\n\n<p>in general I would recommend replacing all the IIFs in you vb code, unless you wanted it to evealueate both items:</p>\n\n<pre><code>Dim value = IIf(somthing, LoadAndGetValue1(), LoadAndGetValue2())\n</code></pre>\n\n<p>you can be sure that both values were loaded.</p>\n"
},
{
"answer_id": 1120610,
"author": "Shimmy Weitzhandler",
"author_id": 75500,
"author_profile": "https://Stackoverflow.com/users/75500",
"pm_score": 3,
"selected": false,
"text": "<p>You can use reserved keyword for properties and variable names if you surround the name with [ and ]</p>\n\n<pre><code>Public Class Item\n Private Value As Integer\n Public Sub New(ByVal value As Integer)\n Me.Value = value\n End Sub\n\n Public ReadOnly Property [String]() As String\n Get\n Return Value\n End Get\n End Property\n\n Public ReadOnly Property [Integer]() As Integer\n Get\n Return Value\n End Get\n End Property\n\n Public ReadOnly Property [Boolean]() As Boolean\n Get\n Return Value\n End Get\n End Property\nEnd Class\n\n'Real examples:\nPublic Class PropertyException : Inherits Exception\n Public Sub New(ByVal [property] As String)\n Me.Property = [property]\n End Sub\n\n Private m_Property As String\n Public Property [Property]() As String\n Get\n Return m_Property\n End Get\n Set(ByVal value As String)\n m_Property = value\n End Set\n End Property\nEnd Class\n\nPublic Enum LoginLevel\n [Public] = 0\n Account = 1\n Admin = 2\n [Default] = Account\nEnd Enum\n</code></pre>\n"
},
{
"answer_id": 1124247,
"author": "Shimmy Weitzhandler",
"author_id": 75500,
"author_profile": "https://Stackoverflow.com/users/75500",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Private Sub Button1_Click(ByVal sender As Button, ByVal e As System.EventArgs)\n Handles Button1.Click\n sender.Enabled = True\n DisableButton(sender)\nEnd Sub\n\nPrivate Sub Disable(button As Object)\n button.Enabled = false\nEnd Sub\n</code></pre>\n\n<p>In this snippet you have 2 (maybe more?) things that you could never do in C#:</p>\n\n<ol>\n<li>Handles Button1.Click - attach a handler to the event externally!</li>\n<li>VB's implicitness allows you to declare the first param of the handler as the expexted type. in C# you cannot address a delegate to a different pattern, even it's the expected type.</li>\n</ol>\n\n<p>Also, in C# you cannot use expected functionality on object - in C# you can dream about it (now they made the dynamic keyword, but it's far away from VB).\nIn C#, if you will write (new object()).Enabled you will get an error that type object doesn't have a method 'Enabled'.\nNow, I am not the one who will recommend you if this is safe or not, the info is provided AS IS, do on your own, bus still, sometimes (like when working with COM objects) this is such a good thing.\nI personally always write (sender As Button) when the expected value is surely a button.</p>\n\n<p>Actually moreover: take this example:</p>\n\n<pre><code>Private Sub control_Click(ByVal sender As Control, ByVal e As System.EventArgs)\n Handles TextBox1.Click, CheckBox1.Click, Button1.Click\n sender.Text = \"Got it?...\"\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 1124512,
"author": "Shimmy Weitzhandler",
"author_id": 75500,
"author_profile": "https://Stackoverflow.com/users/75500",
"pm_score": 1,
"selected": false,
"text": "<p>Differences between <strong>ByVal</strong> and <strong>ByRef</strong> keywords:</p>\n\n<pre><code>Module Module1\n\n Sub Main()\n Dim str1 = \"initial\"\n Dim str2 = \"initial\"\n DoByVal(str1)\n DoByRef(str2)\n\n Console.WriteLine(str1)\n Console.WriteLine(str2)\n End Sub\n\n Sub DoByVal(ByVal str As String)\n str = \"value 1\"\n End Sub\n\n Sub DoByRef(ByRef str As String)\n str = \"value 2\"\n End Sub\nEnd Module\n\n'Results:\n'initial\n'value 2\n</code></pre>\n"
},
{
"answer_id": 1207521,
"author": "Youssef",
"author_id": 10968,
"author_profile": "https://Stackoverflow.com/users/10968",
"pm_score": 3,
"selected": false,
"text": "<p>One of the features I found really useful and helped to solve many bugs is explicitly passing arguments to functions, especially when using optional.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>Public Function DoSomething(byval x as integer, optional y as boolean=True, optional z as boolean=False)\n' ......\nEnd Function\n</code></pre>\n\n<p>then you can call it like this:</p>\n\n<pre><code>DoSomething(x:=1, y:=false)\nDoSomething(x:=2, z:=true)\nor\nDoSomething(x:=3,y:=false,z:=true)\n</code></pre>\n\n<p>This is much cleaner and bug free then calling the function like this</p>\n\n<pre><code>DoSomething(1,true)\n</code></pre>\n"
},
{
"answer_id": 1296608,
"author": "Craig Gidney",
"author_id": 52239,
"author_profile": "https://Stackoverflow.com/users/52239",
"pm_score": 2,
"selected": false,
"text": "<p>The Nothing keyword can mean default(T) or null, depending on the context. You can exploit this to make a very interesting method:</p>\n\n<pre><code>'''<summary>Returns true for reference types, false for struct types.</summary>'\nPublic Function IsReferenceType(Of T)() As Boolean\n Return DirectCast(Nothing, T) Is Nothing\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 1446195,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 3,
"selected": false,
"text": "<h2>Refined Error Handling using When</h2>\n\n<p>Notice the use of <code>when</code> in the line <code>Catch ex As IO.FileLoadException When attempt < 3</code></p>\n\n<pre><code>Do\n Dim attempt As Integer\n Try\n ''// something that might cause an error.\n Catch ex As IO.FileLoadException When attempt < 3\n If MsgBox(\"do again?\", MsgBoxStyle.YesNo) = MsgBoxResult.No Then\n Exit Do\n End If\n Catch ex As Exception\n ''// if any other error type occurs or the attempts are too many\n MsgBox(ex.Message)\n Exit Do\n End Try\n ''// increment the attempt counter.\n attempt += 1\nLoop\n</code></pre>\n\n<p>Recently viewed in <a href=\"http://www.vbrad.com/article.aspx?id=65\" rel=\"nofollow noreferrer\">VbRad</a></p>\n"
},
{
"answer_id": 1612781,
"author": "Marcus Andrén",
"author_id": 135502,
"author_profile": "https://Stackoverflow.com/users/135502",
"pm_score": 3,
"selected": false,
"text": "<p>When declaring an array in vb.net always use the \"0 to xx\" syntax.</p>\n\n<pre><code>Dim b(0 to 9) as byte 'Declares an array of 10 bytes\n</code></pre>\n\n<p>It makes it very clear about the span of the array. Compare it with the equivalent</p>\n\n<pre><code>Dim b(9) as byte 'Declares another array of 10 bytes\n</code></pre>\n\n<p>Even if you know that the second example consists of 10 elements, it just doesn't feel obvious. And I can't remember the number of times when I have seen code from a programmer who wanted the above but instead wrote</p>\n\n<pre><code>Dim b(10) as byte 'Declares another array of 10 bytes\n</code></pre>\n\n<p>This is of course completely wrong. As b(10) creates an array of 11 bytes. And it can easily cause bugs as it looks correct to anyone who doesn't know what to look for.</p>\n\n<p>The \"0 to xx\" syntax also works with the below</p>\n\n<pre><code>Dim b As Byte() = New Byte(0 To 9) {} 'Another way to create a 10 byte array\nReDim b(0 to 9) 'Assigns a new 10 byte array to b\n</code></pre>\n\n<p>By using the full syntax you will also demonstrate to anyone who reads your code in the future that you knew what you were doing.</p>\n"
},
{
"answer_id": 1836103,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a funny one that I haven't seen; I know it works in VS 2008, at least:</p>\n\n<p><strong>If you accidentally end your VB line with a semicolon</strong>, because you've been doing too much C#, <strong>the semicolon is automatically removed</strong>. It's actually impossible (again, in VS 2008 at least) to accidentally end a VB line with a semicolon. Try it!</p>\n\n<p>(It's not perfect; if you type the semicolon halfway through your final class name, it won't autocomplete the class name.)</p>\n"
},
{
"answer_id": 1925143,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 4,
"selected": false,
"text": "<p>There are a couple of answers about XML Literals, but not about this specific case:</p>\n\n<p>You can use XML Literals to enclose string literals that would otherwise need to be escaped. String literals that contain double-quotes, for instance.</p>\n\n<p>Instead of this:</p>\n\n<pre><code>Dim myString = _\n \"This string contains \"\"quotes\"\" and they're ugly.\"\n</code></pre>\n\n<p>You can do this:</p>\n\n<pre><code>Dim myString = _\n <string>This string contains \"quotes\" and they're nice.</string>.Value\n</code></pre>\n\n<p>This is especially useful if you're testing a literal for CSV parsing:</p>\n\n<pre><code>Dim csvTestYuck = _\n \"\"\"Smith\"\", \"\"Bob\"\", \"\"123 Anywhere St\"\", \"\"Los Angeles\"\", \"\"CA\"\"\"\n\nDim csvTestMuchBetter = _\n <string>\"Smith\", \"Bob\", \"123 Anywhere St\", \"Los Angeles\", \"CA\"</string>.Value\n</code></pre>\n\n<p>(You don't have to use the <code><string></code> tag, of course; you can use any tag you like.)</p>\n"
},
{
"answer_id": 2837501,
"author": "Chris Haas",
"author_id": 231316,
"author_profile": "https://Stackoverflow.com/users/231316",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Forcing ByVal</strong></p>\n\n<p>In VB, if you wrap your arguments in an extra set of parentheses you can override the ByRef declaration of the method and turn it into a ByVal. For instance, the following code produces 4, 5, 5 instead of 4,5,6</p>\n\n<pre><code>Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n Dim R = 4\n Trace.WriteLine(R)\n Test(R)\n Trace.WriteLine(R)\n Test((R))\n Trace.WriteLine(R)\nEnd Sub\nPrivate Sub Test(ByRef i As Integer)\n i += 1\nEnd Sub\n</code></pre>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/8bkbyhtx.aspx#sectionToggle1\" rel=\"nofollow noreferrer\">Argument Not Being Modified by Procedure Call - Underlying Variable</a></p>\n"
},
{
"answer_id": 2969343,
"author": "swight",
"author_id": 357868,
"author_profile": "https://Stackoverflow.com/users/357868",
"pm_score": -1,
"selected": false,
"text": "<p><strong>The Me Keyword</strong></p>\n\n<p>The \"Me\" Keyword is unique in VB.Net. I know it is rather common but there is a difference between \"Me\" and the C# equivalent \"this\". The difference is \"this\" is read only and \"Me\" is not. This is valuable in constructors where you have an instance of a variable you want the variable being constructed to equal already as you can just set \"Me = TheVariable\" as opposed to C# where you would have to copy each field of the variable manually(which can be horrible if there are many fields and error prone). The C# workaround would be to do the assignment outside the constructor. Which means you now if the object is self-constructing to a complete object you now need another function. </p>\n"
},
{
"answer_id": 3934688,
"author": "David T. Macknet",
"author_id": 6850,
"author_profile": "https://Stackoverflow.com/users/6850",
"pm_score": 0,
"selected": false,
"text": "<p>Attributes for methods! For example, a property which shouldn't be available during design time can be 1) hidden from the properties window, 2) not serialized (particularly annoying for user controls, or for controls which are loaded from a database):</p>\n\n<pre><code><System.ComponentModel.Browsable(False), _\nSystem.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden), _\nSystem.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always), _\nSystem.ComponentModel.Category(\"Data\")> _\nPublic Property AUX_ID() As String\n <System.Diagnostics.DebuggerStepThrough()> _\n Get\n Return mAUX_ID\n End Get\n <System.Diagnostics.DebuggerStepThrough()> _\n Set(ByVal value As String)\n mAUX_ID = value\n End Set\nEnd Property\n</code></pre>\n\n<p>Putting in the <code>DebuggerStepThrough()</code> is also <strong>very helpful</strong> if you do any amount of debugging (note that you can still put a break-point within the function or whatever, but that you can't single-step through that function).</p>\n\n<p>Also, the ability to put things in categories (e.g., \"Data\") means that, if you <em>do</em> want the property to show up in the properties tool-window, that particular property will show up in that category.</p>\n"
},
{
"answer_id": 3935361,
"author": "David T. Macknet",
"author_id": 6850,
"author_profile": "https://Stackoverflow.com/users/6850",
"pm_score": 2,
"selected": false,
"text": "<p>Nullable Dates! This is particularly useful in cases where you have data going in / coming out of a database (in this case, MSSQL Server). I have two procedures to give me a SmallDateTime parameter, populated with a value. One of them takes a plain old date and tests to see if there's any value in it, assigning a default date. The other version accepts a <code>Nullable(Of Date)</code> so that I can leave the date valueless, accepting whatever the default was from the stored procedure</p>\n\n<pre><code><System.Diagnostics.DebuggerStepThrough> _\nProtected Function GP(ByVal strName As String, ByVal dtValue As Date) As SqlParameter\n Dim aParm As SqlParameter = New SqlParameter\n Dim unDate As Date\n With aParm\n .ParameterName = strName\n .Direction = ParameterDirection.Input\n .SqlDbType = SqlDbType.SmallDateTime\n If unDate = dtValue Then 'Unassigned variable\n .Value = \"1/1/1900 12:00:00 AM\" 'give it a default which is accepted by smalldatetime\n Else\n .Value = CDate(dtValue.ToShortDateString)\n End If\n End With\n Return aParm\nEnd Function\n<System.Diagnostics.DebuggerStepThrough()> _\nProtected Function GP(ByVal strName As String, ByVal dtValue As Nullable(Of Date)) As SqlParameter\n Dim aParm As SqlParameter = New SqlParameter\n Dim unDate As Date\n With aParm\n .ParameterName = strName\n .Direction = ParameterDirection.Input\n .SqlDbType = SqlDbType.SmallDateTime\n If dtValue.HasValue = False Then\n '// it's nullable, so has no value\n ElseIf unDate = dtValue.Value Then 'Unassigned variable\n '// still, it's nullable for a reason, folks!\n Else\n .Value = CDate(dtValue.Value.ToShortDateString)\n End If\n End With\n Return aParm\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 4105681,
"author": "Parsa",
"author_id": 60996,
"author_profile": "https://Stackoverflow.com/users/60996",
"pm_score": 3,
"selected": false,
"text": "<p>Unlike <code>break</code> in C languages in VB you can <code>Exit</code> or <code>Continue</code> the block you want to:</p>\n\n<pre><code>For i As Integer = 0 To 100\n While True\n Exit While\n Select Case i\n Case 1\n Exit Select\n Case 2\n Exit For\n Case 3\n Exit While\n Case Else\n Exit Sub\n End Select\n Continue For\n End While\nNext\n</code></pre>\n"
},
{
"answer_id": 5508514,
"author": "PdotWang",
"author_id": 672995,
"author_profile": "https://Stackoverflow.com/users/672995",
"pm_score": 1,
"selected": false,
"text": "<p>Documentation of code</p>\n\n<pre><code>''' <summary>\n''' \n''' </summary>\n''' <remarks></remarks>\nSub use_3Apostrophe()\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 5942089,
"author": "Hedi Guizani",
"author_id": 630625,
"author_profile": "https://Stackoverflow.com/users/630625",
"pm_score": 0,
"selected": false,
"text": "<p>Optional arguments again !</p>\n\n<pre><code>Function DoSmtg(Optional a As string, b As Integer, c As String)\n 'DoSmtg\nEnd \n\n' Call\nDoSmtg(,,\"c argument\")\n\nDoSmtg(,\"b argument\")\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12842/"
]
| I have learned quite a bit browsing through [Hidden Features
of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c) and was surprised when I couldn't find something
similar for VB.NET.
So what are some of its hidden or lesser known features? | The `Exception When` clause is largely unknown.
Consider this:
```
Public Sub Login(host as string, user as String, password as string, _
Optional bRetry as Boolean = False)
Try
ssh.Connect(host, user, password)
Catch ex as TimeoutException When Not bRetry
''//Try again, but only once.
Login(host, user, password, True)
Catch ex as TimeoutException
''//Log exception
End Try
End Sub
``` |
102,093 | <p>I wrote a small <code>PHP</code> application several months ago that uses the <code>WordPress XMLRPC library</code> to synchronize two separate WordPress blogs. I have a general "RPCRequest" function that packages the request, sends it, and returns the server response, and I have several more specific functions that customize the type of request that is sent.</p>
<p>In this particular case, I am calling "getPostIDs" to retrieve the number of posts on the remote server and their respective postids. Here is the code:</p>
<pre><code>$rpc = new WordRPC('http://mywordpressurl.com/xmlrpc.php', 'username', 'password');
$rpc->getPostIDs();
</code></pre>
<p>I'm receiving the following error message:</p>
<pre><code>expat reports error code 5
description: Invalid document end
line: 1
column: 1
byte index: 0
total bytes: 0
data beginning 0 before byte index:
</code></pre>
<p>Kind of a cliffhanger ending, which is also strange. But since the error message isn't formatted in XML, my intuition is that it's the local XMLRPC library that is generating the error, not the remote server.</p>
<p>Even stranger, if I change the "getPostIDs()" call to "getPostIDs(1)" or any other integer, it works just fine.</p>
<p>Here is the code for the WordRPC class:</p>
<pre><code>public function __construct($url, $user, $pass) {
$this->url = $url;
$this->username = $user;
$this->password = $pass;
$id = $this->RPCRequest("blogger.getUserInfo",
array("null", $this->username, $this->password));
$this->blogID = $id['userid'];
}
public function RPCRequest($method, $params) {
$request = xmlrpc_encode_request($method, $params);
$context = stream_context_create(array('http' => array(
'method' => "POST",
'header' => "Content-Type: text/xml",
'content' => $request
)));
$file = file_get_contents($this->url, false, $context);
return xmlrpc_decode($file);
}
public function getPostIDs($num_posts = 0) {
return $this->RPCRequest("mt.getRecentPostTitles",
array($this->blogID, $this->username,
$this->password, $num_posts));
}
</code></pre>
<p>As I mentioned, it works fine if "getPostIDs" is given a positive integer argument. Furthermore, this used to work perfectly well as is; the default parameter of 0 simply indicates to the RPC server that it should retrieve <em>all</em> posts, not just the most recent <code>$num_posts</code> posts. Only recently has this error started showing up.</p>
<p>I've tried googling the error without much luck. My question, then, is <strong>what exactly does "expat reports error code 5" mean, and who is generating the error?</strong> Any details/suggestions/insights beyond that are welcome, too!</p>
| [
{
"answer_id": 104047,
"author": "Novaktually",
"author_id": 13243,
"author_profile": "https://Stackoverflow.com/users/13243",
"pm_score": 0,
"selected": false,
"text": "<p>Expat is the XML parser in PHP. Error code 5 is one of many expat error constants, in this case: <code>XML_ERROR_UNCLOSED_TOKEN</code>. Sounds to me like there's an error in the result returned from the RPC call. You might want to do some error checking in RPCRequest after <code>file_get_contents</code> and before <code>xmlrpc_decode</code>.</p>\n"
},
{
"answer_id": 123182,
"author": "Magsol",
"author_id": 13604,
"author_profile": "https://Stackoverflow.com/users/13604",
"pm_score": 3,
"selected": true,
"text": "<p>@Novak: Thanks for your suggestion. The problem turned out to be a memory issue; by retrieving all the posts from the remote location, the response exceeded the amount of memory PHP was allowed to utilize, hence the unclosed token error.</p>\n\n<p>The problem with the cryptic and incomplete error message was due to an outdated version of the XML-RPC library being used. Once I'd upgraded the version of WordPress, it provided me with the complete error output, including the memory error.</p>\n"
},
{
"answer_id": 338700,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>i fixed this error installing php-xmlrpc module on apache</p>\n\n<p>php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13604/"
]
| I wrote a small `PHP` application several months ago that uses the `WordPress XMLRPC library` to synchronize two separate WordPress blogs. I have a general "RPCRequest" function that packages the request, sends it, and returns the server response, and I have several more specific functions that customize the type of request that is sent.
In this particular case, I am calling "getPostIDs" to retrieve the number of posts on the remote server and their respective postids. Here is the code:
```
$rpc = new WordRPC('http://mywordpressurl.com/xmlrpc.php', 'username', 'password');
$rpc->getPostIDs();
```
I'm receiving the following error message:
```
expat reports error code 5
description: Invalid document end
line: 1
column: 1
byte index: 0
total bytes: 0
data beginning 0 before byte index:
```
Kind of a cliffhanger ending, which is also strange. But since the error message isn't formatted in XML, my intuition is that it's the local XMLRPC library that is generating the error, not the remote server.
Even stranger, if I change the "getPostIDs()" call to "getPostIDs(1)" or any other integer, it works just fine.
Here is the code for the WordRPC class:
```
public function __construct($url, $user, $pass) {
$this->url = $url;
$this->username = $user;
$this->password = $pass;
$id = $this->RPCRequest("blogger.getUserInfo",
array("null", $this->username, $this->password));
$this->blogID = $id['userid'];
}
public function RPCRequest($method, $params) {
$request = xmlrpc_encode_request($method, $params);
$context = stream_context_create(array('http' => array(
'method' => "POST",
'header' => "Content-Type: text/xml",
'content' => $request
)));
$file = file_get_contents($this->url, false, $context);
return xmlrpc_decode($file);
}
public function getPostIDs($num_posts = 0) {
return $this->RPCRequest("mt.getRecentPostTitles",
array($this->blogID, $this->username,
$this->password, $num_posts));
}
```
As I mentioned, it works fine if "getPostIDs" is given a positive integer argument. Furthermore, this used to work perfectly well as is; the default parameter of 0 simply indicates to the RPC server that it should retrieve *all* posts, not just the most recent `$num_posts` posts. Only recently has this error started showing up.
I've tried googling the error without much luck. My question, then, is **what exactly does "expat reports error code 5" mean, and who is generating the error?** Any details/suggestions/insights beyond that are welcome, too! | @Novak: Thanks for your suggestion. The problem turned out to be a memory issue; by retrieving all the posts from the remote location, the response exceeded the amount of memory PHP was allowed to utilize, hence the unclosed token error.
The problem with the cryptic and incomplete error message was due to an outdated version of the XML-RPC library being used. Once I'd upgraded the version of WordPress, it provided me with the complete error output, including the memory error. |
102,171 | <p>I'm looking for a method that computes the line number of a given text position in a JTextPane with wrapping enabled.</p>
<p>Example:</p>
<blockquote>
<p>This a very very very very very very very very very very very very very very very very very very very very very very long line.<br>
This is another very very very very very very very very very very very very very very very very very very very very very very long line.<strong>|</strong></p>
</blockquote>
<p>The cursor is on line number four, not two.</p>
<p>Can someone provide me with the implementation of the method:</p>
<pre><code>int getLineNumber(JTextPane pane, int pos)
{
return ???
}
</code></pre>
| [
{
"answer_id": 102737,
"author": "Richard",
"author_id": 16475,
"author_profile": "https://Stackoverflow.com/users/16475",
"pm_score": 4,
"selected": true,
"text": "<p>Try this</p>\n\n<pre><code> /**\n * Return an int containing the wrapped line index at the given position\n * @param component JTextPane\n * @param int pos\n * @return int\n */\n public int getLineNumber(JTextPane component, int pos) \n {\n int posLine;\n int y = 0;\n\n try\n {\n Rectangle caretCoords = component.modelToView(pos);\n y = (int) caretCoords.getY();\n }\n catch (BadLocationException ex)\n {\n }\n\n int lineHeight = component.getFontMetrics(component.getFont()).getHeight();\n posLine = (y / lineHeight) + 1;\n return posLine;\n }\n</code></pre>\n"
},
{
"answer_id": 4063877,
"author": "StanislavL",
"author_id": 301607,
"author_profile": "https://Stackoverflow.com/users/301607",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://java-sl.com/tip_row_column.html\" rel=\"noreferrer\">http://java-sl.com/tip_row_column.html</a>\nAn alternative which works with text fragments formatted with different styles</p>\n"
},
{
"answer_id": 41419359,
"author": "Morgan",
"author_id": 6389372,
"author_profile": "https://Stackoverflow.com/users/6389372",
"pm_score": 1,
"selected": false,
"text": "<p>you could try this:</p>\n\n<pre><code>public int getLineNumberAt(JTextPane pane, int pos) {\n return pane.getDocument().getDefaultRootElement().getElementIndex(pos);\n}\n</code></pre>\n\n<p>Keep in mind that line numbers always start at 0.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8330/"
]
| I'm looking for a method that computes the line number of a given text position in a JTextPane with wrapping enabled.
Example:
>
> This a very very very very very very very very very very very very very very very very very very very very very very long line.
>
> This is another very very very very very very very very very very very very very very very very very very very very very very long line.**|**
>
>
>
The cursor is on line number four, not two.
Can someone provide me with the implementation of the method:
```
int getLineNumber(JTextPane pane, int pos)
{
return ???
}
``` | Try this
```
/**
* Return an int containing the wrapped line index at the given position
* @param component JTextPane
* @param int pos
* @return int
*/
public int getLineNumber(JTextPane component, int pos)
{
int posLine;
int y = 0;
try
{
Rectangle caretCoords = component.modelToView(pos);
y = (int) caretCoords.getY();
}
catch (BadLocationException ex)
{
}
int lineHeight = component.getFontMetrics(component.getFont()).getHeight();
posLine = (y / lineHeight) + 1;
return posLine;
}
``` |
102,185 | <p>MXML lets you do some really quite powerful data binding such as:</p>
<pre><code><mx:Button id="myBtn" label="Buy an {itemName}" visible="{itemName!=null}"/>
</code></pre>
<p>I've found that the BindingUtils class can bind values to simple properties, but neither of the bindings above do this. Is it possible to do the same in AS3 code, or is Flex silently generating many lines of code from my MXML?
Can anyone duplicate the above in pure AS3, starting from:</p>
<pre><code>var myBtn:Button = new Button();
myBtn.id="myBtn";
???
</code></pre>
| [
{
"answer_id": 102851,
"author": "Marc Hughes",
"author_id": 6791,
"author_profile": "https://Stackoverflow.com/users/6791",
"pm_score": 0,
"selected": false,
"text": "<p>I believe flex generates a small anonymous function to deal with this.</p>\n\n<p>You could do similar using a ChangeWatcher. You could probably even make a new anonymous function in the changewatcher call.</p>\n"
},
{
"answer_id": 102924,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 2,
"selected": false,
"text": "<p>The way to do it is to use <code>bindSetter</code>. That is also how it is done behind the scenes when the MXML in your example is transformed to ActionScript before being compiled.</p>\n\n<pre><code>// assuming the itemName property is defined on this:\nBindingUtils.bindSetter(itemNameChanged, this, [\"itemName\"]);\n\n// ...\n\nprivate function itemNameChanged( newValue : String ) : void {\n myBtn.label = newValue;\n myBtn.visible = newValue != null;\n}\n</code></pre>\n\n<p>...except that the code generated by the MXML to ActionScript conversion is longer as it has to be more general. In this example it would likely have generated two functions, one for each binding expression.</p>\n"
},
{
"answer_id": 104360,
"author": "defmeta",
"author_id": 10875,
"author_profile": "https://Stackoverflow.com/users/10875",
"pm_score": 2,
"selected": false,
"text": "<p>You can also view the auto-generated code that flex makes when it compiles your mxml file, by adding a -keep argument to your compiler settings. You can find your settings by selecting your projects properties and looking at the \"Flex Compiler\" option, then under \"Additional compiler arguments:\" add \"-keep\" to what is already there.</p>\n\n<p>Once done Flex will create a \"generated\" directory in your source folder and inside you'll find all teh temporary as files that were used during compilation.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13220/"
]
| MXML lets you do some really quite powerful data binding such as:
```
<mx:Button id="myBtn" label="Buy an {itemName}" visible="{itemName!=null}"/>
```
I've found that the BindingUtils class can bind values to simple properties, but neither of the bindings above do this. Is it possible to do the same in AS3 code, or is Flex silently generating many lines of code from my MXML?
Can anyone duplicate the above in pure AS3, starting from:
```
var myBtn:Button = new Button();
myBtn.id="myBtn";
???
``` | The way to do it is to use `bindSetter`. That is also how it is done behind the scenes when the MXML in your example is transformed to ActionScript before being compiled.
```
// assuming the itemName property is defined on this:
BindingUtils.bindSetter(itemNameChanged, this, ["itemName"]);
// ...
private function itemNameChanged( newValue : String ) : void {
myBtn.label = newValue;
myBtn.visible = newValue != null;
}
```
...except that the code generated by the MXML to ActionScript conversion is longer as it has to be more general. In this example it would likely have generated two functions, one for each binding expression. |
102,198 | <p>Is there a way to "align" columns in a data repeater control? </p>
<p>I.E currently it looks like this:</p>
<pre><code>user1 - colA colB colC colD colE
user2 - colD colE
</code></pre>
<p>I want it to look like:</p>
<pre><code> user1
-colA
-colB
-colC
-colD
-colE
user1
-colD
-colE
</code></pre>
<p>I need to columns for each record to align properly when additional
records might not have data for a given column.</p>
<p>The requirements call for a repeater and not a grid control.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 102233,
"author": "Nick Craver",
"author_id": 13249,
"author_profile": "https://Stackoverflow.com/users/13249",
"pm_score": 2,
"selected": false,
"text": "<p>If you have access to how many columns are mising in the repeat, then just the following as the table tag. I you don't have access to this, can you post the source for your data repeater and what DataSource you're going against?</p>\n\n<pre><code><td colspan='<%# MissingCount(Contatiner.DataItem) %>'>\n</code></pre>\n"
},
{
"answer_id": 102367,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p></p>\n\n<pre><code> <tr class=\"RadGridItem\">\n <td width=\"100\">\n <asp:Label ID=\"lblFullName\" runat=\"server\" \n Text ='<%# DataBinder.Eval(Container.DataItem, \"FullName\") %>'\n ToolTip='<%# \"Current Grade: \" + DataBinder.Eval(Container.DataItem,\"CurrentGrade\") + \"%\" +\n \" Percent Complete: \" + DataBinder.Eval(Container.DataItem,\"PercentComplete\") + \"%\" %>' />\n </td>\n <asp:Repeater ID=\"rptAssessments\" runat=\"server\" DataSource='<%# DataBinder.Eval(Container.DataItem, \"EnrollmentAssessments\") %>'>\n <ItemTemplate>\n <td style=\"padding :0px 0px 0px 0px; width:20px; height: 20px;\">\n <asp:LinkButton ID=\"lnkEdit\" runat=\"server\"\n OnClick=\"AssessmentClick\" \n style=' <%# \"color:\" + this.GetAssessmentColor(Container.DataItem) %>'\n ToolTip='<%# DataBinder.Eval(Container.DataItem, \"AssessmentName\") + Environment.NewLine + \n DataBinder.Eval(Container.DataItem, \"EnrollmentAssessmentStateName\") + \"(\" + \n DataBinder.Eval(Container.DataItem, \"PercentGradeDisplay\") + \"%) \" + \n GetPointsPossible(Container.DataItem) + \" pts possible\" %>'\n CommandArgument='<%# DataBinder.Eval(Container.DataItem, \"EnrollmentAssessmentID\") %>'\n Text='<%# this.GetAssessmentDisplay(Container.DataItem) %>' />\n </td>\n </ItemTemplate>\n </asp:Repeater>\n </tr>\n</ItemTemplate>\n</code></pre>\n\n<p>This is the code. The number of columns will be dynamic based on the criteria used to generate the list.</p>\n\n<p>Thanks.</p>\n"
},
{
"answer_id": 104346,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 1,
"selected": false,
"text": "<p>I would suggest that instead of using <code><td></code> to define the columns, that you use CSS instead.</p>\n\n<pre><code>.collink {\n width: 20px; \n float: left; \n height: 20px;\n}\n</code></pre>\n\n<p>AND</p>\n\n<pre><code><td style=\"padding :0px 0px 0px 0px;\">\n <div class=\"collink\">\n <asp:LinkButton ID=\"lnkEdit\" runat=\"server\" ... />\n </div>\n</td>\n</code></pre>\n\n<p>This approach lets the content grow without actually affecting the table structure.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Is there a way to "align" columns in a data repeater control?
I.E currently it looks like this:
```
user1 - colA colB colC colD colE
user2 - colD colE
```
I want it to look like:
```
user1
-colA
-colB
-colC
-colD
-colE
user1
-colD
-colE
```
I need to columns for each record to align properly when additional
records might not have data for a given column.
The requirements call for a repeater and not a grid control.
Any ideas? | If you have access to how many columns are mising in the repeat, then just the following as the table tag. I you don't have access to this, can you post the source for your data repeater and what DataSource you're going against?
```
<td colspan='<%# MissingCount(Contatiner.DataItem) %>'>
``` |
102,213 | <p>I am getting ready to start a new asp.net web project, and I am going to LINQ-to-SQL. I have done a little bit of work getting my data layer setup using some info I found by <a href="http://mikehadlow.blogspot.com/" rel="nofollow noreferrer" title="Mike Hadlow">Mike Hadlow</a> that uses an Interface and generics to create a Repository for each table in the database. I thought this was an interesting approach at first. However, now I think it might make more sense to create a base Repository class and inherit from it to create a TableNameRepository class for the tables I need to access. </p>
<p>Which approach will be allow me to add functionality specific to a Table in a clean testable way? Here is my Repository implementation for reference.</p>
<pre><code>public class Repository<T> : IRepository<T> where T : class, new()
{
protected IDataConnection _dcnf;
public Repository()
{
_dcnf = new DataConnectionFactory() as IDataConnection;
}
// Constructor injection for dependency on DataContext
// to actually connect to a database
public Repository(IDataConnection dc)
{
_dcnf = dc;
}
/// <summary>
/// Return all instances of type T.
/// </summary>
/// <returns>IEnumerable<T></returns>
public virtual IEnumerable<T> GetAll()
{
return GetTable;
}
public virtual T GetById(int id)
{
var itemParam = Expression.Parameter(typeof(T), "item");
var whereExp = Expression.Lambda<Func<T, bool>>
(
Expression.Equal(
Expression.Property(itemParam, PrimaryKeyName),
Expression.Constant(id)
), new ParameterExpression[] { itemParam }
);
return _dcnf.Context.GetTable<T>().Where(whereExp).Single();
}
/// <summary>
/// Return all instances of type T that match the expression exp.
/// </summary>
/// <param name="exp"></param>
/// <returns>IEnumerable<T></returns>
public virtual IEnumerable<T> FindByExp(Func<T, bool> exp)
{
return GetTable.Where<T>(exp);
}
/// <summary>See IRepository.</summary>
/// <param name="exp"></param><returns></returns>
public virtual T Single(Func<T, bool> exp)
{
return GetTable.Single(exp);
}
/// <summary>See IRepository.</summary>
/// <param name="entity"></param>
public virtual void MarkForDeletion(T entity)
{
_dcnf.Context.GetTable<T>().DeleteOnSubmit(entity);
}
/// <summary>
/// Create a new instance of type T.
/// </summary>
/// <returns>T</returns>
public virtual T Create()
{
//T entity = Activator.CreateInstance<T>();
T entity = new T();
GetTable.InsertOnSubmit(entity);
return entity;
}
/// <summary>See IRepository.</summary>
public virtual void SaveAll()
{
_dcnf.SaveAll();
}
#region Properties
private string PrimaryKeyName
{
get { return TableMetadata.RowType.IdentityMembers[0].Name; }
}
private System.Data.Linq.Table<T> GetTable
{
get { return _dcnf.Context.GetTable<T>(); }
}
private System.Data.Linq.Mapping.MetaTable TableMetadata
{
get { return _dcnf.Context.Mapping.GetTable(typeof(T)); }
}
private System.Data.Linq.Mapping.MetaType ClassMetadata
{
get { return _dcnf.Context.Mapping.GetMetaType(typeof(T)); }
}
#endregion
}
</code></pre>
| [
{
"answer_id": 103668,
"author": "Squirrel",
"author_id": 11835,
"author_profile": "https://Stackoverflow.com/users/11835",
"pm_score": 2,
"selected": true,
"text": "<p>I'd be tempted to suggest that whether you use concrete types or not shouldn't matter, as if your using dependency injection (castle?) to create the repositories (so you can wrap them with different caches etc) then your codebase will be none the wiser whichever way you've done it.</p>\n\n<p>Then just ask your DI for a repository. E.g. for castle:</p>\n\n<pre><code>public class Home {\n public static IRepository<T> For<T> {\n get {\n return Container.Resolve<IRepository<T>>();\n }\n }\n}\n</code></pre>\n\n<p>Personally, I'd not bottom out the types until you find a need to.</p>\n\n<p>I guess the other half of your question is whether you can easily provide an in memory implementation of IRepository for testing and caching purposes. For this I would watch out as linq-to-objects can be slow and you might find something like <a href=\"http://www.codeplex.com/i4o\" rel=\"nofollow noreferrer\">http://www.codeplex.com/i4o</a> useful.</p>\n"
},
{
"answer_id": 4933553,
"author": "Frederik Gheysels",
"author_id": 55774,
"author_profile": "https://Stackoverflow.com/users/55774",
"pm_score": 3,
"selected": false,
"text": "<p>You should not create a repository for every table.<br>\nInstead, you should create a repository for every 'entity root' (or aggregate root) that exists in your domain model. You can learn more about the pattern and see a working example here: </p>\n\n<p><a href=\"http://deviq.com/repository-pattern/\" rel=\"nofollow\">http://deviq.com/repository-pattern/</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203/"
]
| I am getting ready to start a new asp.net web project, and I am going to LINQ-to-SQL. I have done a little bit of work getting my data layer setup using some info I found by [Mike Hadlow](http://mikehadlow.blogspot.com/ "Mike Hadlow") that uses an Interface and generics to create a Repository for each table in the database. I thought this was an interesting approach at first. However, now I think it might make more sense to create a base Repository class and inherit from it to create a TableNameRepository class for the tables I need to access.
Which approach will be allow me to add functionality specific to a Table in a clean testable way? Here is my Repository implementation for reference.
```
public class Repository<T> : IRepository<T> where T : class, new()
{
protected IDataConnection _dcnf;
public Repository()
{
_dcnf = new DataConnectionFactory() as IDataConnection;
}
// Constructor injection for dependency on DataContext
// to actually connect to a database
public Repository(IDataConnection dc)
{
_dcnf = dc;
}
/// <summary>
/// Return all instances of type T.
/// </summary>
/// <returns>IEnumerable<T></returns>
public virtual IEnumerable<T> GetAll()
{
return GetTable;
}
public virtual T GetById(int id)
{
var itemParam = Expression.Parameter(typeof(T), "item");
var whereExp = Expression.Lambda<Func<T, bool>>
(
Expression.Equal(
Expression.Property(itemParam, PrimaryKeyName),
Expression.Constant(id)
), new ParameterExpression[] { itemParam }
);
return _dcnf.Context.GetTable<T>().Where(whereExp).Single();
}
/// <summary>
/// Return all instances of type T that match the expression exp.
/// </summary>
/// <param name="exp"></param>
/// <returns>IEnumerable<T></returns>
public virtual IEnumerable<T> FindByExp(Func<T, bool> exp)
{
return GetTable.Where<T>(exp);
}
/// <summary>See IRepository.</summary>
/// <param name="exp"></param><returns></returns>
public virtual T Single(Func<T, bool> exp)
{
return GetTable.Single(exp);
}
/// <summary>See IRepository.</summary>
/// <param name="entity"></param>
public virtual void MarkForDeletion(T entity)
{
_dcnf.Context.GetTable<T>().DeleteOnSubmit(entity);
}
/// <summary>
/// Create a new instance of type T.
/// </summary>
/// <returns>T</returns>
public virtual T Create()
{
//T entity = Activator.CreateInstance<T>();
T entity = new T();
GetTable.InsertOnSubmit(entity);
return entity;
}
/// <summary>See IRepository.</summary>
public virtual void SaveAll()
{
_dcnf.SaveAll();
}
#region Properties
private string PrimaryKeyName
{
get { return TableMetadata.RowType.IdentityMembers[0].Name; }
}
private System.Data.Linq.Table<T> GetTable
{
get { return _dcnf.Context.GetTable<T>(); }
}
private System.Data.Linq.Mapping.MetaTable TableMetadata
{
get { return _dcnf.Context.Mapping.GetTable(typeof(T)); }
}
private System.Data.Linq.Mapping.MetaType ClassMetadata
{
get { return _dcnf.Context.Mapping.GetMetaType(typeof(T)); }
}
#endregion
}
``` | I'd be tempted to suggest that whether you use concrete types or not shouldn't matter, as if your using dependency injection (castle?) to create the repositories (so you can wrap them with different caches etc) then your codebase will be none the wiser whichever way you've done it.
Then just ask your DI for a repository. E.g. for castle:
```
public class Home {
public static IRepository<T> For<T> {
get {
return Container.Resolve<IRepository<T>>();
}
}
}
```
Personally, I'd not bottom out the types until you find a need to.
I guess the other half of your question is whether you can easily provide an in memory implementation of IRepository for testing and caching purposes. For this I would watch out as linq-to-objects can be slow and you might find something like <http://www.codeplex.com/i4o> useful. |
102,215 | <p>What is the best way to add "Expires" in http header for static content? eg. images, css, js</p>
<p>The web server is IIS 6.0; the language is classical ASP</p>
| [
{
"answer_id": 102302,
"author": "Aaron",
"author_id": 7659,
"author_profile": "https://Stackoverflow.com/users/7659",
"pm_score": -1,
"selected": false,
"text": "<p>I don't know if this is what you are looking for, but it does keep my pages from being cached.</p>\n\n<pre><code><META HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">\n<META HTTP-EQUIV=\"Cache-Control\" CONTENT=\"no-store\">\n<META HTTP-EQUIV=\"Cache-Control\" CONTENT=\"no-cache\">\n<META HTTP-EQUIV=\"Expires\" CONTENT=\"0\">\n<META HTTP-EQUIV=\"Cache-Control\" CONTENT=\"max-age=0\">\n</code></pre>\n\n<p>I got these from an article on line that I no longer have a reference for.</p>\n"
},
{
"answer_id": 102331,
"author": "Nick Craver",
"author_id": 13249,
"author_profile": "https://Stackoverflow.com/users/13249",
"pm_score": 2,
"selected": false,
"text": "<p>I think this is what you're after, It's Content Expiration under HTTP Headers in IIS Manager. I use the pattern of sticking static content under a folder like ~/Resources and setting the expiration on that particular folder to have a much longer life than the rest of the application.</p>\n\n<p>Here's a link to the full article: <strong><a href=\"http://technet.microsoft.com/en-us/library/cc732442.aspx\" rel=\"nofollow noreferrer\">IIS 6.0 F1: Web Site Properties - HTTP Headers Tab</a></strong></p>\n"
},
{
"answer_id": 104073,
"author": "Christopher G. Lewis",
"author_id": 13532,
"author_profile": "https://Stackoverflow.com/users/13532",
"pm_score": 4,
"selected": true,
"text": "<p>You could try something like this:</p>\n\n<pre><code>@ECHO OFF \nREM ---------------------------------------------------------------------------\nREM Caching - sets the caching on static files in a web site\nREM syntax \nREM Caching.CMD 1 d:\\sites\\MySite\\WWWRoot\\*.CSS\nREM \nREM %1 is the WebSite ID\nREM %2 is the path & Wildcard - for example, d:\\sites\\MySite\\WWWRoot\\*.CSS\nREM _adsutil is the path to ADSUtil.VBS\nREM ---------------------------------------------------------------------------\n\nSETLOCAL\n\nSET _adsutil=D:\\Apps\\Scripts\\adsutil.vbs\n\nFOR %%i IN (%2) DO (\n ECHO Setting Caching on %%~ni%%~xi\n CSCRIPT %_adsutil% CREATE W3SVC/%1/root/%%~ni%%~xi \"IIsWebFile\"\n CSCRIPT %_adsutil% SET W3SVC/%1/root/%%~ni%%~xi/HttpExpires \"D, 0x69780\"\n ECHO.\n)\n</code></pre>\n\n<p>Which sets the caching value for each CSS file in a web root to 5 days, then run it like this:</p>\n\n<pre><code>Caching.CMD 1 \\site\\wwwroot\\*.css\nCaching.CMD 1 \\site\\wwwroot\\*.js\nCaching.CMD 1 \\site\\wwwroot\\*.html\nCaching.CMD 1 \\site\\wwwroot\\*.htm\nCaching.CMD 1 \\site\\wwwroot\\*.gif\nCaching.CMD 1 \\site\\wwwroot\\*.jpg\n</code></pre>\n\n<p>Kind of painful, but workable.</p>\n\n<p>BTW - to get the value for HttpExpires, set the value in the GUI, then run </p>\n\n<pre><code>AdsUtil.vbs ENUM W3SVC/1/root/File.txt\n</code></pre>\n\n<p>to get the actual value you need</p>\n"
},
{
"answer_id": 482019,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>in IIS admin you can set it for each file type or you can (for dynamic ones like aspx) do it in the code. After you have it setup you need to check the headers that are output with a tool like Mozilla firefox + live headers plugin - or you can use a web based tool like <a href=\"http://www.httpviewer.net/\" rel=\"nofollow noreferrer\">http://www.httpviewer.net/</a></p>\n"
},
{
"answer_id": 702659,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Terrible solution, the first command to create with adsutil will fail with error -2147024713 (0x800700B7) since the files your trying to create already exists.</p>\n\n<p>Thanks.</p>\n"
},
{
"answer_id": 33717904,
"author": "Miss.Vy",
"author_id": 5234614,
"author_profile": "https://Stackoverflow.com/users/5234614",
"pm_score": 1,
"selected": false,
"text": "<p>For others coming from google: this will <strong>not work in iis6</strong> but works in 7 and above.</p>\n\n<p>In your web.config: </p>\n\n<pre><code><staticContent>\n <clientCache cacheControlMode=\"UseMaxAge\" cacheControlMaxAge=\"7.00:00:00\" />\n</staticContent>\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
]
| What is the best way to add "Expires" in http header for static content? eg. images, css, js
The web server is IIS 6.0; the language is classical ASP | You could try something like this:
```
@ECHO OFF
REM ---------------------------------------------------------------------------
REM Caching - sets the caching on static files in a web site
REM syntax
REM Caching.CMD 1 d:\sites\MySite\WWWRoot\*.CSS
REM
REM %1 is the WebSite ID
REM %2 is the path & Wildcard - for example, d:\sites\MySite\WWWRoot\*.CSS
REM _adsutil is the path to ADSUtil.VBS
REM ---------------------------------------------------------------------------
SETLOCAL
SET _adsutil=D:\Apps\Scripts\adsutil.vbs
FOR %%i IN (%2) DO (
ECHO Setting Caching on %%~ni%%~xi
CSCRIPT %_adsutil% CREATE W3SVC/%1/root/%%~ni%%~xi "IIsWebFile"
CSCRIPT %_adsutil% SET W3SVC/%1/root/%%~ni%%~xi/HttpExpires "D, 0x69780"
ECHO.
)
```
Which sets the caching value for each CSS file in a web root to 5 days, then run it like this:
```
Caching.CMD 1 \site\wwwroot\*.css
Caching.CMD 1 \site\wwwroot\*.js
Caching.CMD 1 \site\wwwroot\*.html
Caching.CMD 1 \site\wwwroot\*.htm
Caching.CMD 1 \site\wwwroot\*.gif
Caching.CMD 1 \site\wwwroot\*.jpg
```
Kind of painful, but workable.
BTW - to get the value for HttpExpires, set the value in the GUI, then run
```
AdsUtil.vbs ENUM W3SVC/1/root/File.txt
```
to get the actual value you need |
102,261 | <p>First off, I'm working on an app that's written such that some of your typical debugging tools can't be used (or at least I can't figure out how :). </p>
<p>JavaScript, html, etc are all "cooked" and encoded (I think; I'm a little fuzzy on how the process works) before being deployed, so I can't attach VS 2005 to ie, and firebug lite doesn't work well. Also, the interface is in frames (yuck), so some other tools don't work as well.</p>
<p>Firebug works great in Firefox, which isn't having this problem (nor is Safari), so I'm hoping someone might spot something "obviously" wrong with the way my code will play with IE. There's more information that can be given about its quirkiness, but let's start with this.</p>
<p>Basically, I have a function that "collapses" tables into their headers by making normal table rows not visible. I have <code>"onclick='toggleDisplay("theTableElement", "theCollapseImageElement")'"</code> in the <code><tr></code> tags, and tables start off with "class='closed'". </p>
<p>Single clicks collapse and expand tables in FF & Safari, but IE tables require multiple clicks (a seemingly arbitrary number between 1 and 5) to expand. Sometimes after initially getting "opened", the tables will expand and collapse with a single click for a little while, only to eventually revert to requiring multiple clicks. I can tell from what little I can see in Visual Studio that the function is actually being reached each time. Thanks in advance for any advice!</p>
<p>Here's the JS code:</p>
<pre><code>bURL_RM_RID="some image prefix";
CLOSED_TBL="closed";
OPEN_TBL="open";
CLOSED_IMG= bURL_RM_RID+'166';
OPENED_IMG= bURL_RM_RID+'167';
//collapses/expands tbl (a table) and swaps out the image tblimg
function toggleDisplay(tbl, tblimg) {
var rowVisible;
var tblclass = tbl.getAttribute("class");
var tblRows = tbl.rows;
var img = tblimg;
//Are we expanding or collapsing the table?
if (tblclass == CLOSED_TBL) rowVisible = false;
else rowVisible = true;
for (i = 0; i < tblRows.length; i++) {
if (tblRows[i].className != "headerRow") {
tblRows[i].style.display = (rowVisible) ? "none" : "";
}
}
//set the collapse images to the correct state and swap the class name
rowVisible = !rowVisible;
if (rowVisible) {
img.setAttribute("src", CLOSED_IMG);
tbl.setAttribute("class",OPEN_TBL);
}
else {
img.setAttribute("src", OPENED_IMG);
tbl.setAttribute("class",CLOSED_TBL);
}
}
</code></pre>
<p></p>
| [
{
"answer_id": 102295,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried changing this line</p>\n\n<pre><code>tblRows[i].style.display = (rowVisible) ? \"none\" : \"\";\n</code></pre>\n\n<p>to something like</p>\n\n<pre><code>tblRows[i].style.display = (rowVisible) ? \"none\" : \"table-row\";\n</code></pre>\n\n<p>or</p>\n\n<pre><code>tblRows[i].style.display = (rowVisible) ? \"none\" : \"auto\";\n</code></pre>\n"
},
{
"answer_id": 102335,
"author": "Lark",
"author_id": 8804,
"author_profile": "https://Stackoverflow.com/users/8804",
"pm_score": 0,
"selected": false,
"text": "<p>You might want to place your onclick call on the actual <code><tr></code> tag rather than the individual <code><th></code> tags. This way you have less JS in your HTML which will make it more maintainable.</p>\n"
},
{
"answer_id": 102387,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 0,
"selected": false,
"text": "<p>If you enable script debugging in IE (Tools->Internet Options->Advanced) and put a 'debugger;' statement in the code, IE will automatically bring up Visual Studio when it hits the debugger statement.</p>\n"
},
{
"answer_id": 102456,
"author": "JW.",
"author_id": 4321,
"author_profile": "https://Stackoverflow.com/users/4321",
"pm_score": 0,
"selected": false,
"text": "<p>I have had issues with this in IE. If I remember correctly, I needed to put an initial value for the \"display\" style, directly on the HTML as it was initially generated. For example:</p>\n\n<pre><code><table>\n <tr style=\"display:none\"> ... </tr>\n <tr style=\"display:\"> ... </tr>\n</table>\n</code></pre>\n\n<p>Then I could use JavaScript to change the style, the way you're doing it.</p>\n"
},
{
"answer_id": 102561,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 3,
"selected": true,
"text": "<p>setAttribute is unreliable in IE. It treats attribute access and object property access as the same thing, so because the DOM property for the 'class' attribute is called 'className', you would have to use that instead on IE.</p>\n\n<p>This bug is fixed in the new IE8 beta, but it is easier simply to use the DOM Level 1 HTML property directly:</p>\n\n<pre><code>img.src= CLOSED_IMAGE;\ntbl.className= OPEN_TBL;\n</code></pre>\n\n<p>You can also do the table folding in the stylesheet, which will be faster and will save you the bother of having to loop over the table rows in script:</p>\n\n<pre><code>table.closed tr { display: none; }\n</code></pre>\n"
},
{
"answer_id": 103126,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I always use style.display = \"block\" and style.display = \"none\"</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18860/"
]
| First off, I'm working on an app that's written such that some of your typical debugging tools can't be used (or at least I can't figure out how :).
JavaScript, html, etc are all "cooked" and encoded (I think; I'm a little fuzzy on how the process works) before being deployed, so I can't attach VS 2005 to ie, and firebug lite doesn't work well. Also, the interface is in frames (yuck), so some other tools don't work as well.
Firebug works great in Firefox, which isn't having this problem (nor is Safari), so I'm hoping someone might spot something "obviously" wrong with the way my code will play with IE. There's more information that can be given about its quirkiness, but let's start with this.
Basically, I have a function that "collapses" tables into their headers by making normal table rows not visible. I have `"onclick='toggleDisplay("theTableElement", "theCollapseImageElement")'"` in the `<tr>` tags, and tables start off with "class='closed'".
Single clicks collapse and expand tables in FF & Safari, but IE tables require multiple clicks (a seemingly arbitrary number between 1 and 5) to expand. Sometimes after initially getting "opened", the tables will expand and collapse with a single click for a little while, only to eventually revert to requiring multiple clicks. I can tell from what little I can see in Visual Studio that the function is actually being reached each time. Thanks in advance for any advice!
Here's the JS code:
```
bURL_RM_RID="some image prefix";
CLOSED_TBL="closed";
OPEN_TBL="open";
CLOSED_IMG= bURL_RM_RID+'166';
OPENED_IMG= bURL_RM_RID+'167';
//collapses/expands tbl (a table) and swaps out the image tblimg
function toggleDisplay(tbl, tblimg) {
var rowVisible;
var tblclass = tbl.getAttribute("class");
var tblRows = tbl.rows;
var img = tblimg;
//Are we expanding or collapsing the table?
if (tblclass == CLOSED_TBL) rowVisible = false;
else rowVisible = true;
for (i = 0; i < tblRows.length; i++) {
if (tblRows[i].className != "headerRow") {
tblRows[i].style.display = (rowVisible) ? "none" : "";
}
}
//set the collapse images to the correct state and swap the class name
rowVisible = !rowVisible;
if (rowVisible) {
img.setAttribute("src", CLOSED_IMG);
tbl.setAttribute("class",OPEN_TBL);
}
else {
img.setAttribute("src", OPENED_IMG);
tbl.setAttribute("class",CLOSED_TBL);
}
}
```
| setAttribute is unreliable in IE. It treats attribute access and object property access as the same thing, so because the DOM property for the 'class' attribute is called 'className', you would have to use that instead on IE.
This bug is fixed in the new IE8 beta, but it is easier simply to use the DOM Level 1 HTML property directly:
```
img.src= CLOSED_IMAGE;
tbl.className= OPEN_TBL;
```
You can also do the table folding in the stylesheet, which will be faster and will save you the bother of having to loop over the table rows in script:
```
table.closed tr { display: none; }
``` |
102,271 | <p>More information from <a href="http://en.wikipedia.org/wiki/Perl_6#Junctions" rel="noreferrer">the Perl 6 Wikipedia entry</a></p>
<p><strong>Junctions</strong></p>
<p>Perl 6 introduces the concept of junctions: values that are composites of other values.[24] In the earliest days of Perl 6's design, these were called "superpositions", by analogy to the concept in quantum physics of quantum superpositions — waveforms that can simultaneously occupy several states until observation "collapses" them. A Perl 5 module released in 2000 by Damian Conway called Quantum::Superpositions[25] provided an initial proof of concept. While at first, such superpositional values seemed like merely a programmatic curiosity, over time their utility and intuitiveness became widely recognized, and junctions now occupy a central place in Perl 6's design.</p>
<p>In their simplest form, junctions are created by combining a set of values with junctive operators:</p>
<pre><code>my $any_even_digit = 0|2|4|6|8; # any(0, 2, 4, 6, 8)
my $all_odd_digits = 1&3&5&7&9; # all(1, 3, 5, 7, 9)
</code></pre>
<p>| indicates a value which is equal to either its left or right-hand arguments. & indicates a value which is equal to both its left and right-hand arguments. These values can be used in any code that would use a normal value. Operations performed on a junction act on all members of the junction equally, and combine according to the junctive operator. So, ("apple"|"banana") ~ "s" would yield "apples"|"bananas". In comparisons, junctions return a single true or false result for the comparison. "any" junctions return true if the comparison is true for any one of the elements of the junction. "all" junctions return true if the comparison is true for all of the elements of the junction.</p>
<p>Junctions can also be used to more richly augment the type system by introducing a style of generic programming that is constrained to junctions of types:</p>
<pre><code>sub get_tint ( RGB_Color|CMYK_Color $color, num $opacity) { ... }
sub store_record (Record&Storable $rec) { ... }
</code></pre>
| [
{
"answer_id": 117746,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 5,
"selected": true,
"text": "<p>How many days are in a given month?</p>\n\n<pre><code>given( $month ){\n when any(qw'1 3 5 7 8 10 12') {\n $day = 31\n }\n when any(qw'4 6 9 11') {\n $day = 30\n }\n when 2 {\n $day = 29\n }\n}\n</code></pre>\n"
},
{
"answer_id": 118244,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 3,
"selected": false,
"text": "<p>The most attractive feature of junctions is that you don't need to write a lot of code test for complex situations. You describe the situation with the junctions, then apply the test. You don't think about how you get the answer (for instance, using short circuit operators or if blocks) but what question you are asking.</p>\n"
},
{
"answer_id": 118441,
"author": "Eevee",
"author_id": 17875,
"author_profile": "https://Stackoverflow.com/users/17875",
"pm_score": 3,
"selected": false,
"text": "<p>Autothreading sounds cool, although I don't know what its current status is.</p>\n\n<pre><code>for all(@files) -> $file {\n do_something($file);\n}\n</code></pre>\n\n<p>Junctions have no order, so the VM is free to spawn a thread for every element in <code>@files</code> and process them all in parallel.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18446/"
]
| More information from [the Perl 6 Wikipedia entry](http://en.wikipedia.org/wiki/Perl_6#Junctions)
**Junctions**
Perl 6 introduces the concept of junctions: values that are composites of other values.[24] In the earliest days of Perl 6's design, these were called "superpositions", by analogy to the concept in quantum physics of quantum superpositions — waveforms that can simultaneously occupy several states until observation "collapses" them. A Perl 5 module released in 2000 by Damian Conway called Quantum::Superpositions[25] provided an initial proof of concept. While at first, such superpositional values seemed like merely a programmatic curiosity, over time their utility and intuitiveness became widely recognized, and junctions now occupy a central place in Perl 6's design.
In their simplest form, junctions are created by combining a set of values with junctive operators:
```
my $any_even_digit = 0|2|4|6|8; # any(0, 2, 4, 6, 8)
my $all_odd_digits = 1&3&5&7&9; # all(1, 3, 5, 7, 9)
```
| indicates a value which is equal to either its left or right-hand arguments. & indicates a value which is equal to both its left and right-hand arguments. These values can be used in any code that would use a normal value. Operations performed on a junction act on all members of the junction equally, and combine according to the junctive operator. So, ("apple"|"banana") ~ "s" would yield "apples"|"bananas". In comparisons, junctions return a single true or false result for the comparison. "any" junctions return true if the comparison is true for any one of the elements of the junction. "all" junctions return true if the comparison is true for all of the elements of the junction.
Junctions can also be used to more richly augment the type system by introducing a style of generic programming that is constrained to junctions of types:
```
sub get_tint ( RGB_Color|CMYK_Color $color, num $opacity) { ... }
sub store_record (Record&Storable $rec) { ... }
``` | How many days are in a given month?
```
given( $month ){
when any(qw'1 3 5 7 8 10 12') {
$day = 31
}
when any(qw'4 6 9 11') {
$day = 30
}
when 2 {
$day = 29
}
}
``` |
102,278 | <p>OK, so practically every database based application has to deal with "non-active" records. Either, soft-deletions or marking something as "to be ignored". I'm curious as to whether there are any radical alternatives thoughts on an `active' column (or a status column).</p>
<p>For example, if I had a list of people</p>
<pre><code>CREATE TABLE people (
id INTEGER PRIMARY KEY,
name VARCHAR(100),
active BOOLEAN,
...
);
</code></pre>
<p>That means to get a list of active people, you need to use</p>
<pre><code>SELECT * FROM people WHERE active=True;
</code></pre>
<p>Does anyone suggest that non active records would be moved off to a separate table and where appropiate a UNION is done to join the two?</p>
<p>Curiosity striking...</p>
<p><strong>EDIT:</strong> I should make clear, I'm coming at this from a purist perspective. I can see how data archiving might be necessary for large amounts of data, but that is not where I'm coming from. If you do a SELECT * FROM people it would make sense to me that those entries are in a sense "active"</p>
<p>Thanks</p>
| [
{
"answer_id": 102297,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 0,
"selected": false,
"text": "<p>We use active flags quite often. If your database is going to be very large, I could see the value in migrating inactive values to a separate table, though.</p>\n\n<p>You would then only require a union of the tables when someone wants to see all records, active or inactive.</p>\n"
},
{
"answer_id": 102300,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": false,
"text": "<p>Well, to ensure that you only draw active records in most situations, you could create views that only contain the active records. That way it's much easier to not leave out the active part.</p>\n"
},
{
"answer_id": 102304,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 1,
"selected": false,
"text": "<p>The active flag is sort of ugly, but it is simple and works well.</p>\n\n<p>You could move them to another table as you suggested. I'd suggest looking at the percentage of active / inactive records. If you have over 20 or 30 % inactive records, then you might consider moving them elsewhere. Otherwise, it's not a big deal.</p>\n"
},
{
"answer_id": 102308,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 0,
"selected": false,
"text": "<p>In most cases a binary field indicating deletion is sufficient. Often there is a clean up mechanism that will remove those deleted records after a certain amount of time, so you may wish to start the schema with a deleted timestamp.</p>\n"
},
{
"answer_id": 102314,
"author": "Mostlyharmless",
"author_id": 12881,
"author_profile": "https://Stackoverflow.com/users/12881",
"pm_score": 0,
"selected": false,
"text": "<p>Moving off to a separate table and bringing them back up takes time. Depending on how many records go offline and how often you need to bring them back, it might or might not be a good idea.</p>\n\n<p>If the mostly dont come back once they are buried, and are only used for summaries/reports/whatever, then it will make your main table smaller, queries simpler and probably faster.</p>\n"
},
{
"answer_id": 102329,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, we would. We currently have the \"active='T/F'\" column in many of our tables, mainly to show the 'latest' row. When a new row is inserted, the previous T row is marked F to keep it for audit purposes.</p>\n\n<p>Now, we're moving to a 2-table approach, when a new row is inserted, the previous row is moved to an history table. This give us better performance for the majority of cases - looking at the current data.</p>\n\n<p>The cost is slightly more than the old method, previously you had to update and insert, now you have to insert and update (ie instead of inserting a new T row, you modify the existing row with all the new data), so the cost is just that of passing in a whole row of data instead of passing in just the changes. That's hardly going to make any effect.</p>\n\n<p>The performance benefit is that your main table's index is significantly smaller, and you can optimise your tablespaces better (they won't grow quite so much!) </p>\n"
},
{
"answer_id": 102333,
"author": "Mike McAllister",
"author_id": 16247,
"author_profile": "https://Stackoverflow.com/users/16247",
"pm_score": 6,
"selected": true,
"text": "<p>You partition the table on the active flag, so that active records are in one partition, and inactive records are in the other partition. Then you create an active view for each table which automatically has the active filter on it. The database query engine automatically restricts the query to the partition that has the active records in it, which is much faster than even using an index on that flag.</p>\n\n<p>Here is an example of how to create a partitioned table in Oracle. Oracle doesn't have boolean column types, so I've modified your table structure for Oracle purposes.</p>\n\n<pre><code>CREATE TABLE people\n(\n id NUMBER(10),\n name VARCHAR2(100),\n active NUMBER(1)\n)\nPARTITION BY LIST(active)\n(\n PARTITION active_records VALUES (0)\n PARTITION inactive_records VALUES (1)\n);\n</code></pre>\n\n<p>If you wanted to you could put each partition in different tablespaces. You can also partition your indexes as well.</p>\n\n<p>Incidentally, this seems a repeat of <a href=\"https://stackoverflow.com/questions/68323/what-is-the-best-way-to-implement-soft-deletion\">this</a> question, as a newbie I need to ask, what's the procedure on dealing with unintended duplicates?</p>\n\n<p><strong>Edit:</strong> As requested in comments, provided an example for creating a partitioned table in Oracle</p>\n"
},
{
"answer_id": 102349,
"author": "Nathen Silver",
"author_id": 6136,
"author_profile": "https://Stackoverflow.com/users/6136",
"pm_score": 0,
"selected": false,
"text": "<p>We use both methods for dealing with inactive records. The method we use is dependent upon the situation. For records that are essentially lookup values, we use the Active bit field. This allows us to deactivate entries so they wont be used, but also allows us to maintain data integrity with relations.</p>\n\n<p>We use the \"move to separation table\" method where the data is no longer needed and the data is not part of a relation.</p>\n"
},
{
"answer_id": 102368,
"author": "Jasha87",
"author_id": 18874,
"author_profile": "https://Stackoverflow.com/users/18874",
"pm_score": 0,
"selected": false,
"text": "<p>The situation really dictates the solution, methinks:</p>\n\n<p>If the table contains users, then several \"flag\" fields could be used. One for Deleted, Disabled etc. Or if space is an issue, then a flag for disabled would suffice, and then actually deleting the row if they have been deleted.</p>\n\n<p>It also depends on policies for storing data. If there are policies for keeping data archived, then a separate table would most likely be necessary after any great length of time.</p>\n"
},
{
"answer_id": 102386,
"author": "user13276",
"author_id": 13276,
"author_profile": "https://Stackoverflow.com/users/13276",
"pm_score": 0,
"selected": false,
"text": "<p>No - this is a pretty common thing - couple of variations depending on specific requirements (but you already covered them):</p>\n\n<p>1) If you expect to have a whole BUNCH of data - like multiple terabytes or more - not a bad idea to archive deleted records immediately - though you might use a combination approach of marking as deleted then copying to archive tables.</p>\n\n<p>2) Of course the option to hard delete a record still exists - though us developers tend to be data pack-rats - I suggest that you should look at the business process and decide if there is now any need to even keep the data - if there is - do so... if there isn't - you should probably feel free just to throw the stuff away.....again, according to the specific business scenario.</p>\n"
},
{
"answer_id": 102505,
"author": "Greg",
"author_id": 18926,
"author_profile": "https://Stackoverflow.com/users/18926",
"pm_score": 2,
"selected": false,
"text": "<p>We use an enum('ACTIVE','INACTIVE','DELETED') in most tables so we actually have a 3-way flag. I find it works well for us in different situations. Your mileage may vary.</p>\n"
},
{
"answer_id": 102507,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 2,
"selected": false,
"text": "<p>Moving inactive stuff is usually a stupid idea. It's a lot of overhead with lots of potential for bugs, everything becomes more complicated, like unarchiving the stuff etc. What do you do with related data? If you move all that, too, you have to modify every single query. If you don't move it, what advantage were you hoping to get?</p>\n\n<p>That leads to the next point: WHY would you move it? A properly indexed table requires one additional lookup when the size doubles. Any performance improvement is bound to be negligible. And why would you even think about it until the distant future time when you actually have performance problems? </p>\n"
},
{
"answer_id": 102526,
"author": "Arthur Thomas",
"author_id": 14009,
"author_profile": "https://Stackoverflow.com/users/14009",
"pm_score": 2,
"selected": false,
"text": "<p>I think looking at it strictly as a piece of data then the way that is shown in the original post is proper. The active flag piece of data is directly dependent upon the primary key and should be in the table.</p>\n\n<p>That table holds data on people, irrespective of the current status of their data.</p>\n"
},
{
"answer_id": 103634,
"author": "Simon Munro",
"author_id": 3893,
"author_profile": "https://Stackoverflow.com/users/3893",
"pm_score": 0,
"selected": false,
"text": "<p>From a 'purist perspective' the realtional model doesn't differentiate between a view and a table - both are relations. So that use of a view that uses the discriminator is perfectly meaningful and valid provided the entities are correctly named e.g. Person/ActivePerson.</p>\n\n<p>Also, from a 'purist perspective' the table should be named person, not people as the name of the relation reflects a tuple, not the entire set.</p>\n"
},
{
"answer_id": 111038,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 1,
"selected": false,
"text": "<p>Binary flags like this in your schema are a BAD idea. Consider the query </p>\n\n<pre>SELECT count(*) FROM users WHERE active=1</pre>\n\n<p>Looks simple enough. But what happens when you have a large number of users, so many that adding an index to this table would be required. Again, it looks straight forward</p>\n\n<pre>ALTER TABLE users ADD INDEX index_users_on_active (active)</pre>\n\n<p>EXCEPT!! This index is useless because the cardinality on this column is exactly two! Any database query optimiser will ignore this index because of it's low cardinality and do a table scan.</p>\n\n<p>Before filling up your schema with helpful flags consider how you are going to access that data.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/108503/mysql-advisable-number-of-rows#108784\">https://stackoverflow.com/questions/108503/mysql-advisable-number-of-rows</a></p>\n"
},
{
"answer_id": 5033792,
"author": "Ralph Smith",
"author_id": 2066143,
"author_profile": "https://Stackoverflow.com/users/2066143",
"pm_score": 0,
"selected": false,
"text": "<p>Regarding indexing the boolean, why not:</p>\n\n<pre><code>ALTER TABLE users ADD INDEX index_users_on_active (id, active) ; \n</code></pre>\n\n<p>Would that not improve the search?<br>\nHowever I don't know how much of that answer depends on the platform.</p>\n"
},
{
"answer_id": 56963710,
"author": "user1454926",
"author_id": 1454926,
"author_profile": "https://Stackoverflow.com/users/1454926",
"pm_score": 0,
"selected": false,
"text": "<p>This is an old question but for those search for low cardinality/selectivity indexes, I'd like to propose the following approach that avoids partitioning, secondary tables, etc.:</p>\n\n<p>The trick is to use \"dateInactivated\" column that stores the timestamp of when the record is inactivated/deleted. As the name implies, the value is NULL while the record is active, but once inactivated, write in the system datetime. Thus, an index on that column ends up having high selectivity as the number of \"deleted\" records grows since each record will have a unique (not strictly speaking) value. </p>\n\n<p>Then your query becomes:</p>\n\n<pre><code>SELECT * FROM people WHERE dateInactivated is NULL;\n</code></pre>\n\n<p>The index will pull in just the right set of rows that you care about.</p>\n"
},
{
"answer_id": 60047574,
"author": "Max",
"author_id": 11363488,
"author_profile": "https://Stackoverflow.com/users/11363488",
"pm_score": 0,
"selected": false,
"text": "<p>Filtering data on a bit flag for big tables is not really good in terms of performance. In case when 'active' determinate virtual deletion you can create 'TableName_delted' table with the same structure and move deleted data there using delete trigger. </p>\n\n<p>That solution will help with performance and simplifies data queries. </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087/"
]
| OK, so practically every database based application has to deal with "non-active" records. Either, soft-deletions or marking something as "to be ignored". I'm curious as to whether there are any radical alternatives thoughts on an `active' column (or a status column).
For example, if I had a list of people
```
CREATE TABLE people (
id INTEGER PRIMARY KEY,
name VARCHAR(100),
active BOOLEAN,
...
);
```
That means to get a list of active people, you need to use
```
SELECT * FROM people WHERE active=True;
```
Does anyone suggest that non active records would be moved off to a separate table and where appropiate a UNION is done to join the two?
Curiosity striking...
**EDIT:** I should make clear, I'm coming at this from a purist perspective. I can see how data archiving might be necessary for large amounts of data, but that is not where I'm coming from. If you do a SELECT \* FROM people it would make sense to me that those entries are in a sense "active"
Thanks | You partition the table on the active flag, so that active records are in one partition, and inactive records are in the other partition. Then you create an active view for each table which automatically has the active filter on it. The database query engine automatically restricts the query to the partition that has the active records in it, which is much faster than even using an index on that flag.
Here is an example of how to create a partitioned table in Oracle. Oracle doesn't have boolean column types, so I've modified your table structure for Oracle purposes.
```
CREATE TABLE people
(
id NUMBER(10),
name VARCHAR2(100),
active NUMBER(1)
)
PARTITION BY LIST(active)
(
PARTITION active_records VALUES (0)
PARTITION inactive_records VALUES (1)
);
```
If you wanted to you could put each partition in different tablespaces. You can also partition your indexes as well.
Incidentally, this seems a repeat of [this](https://stackoverflow.com/questions/68323/what-is-the-best-way-to-implement-soft-deletion) question, as a newbie I need to ask, what's the procedure on dealing with unintended duplicates?
**Edit:** As requested in comments, provided an example for creating a partitioned table in Oracle |
102,317 | <p>I have two tables Organisation and Employee having one to many relation i.e one organisation can have multiple employees. Now I want to select all information of a particular organisation plus first name of all employees for this organisation. What’s the best way to do it? Can I get all of this in single record set or I will have to get multiple rows based on no. of employees? Here is a bit graphical demonstration of what I want:</p>
<pre><code>Org_ID Org_Address Org_OtherDetails Employess
1 132A B Road List of details Emp1, Emp2, Emp3.....
</code></pre>
| [
{
"answer_id": 102361,
"author": "Mike McAllister",
"author_id": 16247,
"author_profile": "https://Stackoverflow.com/users/16247",
"pm_score": 0,
"selected": false,
"text": "<p>If you use Oracle you can create a PL/SQL function you can use in your query that accepts an organization_id as input, and returns the first name of all employees belonging to that org as a string. For example:-</p>\n\n<pre><code>select\n o.org_id,\n o.org_address,\n o.org_otherdetails,\n org_employees( o.org_id ) as org_employees\nfrom\n organization o\n</code></pre>\n"
},
{
"answer_id": 102375,
"author": "Aaron",
"author_id": 7659,
"author_profile": "https://Stackoverflow.com/users/7659",
"pm_score": 0,
"selected": false,
"text": "<p>It all depends. \nIf you do a join, you get all the organization data on every row. (1 row per employee). That has a cost.\nIf you do two queries. (Org and Emp) that has a different cost. </p>\n\n<p>Pick your poison.</p>\n"
},
{
"answer_id": 102442,
"author": "Adam",
"author_id": 13320,
"author_profile": "https://Stackoverflow.com/users/13320",
"pm_score": 2,
"selected": false,
"text": "<p>in MS SQL you can do:</p>\n\n<pre><code>create function dbo.table2list (@input int)\nreturns varchar(8000)\nas\nBEGIN\ndeclare @putout varchar(8000)\nset @putout = ''\nselect @putout = @putout + ', ' + <employeename>\nfrom <employeetable>\nwhere <orgid> = @input\nreturn @putout\nend\n</code></pre>\n\n<p>then do:</p>\n\n<pre><code>select * from org, dbo.table2list(orgid)\nfrom <organisationtable>\n</code></pre>\n\n<p>I think you can do it with COALESCE() as well, but can't remember the syntax off the top of my head</p>\n"
},
{
"answer_id": 102499,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 0,
"selected": false,
"text": "<p>The short answer is \"no\". </p>\n\n<p>As noted in other answers, there are vendor-specific ways to achieve this result, but there is no pure SQL solution which works in one query. </p>\n\n<p>sorry about that :(</p>\n\n<p>Presumably one of the vendor specific solutions will work for you? </p>\n"
},
{
"answer_id": 104964,
"author": "mike",
"author_id": 19217,
"author_profile": "https://Stackoverflow.com/users/19217",
"pm_score": 0,
"selected": false,
"text": "<p>Here's what you can do, you have 2 options:</p>\n\n<pre><code>select *\nFROM\n users u\n LEFT JOIN organizations o ON (u.idorg = o.id);\n</code></pre>\n\n<p>This way you will get extra data on each row - full organization info you don't really need.</p>\n\n<p>Or you can do:</p>\n\n<pre><code>select o.*, group_concat(u.name)\nFROM\n users u\n LEFT JOIN organizations o ON (u.idorg = o.id)\nGROUP BY\n o.id\n</code></pre>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat</a></p>\n\n<p>The second approach is applicable if you want to see ie. list of usernames \"user1, user2, user3\", but don't want to operate on the fields themselves...</p>\n"
},
{
"answer_id": 106149,
"author": "igelkott",
"author_id": 2052165,
"author_profile": "https://Stackoverflow.com/users/2052165",
"pm_score": 2,
"selected": false,
"text": "<p>Since the question is tagged as MySQL, you should be able to use a MySQL-specific solution, namely, GROUP_CONCAT. For example,</p>\n\n<pre><code>select Org_ID, Org_Address, Org_OtherDetails,\n GROUP_CONCAT(employees) as Employees\nfrom employees a, organization b\nwhere a.org_id=b.org_id\ngroup by b.org_id;\n</code></pre>\n"
},
{
"answer_id": 106334,
"author": "mdahlman",
"author_id": 8373,
"author_profile": "https://Stackoverflow.com/users/8373",
"pm_score": 5,
"selected": false,
"text": "<p>The original question was database specific, but perhaps this is a good place to include a more generic answer. It's a common question. The concept that you are describing is often referred to as 'Group Concatenation'. There's no standard solution in SQL-92 or SQL-99. So you'll need a vendor-specific solution.</p>\n<ul>\n<li><strong>MySQL</strong> - Use the built-in GROUP_CONCAT function. In your example you would want something like this:</li>\n</ul>\n<pre>select \n o.ID, o.Address, o.OtherDetails,\n GROUP_CONCAT( concat(e.firstname, ' ', e.lastname) ) as Employees\nfrom \n employees e \n inner join organization o on o.org_id=e.org_id\ngroup by o.org_id\n</pre>\n<ul>\n<li><strong>PostgreSQL</strong> - PostgreSQL 9.0 is equally simple now that string_agg(expression, delimiter) is built-in. Here it is with 'comma-space' between elements:</li>\n</ul>\n<pre>select \n o.ID, o.Address, o.OtherDetails,\n STRING_AGG( (e.firstname || ' ' || e.lastname), ', ' ) as Employees\nfrom \n employees e \n inner join organization o on o.org_id=e.org_id\ngroup by o.org_id\n</pre>\n<p>PostgreSQL before 9.0 allows you to define your own aggregate functions with CREATE AGGREGATE. Slightly more work than MySQL, but much more flexible. See this <a href=\"https://stackoverflow.com/questions/43870/how-to-concatenate-strings-of-a-string-field-in-a-postgresql-group-by-query\">other post</a> for more details. (Of course PostgreSQL 9.0 and later have this option as well.)</p>\n<ul>\n<li><p><strong>Oracle</strong> - same idea using <strong>LISTAGG</strong>.</p>\n</li>\n<li><p><strong>MS SQL Server</strong> - same idea using <strong>STRING_AGG</strong></p>\n</li>\n<li><p><strong>Fallback solution</strong> - in other database technologies or in very very old versions of the technologies listed above you don't have these group concatenation functions. In that case create a stored procedure that takes the org_id as its input and outputs the concatenated employee names. Then use this stored procedure in your query. Some of the other responses here include some details about how to write stored procedures like these.</p>\n</li>\n</ul>\n<pre>select \n o.ID, o.Address, o.OtherDetails,\n MY_CUSTOM_GROUP_CONCAT_PROCEDURE( o.ID ) as Employees\nfrom \n organization o\n</pre>\n"
},
{
"answer_id": 6059255,
"author": "Orlando Colamatteo",
"author_id": 222606,
"author_profile": "https://Stackoverflow.com/users/222606",
"pm_score": 0,
"selected": false,
"text": "<p>For SQL Server SQLCLR aggregates in this project are inspired by the MSDN code sample however they perform much better and allow for sorting (as strings) and alternate delimiters if needed. They offer <em>almost</em> equivalent functionality to MySQL's GROUP_CONCAT for SQL Server. </p>\n\n<p>A full comparison of the advantages/disadvantages of the CLR aggregates and the FOR XML solution can be found in the documentation:</p>\n\n<p><a href=\"http://groupconcat.codeplex.com\" rel=\"nofollow\">http://groupconcat.codeplex.com</a></p>\n"
},
{
"answer_id": 66589552,
"author": "Dylan Kennard",
"author_id": 15094747,
"author_profile": "https://Stackoverflow.com/users/15094747",
"pm_score": 0,
"selected": false,
"text": "<p>For SQL Server 2017 & Azure SQL there is now a function STRING_AGG (Transact-SQL) for this to be on par more with MySQL:</p>\n<p><a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver15</a>.</p>\n<pre><code>SELECT attribute1, STRING_AGG (attribute2, '|') AS Attribute2\nFROM table\nGROUP BY attribute\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have two tables Organisation and Employee having one to many relation i.e one organisation can have multiple employees. Now I want to select all information of a particular organisation plus first name of all employees for this organisation. What’s the best way to do it? Can I get all of this in single record set or I will have to get multiple rows based on no. of employees? Here is a bit graphical demonstration of what I want:
```
Org_ID Org_Address Org_OtherDetails Employess
1 132A B Road List of details Emp1, Emp2, Emp3.....
``` | The original question was database specific, but perhaps this is a good place to include a more generic answer. It's a common question. The concept that you are describing is often referred to as 'Group Concatenation'. There's no standard solution in SQL-92 or SQL-99. So you'll need a vendor-specific solution.
* **MySQL** - Use the built-in GROUP\_CONCAT function. In your example you would want something like this:
```
select
o.ID, o.Address, o.OtherDetails,
GROUP_CONCAT( concat(e.firstname, ' ', e.lastname) ) as Employees
from
employees e
inner join organization o on o.org_id=e.org_id
group by o.org_id
```
* **PostgreSQL** - PostgreSQL 9.0 is equally simple now that string\_agg(expression, delimiter) is built-in. Here it is with 'comma-space' between elements:
```
select
o.ID, o.Address, o.OtherDetails,
STRING_AGG( (e.firstname || ' ' || e.lastname), ', ' ) as Employees
from
employees e
inner join organization o on o.org_id=e.org_id
group by o.org_id
```
PostgreSQL before 9.0 allows you to define your own aggregate functions with CREATE AGGREGATE. Slightly more work than MySQL, but much more flexible. See this [other post](https://stackoverflow.com/questions/43870/how-to-concatenate-strings-of-a-string-field-in-a-postgresql-group-by-query) for more details. (Of course PostgreSQL 9.0 and later have this option as well.)
* **Oracle** - same idea using **LISTAGG**.
* **MS SQL Server** - same idea using **STRING\_AGG**
* **Fallback solution** - in other database technologies or in very very old versions of the technologies listed above you don't have these group concatenation functions. In that case create a stored procedure that takes the org\_id as its input and outputs the concatenated employee names. Then use this stored procedure in your query. Some of the other responses here include some details about how to write stored procedures like these.
```
select
o.ID, o.Address, o.OtherDetails,
MY_CUSTOM_GROUP_CONCAT_PROCEDURE( o.ID ) as Employees
from
organization o
``` |
102,343 | <p>I have a need to open a popup detail window from a gridview (VS 2005 / 2008). What I am trying to do is in the markup for my TemplateColumn have an asp:Button control, sort of like this:</p>
<pre><code><asp:Button ID="btnShowDetails" runat="server" CausesValidation="false"
CommandName="Details" Text="Order Details"
onClientClick="window.open('PubsOrderDetails.aspx?OrderId=<%# Eval("order_id") %>',
'','scrollbars=yes,resizable=yes, width=350, height=550');"
</code></pre>
<p>Of course, what isn't working is the appending of the <%# Eval...%> section to set the query string variable.</p>
<p>Any suggestions? Or is there a far better way of achieving the same result?</p>
| [
{
"answer_id": 102373,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 5,
"selected": true,
"text": "<p>I believe the way to do it is</p>\n\n<blockquote>\n<pre><code>onClientClick=<%# string.Format(\"window.open('PubsOrderDetails.aspx?OrderId={0}',scrollbars=yes,resizable=yes, width=350, height=550);\", Eval(\"order_id\")) %>\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 102411,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 2,
"selected": false,
"text": "<p>I like @<a href=\"https://stackoverflow.com/questions/102343/including-eval-bind-values-in-onclientclick-code#102373\">AviewAnew</a>'s suggestion, though you can also just write that from the code-behind by wiring up and event to the grid views ItemDataBound event. You'd then use the FindControl method on the event args you get to grab a reference to your button, and set the <em>onclick</em> attribute to your window.open statement.</p>\n"
},
{
"answer_id": 102479,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 2,
"selected": false,
"text": "<p>Do this in the code-behind. Just use an event handler for gridview_RowDataBound. (My example uses a gridview with the id of \"gvBoxes\".</p>\n\n<pre><code>Private Sub gvBoxes_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvBoxes.RowDataBound\n Select Case e.Row.RowType\n Case DataControlRowType.DataRow\n Dim btn As Button = e.Row.FindControl(\"btnShowDetails\")\n btn.OnClientClick = \"window.open('PubsOrderDetails.aspx?OrderId=\" & DataItem.Eval(\"OrderId\") & \"','','scrollbars=yes,resizable=yes, width=350, height=550');\"\n End Select \nEnd Sub\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12253/"
]
| I have a need to open a popup detail window from a gridview (VS 2005 / 2008). What I am trying to do is in the markup for my TemplateColumn have an asp:Button control, sort of like this:
```
<asp:Button ID="btnShowDetails" runat="server" CausesValidation="false"
CommandName="Details" Text="Order Details"
onClientClick="window.open('PubsOrderDetails.aspx?OrderId=<%# Eval("order_id") %>',
'','scrollbars=yes,resizable=yes, width=350, height=550');"
```
Of course, what isn't working is the appending of the <%# Eval...%> section to set the query string variable.
Any suggestions? Or is there a far better way of achieving the same result? | I believe the way to do it is
>
>
> ```
> onClientClick=<%# string.Format("window.open('PubsOrderDetails.aspx?OrderId={0}',scrollbars=yes,resizable=yes, width=350, height=550);", Eval("order_id")) %>
>
> ```
>
> |
102,382 | <p>I use ssh-agent with password-protected keys on Linux. Every time I log into a certain machine, I do this:</p>
<pre><code>eval `ssh-agent` && ssh-add
</code></pre>
<p>This works well enough, but every time I log in and do this, I create another ssh-agent. Once in a while, I will do a <code>killall ssh-agent</code> to reap them. Is there a simple way to reuse the same ssh-agent process across different sessions?</p>
| [
{
"answer_id": 102420,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 2,
"selected": false,
"text": "<p>How much control do you have over this machine? One answer would be to run ssh-agent as a daemon process. Other options are explained on <a href=\"http://mah.everybody.org/docs/ssh\" rel=\"nofollow noreferrer\">this web page</a>, basically testing to see if the agent is around and then running it if it's not.</p>\n\n<p>To reproduce one of the ideas here:</p>\n\n<pre><code>SSH_ENV=\"$HOME/.ssh/environment\"\n\nfunction start_agent {\n echo \"Initialising new SSH agent...\"\n /usr/bin/ssh-agent | sed 's/^echo/#echo/' > \"${SSH_ENV}\"\n echo succeeded\n chmod 600 \"${SSH_ENV}\"\n . \"${SSH_ENV}\" > /dev/null\n /usr/bin/ssh-add;\n}\n\n# Source SSH settings, if applicable\n\nif [ -f \"${SSH_ENV}\" ]; then\n . \"${SSH_ENV}\" > /dev/null\n #ps ${SSH_AGENT_PID} doesn’t work under cywgin\n ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {\n start_agent;\n }\nelse\n start_agent;\nfi \n</code></pre>\n"
},
{
"answer_id": 102432,
"author": "Aaron Arbery",
"author_id": 18478,
"author_profile": "https://Stackoverflow.com/users/18478",
"pm_score": 4,
"selected": true,
"text": "<p>have a look at Keychain. It was written b people in a similar situation to yourself.\n<a href=\"http://www.gentoo.org/proj/en/keychain/\" rel=\"noreferrer\">Keychain</a></p>\n"
},
{
"answer_id": 106720,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 0,
"selected": false,
"text": "<p>Depending on which shell you use, you can set different profiles for login shells and mere regular new shells. In general you want to start ssh-agent for login shells, but not for every subshell. In bash these files would be <code>.bashrc</code> and <code>.bash_login</code>, for example.</p>\n\n<p>Most desktop linuxes these days run ssh-agent for you. You just add your key with ssh-add, and then forward the keys over to remote ssh sessions by running </p>\n\n<pre>\nssh -A\n</pre>\n"
},
{
"answer_id": 106727,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>You can do:</p>\n\n<pre><code>ssh-agent $SHELL\n</code></pre>\n\n<p>This will cause ssh-agent to exit when the shell exits. They still won't be shared across sessions, but at least they will go away when you do.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
]
| I use ssh-agent with password-protected keys on Linux. Every time I log into a certain machine, I do this:
```
eval `ssh-agent` && ssh-add
```
This works well enough, but every time I log in and do this, I create another ssh-agent. Once in a while, I will do a `killall ssh-agent` to reap them. Is there a simple way to reuse the same ssh-agent process across different sessions? | have a look at Keychain. It was written b people in a similar situation to yourself.
[Keychain](http://www.gentoo.org/proj/en/keychain/) |
102,394 | <p>I am trying to sort a dict based on its key and return an iterator to the values from within an overridden iter method in a class. Is there a nicer and more efficient way of doing this than creating a new list, inserting into the list as I sort through the keys?</p>
| [
{
"answer_id": 102438,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 2,
"selected": false,
"text": "<p>By far the easiest approach, and almost certainly the fastest, is something along the lines of:</p>\n\n<pre><code>def sorted_dict(d):\n keys = d.keys()\n keys.sort()\n for key in keys:\n yield d[key]\n</code></pre>\n\n<p>You can't sort without fetching all keys. Fetching all keys into a list and then sorting that list is the most efficient way to do that; list sorting is very fast, and fetching the keys list like that is as fast as it can be. You can then either create a new list of values or yield the values as the example does. Keep in mind that you can't modify the dict if you are iterating over it (the next iteration would fail) so if you want to modify the dict before you're done with the result of sorted_dict(), make it return a list.</p>\n"
},
{
"answer_id": 102443,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 4,
"selected": true,
"text": "<p>How about something like this:</p>\n\n<pre><code>def itersorted(d):\n for key in sorted(d):\n yield d[key]\n</code></pre>\n"
},
{
"answer_id": 102480,
"author": "LJ.",
"author_id": 4849,
"author_profile": "https://Stackoverflow.com/users/4849",
"pm_score": -1,
"selected": false,
"text": "<p>Assuming you want a default sort order, you can used <code>sorted(list)</code> or <code>list.sort()</code>. If you want your own sort logic, Python lists support the ability to sort based on a function you pass in. For example, the following would be a way to sort numbers from least to greatest (the default behavior) using a function.</p>\n<pre><code>def compareTwo(a, b):\n if a > b:\n return 1\n if a == b:\n return 0\n if a < b:\n return -1\n\nList.Sort(compareTwo)\nprint a\n</code></pre>\n<p>This approach is conceptually a bit cleaner than manually creating a new list and appending the new values and allows you to control the sort logic.</p>\n"
},
{
"answer_id": 103187,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 2,
"selected": false,
"text": "<pre><code>def sortedDict(dictobj):\n return (value for key, value in sorted(dictobj.iteritems()))\n</code></pre>\n\n<p>This will create a single intermediate list, the 'sorted()' method returns a real list. But at least it's only one.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18909/"
]
| I am trying to sort a dict based on its key and return an iterator to the values from within an overridden iter method in a class. Is there a nicer and more efficient way of doing this than creating a new list, inserting into the list as I sort through the keys? | How about something like this:
```
def itersorted(d):
for key in sorted(d):
yield d[key]
``` |
102,457 | <p>Given an existing valid SVG document, what's the best way to create "informational popups", so that when you hover or click on certain elements (let's say ) you popup a box with an arbitrary amount (i.e. not just a single line tooltip) of extra information?</p>
<p>This should display correctly at least in Firefox and be invisible if the image was rasterized to a bitmap format.</p>
| [
{
"answer_id": 105636,
"author": "Sparr",
"author_id": 13675,
"author_profile": "https://Stackoverflow.com/users/13675",
"pm_score": 6,
"selected": true,
"text": "<pre><code><svg>\n <text id=\"thingyouhoverover\" x=\"50\" y=\"35\" font-size=\"14\">Mouse over me!</text>\n <text id=\"thepopup\" x=\"250\" y=\"100\" font-size=\"30\" fill=\"black\" visibility=\"hidden\">Change me\n <set attributeName=\"visibility\" from=\"hidden\" to=\"visible\" begin=\"thingyouhoverover.mouseover\" end=\"thingyouhoverover.mouseout\"/>\n </text>\n</svg>\n</code></pre>\n\n<p>Further explanation can be found <a href=\"http://web.archive.org/web/20121023190528/http://www.ibm.com/developerworks/library/x-svgint/\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 4831948,
"author": "Peter Collingridge",
"author_id": 566920,
"author_profile": "https://Stackoverflow.com/users/566920",
"pm_score": 2,
"selected": false,
"text": "<p>Since the <code><set></code> element doesn't work with Firefox 3, I think you have to use ECMAScript.</p>\n\n<p>If you add the following script element into your SVG:</p>\n\n<pre><code> <script type=\"text/ecmascript\"> <![CDATA[\n\n function init(evt) {\n if ( window.svgDocument == null ) {\n // Define SGV\n svgDocument = evt.target.ownerDocument;\n }\n tooltip = svgDocument.getElementById('tooltip');\n }\n\n function ShowTooltip(evt) {\n // Put tooltip in the right position, change the text and make it visible\n tooltip.setAttributeNS(null,\"x\",evt.clientX+10);\n tooltip.setAttributeNS(null,\"y\",evt.clientY+30);\n tooltip.firstChild.data = evt.target.getAttributeNS(null,\"mouseovertext\");\n tooltip.setAttributeNS(null,\"visibility\",\"visible\");\n }\n\n function HideTooltip(evt) {\n tooltip.setAttributeNS(null,\"visibility\",\"hidden\");\n }\n ]]></script>\n</code></pre>\n\n<p>You need to add <code>onload=\"init(evt)\"</code> into the SVG element to call the init() function.</p>\n\n<p>Then, to the end of the SVG, add the tooltip text:</p>\n\n<pre><code><text id=\"tooltip\" x=\"0\" y=\"0\" visibility=\"hidden\">Tooltip</text>\n</code></pre>\n\n<p>Finally, to each of the element that you want to have the mouseover function add:</p>\n\n<pre><code>onmousemove=\"ShowTooltip(evt)\"\nonmouseout=\"HideTooltip(evt)\"\nmouseovertext=\"Whatever text you want to show\"\n</code></pre>\n\n<p>I've written a more detailed explanation with improved functionality at <a href=\"http://www.petercollingridge.co.uk/interactive-svg-components/tooltip\" rel=\"nofollow\">http://www.petercollingridge.co.uk/interactive-svg-components/tooltip</a></p>\n\n<p>I haven't yet included multi-line tooltips, which would require multiple <code><tspan></code> elements and manual word wrapping.</p>\n"
},
{
"answer_id": 12904788,
"author": "Neil Fraser",
"author_id": 154079,
"author_profile": "https://Stackoverflow.com/users/154079",
"pm_score": 6,
"selected": false,
"text": "<p>This question was asked in 2008. SVG has improved rapidly in the intervening four years. Now tooltips are fully supported in all platforms I'm aware of. Use a <code><title></code> tag (not an attribute) and you will get a native tooltip.</p>\n\n<p>Here are the docs:\n<a href=\"https://developer.mozilla.org/en-US/docs/SVG/Element/title\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/SVG/Element/title</a></p>\n"
},
{
"answer_id": 18352578,
"author": "Aravind Cheekkallur",
"author_id": 2549636,
"author_profile": "https://Stackoverflow.com/users/2549636",
"pm_score": 1,
"selected": false,
"text": "<p>This should work:</p>\n\n<pre><code>nodeEnter.append(\"svg:element\")\n .style(\"fill\", function(d) { return d._children ? \"lightsteelblue\" : \"#fff\"; })\n .append(\"svg:title\")\n .text(function(d) {return d.Name+\"\\n\"+d.Age+\"\\n\"+d.Dept;}); // It shows the tool tip box with item [Name,Age,Dept] and upend to the svg dynamicaly\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2846/"
]
| Given an existing valid SVG document, what's the best way to create "informational popups", so that when you hover or click on certain elements (let's say ) you popup a box with an arbitrary amount (i.e. not just a single line tooltip) of extra information?
This should display correctly at least in Firefox and be invisible if the image was rasterized to a bitmap format. | ```
<svg>
<text id="thingyouhoverover" x="50" y="35" font-size="14">Mouse over me!</text>
<text id="thepopup" x="250" y="100" font-size="30" fill="black" visibility="hidden">Change me
<set attributeName="visibility" from="hidden" to="visible" begin="thingyouhoverover.mouseover" end="thingyouhoverover.mouseout"/>
</text>
</svg>
```
Further explanation can be found [here](http://web.archive.org/web/20121023190528/http://www.ibm.com/developerworks/library/x-svgint/). |
102,468 | <p>I'm trying to write a piece of code that will do the following:</p>
<p>Take the numbers 0 to 9 and assign one or more letters to this number. For example:</p>
<pre><code>0 = N,
1 = L,
2 = T,
3 = D,
4 = R,
5 = V or F,
6 = B or P,
7 = Z,
8 = H or CH or J,
9 = G
</code></pre>
<p>When I have a code like 0123, it's an easy job to encode it. It will obviously make up the code NLTD. When a number like 5,6 or 8 is introduced, things get different. A number like 051 would result in more than one possibility:</p>
<p>NVL and NFL</p>
<p>It should be obvious that this gets even "worse" with longer numbers that include several digits like 5,6 or 8.</p>
<p>Being pretty bad at mathematics, I have not yet been able to come up with a decent solution that will allow me to feed the program a bunch of numbers and have it spit out all the possible letter combinations. So I'd love some help with it, 'cause I can't seem to figure it out. Dug up some information about permutations and combinations, but no luck.</p>
<p>Thanks for any suggestions/clues. The language I need to write the code in is PHP, but any general hints would be highly appreciated.</p>
<h3>Update:</h3>
<p>Some more background: (and thanks a lot for the quick responses!)</p>
<p>The idea behind my question is to build a script that will help people to easily convert numbers they want to remember to words that are far more easily remembered. This is sometimes referred to as "pseudo-numerology".</p>
<p>I want the script to give me all the possible combinations that are then held against a database of stripped words. These stripped words just come from a dictionary and have all the letters I mentioned in my question stripped out of them. That way, the number to be encoded can usually easily be related to a one or more database records. And when that happens, you end up with a list of words that you can use to remember the number you wanted to remember.</p>
| [
{
"answer_id": 102510,
"author": "David Pierre",
"author_id": 18296,
"author_profile": "https://Stackoverflow.com/users/18296",
"pm_score": 3,
"selected": false,
"text": "<p>It can be done easily recursively.</p>\n\n<p>The idea is that to handle the whole code of size n, you must handle first the n - 1 digits.\nOnce you have all answers for n-1 digits, the answers for the whole are deduced by appending to them the correct(s) char(s) for the last one.</p>\n"
},
{
"answer_id": 102595,
"author": "Bravax",
"author_id": 13911,
"author_profile": "https://Stackoverflow.com/users/13911",
"pm_score": 0,
"selected": false,
"text": "<p>Could you do the following:\nCreate a results array.\nCreate an item in the array with value \"\"</p>\n\n<p>Loop through the numbers, say 051 analyzing each one individually.</p>\n\n<p>Each time a 1 to 1 match between a number is found add the correct value to all items in the results array.\nSo \"\" becomes N.</p>\n\n<p>Each time a 1 to many match is found, add new rows to the results array with one option, and update the existing results with the other option.\nSo N becomes NV and a new item is created NF</p>\n\n<p>Then the last number is a 1 to 1 match so the items in the results array become\nNVL and NFL</p>\n\n<p>To produce the results loop through the results array, printing them, or whatever.</p>\n"
},
{
"answer_id": 102664,
"author": "jdmichal",
"author_id": 12275,
"author_profile": "https://Stackoverflow.com/users/12275",
"pm_score": 0,
"selected": false,
"text": "<p>Let <code>p<sub>n</sub></code> be a list of all possible letter combinations of a given number string <code>s</code> up to the <code>n<sup>th</sup></code> digit.</p>\n\n<p>Then, the following algorithm will generate <code>p<sub>n+1</sub></code>:</p>\n\n<pre><code>digit = s[n+1];\nforeach(letter l that digit maps to)\n{\n foreach(entry e in p(n))\n {\n newEntry = append l to e;\n add newEntry to p(n+1);\n }\n}\n</code></pre>\n\n<p>The first iteration is somewhat of a special case, since p<sub>-1</sub> is undefined. You can simply initialize p<sub>0</sub> as the list of all possible characters for the first character.</p>\n\n<p>So, your 051 example:</p>\n\n<p>Iteration 0:</p>\n\n<pre><code>p(0) = {N}\n</code></pre>\n\n<p>Iteration 1:</p>\n\n<pre><code>digit = 5\nforeach({V, F})\n{\n foreach(p(0) = {N})\n {\n newEntry = N + V or N + F\n p(1) = {NV, NF}\n }\n}\n</code></pre>\n\n<p>Iteration 2:</p>\n\n<pre><code>digit = 1\nforeach({L})\n{\n foreach(p(1) = {NV, NF})\n {\n newEntry = NV + L or NF + L\n p(2) = {NVL, NFL}\n }\n}\n</code></pre>\n"
},
{
"answer_id": 102676,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 3,
"selected": true,
"text": "<p>The general structure you want to hold your number -> letter assignments is an array or arrays, similar to:</p>\n\n<pre><code>// 0 = N, 1 = L, 2 = T, 3 = D, 4 = R, 5 = V or F, 6 = B or P, 7 = Z, \n// 8 = H or CH or J, 9 = G\n$numberMap = new Array (\n 0 => new Array(\"N\"),\n 1 => new Array(\"L\"),\n 2 => new Array(\"T\"),\n 3 => new Array(\"D\"),\n 4 => new Array(\"R\"),\n 5 => new Array(\"V\", \"F\"),\n 6 => new Array(\"B\", \"P\"),\n 7 => new Array(\"Z\"),\n 8 => new Array(\"H\", \"CH\", \"J\"),\n 9 => new Array(\"G\"),\n);\n</code></pre>\n\n<p>Then, a bit of recursive logic gives us a function similar to:</p>\n\n<pre><code>function GetEncoding($number) {\n $ret = new Array();\n for ($i = 0; $i < strlen($number); $i++) {\n // We're just translating here, nothing special.\n // $var + 0 is a cheap way of forcing a variable to be numeric\n $ret[] = $numberMap[$number[$i]+0];\n }\n}\n\nfunction PrintEncoding($enc, $string = \"\") {\n // If we're at the end of the line, then print!\n if (count($enc) === 0) {\n print $string.\"\\n\";\n return;\n }\n\n // Otherwise, soldier on through the possible values.\n // Grab the next 'letter' and cycle through the possibilities for it.\n foreach ($enc[0] as $letter) {\n // And call this function again with it!\n PrintEncoding(array_slice($enc, 1), $string.$letter);\n }\n}\n</code></pre>\n\n<p>Three cheers for recursion! This would be used via:</p>\n\n<pre><code>PrintEncoding(GetEncoding(\"052384\"));\n</code></pre>\n\n<p>And if you really want it as an array, play with output buffering and explode using \"\\n\" as your split string.</p>\n"
},
{
"answer_id": 102696,
"author": "HenryR",
"author_id": 2827,
"author_profile": "https://Stackoverflow.com/users/2827",
"pm_score": 0,
"selected": false,
"text": "<p>The form you want is probably something like:</p>\n\n<pre><code>function combinations( $str ){\n$l = len( $str );\n$results = array( );\nif ($l == 0) { return $results; }\nif ($l == 1)\n{ \n foreach( $codes[ $str[0] ] as $code )\n {\n $results[] = $code;\n }\n return $results;\n}\n$cur = $str[0];\n$combs = combinations( substr( $str, 1, $l ) );\nforeach ($codes[ $cur ] as $code)\n{\n foreach ($combs as $comb)\n {\n $results[] = $code.$comb;\n }\n}\nreturn $results;}\n</code></pre>\n\n<p>This is ugly, pidgin-php so please verify it first. The basic idea is to generate every combination of the string from [1..n] and then prepend to the front of all those combinations each possible code for str[0]. Bear in mind that in the worst case this will have performance exponential in the length of your string, because that much ambiguity is actually present in your coding scheme. </p>\n"
},
{
"answer_id": 102764,
"author": "florin",
"author_id": 18308,
"author_profile": "https://Stackoverflow.com/users/18308",
"pm_score": 0,
"selected": false,
"text": "<p>The trick is not only to generate all possible letter combinations that match a given number, but to select the letter sequence that is most easy to remember. A suggestion would be to run the <a href=\"http://en.wikipedia.org/wiki/Soundex\" rel=\"nofollow noreferrer\">soundex</a> algorithm on each of the sequence and try to match against an English language dictionary such as <a href=\"http://wordnet.princeton.edu/\" rel=\"nofollow noreferrer\">Wordnet</a> to find the most 'real-word-sounding' sequences.</p>\n"
},
{
"answer_id": 102886,
"author": "J Miller",
"author_id": 16976,
"author_profile": "https://Stackoverflow.com/users/16976",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a recursive solution in Python.</p>\n\n<pre><code>#!/usr/bin/env/python\n\nimport sys\n\nENCODING = {'0':['N'],\n '1':['L'],\n '2':['T'],\n '3':['D'],\n '4':['R'],\n '5':['V', 'F'],\n '6':['B', 'P'],\n '7':['Z'],\n '8':['H', 'CH', 'J'],\n '9':['G']\n }\n\ndef decode(str):\n if len(str) == 0:\n return ''\n elif len(str) == 1:\n return ENCODING[str]\n else:\n result = []\n for prefix in ENCODING[str[0]]:\n result.extend([prefix + suffix for suffix in decode(str[1:])])\n return result\n\nif __name__ == '__main__':\n print decode(sys.argv[1])\n</code></pre>\n\n<p>Example output:</p>\n\n<pre><code>$ ./demo 1\n['L']\n$ ./demo 051\n['NVL', 'NFL']\n$ ./demo 0518\n['NVLH', 'NVLCH', 'NVLJ', 'NFLH', 'NFLCH', 'NFLJ']\n</code></pre>\n"
},
{
"answer_id": 102957,
"author": "ljorquera",
"author_id": 9132,
"author_profile": "https://Stackoverflow.com/users/9132",
"pm_score": 2,
"selected": false,
"text": "<p>This kind of problem are usually resolved with recursion. In ruby, one (quick and dirty) solution would be</p>\n\n<pre><code>@values = Hash.new([])\n\n\n@values[\"0\"] = [\"N\"] \n@values[\"1\"] = [\"L\"] \n@values[\"2\"] = [\"T\"] \n@values[\"3\"] = [\"D\"] \n@values[\"4\"] = [\"R\"] \n@values[\"5\"] = [\"V\",\"F\"] \n@values[\"6\"] = [\"B\",\"P\"] \n@values[\"7\"] = [\"Z\"] \n@values[\"8\"] = [\"H\",\"CH\",\"J\"] \n@values[\"9\"] = [\"G\"]\n\ndef find_valid_combinations(buffer,number)\n first_char = number.shift\n @values[first_char].each do |key|\n if(number.length == 0) then\n puts buffer + key\n else\n find_valid_combinations(buffer + key,number.dup)\n end\n end\nend\n\nfind_valid_combinations(\"\",ARGV[0].split(\"\"))\n</code></pre>\n\n<p>And if you run this from the command line you will get:</p>\n\n<pre><code>$ ruby r.rb 051\nNVL\nNFL\n</code></pre>\n\n<p>This is related to <a href=\"http://en.wikipedia.org/wiki/Brute_force_search\" rel=\"nofollow noreferrer\">brute-force search</a> and <a href=\"http://en.wikipedia.org/wiki/Backtracking\" rel=\"nofollow noreferrer\">backtracking</a></p>\n"
},
{
"answer_id": 103709,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 2,
"selected": false,
"text": "<p>There's actually a much better solution than enumerating all the possible translations of a number and looking them up: Simply do the reverse computation on every word in your dictionary, and store the string of digits in another field. So if your mapping is:</p>\n\n<pre><code>0 = N,\n1 = L,\n2 = T,\n3 = D,\n4 = R,\n5 = V or F,\n6 = B or P,\n7 = Z,\n8 = H or CH or J,\n9 = G\n</code></pre>\n\n<p>your reverse mapping is:</p>\n\n<pre><code>N = 0,\nL = 1,\nT = 2,\nD = 3,\nR = 4,\nV = 5,\nF = 5,\nB = 6,\nP = 6,\nZ = 7,\nH = 8,\nJ = 8,\nG = 9\n</code></pre>\n\n<p>Note there's no mapping for 'ch', because the 'c' will be dropped, and the 'h' will be converted to 8 anyway.</p>\n\n<p>Then, all you have to do is iterate through each letter in the dictionary word, output the appropriate digit if there's a match, and do nothing if there isn't.</p>\n\n<p>Store all the generated digit strings as another field in the database. When you want to look something up, just perform a simple query for the number entered, instead of having to do tens (or hundreds, or thousands) of lookups of potential words.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18922/"
]
| I'm trying to write a piece of code that will do the following:
Take the numbers 0 to 9 and assign one or more letters to this number. For example:
```
0 = N,
1 = L,
2 = T,
3 = D,
4 = R,
5 = V or F,
6 = B or P,
7 = Z,
8 = H or CH or J,
9 = G
```
When I have a code like 0123, it's an easy job to encode it. It will obviously make up the code NLTD. When a number like 5,6 or 8 is introduced, things get different. A number like 051 would result in more than one possibility:
NVL and NFL
It should be obvious that this gets even "worse" with longer numbers that include several digits like 5,6 or 8.
Being pretty bad at mathematics, I have not yet been able to come up with a decent solution that will allow me to feed the program a bunch of numbers and have it spit out all the possible letter combinations. So I'd love some help with it, 'cause I can't seem to figure it out. Dug up some information about permutations and combinations, but no luck.
Thanks for any suggestions/clues. The language I need to write the code in is PHP, but any general hints would be highly appreciated.
### Update:
Some more background: (and thanks a lot for the quick responses!)
The idea behind my question is to build a script that will help people to easily convert numbers they want to remember to words that are far more easily remembered. This is sometimes referred to as "pseudo-numerology".
I want the script to give me all the possible combinations that are then held against a database of stripped words. These stripped words just come from a dictionary and have all the letters I mentioned in my question stripped out of them. That way, the number to be encoded can usually easily be related to a one or more database records. And when that happens, you end up with a list of words that you can use to remember the number you wanted to remember. | The general structure you want to hold your number -> letter assignments is an array or arrays, similar to:
```
// 0 = N, 1 = L, 2 = T, 3 = D, 4 = R, 5 = V or F, 6 = B or P, 7 = Z,
// 8 = H or CH or J, 9 = G
$numberMap = new Array (
0 => new Array("N"),
1 => new Array("L"),
2 => new Array("T"),
3 => new Array("D"),
4 => new Array("R"),
5 => new Array("V", "F"),
6 => new Array("B", "P"),
7 => new Array("Z"),
8 => new Array("H", "CH", "J"),
9 => new Array("G"),
);
```
Then, a bit of recursive logic gives us a function similar to:
```
function GetEncoding($number) {
$ret = new Array();
for ($i = 0; $i < strlen($number); $i++) {
// We're just translating here, nothing special.
// $var + 0 is a cheap way of forcing a variable to be numeric
$ret[] = $numberMap[$number[$i]+0];
}
}
function PrintEncoding($enc, $string = "") {
// If we're at the end of the line, then print!
if (count($enc) === 0) {
print $string."\n";
return;
}
// Otherwise, soldier on through the possible values.
// Grab the next 'letter' and cycle through the possibilities for it.
foreach ($enc[0] as $letter) {
// And call this function again with it!
PrintEncoding(array_slice($enc, 1), $string.$letter);
}
}
```
Three cheers for recursion! This would be used via:
```
PrintEncoding(GetEncoding("052384"));
```
And if you really want it as an array, play with output buffering and explode using "\n" as your split string. |
102,477 | <p>Before, I have found the "Cost" in the execution plan to be a good indicator of relative execution time. Why is this case different? Am I a fool for thinking the execution plan has relevance? What specifically can I try to improve v_test performance?</p>
<p>Thank you.</p>
<p>Using Oracle 10g I have a simple query view defined below</p>
<pre><code> create or replace view v_test as
select distinct u.bo_id as bo_id, upper(trim(d.dept_id)) as dept_id
from
cust_bo_users u
join cust_bo_roles r on u.role_name=r.role_name
join cust_dept_roll_up_tbl d on
(r.region is null or trim(r.region)=trim(d.chrgback_reg)) and
(r.prod_id is null or trim(r.prod_id)=trim(d.prod_id)) and
(r.div_id is null or trim(r.div_id)=trim(d.div_id )) and
(r.clus_id is null or trim(r.clus_id )=trim( d.clus_id)) and
(r.prod_ln_id is null or trim(r.prod_ln_id)=trim(d.prod_ln_id)) and
(r.dept_id is null or trim(r.dept_id)=trim(d.dept_id))
</code></pre>
<p>defined to replace the following view</p>
<pre><code> create or replace view v_bo_secured_detail
select distinct Q.BO_ID, Q.DEPT_ID
from (select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'REGION' and
trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG))
union all
select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'RG_PROD' and
trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG)) and
trim(R.PROD_ID) = UPPER(trim(D.PROD_ID))
union all
select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'PROD' and
trim(R.PROD_ID) = UPPER(trim(D.PROD_ID))
union all
select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'DIV' and
trim(R.DIV_ID) = UPPER(trim(D.DIV_ID))
union all
select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'RG_DIV' and
trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG)) and
trim(R.DIV_ID) = UPPER(trim(D.DIV_ID))
union all
select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'CLUS' and
trim(R.CLUS_ID) = UPPER(trim(D.CLUS_ID))
union all
select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'RG_CLUS' and
trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG)) and
trim(R.CLUS_ID) = UPPER(trim(D.CLUS_ID))
union all
select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'PROD_LN' and
trim(R.PROD_LN_ID) = UPPER(trim(D.PROD_LN_ID))
union all
select U.BO_ID BO_ID, UPPER(trim(R.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'DEPT') Q
</code></pre>
<p>with the goal of removing the dependency on the ROLE_LEVEL column.</p>
<p>The execution plan for v_test is significantly lower than v_bo_secured_detail for simple</p>
<pre><code>select * from <view> where bo_id='value'
</code></pre>
<p>queries. And is significantly lower when used in a real world query</p>
<pre><code> select CT_REPORT.RPT_KEY,
CT_REPORT_ENTRY.RPE_KEY,
CT_REPORT_ENTRY.CUSTOM16,
Exp_Sub_Type.value,
min(CT_REPORT_PAYMENT_CONF.PAY_DATE),
CT_REPORT.PAID_DATE
from CT_REPORT,
<VIEW> SD,
CT_REPORT_ENTRY,
CT_LIST_ITEM_LANG Exp_Sub_Type,
CT_REPORT_PAYMENT_CONF,
CT_STATUS_LANG Payment_Status
where (CT_REPORT_ENTRY.RPT_KEY = CT_REPORT.RPT_KEY) and
(Payment_Status.STAT_KEY = CT_REPORT.PAY_KEY) and
(Exp_Sub_Type.LI_KEY = CT_REPORT_ENTRY.CUSTOM9 and Exp_Sub_Type.LANG_CODE = 'en') and
(CT_REPORT.RPT_KEY = CT_REPORT_PAYMENT_CONF.RPT_KEY) and
(SD.BO_ID = 'JZHU9') and
(SD.DEPT_ID = UPPER(CT_REPORT_ENTRY.CUSTOM5)) and
(Payment_Status.name = 'Payment Confirmed' and (Payment_Status.LANG_CODE = 'en') and
CT_REPORT.PAID_DATE > to_date('01/01/2008', 'mm/dd/yyyy') and Exp_Sub_Type.value != 'Korea')
group by CT_REPORT.RPT_KEY,
CT_REPORT_ENTRY.RPE_KEY,
CT_REPORT_ENTRY.CUSTOM16,
Exp_Sub_Type.value,
CT_REPORT.PAID_DATE
</code></pre>
<p>The execution times are WILDLY different. The v_test view taking 15 hours, and the v_bo_secured_detail taking a few seconds.</p>
<hr>
<p><strong>Thank you all who responded</strong></p>
<p>This is one to remember for me. The places where the theory and mathematics of the expressions meets the reality of hardware based execution. Ouch.</p>
| [
{
"answer_id": 102749,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 1,
"selected": false,
"text": "<p>One aspect of low-cost -- high execution time is that when you are looking at large data-sets, it is often more efficient on the whole to do things in bulk, whereas if you want a quick results, it is more efficient to do as little work as possible to get the first record. The repetitiveness of doing the small operations that give the appearance of a quick response will not likely give a good result when working on the large sets. </p>\n\n<p>Many times, when you want a quick result, the USE_NL optimizer hint will help. </p>\n\n<p>Also, in your test view, it is relying on IS NULL... IS NULL cannot use an index nor can using a function such as trim on the 'table-side' parameter.</p>\n"
},
{
"answer_id": 102763,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 2,
"selected": false,
"text": "<p>An execution plan is theory, the execution time is reality.</p>\n\n<p>The plan shows you how the engine goes about performing your query, but some steps might cause an inordinate amount of work to resolve the query. The use of \"x is null or x = y\" smells bad. If r and d are big tables you might have some sort of combinatorial explosion hitting you and the request cycles endlessly through large lists of disk blocks. I imagine you're seeing lots of I/O during the execution.</p>\n\n<p>On the other hand, the unioned selects are short and sweet, and so probably reuse lots of disk blocks that are still lying around from the earlier selects, and/or you have some degree of parallelism benefitting from reads on the same disk blocks.</p>\n\n<p>Also using trim() and upper() everywhere looks a bit suspicious. If your data are so unclean it might be worth running some periodic housecleaning from time to time, so that you can say \"x = y\" and know it works.</p>\n\n<p>update: you asked for tips to improve v_test. Clean your data so that trim() and upper() are unnecessay. They may preclude indexes from being used (although that would be affecting the unioned select version as well).</p>\n\n<p>If you can't get rid of \"x is null or x = y\" then y = nvl(x,'does-not-exist') might have better characteristics (assuming 'does-not-exist' is a \"can't happen\" id value).</p>\n"
},
{
"answer_id": 102777,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 0,
"selected": false,
"text": "<p>Have you gathered optimiser stats on all the underlying tables? Without them the optimiser's estimates may be wildly out of kilter with reality.</p>\n"
},
{
"answer_id": 102787,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 3,
"selected": true,
"text": "<p>As <a href=\"http://download.oracle.com/docs/cd/A87860_01/doc/server.817/a76965/c20a_opt.htm#16287\" rel=\"nofollow noreferrer\">the Oracle documentation says</a>, the cost is the estimated cost relative to a particular execution plan. When you tweak the query, the particular execution plan that costs are calculated relative to can change. Sometimes dramatically.</p>\n\n<p>The problem with v_test's performance is that Oracle can think of no way to execute it other than performing a nested loop, for each cust_bo_roles, scan all of cust_dept_roll_up_tbl to find a match. If the table are of size n and m, this takes n*m time, which is slow for large tables. By contrast v_bo_secured_detail is set up so that it is a series of queries, each of which can be done through some other mechanism. (Oracle has a number it may use, including using an index, building a hash on the fly, or sorting the datasets and merging them. These operations are all O(n*log(n)) or better.) A small series of fast queries is fast.</p>\n\n<p>As painful as it is, if you want this query to be fast then you need to break it out like the previous query did.</p>\n"
},
{
"answer_id": 102855,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 0,
"selected": false,
"text": "<p>When you say the \"query plan is lower\", do you mean it is shorter, or that the actual cost estimates are lower? One obvious problem with your replacement view is that the join with cust_dept_roll_up_tbl uses almost exclusively unindexable criteria (the \"is null\" tests can be satisfied by an index, but the ones involving calling trim on each argument can't be), so the planner has to make at least one, and probably several sequential scans of the table to satisfy the query.</p>\n\n<p>I'm not sure if Oracle has this limitation, but many DBs can only do a single index scan per included table, so even if you clean up your join conditions to be indexable, it may be able to satisfy only one condition with an index scan and have to use sequential scans for the remainder.</p>\n"
},
{
"answer_id": 8177490,
"author": "Zorkus",
"author_id": 1965110,
"author_profile": "https://Stackoverflow.com/users/1965110",
"pm_score": 0,
"selected": false,
"text": "<p>To elaborate about a cost a bit.</p>\n\n<p>In Oracle 9/10g, simplifying a bit, the cost is determined by formula:</p>\n\n<p>Cost = (SrCount * SrTime + MbrCount * MbrTime + CpuCyclesCount * CpuCycleTime) / SrTime </p>\n\n<p>Where SrCount - count total single block reads made, SrTime - average time of one single block read according to gathered system statistics, MbrCount and MbrTime, the same for multiblock read correspondingly (ones use during full table scans and index fast full scans), Cpu related metrics are self-explanatory..and all divided by single block read time.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736623/"
]
| Before, I have found the "Cost" in the execution plan to be a good indicator of relative execution time. Why is this case different? Am I a fool for thinking the execution plan has relevance? What specifically can I try to improve v\_test performance?
Thank you.
Using Oracle 10g I have a simple query view defined below
```
create or replace view v_test as
select distinct u.bo_id as bo_id, upper(trim(d.dept_id)) as dept_id
from
cust_bo_users u
join cust_bo_roles r on u.role_name=r.role_name
join cust_dept_roll_up_tbl d on
(r.region is null or trim(r.region)=trim(d.chrgback_reg)) and
(r.prod_id is null or trim(r.prod_id)=trim(d.prod_id)) and
(r.div_id is null or trim(r.div_id)=trim(d.div_id )) and
(r.clus_id is null or trim(r.clus_id )=trim( d.clus_id)) and
(r.prod_ln_id is null or trim(r.prod_ln_id)=trim(d.prod_ln_id)) and
(r.dept_id is null or trim(r.dept_id)=trim(d.dept_id))
```
defined to replace the following view
```
create or replace view v_bo_secured_detail
select distinct Q.BO_ID, Q.DEPT_ID
from (select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'REGION' and
trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG))
union all
select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'RG_PROD' and
trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG)) and
trim(R.PROD_ID) = UPPER(trim(D.PROD_ID))
union all
select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'PROD' and
trim(R.PROD_ID) = UPPER(trim(D.PROD_ID))
union all
select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'DIV' and
trim(R.DIV_ID) = UPPER(trim(D.DIV_ID))
union all
select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'RG_DIV' and
trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG)) and
trim(R.DIV_ID) = UPPER(trim(D.DIV_ID))
union all
select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'CLUS' and
trim(R.CLUS_ID) = UPPER(trim(D.CLUS_ID))
union all
select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'RG_CLUS' and
trim(R.REGION) = UPPER(trim(D.CHRGBACK_REG)) and
trim(R.CLUS_ID) = UPPER(trim(D.CLUS_ID))
union all
select U.BO_ID BO_ID, UPPER(trim(D.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R, CUST_DEPT_ROLL_UP_TBL D
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'PROD_LN' and
trim(R.PROD_LN_ID) = UPPER(trim(D.PROD_LN_ID))
union all
select U.BO_ID BO_ID, UPPER(trim(R.DEPT_ID)) DEPT_ID
from CUST_BO_USERS U, CUST_BO_ROLES R
where U.ROLE_NAME = R.ROLE_NAME and
R.ROLE_LEVEL = 'DEPT') Q
```
with the goal of removing the dependency on the ROLE\_LEVEL column.
The execution plan for v\_test is significantly lower than v\_bo\_secured\_detail for simple
```
select * from <view> where bo_id='value'
```
queries. And is significantly lower when used in a real world query
```
select CT_REPORT.RPT_KEY,
CT_REPORT_ENTRY.RPE_KEY,
CT_REPORT_ENTRY.CUSTOM16,
Exp_Sub_Type.value,
min(CT_REPORT_PAYMENT_CONF.PAY_DATE),
CT_REPORT.PAID_DATE
from CT_REPORT,
<VIEW> SD,
CT_REPORT_ENTRY,
CT_LIST_ITEM_LANG Exp_Sub_Type,
CT_REPORT_PAYMENT_CONF,
CT_STATUS_LANG Payment_Status
where (CT_REPORT_ENTRY.RPT_KEY = CT_REPORT.RPT_KEY) and
(Payment_Status.STAT_KEY = CT_REPORT.PAY_KEY) and
(Exp_Sub_Type.LI_KEY = CT_REPORT_ENTRY.CUSTOM9 and Exp_Sub_Type.LANG_CODE = 'en') and
(CT_REPORT.RPT_KEY = CT_REPORT_PAYMENT_CONF.RPT_KEY) and
(SD.BO_ID = 'JZHU9') and
(SD.DEPT_ID = UPPER(CT_REPORT_ENTRY.CUSTOM5)) and
(Payment_Status.name = 'Payment Confirmed' and (Payment_Status.LANG_CODE = 'en') and
CT_REPORT.PAID_DATE > to_date('01/01/2008', 'mm/dd/yyyy') and Exp_Sub_Type.value != 'Korea')
group by CT_REPORT.RPT_KEY,
CT_REPORT_ENTRY.RPE_KEY,
CT_REPORT_ENTRY.CUSTOM16,
Exp_Sub_Type.value,
CT_REPORT.PAID_DATE
```
The execution times are WILDLY different. The v\_test view taking 15 hours, and the v\_bo\_secured\_detail taking a few seconds.
---
**Thank you all who responded**
This is one to remember for me. The places where the theory and mathematics of the expressions meets the reality of hardware based execution. Ouch. | As [the Oracle documentation says](http://download.oracle.com/docs/cd/A87860_01/doc/server.817/a76965/c20a_opt.htm#16287), the cost is the estimated cost relative to a particular execution plan. When you tweak the query, the particular execution plan that costs are calculated relative to can change. Sometimes dramatically.
The problem with v\_test's performance is that Oracle can think of no way to execute it other than performing a nested loop, for each cust\_bo\_roles, scan all of cust\_dept\_roll\_up\_tbl to find a match. If the table are of size n and m, this takes n\*m time, which is slow for large tables. By contrast v\_bo\_secured\_detail is set up so that it is a series of queries, each of which can be done through some other mechanism. (Oracle has a number it may use, including using an index, building a hash on the fly, or sorting the datasets and merging them. These operations are all O(n\*log(n)) or better.) A small series of fast queries is fast.
As painful as it is, if you want this query to be fast then you need to break it out like the previous query did. |
102,514 | <p>I'm trying to create the IDL for the IConverterSession interface and I'm confused by the definition of the <a href="http://msdn.microsoft.com/en-us/library/bb905204.aspx" rel="nofollow noreferrer">MIMETOMAPI</a> method. It specifies the <code>LPMESSAGE pmsg</code> parameter as [out] yet the comments state its the pointer to the MAPI message to be loaded.</p>
<p>Its unclear to me whether the functions allocates the MAPI message object and sets the pointer in which case shouldn't it be a pointer to a pointer of MESSAGE? OR is the calling code expected to have instanced the message object already in which case why is marked [out] and not [in]?</p>
<p>Utlitmately this interface is to be consumed from VB6 code so it will either have to be [in] or [in, out] but I do need to know whether in the the IDL I used:-</p>
<pre><code>[in] IMessage pmsg*
</code></pre>
<p>OR</p>
<pre><code>[in, out] IMessage pmsg**
</code></pre>
| [
{
"answer_id": 103283,
"author": "Alejandro Bologna",
"author_id": 9263,
"author_profile": "https://Stackoverflow.com/users/9263",
"pm_score": 3,
"selected": true,
"text": "<p>I think in this case the documentation is misleading when it marks the parameter as [out]. You have to pass a valid LPMESSAGE to the method, and that's why is not a double pointer. So i would go with [in] on your idl definition.</p>\n"
},
{
"answer_id": 8418953,
"author": "Martyn Davis",
"author_id": 305351,
"author_profile": "https://Stackoverflow.com/users/305351",
"pm_score": 1,
"selected": false,
"text": "<p>See MAPIMime.h from MFCMapi source (http://mfcmapi.codeplex.com/) as a definitive source.</p>\n"
},
{
"answer_id": 57829162,
"author": "LindaLu-MSFT",
"author_id": 8447620,
"author_profile": "https://Stackoverflow.com/users/8447620",
"pm_score": 0,
"selected": false,
"text": "<p>The correct documentation can be found here: <a href=\"https://learn.microsoft.com/en-us/office/client-developer/outlook/mapi/iconvertersession-mimetomapi\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/office/client-developer/outlook/mapi/iconvertersession-mimetomapi</a>. The caller must supply a message for the API to fill out, so the object must go [in]. </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17516/"
]
| I'm trying to create the IDL for the IConverterSession interface and I'm confused by the definition of the [MIMETOMAPI](http://msdn.microsoft.com/en-us/library/bb905204.aspx) method. It specifies the `LPMESSAGE pmsg` parameter as [out] yet the comments state its the pointer to the MAPI message to be loaded.
Its unclear to me whether the functions allocates the MAPI message object and sets the pointer in which case shouldn't it be a pointer to a pointer of MESSAGE? OR is the calling code expected to have instanced the message object already in which case why is marked [out] and not [in]?
Utlitmately this interface is to be consumed from VB6 code so it will either have to be [in] or [in, out] but I do need to know whether in the the IDL I used:-
```
[in] IMessage pmsg*
```
OR
```
[in, out] IMessage pmsg**
``` | I think in this case the documentation is misleading when it marks the parameter as [out]. You have to pass a valid LPMESSAGE to the method, and that's why is not a double pointer. So i would go with [in] on your idl definition. |
102,521 | <p>I know that <a href="http://wiki.lessthandot.com/index.php/How_to_find_the_first_and_last_days_in_years,_months_etc" rel="nofollow noreferrer">Sql Server has some handy built-in quarterly</a> stuff, but what about the .Net native <a href="http://msdn.microsoft.com/en-us/library/system.datetime_members(VS.80).aspx" rel="nofollow noreferrer">DateTime</a> object? What is the best way to add, subtract, and traverse quarters?</p>
<p>Is it a <em>bad thing</em>™ to use the VB-specific <a href="http://msdn.microsoft.com/en-us/library/hcxe65wz(VS.80).aspx" rel="nofollow noreferrer">DateAdd()</a> function? e.g.:</p>
<pre><code>Dim nextQuarter As DateTime = DateAdd(DateInterval.Quarter, 1, DateTime.Now)
</code></pre>
<p>Edit:
Expanding @bslorence's function:</p>
<pre><code>Public Shared Function AddQuarters(ByVal originalDate As DateTime, ByVal quarters As Integer) As Datetime
Return originalDate.AddMonths(quarters * 3)
End Function
</code></pre>
<p>Expanding @Matt's function:</p>
<pre><code>Public Shared Function GetQuarter(ByVal fromDate As DateTime) As Integer
Return ((fromDate.Month - 1) \ 3) + 1
End Function
</code></pre>
<p>Edit: here's a couple more functions that were handy:</p>
<pre><code>Public Shared Function GetFirstDayOfQuarter(ByVal originalDate As DateTime) As DateTime
Return AddQuarters(New DateTime(originalDate.Year, 1, 1), GetQuarter(originalDate) - 1)
End Function
Public Shared Function GetLastDayOfQuarter(ByVal originalDate As DateTime) As DateTime
Return AddQuarters(New DateTime(originalDate.Year, 1, 1), GetQuarter(originalDate)).AddDays(-1)
End Function
</code></pre>
| [
{
"answer_id": 102712,
"author": "Ben Dunlap",
"author_id": 8722,
"author_profile": "https://Stackoverflow.com/users/8722",
"pm_score": 2,
"selected": false,
"text": "<p>How about this:</p>\n\n<pre><code>Dim nextQuarter As DateTime = DateTime.Now.AddMonths(3);\n</code></pre>\n"
},
{
"answer_id": 102834,
"author": "Matt Blaine",
"author_id": 16272,
"author_profile": "https://Stackoverflow.com/users/16272",
"pm_score": 4,
"selected": true,
"text": "<p>I know you can calculate the quarter of a date by:</p>\n\n<pre><code>Dim quarter As Integer = (someDate.Month - 1) \\ 3 + 1\n</code></pre>\n\n<p>If you're using Visual Studio 2008, you could try bolting additional functionality on to the DateTime class by taking a look at <a href=\"http://msdn.microsoft.com/en-us/library/bb384936.aspx\" rel=\"noreferrer\">Extension Methods</a>.</p>\n"
},
{
"answer_id": 103111,
"author": "Dan B",
"author_id": 18994,
"author_profile": "https://Stackoverflow.com/users/18994",
"pm_score": 1,
"selected": false,
"text": "<p>One thing to remeber, not all companies end their quarters on the last day of a month. </p>\n"
},
{
"answer_id": 14160623,
"author": "Brian Schmidt",
"author_id": 1902195,
"author_profile": "https://Stackoverflow.com/users/1902195",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Public Function GetLastQuarterStart() As Date\n\n GetLastQuarterStart = DateAdd(DateInterval.Quarter, -1, DateTime.Now).ToString(\"MM/01/yyyy\")\n\nEnd Function\n\nPublic Function GetLastQuarterEnd() As Date\n\n Dim LastQuarterStart As Date = DateAdd(DateInterval.Quarter, -1, DateTime.Now).ToString(\"MM/01/yyyy\")\n Dim MM As String = LastQuarterStart.Month\n Dim DD As Integer = 0\n Dim YYYY As String = LastQuarterStart.Year\n Select Case MM\n Case \"01\", \"03\", \"05\", \"07\", \"08\", \"10\", \"12\"\n DD = 31\n Case \"02\"\n Select Case YYYY\n Case \"2012\", \"2016\", \"2020\", \"2024\", \"2028\", \"2032\"\n DD = 29\n Case Else\n DD = 28\n End Select\n Case Else\n DD = 30\n End Select\n\n Dim LastQuarterEnd As Date = DateAdd(DateInterval.Month, 2, LastQuarterStart)\n\n MM = LastQuarterEnd.Month\n YYYY = LastQuarterEnd.Year\n\n Return String.Format(\"{0}/{1}/{2}\", MM, DD, YYYY)\n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 21579910,
"author": "Jamie Barker",
"author_id": 2117156,
"author_profile": "https://Stackoverflow.com/users/2117156",
"pm_score": 1,
"selected": false,
"text": "<p>Expanding on Matt Blaine's Answer:</p>\n\n<pre><code>Dim intQuarter As Integer = Math.Ceiling(MyDate.Month / 3)\n</code></pre>\n\n<p>Not sure if this would add speed benefits or not but it looks cleaner IMO</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
]
| I know that [Sql Server has some handy built-in quarterly](http://wiki.lessthandot.com/index.php/How_to_find_the_first_and_last_days_in_years,_months_etc) stuff, but what about the .Net native [DateTime](http://msdn.microsoft.com/en-us/library/system.datetime_members(VS.80).aspx) object? What is the best way to add, subtract, and traverse quarters?
Is it a *bad thing*™ to use the VB-specific [DateAdd()](http://msdn.microsoft.com/en-us/library/hcxe65wz(VS.80).aspx) function? e.g.:
```
Dim nextQuarter As DateTime = DateAdd(DateInterval.Quarter, 1, DateTime.Now)
```
Edit:
Expanding @bslorence's function:
```
Public Shared Function AddQuarters(ByVal originalDate As DateTime, ByVal quarters As Integer) As Datetime
Return originalDate.AddMonths(quarters * 3)
End Function
```
Expanding @Matt's function:
```
Public Shared Function GetQuarter(ByVal fromDate As DateTime) As Integer
Return ((fromDate.Month - 1) \ 3) + 1
End Function
```
Edit: here's a couple more functions that were handy:
```
Public Shared Function GetFirstDayOfQuarter(ByVal originalDate As DateTime) As DateTime
Return AddQuarters(New DateTime(originalDate.Year, 1, 1), GetQuarter(originalDate) - 1)
End Function
Public Shared Function GetLastDayOfQuarter(ByVal originalDate As DateTime) As DateTime
Return AddQuarters(New DateTime(originalDate.Year, 1, 1), GetQuarter(originalDate)).AddDays(-1)
End Function
``` | I know you can calculate the quarter of a date by:
```
Dim quarter As Integer = (someDate.Month - 1) \ 3 + 1
```
If you're using Visual Studio 2008, you could try bolting additional functionality on to the DateTime class by taking a look at [Extension Methods](http://msdn.microsoft.com/en-us/library/bb384936.aspx). |
102,531 | <p>Within an XSLT document, is it possible to loop over a set of files in the current directory?</p>
<p>I have a situation where I have a directory full of xml files that need some analysis done to generate a report. I have my stylesheet operating on a single document fine, but I'd like to extend that without going to another tool to merge the xml documents. </p>
<p>I was thinking along these lines:</p>
<pre><code><xsl:for-each select="{IO Selector Here}">
<xsl:variable select="document(@url)" name="contents" />
<!--More stuff here-->
</xsl:for-each>
</code></pre>
| [
{
"answer_id": 102944,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think XSL is set up to work that way: it's designed to be used by something else on one or more documents, and the something else would be responsible for finding files to which the XSLT should be applied. </p>\n\n<p>If you had one main document and a fixed set of supporting documents, you could possibly use the <a href=\"http://www.w3schools.com/xsl/func_document.asp\" rel=\"nofollow noreferrer\"><code>document()</code> function</a> to return specific nodes and/or values, but I suspect your case is different. </p>\n"
},
{
"answer_id": 103320,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 0,
"selected": false,
"text": "<p>From within XSLT I think this will not be possible. </p>\n\n<p>You could pass in all the XML file names to an <xsl:param name=\"files\" /> as a comma separated list and loop over it using recursion and substring-before() and substring-after().</p>\n"
},
{
"answer_id": 103351,
"author": "SteveDonie",
"author_id": 11051,
"author_profile": "https://Stackoverflow.com/users/11051",
"pm_score": 0,
"selected": false,
"text": "<p>I have a command-line tool that could be used for this - it uses the XSLT processor built into Ant (the java build tool) to process input + transform into output. Would be easy to wrap with a batch file for loop.</p>\n\n<p>svn://donie.homeip.net/public/tools</p>\n"
},
{
"answer_id": 104760,
"author": "JeniT",
"author_id": 6739,
"author_profile": "https://Stackoverflow.com/users/6739",
"pm_score": 4,
"selected": true,
"text": "<p>In XSLT 2.0, and with Saxon, you can do this with the <code>collection()</code> function:</p>\n\n<pre><code><xsl:for-each select=\"file:///path/to/directory\">\n <!-- process the documents -->\n</xsl:for-each>\n</code></pre>\n\n<p>See <a href=\"http://www.saxonica.com/documentation/sourcedocs/collections.html\" rel=\"noreferrer\" title=\"Saxonica: XSLT and XQuery Processing: Collections\">http://www.saxonica.com/documentation/sourcedocs/collections.html</a> for more details.</p>\n\n<p>In XSLT 1.0, you have to create an index that lists the documents you want to process with a separate tool. Your environment may provide such a tool; for example, Cocoon has a <a href=\"http://cocoon.apache.org/2.1/userdocs/directory-generator.html\" rel=\"noreferrer\">Directory Generator</a> that creates such an index. But without knowing what your environment is, it's hard to know what to recommend.</p>\n"
},
{
"answer_id": 104772,
"author": "Antosha",
"author_id": 13909,
"author_profile": "https://Stackoverflow.com/users/13909",
"pm_score": 2,
"selected": false,
"text": "<p>As others said, you cannot do it in a platform-independent way. In .NET world, you could create a custom XmlResolver so that document('dir://c:/foo/') would return the list of files in the 'c:\\foo' directory in an arbitrary format you wish. See the following links for more information on custom XmlResolver's:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb669135.aspx\" rel=\"nofollow noreferrer\">Customizing the XmlUrlResolver Class</a><br/>\n<a href=\"http://www.tkachenko.com/blog/archives/000105.html\" rel=\"nofollow noreferrer\">The power of XmlResolver</a></p>\n\n<p>Also you may resort to using scripts (like the <a href=\"http://msdn.microsoft.com/en-us/library/ms256042.aspx\" rel=\"nofollow noreferrer\">msxsl:script</a> element) or extensions in your XSLT stylesheet.</p>\n\n<p>All these approaches will make your XSLT code unportable to other platforms.</p>\n"
},
{
"answer_id": 115207,
"author": "Simon Keep",
"author_id": 1127460,
"author_profile": "https://Stackoverflow.com/users/1127460",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using .Net you can use XsltExtension to make calls from your XSLT document to methods in your .net class. The method could then return nodesets back to your XSLT. So your method could handle the file IO part.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1672/"
]
| Within an XSLT document, is it possible to loop over a set of files in the current directory?
I have a situation where I have a directory full of xml files that need some analysis done to generate a report. I have my stylesheet operating on a single document fine, but I'd like to extend that without going to another tool to merge the xml documents.
I was thinking along these lines:
```
<xsl:for-each select="{IO Selector Here}">
<xsl:variable select="document(@url)" name="contents" />
<!--More stuff here-->
</xsl:for-each>
``` | In XSLT 2.0, and with Saxon, you can do this with the `collection()` function:
```
<xsl:for-each select="file:///path/to/directory">
<!-- process the documents -->
</xsl:for-each>
```
See [http://www.saxonica.com/documentation/sourcedocs/collections.html](http://www.saxonica.com/documentation/sourcedocs/collections.html "Saxonica: XSLT and XQuery Processing: Collections") for more details.
In XSLT 1.0, you have to create an index that lists the documents you want to process with a separate tool. Your environment may provide such a tool; for example, Cocoon has a [Directory Generator](http://cocoon.apache.org/2.1/userdocs/directory-generator.html) that creates such an index. But without knowing what your environment is, it's hard to know what to recommend. |
102,534 | <p>Here is the situation: I have 2 pages.</p>
<p>What I want is to have a number of text links(<code><a href=""></code>) on page 1 all directing to page 2, but I want each link to send a different value.</p>
<p>On page 2 I want to show that value like this: </p>
<blockquote>
<p>Hello you clicked {value}</p>
</blockquote>
<p>Another point to take into account is that I can't use any php in this situation, just html.</p>
| [
{
"answer_id": 102564,
"author": "Haabda",
"author_id": 16292,
"author_profile": "https://Stackoverflow.com/users/16292",
"pm_score": 0,
"selected": false,
"text": "<p>You might be able to accomplish this using HTML Anchors.</p>\n\n<p><a href=\"http://www.w3schools.com/HTML/html_links.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/HTML/html_links.asp</a></p>\n"
},
{
"answer_id": 102565,
"author": "Craig",
"author_id": 7861,
"author_profile": "https://Stackoverflow.com/users/7861",
"pm_score": 2,
"selected": false,
"text": "<p>Can you use any scripting? Something like Javascript. If you can, then pass the values along in the query string (just add a \"?ValueName=Value\") to the end of your links. Then on the target page retrieve the query string value. The following site shows how to parse it out: <a href=\"http://adamv.com/dev/javascript/querystring\" rel=\"nofollow noreferrer\">Parsing the Query String</a>.</p>\n\n<p>Here's the Javascript code you would need:</p>\n\n<pre><code>var qs = new Querystring();\nvar v1 = qs.get(\"ValueName\")\n</code></pre>\n\n<p>From there you should be able to work with the passed value.</p>\n"
},
{
"answer_id": 102577,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 1,
"selected": false,
"text": "<p>Javascript can get it. Say, you're trying to get the querystring value from this url: <a href=\"http://foo.com/default.html?foo=bar\" rel=\"nofollow noreferrer\">http://foo.com/default.html?foo=bar</a></p>\n\n<pre><code>var tabvalue = getQueryVariable(\"foo\"); \n\nfunction getQueryVariable(variable)\n{\nvar query = window.location.search.substring(1);\nvar vars = query.split(\"&\");\nfor (var i=0;i<vars.length;i++)\n{\nvar pair = vars[i].split(\"=\");\nif (pair[0] == variable)\n{\nreturn pair[1];\n}\n}\n}\n</code></pre>\n\n<p>** Not 100% certain if my JS code here is correct, as I didn't test it. </p>\n"
},
{
"answer_id": 102586,
"author": "yann.kmm",
"author_id": 15780,
"author_profile": "https://Stackoverflow.com/users/15780",
"pm_score": 0,
"selected": false,
"text": "<p>Append your data to the HREF tag of your links ad use javascript on second page to parse the URL and display wathever you want</p>\n\n<p><a href=\"http://java-programming.suite101.com/article.cfm/how_to_get_url_parts_in_javascript\" rel=\"nofollow noreferrer\">http://java-programming.suite101.com/article.cfm/how_to_get_url_parts_in_javascript</a></p>\n\n<p>It's not clean, but it should work.</p>\n"
},
{
"answer_id": 102651,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Use <strong>document.location.search</strong> and <strong>split()</strong></p>\n\n<pre><code>http://www.example.com/example.html?argument=value\n\nvar queryString = document.location.search();\nvar parts = queryString.split('=');\ndocument.write(parts[0]); // The argument name\ndocument.write(parts[1]); // The value\n</code></pre>\n\n<p>Hope it helps</p>\n"
},
{
"answer_id": 102660,
"author": "jelmer",
"author_id": 16499,
"author_profile": "https://Stackoverflow.com/users/16499",
"pm_score": 0,
"selected": false,
"text": "<p>Well this is pretty basic with javascript, but if you want more of this and more advanced stuff you should really look into php for instance. Using php it's easy to get variables from one page to another, here's an example: </p>\n\n<p>the url: </p>\n\n<pre><code>localhost/index.php?myvar=Hello World\n</code></pre>\n\n<p>You can then access myvar in index.php using this bit of code:</p>\n\n<pre><code>$myvar =$_GET['myvar'];\n</code></pre>\n"
},
{
"answer_id": 103796,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Ok thanks for all your replies, i'll take a look if i can find a way to use the scripts.\nIt's really annoying since i have to work around a CMS, because in the CMS, all pages are created with a Wysiwyg editor which tend to filter out unrecognized tags/scripts.</p>\n\n<p>Edit: Ok it seems that the damn wysiwyg editor only recognizes html tags... (as expected)</p>\n"
},
{
"answer_id": 23451965,
"author": "user3555228",
"author_id": 3555228,
"author_profile": "https://Stackoverflow.com/users/3555228",
"pm_score": 0,
"selected": false,
"text": "<p>Using php</p>\n\n<pre><code><?\n\n$passthis = \"See you on the other side\";\n\necho '<form action=\"whereyouwantittogo.php\" target=\"_blank\" method=\"post\">'.\n'<input type=\"text\" name=\"passthis1\" value=\"'.\n$passthis .' \" /> '.\n'<button type=\"Submit\" value=\"Submit\" >Submit</button>'.\n'</form>';\n\n?>\n</code></pre>\n\n<p>The script for the page you would like to pass the info to:</p>\n\n<pre><code><?\n\n$thispassed = $_POST['passthis1'];\n\necho '<textarea>'. $thispassed .'</textarea>';\necho $thispassed;\n\n?>\n</code></pre>\n\n<p>Use this two codes on seperate pages with the latter at whereyouwantittogo.php and you should be in business.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Here is the situation: I have 2 pages.
What I want is to have a number of text links(`<a href="">`) on page 1 all directing to page 2, but I want each link to send a different value.
On page 2 I want to show that value like this:
>
> Hello you clicked {value}
>
>
>
Another point to take into account is that I can't use any php in this situation, just html. | Can you use any scripting? Something like Javascript. If you can, then pass the values along in the query string (just add a "?ValueName=Value") to the end of your links. Then on the target page retrieve the query string value. The following site shows how to parse it out: [Parsing the Query String](http://adamv.com/dev/javascript/querystring).
Here's the Javascript code you would need:
```
var qs = new Querystring();
var v1 = qs.get("ValueName")
```
From there you should be able to work with the passed value. |
102,535 | <p>I'm starting to learn Python and I've come across generator functions, those that have a yield statement in them. I want to know what types of problems that these functions are really good at solving.</p>
| [
{
"answer_id": 102612,
"author": "Nickolay",
"author_id": 1026,
"author_profile": "https://Stackoverflow.com/users/1026",
"pm_score": 5,
"selected": false,
"text": "<p>See the \"Motivation\" section in <a href=\"http://www.python.org/dev/peps/pep-0255/\" rel=\"noreferrer\">PEP 255</a>.</p>\n\n<p>A non-obvious use of generators is creating interruptible functions, which lets you do things like update UI or run several jobs \"simultaneously\" (interleaved, actually) while not using threads.</p>\n"
},
{
"answer_id": 102632,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 9,
"selected": true,
"text": "<p>Generators give you lazy evaluation. You use them by iterating over them, either explicitly with 'for' or implicitly by passing it to any function or construct that iterates. You can think of generators as returning multiple items, as if they return a list, but instead of returning them all at once they return them one-by-one, and the generator function is paused until the next item is requested.</p>\n\n<p>Generators are good for calculating large sets of results (in particular calculations involving loops themselves) where you don't know if you are going to need all results, or where you don't want to allocate the memory for all results at the same time. Or for situations where the generator uses <em>another</em> generator, or consumes some other resource, and it's more convenient if that happened as late as possible.</p>\n\n<p>Another use for generators (that is really the same) is to replace callbacks with iteration. In some situations you want a function to do a lot of work and occasionally report back to the caller. Traditionally you'd use a callback function for this. You pass this callback to the work-function and it would periodically call this callback. The generator approach is that the work-function (now a generator) knows nothing about the callback, and merely yields whenever it wants to report something. The caller, instead of writing a separate callback and passing that to the work-function, does all the reporting work in a little 'for' loop around the generator.</p>\n\n<p>For example, say you wrote a 'filesystem search' program. You could perform the search in its entirety, collect the results and then display them one at a time. All of the results would have to be collected before you showed the first, and all of the results would be in memory at the same time. Or you could display the results while you find them, which would be more memory efficient and much friendlier towards the user. The latter could be done by passing the result-printing function to the filesystem-search function, or it could be done by just making the search function a generator and iterating over the result.</p>\n\n<p>If you want to see an example of the latter two approaches, see os.path.walk() (the old filesystem-walking function with callback) and os.walk() (the new filesystem-walking generator.) Of course, if you really wanted to collect all results in a list, the generator approach is trivial to convert to the big-list approach:</p>\n\n<pre><code>big_list = list(the_generator)\n</code></pre>\n"
},
{
"answer_id": 102633,
"author": "MvdD",
"author_id": 18044,
"author_profile": "https://Stackoverflow.com/users/18044",
"pm_score": 3,
"selected": false,
"text": "<p>Basically avoiding call-back functions when iterating over input maintaining state.</p>\n\n<p>See <a href=\"http://www.python.org/dev/peps/pep-0255/\" rel=\"noreferrer\">here</a> and <a href=\"http://www.dabeaz.com/generators/index.html\" rel=\"noreferrer\">here</a> for an overview of what can be done using generators.</p>\n"
},
{
"answer_id": 102634,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 7,
"selected": false,
"text": "<p>One of the reasons to use generator is to make the solution clearer for some kind of solutions.</p>\n\n<p>The other is to treat results one at a time, avoiding building huge lists of results that you would process separated anyway. </p>\n\n<p>If you have a fibonacci-up-to-n function like this:</p>\n\n<pre><code># function version\ndef fibon(n):\n a = b = 1\n result = []\n for i in xrange(n):\n result.append(a)\n a, b = b, a + b\n return result\n</code></pre>\n\n<p>You can more easily write the function as this:</p>\n\n<pre><code># generator version\ndef fibon(n):\n a = b = 1\n for i in xrange(n):\n yield a\n a, b = b, a + b\n</code></pre>\n\n<p>The function is clearer. And if you use the function like this:</p>\n\n<pre><code>for x in fibon(1000000):\n print x,\n</code></pre>\n\n<p>in this example, if using the generator version, the whole 1000000 item list won't be created at all, just one value at a time. That would not be the case when using the list version, where a list would be created first.</p>\n"
},
{
"answer_id": 102667,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 4,
"selected": false,
"text": "<p>My favorite uses are \"filter\" and \"reduce\" operations.</p>\n\n<p>Let's say we're reading a file, and only want the lines which begin with \"##\".</p>\n\n<pre><code>def filter2sharps( aSequence ):\n for l in aSequence:\n if l.startswith(\"##\"):\n yield l\n</code></pre>\n\n<p>We can then use the generator function in a proper loop</p>\n\n<pre><code>source= file( ... )\nfor line in filter2sharps( source.readlines() ):\n print line\nsource.close()\n</code></pre>\n\n<p>The reduce example is similar. Let's say we have a file where we need to locate blocks of <code><Location>...</Location></code> lines. [Not HTML tags, but lines that happen to look tag-like.]</p>\n\n<pre><code>def reduceLocation( aSequence ):\n keep= False\n block= None\n for line in aSequence:\n if line.startswith(\"</Location\"):\n block.append( line )\n yield block\n block= None\n keep= False\n elif line.startsWith(\"<Location\"):\n block= [ line ]\n keep= True\n elif keep:\n block.append( line )\n else:\n pass\n if block is not None:\n yield block # A partial block, icky\n</code></pre>\n\n<p>Again, we can use this generator in a proper for loop.</p>\n\n<pre><code>source = file( ... )\nfor b in reduceLocation( source.readlines() ):\n print b\nsource.close()\n</code></pre>\n\n<p>The idea is that a generator function allows us to filter or reduce a sequence, producing a another sequence one value at a time.</p>\n"
},
{
"answer_id": 102674,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 5,
"selected": false,
"text": "<p>Buffering. When it is efficient to fetch data in large chunks, but process it in small chunks, then a generator might help:</p>\n\n<pre><code>def bufferedFetch():\n while True:\n buffer = getBigChunkOfData()\n # insert some code to break on 'end of data'\n for i in buffer: \n yield i\n</code></pre>\n\n<p>The above lets you easily separate buffering from processing. The consumer function can now just get the values one by one without worrying about buffering.</p>\n"
},
{
"answer_id": 102679,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 2,
"selected": false,
"text": "<p>Piles of stuff. Any time you want to generate a sequence of items, but don't want to have to 'materialize' them all into a list at once. For example, you could have a simple generator that returns prime numbers:</p>\n\n<pre><code>def primes():\n primes_found = set()\n primes_found.add(2)\n yield 2\n for i in itertools.count(1):\n candidate = i * 2 + 1\n if not all(candidate % prime for prime in primes_found):\n primes_found.add(candidate)\n yield candidate\n</code></pre>\n\n<p>You could then use that to generate the products of subsequent primes:</p>\n\n<pre><code>def prime_products():\n primeiter = primes()\n prev = primeiter.next()\n for prime in primeiter:\n yield prime * prev\n prev = prime\n</code></pre>\n\n<p>These are fairly trivial examples, but you can see how it can be useful for processing large (potentially infinite!) datasets without generating them in advance, which is only one of the more obvious uses.</p>\n"
},
{
"answer_id": 102682,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 4,
"selected": false,
"text": "<p>The simple explanation:\nConsider a <code>for</code> statement</p>\n\n<pre><code>for item in iterable:\n do_stuff()\n</code></pre>\n\n<p>A lot of the time, all the items in <code>iterable</code> doesn't need to be there from the start, but can be generated on the fly as they're required. This can be a lot more efficient in both </p>\n\n<ul>\n<li>space (you never need to store all the items simultaneously) and </li>\n<li>time (the iteration may finish before all the items are needed).</li>\n</ul>\n\n<p>Other times, you don't even know all the items ahead of time. For example:</p>\n\n<pre><code>for command in user_input():\n do_stuff_with(command)\n</code></pre>\n\n<p>You have no way of knowing all the user's commands beforehand, but you can use a nice loop like this if you have a generator handing you commands:</p>\n\n<pre><code>def user_input():\n while True:\n wait_for_command()\n cmd = get_command()\n yield cmd\n</code></pre>\n\n<p>With generators you can also have iteration over infinite sequences, which is of course not possible when iterating over containers.</p>\n"
},
{
"answer_id": 102701,
"author": "Brian",
"author_id": 1750627,
"author_profile": "https://Stackoverflow.com/users/1750627",
"pm_score": 2,
"selected": false,
"text": "<p>I use generators when our web server is acting as a proxy:</p>\n\n<ol>\n<li>The client requests a proxied url from the server</li>\n<li>The server begins to load the target url</li>\n<li>The server yields to return the results to the client as soon as it gets them</li>\n</ol>\n"
},
{
"answer_id": 740763,
"author": "Andz",
"author_id": 89848,
"author_profile": "https://Stackoverflow.com/users/89848",
"pm_score": 5,
"selected": false,
"text": "<p>I have found that generators are very helpful in cleaning up your code and by giving you a very unique way to encapsulate and modularize code. In a situation where you need something to constantly spit out values based on its own internal processing and when that something needs to be called from anywhere in your code (and not just within a loop or a block for example), generators are <em>the</em> feature to use.</p>\n\n<p>An abstract example would be a Fibonacci number generator that does not live within a loop and when it is called from anywhere will always return the next number in the sequence:</p>\n\n<pre><code>def fib():\n first = 0\n second = 1\n yield first\n yield second\n\n while 1:\n next = first + second\n yield next\n first = second\n second = next\n\nfibgen1 = fib()\nfibgen2 = fib()\n</code></pre>\n\n<p>Now you have two Fibonacci number generator objects which you can call from anywhere in your code and they will always return ever larger Fibonacci numbers in sequence as follows:</p>\n\n<pre><code>>>> fibgen1.next(); fibgen1.next(); fibgen1.next(); fibgen1.next()\n0\n1\n1\n2\n>>> fibgen2.next(); fibgen2.next()\n0\n1\n>>> fibgen1.next(); fibgen1.next()\n3\n5\n</code></pre>\n\n<p>The lovely thing about generators is that they encapsulate state without having to go through the hoops of creating objects. One way of thinking about them is as \"functions\" which remember their internal state.</p>\n\n<p>I got the Fibonacci example from <em><a href=\"http://www.neotitans.com/resources/python/python-generators-tutorial.html\" rel=\"nofollow noreferrer\">Python Generators - What are they?</a></em> and with a little imagination, you can come up with a lot of other situations where generators make for a great alternative to <code>for</code> loops and other traditional iteration constructs.</p>\n"
},
{
"answer_id": 14394854,
"author": "Mirage",
"author_id": 767244,
"author_profile": "https://Stackoverflow.com/users/767244",
"pm_score": 6,
"selected": false,
"text": "<p>I find this explanation which clears my doubt. Because there is a possibility that person who don't know <code>Generators</code> also don't know about <code>yield</code></p>\n\n<p><strong>Return</strong></p>\n\n<p>The return statement is where all the local variables are destroyed and the resulting value is given back (returned) to the caller. Should the same function be called some time later, the function will get a fresh new set of variables.</p>\n\n<p><strong>Yield</strong></p>\n\n<p>But what if the local variables aren't thrown away when we exit a function? This implies that we can <code>resume the function</code> where we left off. This is where the concept of <code>generators</code> are introduced and the <code>yield</code> statement resumes where the <code>function</code> left off.</p>\n\n<pre><code> def generate_integers(N):\n for i in xrange(N):\n yield i\n</code></pre>\n\n<hr>\n\n<pre><code> In [1]: gen = generate_integers(3)\n In [2]: gen\n <generator object at 0x8117f90>\n In [3]: gen.next()\n 0\n In [4]: gen.next()\n 1\n In [5]: gen.next()\n</code></pre>\n\n<p>So that's the difference between <code>return</code> and <code>yield</code> statements in Python.</p>\n\n<p><strong>Yield statement is what makes a function a generator function.</strong></p>\n\n<p>So generators are a simple and powerful tool for creating iterators. They are written like regular functions, but they use the <code>yield</code> statement whenever they want to return data. Each time next() is called, the generator resumes where it left off (it remembers all the data values and which statement was last executed).</p>\n"
},
{
"answer_id": 23334878,
"author": "John Damen",
"author_id": 2829389,
"author_profile": "https://Stackoverflow.com/users/2829389",
"pm_score": 3,
"selected": false,
"text": "<p>Since the send method of a generator has not been mentioned, here is an example:</p>\n\n<pre><code>def test():\n for i in xrange(5):\n val = yield\n print(val)\n\nt = test()\n\n# Proceed to 'yield' statement\nnext(t)\n\n# Send value to yield\nt.send(1)\nt.send('2')\nt.send([3])\n</code></pre>\n\n<p>It shows the possibility to send a value to a running generator. A more advanced course on generators in the video below (including <code>yield</code> from explination, generators for parallel processing, escaping the recursion limit, etc.)</p>\n\n<p><a href=\"http://pyvideo.org/video/2575/generators-the-final-frontier\" rel=\"nofollow noreferrer\">David Beazley on generators at PyCon 2014</a></p>\n"
},
{
"answer_id": 23530101,
"author": "PrivateUser",
"author_id": 736037,
"author_profile": "https://Stackoverflow.com/users/736037",
"pm_score": 6,
"selected": false,
"text": "<h2>Real World Example</h2>\n\n<p>Let's say you have 100 million domains in your MySQL table, and you would like to update Alexa rank for each domain.</p>\n\n<p>First thing you need is to select your domain names from the database.</p>\n\n<p>Let's say your table name is <code>domains</code> and column name is <code>domain</code>.</p>\n\n<p>If you use <code>SELECT domain FROM domains</code> it's going to return 100 million rows which is going to consume lot of memory. So your server might crash.</p>\n\n<p>So you decided to run the program in batches. Let's say our batch size is 1000.</p>\n\n<p>In our first batch we will query the first 1000 rows, check Alexa rank for each domain and update the database row.</p>\n\n<p>In our second batch we will work on the next 1000 rows. In our third batch it will be from 2001 to 3000 and so on.</p>\n\n<p>Now we need a generator function which generates our batches.</p>\n\n<p>Here is our generator function:</p>\n\n<pre><code>def ResultGenerator(cursor, batchsize=1000):\n while True:\n results = cursor.fetchmany(batchsize)\n if not results:\n break\n for result in results:\n yield result\n</code></pre>\n\n<p>As you can see, our function keeps <code>yield</code>ing the results. If you used the keyword <code>return</code> instead of <code>yield</code>, then the whole function would be ended once it reached return.</p>\n\n<pre><code>return - returns only once\nyield - returns multiple times\n</code></pre>\n\n<p>If a function uses the keyword <code>yield</code> then it's a generator.</p>\n\n<p>Now you can iterate like this:</p>\n\n<pre><code>db = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"root\", db=\"domains\")\ncursor = db.cursor()\ncursor.execute(\"SELECT domain FROM domains\")\nfor result in ResultGenerator(cursor):\n doSomethingWith(result)\ndb.close()\n</code></pre>\n"
},
{
"answer_id": 26074771,
"author": "Pithikos",
"author_id": 474563,
"author_profile": "https://Stackoverflow.com/users/474563",
"pm_score": 4,
"selected": false,
"text": "<p>A practical example where you could make use of a generator is if you have some kind of shape and you want to iterate over its corners, edges or whatever. For my own project (source code <a href=\"https://github.com/Pithikos/python-rectangles\">here</a>) I had a rectangle:</p>\n\n<pre><code>class Rect():\n\n def __init__(self, x, y, width, height):\n self.l_top = (x, y)\n self.r_top = (x+width, y)\n self.r_bot = (x+width, y+height)\n self.l_bot = (x, y+height)\n\n def __iter__(self):\n yield self.l_top\n yield self.r_top\n yield self.r_bot\n yield self.l_bot\n</code></pre>\n\n<p>Now I can create a rectangle and loop over its corners:</p>\n\n<pre><code>myrect=Rect(50, 50, 100, 100)\nfor corner in myrect:\n print(corner)\n</code></pre>\n\n<p>Instead of <code>__iter__</code> you could have a method <code>iter_corners</code> and call that with <code>for corner in myrect.iter_corners()</code>. It's just more elegant to use <code>__iter__</code> since then we can use the class instance name directly in the <code>for</code> expression.</p>\n"
},
{
"answer_id": 29079078,
"author": "songololo",
"author_id": 1190200,
"author_profile": "https://Stackoverflow.com/users/1190200",
"pm_score": 3,
"selected": false,
"text": "<p>Some good answers here, however, I'd also recommend a complete read of the Python <a href=\"https://docs.python.org/dev/howto/functional.html\" rel=\"nofollow noreferrer\">Functional Programming tutorial</a> which helps explain some of the more potent use-cases of generators.</p>\n\n<ul>\n<li>Particularly interesting is that it is now possible to <a href=\"https://docs.python.org/dev/howto/functional.html#passing-values-into-a-generator\" rel=\"nofollow noreferrer\">update the yield variable from outside the generator function</a>, hence making it possible to create dynamic and interwoven coroutines with relatively little effort.</li>\n<li>Also see <a href=\"https://www.python.org/dev/peps/pep-0342/\" rel=\"nofollow noreferrer\">PEP 342: Coroutines via Enhanced Generators</a> for more information.</li>\n</ul>\n"
},
{
"answer_id": 46366711,
"author": "Sébastien Wieckowski",
"author_id": 8275142,
"author_profile": "https://Stackoverflow.com/users/8275142",
"pm_score": 0,
"selected": false,
"text": "<p>Also good for printing the prime numbers up to n:</p>\n\n<pre><code>def genprime(n=10):\n for num in range(3, n+1):\n for factor in range(2, num):\n if num%factor == 0:\n break\n else:\n yield(num)\n\nfor prime_num in genprime(100):\n print(prime_num)\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4834/"
]
| I'm starting to learn Python and I've come across generator functions, those that have a yield statement in them. I want to know what types of problems that these functions are really good at solving. | Generators give you lazy evaluation. You use them by iterating over them, either explicitly with 'for' or implicitly by passing it to any function or construct that iterates. You can think of generators as returning multiple items, as if they return a list, but instead of returning them all at once they return them one-by-one, and the generator function is paused until the next item is requested.
Generators are good for calculating large sets of results (in particular calculations involving loops themselves) where you don't know if you are going to need all results, or where you don't want to allocate the memory for all results at the same time. Or for situations where the generator uses *another* generator, or consumes some other resource, and it's more convenient if that happened as late as possible.
Another use for generators (that is really the same) is to replace callbacks with iteration. In some situations you want a function to do a lot of work and occasionally report back to the caller. Traditionally you'd use a callback function for this. You pass this callback to the work-function and it would periodically call this callback. The generator approach is that the work-function (now a generator) knows nothing about the callback, and merely yields whenever it wants to report something. The caller, instead of writing a separate callback and passing that to the work-function, does all the reporting work in a little 'for' loop around the generator.
For example, say you wrote a 'filesystem search' program. You could perform the search in its entirety, collect the results and then display them one at a time. All of the results would have to be collected before you showed the first, and all of the results would be in memory at the same time. Or you could display the results while you find them, which would be more memory efficient and much friendlier towards the user. The latter could be done by passing the result-printing function to the filesystem-search function, or it could be done by just making the search function a generator and iterating over the result.
If you want to see an example of the latter two approaches, see os.path.walk() (the old filesystem-walking function with callback) and os.walk() (the new filesystem-walking generator.) Of course, if you really wanted to collect all results in a list, the generator approach is trivial to convert to the big-list approach:
```
big_list = list(the_generator)
``` |
102,547 | <p>I am trying to add a new hello world service to amfphp, I am developing locally</p>
<pre><code><?php
/**
* First tutorial class
*/
class HelloWorld {
/**
* first simple method
* @returns a string saying 'Hello World!'
*/
function sayHello()
{
return "Hello World!";
}
}
?>
</code></pre>
<p>when exploring in the amfphp browser i get a
"TypeError: Error #1009: Cannot access a property or method of a null object reference."
need help...</p>
| [
{
"answer_id": 104013,
"author": "Antti",
"author_id": 6037,
"author_profile": "https://Stackoverflow.com/users/6037",
"pm_score": 0,
"selected": false,
"text": "<p>You're trying to access a variable/method that's null. The code here is fine so the problem is somewhere else..</p>\n"
},
{
"answer_id": 104232,
"author": "defmeta",
"author_id": 10875,
"author_profile": "https://Stackoverflow.com/users/10875",
"pm_score": 1,
"selected": false,
"text": "<p>Is that the entirety of your source code? I'm sure this isn't the problem but just in case, you <strong><em>are</em></strong> opening the <strong>?php</strong> tag right?</p>\n\n<p>Here's one of my simple service classes:</p>\n\n<pre><code><?php\n\nclass Products {\n\n public function __construct() {\n mysql_connect(\"localhost\", \"myuser\", \"mypass\");\n mysql_select_db(\"mydb\");\n }\n /** \n * Retrieves data\n * @returns data\n */\n function getProduct() {\n $sql = 'SELECT * FROM `content_type_product`'; \n return mysql_query($sql);\n }\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 152622,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 2,
"selected": false,
"text": "<p>I recommend <a href=\"http://www.charlesproxy.com/\" rel=\"nofollow noreferrer\">Charles</a> for solving this type of problem, this let's you see what's going across the wire. In your case it's likely something simple as a syntax error in the php file. PHP will output the error information into what the Service Browser expects to be amf-encoded data, wreaking havoc to any parsing it tries. Using Charles you can easily see this and fix it!</p>\n"
},
{
"answer_id": 249097,
"author": "Ben Throop",
"author_id": 27899,
"author_profile": "https://Stackoverflow.com/users/27899",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with grapefrukt... The browser really doesn't give you good information about PHP errors. Charles is a godsend for doing stuff over AMF and I recommend it highly. You'll get information about the request and the result along with any PHP error messages.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am trying to add a new hello world service to amfphp, I am developing locally
```
<?php
/**
* First tutorial class
*/
class HelloWorld {
/**
* first simple method
* @returns a string saying 'Hello World!'
*/
function sayHello()
{
return "Hello World!";
}
}
?>
```
when exploring in the amfphp browser i get a
"TypeError: Error #1009: Cannot access a property or method of a null object reference."
need help... | I recommend [Charles](http://www.charlesproxy.com/) for solving this type of problem, this let's you see what's going across the wire. In your case it's likely something simple as a syntax error in the php file. PHP will output the error information into what the Service Browser expects to be amf-encoded data, wreaking havoc to any parsing it tries. Using Charles you can easily see this and fix it! |
102,567 | <p>What's the best way to shut down the computer from a C# program?</p>
<p>I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net.</p>
| [
{
"answer_id": 102580,
"author": "RichS",
"author_id": 6247,
"author_profile": "https://Stackoverflow.com/users/6247",
"pm_score": 3,
"selected": false,
"text": "<p>You can launch the shutdown process:</p>\n\n<ul>\n<li><code>shutdown -s -t 0</code> - Shutdown</li>\n<li><code>shutdown -r -t 0</code> - Restart</li>\n</ul>\n"
},
{
"answer_id": 102583,
"author": "roomaroo",
"author_id": 3464,
"author_profile": "https://Stackoverflow.com/users/3464",
"pm_score": 7,
"selected": true,
"text": "<p>Taken from: <a href=\"http://www.geekpedia.com/code36_Shut-down-system-using-Csharp.html\" rel=\"noreferrer\">a Geekpedia post</a></p>\n\n<p>This method uses <a href=\"http://en.wikipedia.org/wiki/Windows_Management_Instrumentation\" rel=\"noreferrer\">WMI</a> to shutdown windows.</p>\n\n<p>You'll need to add a reference to System.Management to your project to use this.</p>\n\n<pre><code>using System.Management;\n\nvoid Shutdown()\n{\n ManagementBaseObject mboShutdown = null;\n ManagementClass mcWin32 = new ManagementClass(\"Win32_OperatingSystem\");\n mcWin32.Get();\n\n // You can't shutdown without security privileges\n mcWin32.Scope.Options.EnablePrivileges = true;\n ManagementBaseObject mboShutdownParams =\n mcWin32.GetMethodParameters(\"Win32Shutdown\");\n\n // Flag 1 means we want to shut down the system. Use \"2\" to reboot.\n mboShutdownParams[\"Flags\"] = \"1\";\n mboShutdownParams[\"Reserved\"] = \"0\";\n foreach (ManagementObject manObj in mcWin32.GetInstances())\n {\n mboShutdown = manObj.InvokeMethod(\"Win32Shutdown\", \n mboShutdownParams, null);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 102596,
"author": "roomaroo",
"author_id": 3464,
"author_profile": "https://Stackoverflow.com/users/3464",
"pm_score": 4,
"selected": false,
"text": "<p>Short and sweet. Call an external program:</p>\n\n<pre><code> using System.Diagnostics;\n\n void Shutdown()\n {\n Process.Start(\"shutdown.exe\", \"-s -t 00\");\n }\n</code></pre>\n\n<p>Note: This calls Windows' Shutdown.exe program, so it'll only work if that program is available.\nYou might have problems on Windows 2000 (where shutdown.exe is only available in the resource kit) or <a href=\"http://www.microsoft.com/windowsembedded/en-us/products/wexpe/default.mspx\" rel=\"noreferrer\">XP Embedded</a>.</p>\n"
},
{
"answer_id": 102598,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 5,
"selected": false,
"text": "<p>This thread provides the code necessary: <a href=\"http://bytes.com/forum/thread251367.html\" rel=\"noreferrer\">http://bytes.com/forum/thread251367.html</a></p>\n\n<p>but here's the relevant code:</p>\n\n<pre><code>using System.Runtime.InteropServices;\n\n[StructLayout(LayoutKind.Sequential, Pack=1)]\ninternal struct TokPriv1Luid\n{\n public int Count;\n public long Luid;\n public int Attr;\n}\n\n[DllImport(\"kernel32.dll\", ExactSpelling=true) ]\ninternal static extern IntPtr GetCurrentProcess();\n\n[DllImport(\"advapi32.dll\", ExactSpelling=true, SetLastError=true) ]\ninternal static extern bool OpenProcessToken( IntPtr h, int acc, ref IntPtr\nphtok );\n\n[DllImport(\"advapi32.dll\", SetLastError=true) ]\ninternal static extern bool LookupPrivilegeValue( string host, string name,\nref long pluid );\n\n[DllImport(\"advapi32.dll\", ExactSpelling=true, SetLastError=true) ]\ninternal static extern bool AdjustTokenPrivileges( IntPtr htok, bool disall,\nref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen );\n\n[DllImport(\"user32.dll\", ExactSpelling=true, SetLastError=true) ]\ninternal static extern bool ExitWindowsEx( int flg, int rea );\n\ninternal const int SE_PRIVILEGE_ENABLED = 0x00000002;\ninternal const int TOKEN_QUERY = 0x00000008;\ninternal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;\ninternal const string SE_SHUTDOWN_NAME = \"SeShutdownPrivilege\";\ninternal const int EWX_LOGOFF = 0x00000000;\ninternal const int EWX_SHUTDOWN = 0x00000001;\ninternal const int EWX_REBOOT = 0x00000002;\ninternal const int EWX_FORCE = 0x00000004;\ninternal const int EWX_POWEROFF = 0x00000008;\ninternal const int EWX_FORCEIFHUNG = 0x00000010;\n\nprivate void DoExitWin( int flg )\n{\n bool ok;\n TokPriv1Luid tp;\n IntPtr hproc = GetCurrentProcess();\n IntPtr htok = IntPtr.Zero;\n ok = OpenProcessToken( hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok );\n tp.Count = 1;\n tp.Luid = 0;\n tp.Attr = SE_PRIVILEGE_ENABLED;\n ok = LookupPrivilegeValue( null, SE_SHUTDOWN_NAME, ref tp.Luid );\n ok = AdjustTokenPrivileges( htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero );\n ok = ExitWindowsEx( flg, 0 );\n }\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>DoExitWin( EWX_SHUTDOWN );\n</code></pre>\n\n<p>or</p>\n\n<pre><code>DoExitWin( EWX_REBOOT );\n</code></pre>\n"
},
{
"answer_id": 102602,
"author": "Yes - that Jake.",
"author_id": 5287,
"author_profile": "https://Stackoverflow.com/users/5287",
"pm_score": 0,
"selected": false,
"text": "<p>There is no .net native method for shutting off the computer. You need to P/Invoke the ExitWindows or ExitWindowsEx API call.</p>\n"
},
{
"answer_id": 102628,
"author": "roomaroo",
"author_id": 3464,
"author_profile": "https://Stackoverflow.com/users/3464",
"pm_score": 4,
"selected": false,
"text": "<p>The old-school ugly method. Use the <code>ExitWindowsEx</code> function from the Win32 API. </p>\n\n<pre><code>using System.Runtime.InteropServices;\n\nvoid Shutdown2()\n{\n const string SE_SHUTDOWN_NAME = \"SeShutdownPrivilege\";\n const short SE_PRIVILEGE_ENABLED = 2;\n const uint EWX_SHUTDOWN = 1;\n const short TOKEN_ADJUST_PRIVILEGES = 32;\n const short TOKEN_QUERY = 8;\n IntPtr hToken;\n TOKEN_PRIVILEGES tkp;\n\n // Get shutdown privileges...\n OpenProcessToken(Process.GetCurrentProcess().Handle, \n TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out hToken);\n tkp.PrivilegeCount = 1;\n tkp.Privileges.Attributes = SE_PRIVILEGE_ENABLED;\n LookupPrivilegeValue(\"\", SE_SHUTDOWN_NAME, out tkp.Privileges.pLuid);\n AdjustTokenPrivileges(hToken, false, ref tkp, 0U, IntPtr.Zero, \n IntPtr.Zero);\n\n // Now we have the privileges, shutdown Windows\n ExitWindowsEx(EWX_SHUTDOWN, 0);\n}\n\n// Structures needed for the API calls\nprivate struct LUID\n{\n public int LowPart;\n public int HighPart;\n}\nprivate struct LUID_AND_ATTRIBUTES\n{\n public LUID pLuid;\n public int Attributes;\n}\nprivate struct TOKEN_PRIVILEGES\n{\n public int PrivilegeCount;\n public LUID_AND_ATTRIBUTES Privileges;\n}\n\n[DllImport(\"advapi32.dll\")]\nstatic extern int OpenProcessToken(IntPtr ProcessHandle, \n int DesiredAccess, out IntPtr TokenHandle);\n\n[DllImport(\"advapi32.dll\", SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool AdjustTokenPrivileges(IntPtr TokenHandle,\n [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges,\n ref TOKEN_PRIVILEGES NewState,\n UInt32 BufferLength,\n IntPtr PreviousState,\n IntPtr ReturnLength);\n\n[DllImport(\"advapi32.dll\")]\nstatic extern int LookupPrivilegeValue(string lpSystemName, \n string lpName, out LUID lpLuid);\n\n[DllImport(\"user32.dll\", SetLastError = true)]\nstatic extern int ExitWindowsEx(uint uFlags, uint dwReason);\n</code></pre>\n\n<p>In production code you should be checking the return values of the API calls, but I left that out to make the example clearer.</p>\n"
},
{
"answer_id": 104258,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 8,
"selected": false,
"text": "<p>Works starting with windows XP, not available in win 2000 or lower: </p>\n\n<p>This is the quickest way to do it:</p>\n\n<pre><code>Process.Start(\"shutdown\",\"/s /t 0\");\n</code></pre>\n\n<p>Otherwise use P/Invoke or WMI like others have said.</p>\n\n<p>Edit: how to avoid creating a window</p>\n\n<pre><code>var psi = new ProcessStartInfo(\"shutdown\",\"/s /t 0\");\npsi.CreateNoWindow = true;\npsi.UseShellExecute = false;\nProcess.Start(psi);\n</code></pre>\n"
},
{
"answer_id": 665422,
"author": "lakshmanaraj",
"author_id": 44541,
"author_profile": "https://Stackoverflow.com/users/44541",
"pm_score": 5,
"selected": false,
"text": "<p>Different methods:</p>\n\n<p>A. <code>System.Diagnostics.Process.Start(\"Shutdown\", \"-s -t 10\");</code></p>\n\n<p>B. Windows Management Instrumentation (WMI) </p>\n\n<ul>\n<li><a href=\"http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=36953\" rel=\"noreferrer\">http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=36953</a></li>\n<li><a href=\"http://www.dreamincode.net/forums/showtopic33948.htm\" rel=\"noreferrer\">http://www.dreamincode.net/forums/showtopic33948.htm</a></li>\n</ul>\n\n<p>C. System.Runtime.InteropServices Pinvoke</p>\n\n<ul>\n<li><a href=\"http://bytes.com/groups/net-c/251367-shutdown-my-computer-using-c\" rel=\"noreferrer\">http://bytes.com/groups/net-c/251367-shutdown-my-computer-using-c</a></li>\n</ul>\n\n<p>D. System Management</p>\n\n<ul>\n<li><a href=\"http://www.geekpedia.com/code36_Shut-down-system-using-Csharp.html\" rel=\"noreferrer\">http://www.geekpedia.com/code36_Shut-down-system-using-Csharp.html</a></li>\n</ul>\n\n<p>After I submit, I have seen so many others also have posted... </p>\n"
},
{
"answer_id": 948656,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to shut down computer remotely then you can use</p>\n\n<pre><code>Using System.Diagnostics;\n</code></pre>\n\n<p>on any button click</p>\n\n<pre><code>{\n Process.Start(\"Shutdown\",\"-i\");\n}\n</code></pre>\n"
},
{
"answer_id": 5109179,
"author": "MisterEd",
"author_id": 632931,
"author_profile": "https://Stackoverflow.com/users/632931",
"pm_score": 2,
"selected": false,
"text": "<p>I tried <a href=\"https://stackoverflow.com/questions/102567/how-to-shutdown-the-computer-from-c/102583#102583\">roomaroo's WMI method</a> to shutdown Windows 2003 Server, but it would not work until I added `[STAThread]' (i.e. \"<a href=\"http://msdn.microsoft.com/en-us/library/ms680112(v=vs.85).aspx\" rel=\"nofollow noreferrer\">Single Threaded Apartment</a>\" threading model) to the Main() declaration:</p>\n\n<pre><code>[STAThread]\npublic static void Main(string[] args) {\n Shutdown();\n}\n</code></pre>\n\n<p>I then tried to shutdown from a thread, and to get that to work I had to set the \"Apartment State\" of the thread to STA as well:</p>\n\n<pre><code>using System.Management;\nusing System.Threading;\n\npublic static class Program {\n\n [STAThread]\n public static void Main(string[] args) {\n Thread t = new Thread(new ThreadStart(Program.Shutdown));\n t.SetApartmentState(ApartmentState.STA);\n t.Start();\n ...\n }\n\n public static void Shutdown() {\n // roomaroo's code\n }\n}\n</code></pre>\n\n<p>I'm a C# noob, so I'm not entirely sure of the significance of STA threads in terms of shutting down the system (even after reading the link I posted above). Perhaps someone else can elaborate...?</p>\n"
},
{
"answer_id": 6929504,
"author": "unbob",
"author_id": 876993,
"author_profile": "https://Stackoverflow.com/users/876993",
"pm_score": 3,
"selected": false,
"text": "<p>Note that <code>shutdown.exe</code> is just a wrapper around <a href=\"http://msdn.microsoft.com/en-us/library/aa376874%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\"><code>InitiateSystemShutdownEx</code></a>, which provides some niceties missing in <code>ExitWindowsEx</code></p>\n"
},
{
"answer_id": 6956451,
"author": "Fazil Mir",
"author_id": 880588,
"author_profile": "https://Stackoverflow.com/users/880588",
"pm_score": 2,
"selected": false,
"text": "<p>**Elaborated Answer... </p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Text;\nusing System.Windows.Forms;\n// Remember to add a reference to the System.Management assembly\nusing System.Management;\nusing System.Diagnostics;\n\nnamespace ShutDown\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void btnShutDown_Click(object sender, EventArgs e)\n {\n ManagementBaseObject mboShutdown = null;\n ManagementClass mcWin32 = new ManagementClass(\"Win32_OperatingSystem\");\n mcWin32.Get();\n\n // You can't shutdown without security privileges\n mcWin32.Scope.Options.EnablePrivileges = true;\n ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters(\"Win32Shutdown\");\n\n // Flag 1 means we want to shut down the system\n mboShutdownParams[\"Flags\"] = \"1\";\n mboShutdownParams[\"Reserved\"] = \"0\";\n\n foreach (ManagementObject manObj in mcWin32.GetInstances())\n {\n mboShutdown = manObj.InvokeMethod(\"Win32Shutdown\", mboShutdownParams, null);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10683826,
"author": "m3z",
"author_id": 289545,
"author_profile": "https://Stackoverflow.com/users/289545",
"pm_score": 3,
"selected": false,
"text": "<p>I had trouble trying to use the WMI method accepted above because i always got privilige not held exceptions despite running the program as an administrator.</p>\n\n<p>The solution was for the process to request the privilege for itself. I found the answer at <a href=\"http://www.dotnet247.com/247reference/msgs/58/292150.aspx\" rel=\"noreferrer\">http://www.dotnet247.com/247reference/msgs/58/292150.aspx</a> written by a guy called Richard Hill.</p>\n\n<p>I've pasted my basic use of his solution below in case that link gets old.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Management;\nusing System.Runtime.InteropServices;\nusing System.Security;\nusing System.Diagnostics;\n\nnamespace PowerControl\n{\n public class PowerControl_Main\n {\n\n\n public void Shutdown()\n {\n ManagementBaseObject mboShutdown = null;\n ManagementClass mcWin32 = new ManagementClass(\"Win32_OperatingSystem\");\n mcWin32.Get();\n\n if (!TokenAdjuster.EnablePrivilege(\"SeShutdownPrivilege\", true))\n {\n Console.WriteLine(\"Could not enable SeShutdownPrivilege\");\n }\n else\n {\n Console.WriteLine(\"Enabled SeShutdownPrivilege\");\n }\n\n // You can't shutdown without security privileges\n mcWin32.Scope.Options.EnablePrivileges = true;\n ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters(\"Win32Shutdown\");\n\n // Flag 1 means we want to shut down the system\n mboShutdownParams[\"Flags\"] = \"1\";\n mboShutdownParams[\"Reserved\"] = \"0\";\n\n foreach (ManagementObject manObj in mcWin32.GetInstances())\n {\n try\n {\n mboShutdown = manObj.InvokeMethod(\"Win32Shutdown\",\n mboShutdownParams, null);\n }\n catch (ManagementException mex)\n {\n Console.WriteLine(mex.ToString());\n Console.ReadKey();\n }\n }\n }\n\n\n }\n\n\n public sealed class TokenAdjuster\n {\n // PInvoke stuff required to set/enable security privileges\n [DllImport(\"advapi32\", SetLastError = true),\n SuppressUnmanagedCodeSecurityAttribute]\n static extern int OpenProcessToken(\n System.IntPtr ProcessHandle, // handle to process\n int DesiredAccess, // desired access to process\n ref IntPtr TokenHandle // handle to open access token\n );\n\n [DllImport(\"kernel32\", SetLastError = true),\n SuppressUnmanagedCodeSecurityAttribute]\n static extern bool CloseHandle(IntPtr handle);\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n static extern int AdjustTokenPrivileges(\n IntPtr TokenHandle,\n int DisableAllPrivileges,\n IntPtr NewState,\n int BufferLength,\n IntPtr PreviousState,\n ref int ReturnLength);\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n static extern bool LookupPrivilegeValue(\n string lpSystemName,\n string lpName,\n ref LUID lpLuid);\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct LUID\n {\n internal int LowPart;\n internal int HighPart;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n struct LUID_AND_ATTRIBUTES\n {\n LUID Luid;\n int Attributes;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n struct _PRIVILEGE_SET\n {\n int PrivilegeCount;\n int Control;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] // ANYSIZE_ARRAY = 1\n LUID_AND_ATTRIBUTES[] Privileges;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct TOKEN_PRIVILEGES\n {\n internal int PrivilegeCount;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]\n internal int[] Privileges;\n }\n const int SE_PRIVILEGE_ENABLED = 0x00000002;\n const int TOKEN_ADJUST_PRIVILEGES = 0X00000020;\n const int TOKEN_QUERY = 0X00000008;\n const int TOKEN_ALL_ACCESS = 0X001f01ff;\n const int PROCESS_QUERY_INFORMATION = 0X00000400;\n\n public static bool EnablePrivilege(string lpszPrivilege, bool\n bEnablePrivilege)\n {\n bool retval = false;\n int ltkpOld = 0;\n IntPtr hToken = IntPtr.Zero;\n TOKEN_PRIVILEGES tkp = new TOKEN_PRIVILEGES();\n tkp.Privileges = new int[3];\n TOKEN_PRIVILEGES tkpOld = new TOKEN_PRIVILEGES();\n tkpOld.Privileges = new int[3];\n LUID tLUID = new LUID();\n tkp.PrivilegeCount = 1;\n if (bEnablePrivilege)\n tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;\n else\n tkp.Privileges[2] = 0;\n if (LookupPrivilegeValue(null, lpszPrivilege, ref tLUID))\n {\n Process proc = Process.GetCurrentProcess();\n if (proc.Handle != IntPtr.Zero)\n {\n if (OpenProcessToken(proc.Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,\n ref hToken) != 0)\n {\n tkp.PrivilegeCount = 1;\n tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;\n tkp.Privileges[1] = tLUID.HighPart;\n tkp.Privileges[0] = tLUID.LowPart;\n const int bufLength = 256;\n IntPtr tu = Marshal.AllocHGlobal(bufLength);\n Marshal.StructureToPtr(tkp, tu, true);\n if (AdjustTokenPrivileges(hToken, 0, tu, bufLength, IntPtr.Zero, ref ltkpOld) != 0)\n {\n // successful AdjustTokenPrivileges doesn't mean privilege could be changed\n if (Marshal.GetLastWin32Error() == 0)\n {\n retval = true; // Token changed\n }\n }\n TOKEN_PRIVILEGES tokp = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(tu,\n typeof(TOKEN_PRIVILEGES));\n Marshal.FreeHGlobal(tu);\n }\n }\n }\n if (hToken != IntPtr.Zero)\n {\n CloseHandle(hToken);\n }\n return retval;\n }\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 27726215,
"author": "Micah Vertal",
"author_id": 4254572,
"author_profile": "https://Stackoverflow.com/users/4254572",
"pm_score": 3,
"selected": false,
"text": "<pre><code>System.Diagnostics.Process.Start(\"shutdown\", \"/s /t 0\")\n</code></pre>\n\n<p>Should work.</p>\n\n<p>For restart, it's /r</p>\n\n<p>This will restart the PC box directly and cleanly, with NO dialogs.</p>\n"
},
{
"answer_id": 38656759,
"author": "user1785960",
"author_id": 1785960,
"author_profile": "https://Stackoverflow.com/users/1785960",
"pm_score": 1,
"selected": false,
"text": "<p>Use shutdown.exe. To avoid problem with passing args, complex execution, execution from WindowForms use PowerShell execute script:</p>\n\n<pre><code>using System.Management.Automation;\n...\nusing (PowerShell PowerShellInstance = PowerShell.Create())\n{\n PowerShellInstance.AddScript(\"shutdown -a; shutdown -r -t 100;\");\n // invoke execution on the pipeline (collecting output)\n Collection<PSObject> PSOutput = PowerShellInstance.Invoke();\n} \n</code></pre>\n\n<p>System.Management.Automation.dll should be installed on OS and available in GAC.</p>\n\n<p>Sorry for My english.</p>\n"
},
{
"answer_id": 44614907,
"author": "man",
"author_id": 7877399,
"author_profile": "https://Stackoverflow.com/users/7877399",
"pm_score": 3,
"selected": false,
"text": "<p>Just to add to Pop Catalin's answer, here's a <strong>one liner</strong> which shuts down the computer without displaying any windows:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>Process.Start(new ProcessStartInfo(\"shutdown\", \"/s /t 0\") {\n CreateNoWindow = true, UseShellExecute = false\n});\n</code></pre>\n\n\n"
},
{
"answer_id": 65347291,
"author": "NthDeveloper",
"author_id": 1844220,
"author_profile": "https://Stackoverflow.com/users/1844220",
"pm_score": 1,
"selected": false,
"text": "<p>For Windows 10, I needed to add /f option in order to shutdown the pc without any question and wait time.</p>\n<pre><code>//This did not work for me\nProcess.Start("shutdown", "/s /t 0");\n\n//But this worked\nProcess.Start("shutdown", "/s /f /t 0");\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3464/"
]
| What's the best way to shut down the computer from a C# program?
I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net. | Taken from: [a Geekpedia post](http://www.geekpedia.com/code36_Shut-down-system-using-Csharp.html)
This method uses [WMI](http://en.wikipedia.org/wiki/Windows_Management_Instrumentation) to shutdown windows.
You'll need to add a reference to System.Management to your project to use this.
```
using System.Management;
void Shutdown()
{
ManagementBaseObject mboShutdown = null;
ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
mcWin32.Get();
// You can't shutdown without security privileges
mcWin32.Scope.Options.EnablePrivileges = true;
ManagementBaseObject mboShutdownParams =
mcWin32.GetMethodParameters("Win32Shutdown");
// Flag 1 means we want to shut down the system. Use "2" to reboot.
mboShutdownParams["Flags"] = "1";
mboShutdownParams["Reserved"] = "0";
foreach (ManagementObject manObj in mcWin32.GetInstances())
{
mboShutdown = manObj.InvokeMethod("Win32Shutdown",
mboShutdownParams, null);
}
}
``` |
102,568 | <p>I'm trying to understand someone else's Perl code without knowing much Perl myself. I would appreciate your help.</p>
<p>I've encountered a Perl function along these lines:</p>
<pre><code>MyFunction($arg1,$arg2__size,$arg3)
</code></pre>
<p>Is there a meaning to the double-underscore syntax in <code>$arg2</code>, or is it just part of the name of the second argument?</p>
| [
{
"answer_id": 102582,
"author": "Haabda",
"author_id": 16292,
"author_profile": "https://Stackoverflow.com/users/16292",
"pm_score": 1,
"selected": false,
"text": "<p>I'm fairly certain arg2__size is just the name of a variable.</p>\n"
},
{
"answer_id": 102636,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 5,
"selected": true,
"text": "<p>There is no specific meaning to the use of a __ inside of a perl variable name. It's likely programmer preference, especially in the case that you've cited in your question. You can see more information about perl variable naming <a href=\"http://perldoc.perl.org/perlvar.html#Technical-Note-on-the-Syntax-of-Variable-Names\" rel=\"nofollow noreferrer\">here</a>. </p>\n"
},
{
"answer_id": 102806,
"author": "hexten",
"author_id": 10032,
"author_profile": "https://Stackoverflow.com/users/10032",
"pm_score": 4,
"selected": false,
"text": "<p>As in most languages underscore is just part of an identifier; no special meaning.</p>\n\n<p>But are you sure it's Perl? There aren't any sigils on the variables. Can you post more context?</p>\n"
},
{
"answer_id": 102865,
"author": "JB.",
"author_id": 12274,
"author_profile": "https://Stackoverflow.com/users/12274",
"pm_score": 2,
"selected": false,
"text": "<p>As far as the interpreter is concerned, an underscore is just another character allowed in identifiers. It can be used as an alternative to concatenation or camel case to form multi-word identifiers.</p>\n\n<p>A leading underscore is often used to mean an identifier is for local use only, <em>e.g.</em> for non-exported parts of a module. It's merely a convention; the interpreter doesn't care.</p>\n"
},
{
"answer_id": 103936,
"author": "Drew Stephens",
"author_id": 17339,
"author_profile": "https://Stackoverflow.com/users/17339",
"pm_score": 2,
"selected": false,
"text": "<p>In the context of your question, the double underscore doesn't have any programmatic meaning. Double underscores does mean something special for a limited number of values in Perl, most notably <code>__FILE__</code> & <code>__LINE__</code>. These are special literals that aren't prefixed with a sigil (<code>$</code>, <code>%</code> or <code>@</code>) and are only interpolated outside of quotes. They contain the full path & name of the currently executing file and the line that is being executed. See the section on 'Special Literals' in <a href=\"http://perldoc.perl.org/perldata.html\" rel=\"nofollow noreferrer\">perldata</a> or <a href=\"http://www.perlmonks.org/?node_id=295986\" rel=\"nofollow noreferrer\">this post on Perl Monks</a></p>\n"
},
{
"answer_id": 106256,
"author": "AmbroseChapel",
"author_id": 242241,
"author_profile": "https://Stackoverflow.com/users/242241",
"pm_score": 1,
"selected": false,
"text": "<p>Mark's answer is of course correct, it has no special meaning.</p>\n\n<p>But I want to note that your example doesn't look like Perl at all. Perl variables aren't barewords. They have the sigils, as you will see from the links above. And Perl doesn't have \"functions\", it has subroutines. </p>\n\n<p>So there may be some confusion about which language we're talking about.</p>\n"
},
{
"answer_id": 968218,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>You will need to tell the interpreter that \"$arg2\" is the name of a variable. and not \"$arg2__size\". For this you will need to use the parenthesis. (This usage is similar to that seen in shell).</p>\n\n<p>This should work\nMyFunction($arg1,${arg2}__size,$arg3)</p>\n\n<p>--Binu</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10261/"
]
| I'm trying to understand someone else's Perl code without knowing much Perl myself. I would appreciate your help.
I've encountered a Perl function along these lines:
```
MyFunction($arg1,$arg2__size,$arg3)
```
Is there a meaning to the double-underscore syntax in `$arg2`, or is it just part of the name of the second argument? | There is no specific meaning to the use of a \_\_ inside of a perl variable name. It's likely programmer preference, especially in the case that you've cited in your question. You can see more information about perl variable naming [here](http://perldoc.perl.org/perlvar.html#Technical-Note-on-the-Syntax-of-Variable-Names). |
102,591 | <p>In my database (SQL 2005) I have a field which holds a comment but in the comment I have an id and I would like to strip out just the id, and IF possible convert it to an int:</p>
<p><code>activation successful of id 1010101</code></p>
<p>The line above is the exact structure of the data in the db field.</p>
<p>And no I don't want to do this in the code of the application, I actually don't want to touch it, just in case you were wondering ;-)</p>
| [
{
"answer_id": 102687,
"author": "Cervo",
"author_id": 16219,
"author_profile": "https://Stackoverflow.com/users/16219",
"pm_score": 0,
"selected": false,
"text": "<pre><code>-- Test table, you will probably use some query \nDECLARE @testTable TABLE(comment VARCHAR(255)) \nINSERT INTO @testTable(comment) \n VALUES ('activation successful of id 1010101')\n\n-- Use Charindex to find \"id \" then isolate the numeric part \n-- Finally check to make sure the number is numeric before converting \nSELECT CASE WHEN ISNUMERIC(JUSTNUMBER)=1 THEN CAST(JUSTNUMBER AS INTEGER) ELSE -1 END \nFROM ( \n select right(comment, len(comment) - charindex('id ', comment)-2) as justnumber \n from @testtable) TT\n</code></pre>\n\n<p>I would also add that this approach is more set based and hence more efficient for a bunch of data values. But it is super easy to do it just for one value as a variable. Instead of using the column comment you can use a variable like <code>@chvComment</code>.</p>\n"
},
{
"answer_id": 102688,
"author": "Matt Blaine",
"author_id": 16272,
"author_profile": "https://Stackoverflow.com/users/16272",
"pm_score": 0,
"selected": false,
"text": "<p>I don't have a means to test it at the moment, but:</p>\n\n<pre><code>select convert(int, substring(fieldName, len('activation successful of id '), len(fieldName) - len('activation successful of id '))) from tableName\n</code></pre>\n"
},
{
"answer_id": 102706,
"author": "njr101",
"author_id": 9625,
"author_profile": "https://Stackoverflow.com/users/9625",
"pm_score": 2,
"selected": true,
"text": "<p>This should do the trick:</p>\n\n<pre><code>SELECT SUBSTRING(column, PATINDEX('%[0-9]%', column), 999)\nFROM table\n</code></pre>\n\n<p>Based on your sample data, this that there is only one occurence of an integer in the string and that it is at the end.</p>\n"
},
{
"answer_id": 102732,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If the comment string is EXACTLY like that you can use replace.</p>\n\n<pre><code>select replace(comment_col, 'activation successful of id ', '') as id from ....\n</code></pre>\n\n<p>It almost certainly won't be though - what about unsuccessful Activations?\nYou might end up with nested replace statements</p>\n\n<pre><code>select replace(replace(comment_col, 'activation not successful of id ', ''), 'activation successful of id ', '') as id from ....\n</code></pre>\n\n<p>[sorry can't tell from this edit screen if that's entirely valid sql]</p>\n\n<p>That starts to get messy; you might consider creating a function and putting the replace statements in that.</p>\n\n<p>If this is a one off job, it won't really matter. You could also use a regex, but that's quite slow (and in any case mean you now have 2 problems).</p>\n"
},
{
"answer_id": 102750,
"author": "Rick Glos",
"author_id": 16008,
"author_profile": "https://Stackoverflow.com/users/16008",
"pm_score": 0,
"selected": false,
"text": "<p>Would you be open to writing a bit of code? One option, create a CLR User Defined function, then use Regex. You can find more details <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163473.aspx\" rel=\"nofollow noreferrer\">here</a>. This will handle complex strings.</p>\n\n<p>If your above line is always formatted as 'activation successful of id #######', with your number at the end of the field, then:</p>\n\n<pre><code>declare @myColumn varchar(100)\nset @myColumn = 'activation successful of id 1010102'\n\n\nSELECT\n @myColumn as [OriginalColumn]\n, CONVERT(int, REVERSE(LEFT(REVERSE(@myColumn), CHARINDEX(' ', REVERSE(@myColumn))))) as [DesiredColumn]\n</code></pre>\n\n<p>Will give you:</p>\n\n<pre><code>OriginalColumn DesiredColumn\n---------------------------------------- -------------\nactivation successful of id 1010102 1010102\n\n(1 row(s) affected)\n</code></pre>\n"
},
{
"answer_id": 102823,
"author": "Dan Roberts",
"author_id": 8345,
"author_profile": "https://Stackoverflow.com/users/8345",
"pm_score": 0,
"selected": false,
"text": "<pre><code>CAST(REVERSE(LEFT(REVERSE(@Test),CHARINDEX(' ',REVERSE(@Test))-1)) AS INTEGER)\n</code></pre>\n"
},
{
"answer_id": 102840,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select cast(right(column_name,charindex(' ',reverse(column_name))) as int)\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841427/"
]
| In my database (SQL 2005) I have a field which holds a comment but in the comment I have an id and I would like to strip out just the id, and IF possible convert it to an int:
`activation successful of id 1010101`
The line above is the exact structure of the data in the db field.
And no I don't want to do this in the code of the application, I actually don't want to touch it, just in case you were wondering ;-) | This should do the trick:
```
SELECT SUBSTRING(column, PATINDEX('%[0-9]%', column), 999)
FROM table
```
Based on your sample data, this that there is only one occurence of an integer in the string and that it is at the end. |
102,606 | <p>Below is part of the XML which I am processing with <a href="http://php.net/XSLTProcessor" rel="nofollow noreferrer">PHP's XSLTProcessor</a>:</p>
<pre><code><result>
<uf x="20" y="0"/>
<uf x="22" y="22"/>
<uf x="4" y="3"/>
<uf x="15" y="15"/>
</result>
</code></pre>
<p>I need to know how many "uf" nodes exist where x == y.</p>
<p>In the above example, that would be 2.</p>
<p>I've tried looping and incrementing a counter variable, but I can't redefine variables.</p>
<p>I've tried lots of combinations of xsl:number, with count/from, but couldn't get the XPath expression right.</p>
<p>Thanks!</p>
| [
{
"answer_id": 102707,
"author": "Oliver Mellet",
"author_id": 12001,
"author_profile": "https://Stackoverflow.com/users/12001",
"pm_score": 1,
"selected": false,
"text": "<pre><code>count('/result/uf[@x = @y]')\n</code></pre>\n"
},
{
"answer_id": 102708,
"author": "Mike Tunnicliffe",
"author_id": 13956,
"author_profile": "https://Stackoverflow.com/users/13956",
"pm_score": 4,
"selected": true,
"text": "<pre><code><xsl:value-of select=\"count(/result/uf[@y=@x])\" />\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14645/"
]
| Below is part of the XML which I am processing with [PHP's XSLTProcessor](http://php.net/XSLTProcessor):
```
<result>
<uf x="20" y="0"/>
<uf x="22" y="22"/>
<uf x="4" y="3"/>
<uf x="15" y="15"/>
</result>
```
I need to know how many "uf" nodes exist where x == y.
In the above example, that would be 2.
I've tried looping and incrementing a counter variable, but I can't redefine variables.
I've tried lots of combinations of xsl:number, with count/from, but couldn't get the XPath expression right.
Thanks! | ```
<xsl:value-of select="count(/result/uf[@y=@x])" />
``` |
102,614 | <p>I am looking for a way to have some control over the shape of a simple MessageBox in Winforms. I would like to control where the passed in text wraps so that the dialog rect is narrower. Windows seems to want to make the dialog as wide as possible before wrapping the text. Is there an easy way to control the maximum width of the dialog without resorting to creating my own custom form?</p>
| [
{
"answer_id": 102622,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 3,
"selected": true,
"text": "<p>You can embed newlines in the text to force it to wrap at a certain point. e.g.</p>\n\n<pre><code>\"message text...\\nmore text...\"\n</code></pre>\n\n<p>update: I posted that thinking it was a win32 API question, but I think the principle should still apply. I assume WinForms eventually calls MessageBox().</p>\n"
},
{
"answer_id": 102629,
"author": "whatsisname",
"author_id": 8159,
"author_profile": "https://Stackoverflow.com/users/8159",
"pm_score": 0,
"selected": false,
"text": "<p>What happens if you throw your own newlines in the string message you pass it? I'm pretty sure that will work if I recall correctly.</p>\n"
},
{
"answer_id": 102635,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/102614/shape-of-a-winforms-messagebox#102622\">This</a>, or alternatively create your own form and use that.</p>\n"
},
{
"answer_id": 102637,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 1,
"selected": false,
"text": "<p>There's really just two ways (sane ways)</p>\n\n<p>1) Add line breaks to your string yourself to limit the lenghth of each line.</p>\n\n<p>2) Make your own form and use it rather than messagebox.</p>\n"
},
{
"answer_id": 4594947,
"author": "winwaed",
"author_id": 481927,
"author_profile": "https://Stackoverflow.com/users/481927",
"pm_score": 0,
"selected": false,
"text": "<p>The \\n newline chars will give you enough flexibility, then do this. I use this a lot. Eg. if I'm giving a warning, the first line will give the warning, and the next line will give the internal error message or further information as appropriate. If you don't do this, you end up with a very wide message box with very little height!</p>\n\n<p>MessageBox only has limited variability - eg. the button types and icon. If you need more, then create your own. You could then do all sorts of things like add URLs, a Help button ,etc.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12281/"
]
| I am looking for a way to have some control over the shape of a simple MessageBox in Winforms. I would like to control where the passed in text wraps so that the dialog rect is narrower. Windows seems to want to make the dialog as wide as possible before wrapping the text. Is there an easy way to control the maximum width of the dialog without resorting to creating my own custom form? | You can embed newlines in the text to force it to wrap at a certain point. e.g.
```
"message text...\nmore text..."
```
update: I posted that thinking it was a win32 API question, but I think the principle should still apply. I assume WinForms eventually calls MessageBox(). |
102,626 | <p>I get this error when I do a <strong>bulk insert</strong> with <code>select * from [table_name]</code>, and another table name:</p>
<pre><code>the locale id '0' of the source column 'PAT_NUM_ADT' and the locale id '1033'
of the destination column 'PAT_ID_OLD' do not match
</code></pre>
<p>I tried resetting my db collation but this did not help. </p>
<p>Has anyone seen this error?</p>
| [
{
"answer_id": 102675,
"author": "hova",
"author_id": 2170,
"author_profile": "https://Stackoverflow.com/users/2170",
"pm_score": 0,
"selected": false,
"text": "<p>I would check what your default locale settings are. Also, you'll need to check the locale of both tables using sp_help to verify they are the same. If they aren't you'll need to convert it to the correct locale</p>\n"
},
{
"answer_id": 2067056,
"author": "sal",
"author_id": 251026,
"author_profile": "https://Stackoverflow.com/users/251026",
"pm_score": 3,
"selected": false,
"text": "<p>If you are copying less than a full set of fields from one table to another, whether that table is on another domain across the world, or is collocated in the same database, you just have to select them in order. SqlBulkCopyColumnMappings do not work. Yes, I tried. I used all four possible constructors, and I used them both as SqlBulkCopyMapping objects and just by providing the same information to the Add method of SqlBulkCopy.ColumnMappings.Add.</p>\n\n<p>My columns are named the same. If you're using a different name as well as a different order, you may well find that you have to actually rename the columns. Good luck.</p>\n"
},
{
"answer_id": 2097868,
"author": "Tom Townsend",
"author_id": 254453,
"author_profile": "https://Stackoverflow.com/users/254453",
"pm_score": 1,
"selected": false,
"text": "<p>The answer by sal </p>\n\n<blockquote>\n <p>If you are copying less than a full\n set of fields from one table to\n another, whether that table is on\n another domain across the world, or is\n collocated in the same database, you\n just have to select them in order.\n SqlBulkCopyColumnMappings do not work.</p>\n</blockquote>\n\n<p>is according to my work absolutely right! Thanks for posting it. Everything has to be the same - data types, etc. Each time it finds a mismatch it throws the mysterious Locale Id error - funny yet frustrating as h###.</p>\n"
},
{
"answer_id": 7188618,
"author": "Marcus Granström",
"author_id": 790582,
"author_profile": "https://Stackoverflow.com/users/790582",
"pm_score": 0,
"selected": false,
"text": "<p>When you change the Collation of a database the table columns keep the old collation so you need to drop the tables and create them again.</p>\n"
},
{
"answer_id": 8257390,
"author": "Deepak Dwivedi",
"author_id": 1063944,
"author_profile": "https://Stackoverflow.com/users/1063944",
"pm_score": 3,
"selected": false,
"text": "<p>It is right that when we use SqlBulkCopy, some time it gives error, the best way to map the columns when you are using SqlBulkCopy.</p>\n\n<p>My Previous Code : </p>\n\n<pre><code>SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(\"Data Source=ServerName;User Id=userid;Password=****;Initial Catalog=Deepak; Pooling=true; Max pool size=200; Min pool size=0\");\n\n SqlConnection con = new SqlConnection(cb.ConnectionString);\n\n SqlCommand cmd = new SqlCommand(\"select Name,Class,Section,RollNo from Student\", con);\n\n con.Open();\n\n SqlDataReader rdr = cmd.ExecuteReader();\n\n SqlBulkCopy sbc = new SqlBulkCopy(\"Data Source=DestinationServer;User Id=destinationserveruserid;Password=******;Initial Catalog=DeepakTransfer; Pooling=true; Max pool size=200; Min pool size=0\");\n\n sbc.DestinationTableName = \"StudentTrans\";\n\n\n sbc.WriteToServer(rdr);\n\n\n sbc.Close();\n rdr.Close();\n con.Close();\n</code></pre>\n\n<p>The Code Was giving me the Error as :\nThe locale id '0' of the source column 'RollNo' and the locale id '1033' of the destination column 'Section' do not match.</p>\n\n<p>Now After Column Mapping my Code Is Running Successfully.</p>\n\n<p>My Modified Code is :</p>\n\n<pre><code>SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(\"Data Source=ServerName;User Id=userid;Password=****;Initial Catalog=Deepak;\");\n\n SqlConnection con = new SqlConnection(cb.ConnectionString);\n\n SqlCommand cmd = new SqlCommand(\"select Name,Class,Section,RollNo from Student\", con);\n\n con.Open();\n\n SqlDataReader rdr = cmd.ExecuteReader();\n\n\n SqlBulkCopy sbc = new SqlBulkCopy(\"Data Source=DestinationServer;User Id=destinationserveruserid;Password=******;Initial Catalog=DeepakTransfer;\");\n\n sbc.DestinationTableName = \"StudentTrans\";\n\n sbc.ColumnMappings.Add(\"Name\", \"Name\");\n sbc.ColumnMappings.Add(\"Class\", \"Class\");\n sbc.ColumnMappings.Add(\"Section\", \"Section\");\n sbc.ColumnMappings.Add(\"RollNo\", \"RollNo\");\n\n sbc.WriteToServer(rdr);\n sbc.Close();\n rdr.Close();\n con.Close();\n</code></pre>\n\n<p>This code is running Successfully.</p>\n"
},
{
"answer_id": 8948083,
"author": "Brett",
"author_id": 602245,
"author_profile": "https://Stackoverflow.com/users/602245",
"pm_score": 3,
"selected": false,
"text": "<p>I just had this error message when bulk copying some data. While it might not have been the exact same problem you were having, I was getting the same error.</p>\n\n<p>Specifically, I was doing the following:\nSELECT NULL AS ColumnName ...</p>\n\n<p>And the destination was a nullable varchar(3).</p>\n\n<p>In this case, all I needed to do was update my select statement as follows:\nSELECT CONVERT(VARCHAR(3),NULL) AS ColumnName...</p>\n\n<p>This worked perfectly and the error message went away!</p>\n"
},
{
"answer_id": 50840011,
"author": "Vadim",
"author_id": 1663523,
"author_profile": "https://Stackoverflow.com/users/1663523",
"pm_score": 1,
"selected": false,
"text": "<p>I was getting same error and it turned out I was copying from VARCHAR column in the DataTable to INT.</p>\n\n<p>After I changed the data type it worked flawlessly. I successfully copied subset of fields, specifying proper field mappings (mappings worked by both field name or sequence number).</p>\n\n<p>So make sure your data types are correct.</p>\n"
},
{
"answer_id": 53719833,
"author": "TheRealZing",
"author_id": 7127621,
"author_profile": "https://Stackoverflow.com/users/7127621",
"pm_score": 0,
"selected": false,
"text": "<p>A great way to debug this is to take the sql query being used in your SqlBulkCopy and run it in management studio as a select-into, for instance, change <code>select * from [table_name]</code> to <code>select * into newTable from [table_name]</code>, then look at the nullability and data types of 'newTable' versus 'table_name'. If there are any differences then you are likely to end up with this misleading error. Adjust the query or target table until they match, and then your command will work.</p>\n"
},
{
"answer_id": 59682767,
"author": "user2046901",
"author_id": 2046901,
"author_profile": "https://Stackoverflow.com/users/2046901",
"pm_score": 0,
"selected": false,
"text": "<p>Many thanks to Deepak Dwivedi for help. Here is little more hack with <strong>COLLATE DATABASE_DEFAULT</strong> which finally solved problem for me:</p>\n\n<pre><code>SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(\"Data Source=ServerName;User Id=userid;Password=****;Initial Catalog=Deepak;\");\nSqlConnection con = new SqlConnection(cb.ConnectionString);\nSqlCommand cmd = new SqlCommand(\"select Name COLLATE DATABASE_DEFAULT Name ,Class COLLATE DATABASE_DEFAULT Class ,Section COLLATE DATABASE_DEFAULT Section ,RollNo COLLATE DATABASE_DEFAULT RollNo from Student\", con);\ncon.Open();\nSqlDataReader rdr = cmd.ExecuteReader();\nSqlBulkCopy sbc = new SqlBulkCopy(\"Data Source=DestinationServer;User Id=destinationserveruserid;Password=******;Initial Catalog=DeepakTransfer;\");\n\nsbc.DestinationTableName = \"StudentTrans\";\n\nsbc.ColumnMappings.Add(\"Name\", \"Name\");\nsbc.ColumnMappings.Add(\"Class\", \"Class\");\nsbc.ColumnMappings.Add(\"Section\", \"Section\");\nsbc.ColumnMappings.Add(\"RollNo\", \"RollNo\");\n\nsbc.WriteToServer(rdr);\nsbc.Close();\nrdr.Close();\ncon.Close();\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I get this error when I do a **bulk insert** with `select * from [table_name]`, and another table name:
```
the locale id '0' of the source column 'PAT_NUM_ADT' and the locale id '1033'
of the destination column 'PAT_ID_OLD' do not match
```
I tried resetting my db collation but this did not help.
Has anyone seen this error? | If you are copying less than a full set of fields from one table to another, whether that table is on another domain across the world, or is collocated in the same database, you just have to select them in order. SqlBulkCopyColumnMappings do not work. Yes, I tried. I used all four possible constructors, and I used them both as SqlBulkCopyMapping objects and just by providing the same information to the Add method of SqlBulkCopy.ColumnMappings.Add.
My columns are named the same. If you're using a different name as well as a different order, you may well find that you have to actually rename the columns. Good luck. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.