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
164,425
<p>I am building a fun little app to determine if I should bike to work.</p> <p>I would like to test to see if it is either Raining or Thunderstorm(ing).</p> <pre><code>public enum WeatherType : byte { Sunny = 0, Cloudy = 1, Thunderstorm = 2, Raining = 4, Snowing = 8, MostlyCloudy = 16 } </code></pre> <p>I was thinking I could do something like: </p> <pre><code>WeatherType _badWeatherTypes = WeatherType.Thunderstorm | WeatherType.Raining; if(currentWeather.Type == _badWeatherTypes) { return false;//don't bike } </code></pre> <p>but this doesn't work because _badWeatherTypes is a combination of both types. I would like to keep them separated out because this is supposed to be a learning experience and having it separate may be useful in other situations (IE, Invoice not paid reason's etc...).</p> <p>I would also rather not do: (this would remove the ability to be configured for multiple people)</p> <pre><code>if(WeatherType.Thunderstorm) { return false; //don't bike } etc... </code></pre>
[ { "answer_id": 164435, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 1, "selected": false, "text": "<p>use the FlagsAttribute. That will allow you to use the enum as a bit mask.</p>\n" }, { "answer_id": 164455, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>Your current code will say whether it's <em>exactly</em> \"raining and thundery\". To find out whether it's \"raining and thundery and possibly something else\" you need:</p>\n\n<pre><code>if ((currentWeather.Type &amp; _badWeatherTypes) == _badWeatherTypes)\n</code></pre>\n\n<p>To find out whether it's \"raining <em>or</em> thundery, and possibly something else\" you need:</p>\n\n<pre><code>if ((currentWeather.Type &amp; _badWeatherTypes) != 0)\n</code></pre>\n\n<p>EDIT (for completeness):</p>\n\n<p>It would be good to use the <code>FlagsAttribute</code>, i.e. decorate the type with <code>[Flags]</code>. This is not necessary for the sake of this bitwise logic, but affects how <code>ToString()</code> behaves. The C# compiler ignores this attribute (at least at the moment; the C# 3.0 spec doesn't mention it) but it's generally a good idea for enums which are effectively flags, and it documents the intended use of the type. At the same time, the convention is that when you use flags, you pluralise the enum name - so you'd change it to <code>WeatherTypes</code> (because any actual value is effectively 0 or more weather types).</p>\n\n<p>It would also be worth thinking about what \"Sunny\" really means. It's currently got a value of 0, which means it's the absence of everything else; you couldn't have it sunny and raining at the same time (which is physically possible, of course). Please don't write code to prohibit rainbows! ;) On the other hand, if in your real use case you genuinely want a value which means \"the absence of all other values\" then you're fine.</p>\n" }, { "answer_id": 164459, "author": "David Alpert", "author_id": 8997, "author_profile": "https://Stackoverflow.com/users/8997", "pm_score": 0, "selected": false, "text": "<p>You need to use the [Flags] attribute (<a href=\"http://weblogs.asp.net/wim/archive/2004/04/07/109095.aspx\" rel=\"nofollow noreferrer\">check here</a>) on your enum; then you can use bitwise and to check for individual matches.</p>\n" }, { "answer_id": 164466, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 0, "selected": false, "text": "<p>You should be using the Flags attribute on your enum. Beyond that, you also need to test to see if a particular flag is set by:</p>\n\n<pre><code>(currentWeather.Type &amp; WeatherType.Thunderstorm == WeatherType.Thunderstorm)\n</code></pre>\n\n<p>This will test if currentWeather.Type has the WeatherType.Thunderstorm flag set.</p>\n" }, { "answer_id": 164591, "author": "Ken Wootton", "author_id": 7357, "author_profile": "https://Stackoverflow.com/users/7357", "pm_score": 0, "selected": false, "text": "<p>I wouldn't limit yourself to the bit world. Enums and bitwise operators are, as you found out, not the same thing. If you want to solve this using bitwise operators, I'd stick to just them, i.e. don't bother with enums. However, I'd something like the following:</p>\n\n<pre><code> WeatherType[] badWeatherTypes = new WeatherType[]\n { \n WeatherType.Thunderstorm, \n WeatherType.Raining\n };\n\n if (Array.IndexOf(badWeatherTypes, currentWeather.Type) &gt;= 0)\n {\n return false;\n }\n</code></pre>\n" }, { "answer_id": 8067396, "author": "LawrenceF", "author_id": 1037992, "author_profile": "https://Stackoverflow.com/users/1037992", "pm_score": 2, "selected": false, "text": "<p>I'm not sure that it should be a flag - I think that you should have an range input for:</p>\n\n<ul>\n<li>Temperature</li>\n<li>How much it's raining</li>\n<li>Wind strength</li>\n<li>any other input you fancy (e.g. thunderstorm)</li>\n</ul>\n\n<p>you can then use an algorithm to determine if the conditions are sufficiently good. </p>\n\n<p>I think you should also have an input for how likely the weather is to remain the same for cycling home. The criteria may be different - you can shower and change more easliy when you get home.</p>\n\n<p>If you really want to make it interesting, collect the input data from a weather service api, and evaulate the decision each day - Yes, I should have cycled, or no, it was a mistake. Then perhaps you can have the app learn to make better decisions.</p>\n\n<p>Next step is to \"socialize\" your decision, and see whether other people hear you are making the same decisions.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18821/" ]
I am building a fun little app to determine if I should bike to work. I would like to test to see if it is either Raining or Thunderstorm(ing). ``` public enum WeatherType : byte { Sunny = 0, Cloudy = 1, Thunderstorm = 2, Raining = 4, Snowing = 8, MostlyCloudy = 16 } ``` I was thinking I could do something like: ``` WeatherType _badWeatherTypes = WeatherType.Thunderstorm | WeatherType.Raining; if(currentWeather.Type == _badWeatherTypes) { return false;//don't bike } ``` but this doesn't work because \_badWeatherTypes is a combination of both types. I would like to keep them separated out because this is supposed to be a learning experience and having it separate may be useful in other situations (IE, Invoice not paid reason's etc...). I would also rather not do: (this would remove the ability to be configured for multiple people) ``` if(WeatherType.Thunderstorm) { return false; //don't bike } etc... ```
Your current code will say whether it's *exactly* "raining and thundery". To find out whether it's "raining and thundery and possibly something else" you need: ``` if ((currentWeather.Type & _badWeatherTypes) == _badWeatherTypes) ``` To find out whether it's "raining *or* thundery, and possibly something else" you need: ``` if ((currentWeather.Type & _badWeatherTypes) != 0) ``` EDIT (for completeness): It would be good to use the `FlagsAttribute`, i.e. decorate the type with `[Flags]`. This is not necessary for the sake of this bitwise logic, but affects how `ToString()` behaves. The C# compiler ignores this attribute (at least at the moment; the C# 3.0 spec doesn't mention it) but it's generally a good idea for enums which are effectively flags, and it documents the intended use of the type. At the same time, the convention is that when you use flags, you pluralise the enum name - so you'd change it to `WeatherTypes` (because any actual value is effectively 0 or more weather types). It would also be worth thinking about what "Sunny" really means. It's currently got a value of 0, which means it's the absence of everything else; you couldn't have it sunny and raining at the same time (which is physically possible, of course). Please don't write code to prohibit rainbows! ;) On the other hand, if in your real use case you genuinely want a value which means "the absence of all other values" then you're fine.
164,427
<p>I've made a Django site, but I've drank the Koolaid and I want to make an <em>IPhone</em> version. After putting much thought into I've come up with two options:</p> <ol> <li>Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework.</li> <li>Find some time of middleware that reads the user-agent, and changes the template directories dynamically.</li> </ol> <p>I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation <a href="http://docs.djangoproject.com/en/dev/topics/settings/" rel="noreferrer">discourages changing settings on the fly</a>. I found a <a href="http://www.djangosnippets.org/snippets/1098/" rel="noreferrer">snippet</a> that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user.</p> <p>Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites?</p> <p><strong>Update</strong></p> <p>I went with a combination of middleware and tweaking the template call.</p> <p>For the middleware, I used <a href="http://code.google.com/p/minidetector/" rel="noreferrer">minidetector</a>. I like it because it detects a <a href="http://www.youtube.com/watch?v=b6E682C7Jj4" rel="noreferrer">plethora</a> of mobile user-agents. All I have to do is check request.mobile in my views.</p> <p>For the template call tweak:</p> <pre><code> def check_mobile(request, template_name): if request.mobile: return 'mobile-%s'%template_name return template_name </code></pre> <p>I use this for any view that I know I have both versions.</p> <p><strong>TODO:</strong></p> <ul> <li>Figure out how to access <em>request.mobile</em> in an extended version of render_to_response so I don't have to use check_mobile('template_name.html')</li> <li>Using the previous automagically fallback to the regular template if no mobile version exists.</li> </ul>
[ { "answer_id": 164507, "author": "Aaron", "author_id": 11176, "author_profile": "https://Stackoverflow.com/users/11176", "pm_score": 5, "selected": true, "text": "<p>Rather than changing the template directories dynamically you could modify the request and add a value that lets your view know if the user is on an iphone or not. Then wrap render_to_response (or whatever you are using for creating HttpResponse objects) to grab the iphone version of the template instead of the standard html version if they are using an iphone. </p>\n" }, { "answer_id": 164616, "author": "Dmitry Shevchenko", "author_id": 7437, "author_profile": "https://Stackoverflow.com/users/7437", "pm_score": 1, "selected": false, "text": "<p>How about redirecting user to i.xxx.com after parsing his UA in some middleware? I highly doubt that mobile users care how url look like, still they can access your site using main url.</p>\n" }, { "answer_id": 189367, "author": "ak.", "author_id": 20672, "author_profile": "https://Stackoverflow.com/users/20672", "pm_score": 2, "selected": false, "text": "<p>You should take a look at the <a href=\"http://code.google.com/p/django-mobileadmin/\" rel=\"nofollow noreferrer\">django-mobileadmin</a> source code, which solved exactly this problem.</p>\n" }, { "answer_id": 207954, "author": "zgoda", "author_id": 12138, "author_profile": "https://Stackoverflow.com/users/12138", "pm_score": 2, "selected": false, "text": "<p>Other way would be creating your own template loader that loads templates specific to user agent. This is pretty generic technique and can be use to dynamically determine what template has to be loaded depending on other factors too, like requested language (good companion to existing Django i18n machinery).</p>\n\n<p>Django Book has a <a href=\"http://www.djangobook.com/en/1.0/chapter10/#cn234\" rel=\"nofollow noreferrer\">section on this subject</a>.</p>\n" }, { "answer_id": 216377, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I'm developing djangobile, a django mobile extension: <a href=\"http://code.google.com/p/djangobile/\" rel=\"nofollow noreferrer\">http://code.google.com/p/djangobile/</a></p>\n" }, { "answer_id": 299780, "author": "Amit", "author_id": 29120, "author_profile": "https://Stackoverflow.com/users/29120", "pm_score": 2, "selected": false, "text": "<p>There is a nice article which explains how to render the same data by different templates\n<a href=\"http://www.postneo.com/2006/07/26/acknowledging-the-mobile-web-with-django\" rel=\"nofollow noreferrer\">http://www.postneo.com/2006/07/26/acknowledging-the-mobile-web-with-django</a></p>\n\n<p>You still need to automatically redirect the user to mobile site however and this can be done using several methods (your check_mobile trick will work too)</p>\n" }, { "answer_id": 3487254, "author": "Aneil Mallavarapu", "author_id": 305149, "author_profile": "https://Stackoverflow.com/users/305149", "pm_score": 4, "selected": false, "text": "<p>Detect the user agent in middleware, switch the url bindings, profit!</p>\n\n<p>How? Django request objects have a .urlconf attribute, which can be set by middleware.</p>\n\n<p>From django docs:</p>\n\n<blockquote>\n <p>Django determines the root URLconf\n module to use. Ordinarily, this is the\n value of the ROOT_URLCONF setting, but\n if the incoming HttpRequest object has\n an attribute called urlconf (set by\n middleware request processing), its\n value will be used in place of the\n ROOT_URLCONF setting.</p>\n</blockquote>\n\n<ol>\n<li><p>In yourproj/middlware.py, write a class that checks the http_user_agent string:</p>\n\n<pre><code>import re\nMOBILE_AGENT_RE=re.compile(r\".*(iphone|mobile|androidtouch)\",re.IGNORECASE)\nclass MobileMiddleware(object):\n def process_request(self,request):\n if MOBILE_AGENT_RE.match(request.META['HTTP_USER_AGENT']):\n request.urlconf=\"yourproj.mobile_urls\"\n</code></pre></li>\n<li><p>Don't forget to add this to MIDDLEWARE_CLASSES in settings.py:</p>\n\n<pre><code>MIDDLEWARE_CLASSES= [...\n 'yourproj.middleware.MobileMiddleware',\n...]\n</code></pre></li>\n<li><p>Create a mobile urlconf, yourproj/mobile_urls.py:</p>\n\n<pre><code>urlpatterns=patterns('',('r'/?$', 'mobile.index'), ...)\n</code></pre></li>\n</ol>\n" }, { "answer_id": 4152279, "author": "Thomas", "author_id": 234254, "author_profile": "https://Stackoverflow.com/users/234254", "pm_score": 1, "selected": false, "text": "<p>best possible scenario: use minidetector to add the extra info to the request, then use django's built in request context to pass it to your templates like so</p>\n\n<pre><code>from django.shortcuts import render_to_response\nfrom django.template import RequestContext\n\ndef my_view_on_mobile_and_desktop(request)\n .....\n render_to_response('regular_template.html', \n {'my vars to template':vars}, \n context_instance=RequestContext(request))\n</code></pre>\n\n<p>then in your template you are able to introduce stuff like:</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n {% block head %}\n &lt;title&gt;blah&lt;/title&gt;\n {% if request.mobile %}\n &lt;link rel=\"stylesheet\" href=\"{{ MEDIA_URL }}/styles/base-mobile.css\"&gt;\n {% else %}\n &lt;link rel=\"stylesheet\" href=\"{{ MEDIA_URL }}/styles/base-desktop.css\"&gt;\n {% endif %}\n &lt;/head&gt;\n &lt;body&gt;\n &lt;div id=\"navigation\"&gt;\n {% include \"_navigation.html\" %}\n &lt;/div&gt;\n {% if not request.mobile %}\n &lt;div id=\"sidebar\"&gt;\n &lt;p&gt; sidebar content not fit for mobile &lt;/p&gt;\n &lt;/div&gt;\n {% endif %&gt;\n &lt;div id=\"content\"&gt;\n &lt;article&gt;\n {% if not request.mobile %}\n &lt;aside&gt;\n &lt;p&gt; aside content &lt;/p&gt;\n &lt;/aside&gt;\n {% endif %}\n &lt;p&gt; article content &lt;/p&gt;\n &lt;/aricle&gt;\n &lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 14510830, "author": "Samora Dake", "author_id": 1068519, "author_profile": "https://Stackoverflow.com/users/1068519", "pm_score": 0, "selected": false, "text": "<p>A simple solution is to create a wrapper around <code>django.shortcuts.render</code>. I put mine in a <code>utils</code> library in the root of my application. The wrapper works by automatically rendering templates in either a \"mobile\" or \"desktop\" folder.</p>\n\n<p>In <code>utils.shortcuts</code>:</p>\n\n<blockquote>\n<pre><code>from django.shortcuts import render\nfrom user_agents import parse\n\ndef my_render(request, *args, **kwargs):\n \"\"\"\n An extension of django.shortcuts.render.\n\n Appends 'mobile/' or 'desktop/' to a given template location\n to render the appropriate template for mobile or desktop\n\n depends on user_agents python library\n https://github.com/selwin/python-user-agents\n\n \"\"\"\n template_location = args[0]\n args_list = list(args)\n\n ua_string = request.META['HTTP_USER_AGENT']\n user_agent = parse(ua_string)\n\n if user_agent.is_mobile:\n args_list[0] = 'mobile/' + template_location\n args = tuple(args_list)\n return render(request, *args, **kwargs)\n else:\n args_list[0] = 'desktop/' + template_location\n args = tuple(args_list)\n return render(request, *args, **kwargs)\n</code></pre>\n</blockquote>\n\n<p>In <code>view</code>:</p>\n\n<blockquote>\n<pre><code>from utils.shortcuts import my_render\n\ndef home(request): return my_render(request, 'home.html')\n</code></pre>\n</blockquote>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24630/" ]
I've made a Django site, but I've drank the Koolaid and I want to make an *IPhone* version. After putting much thought into I've come up with two options: 1. Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework. 2. Find some time of middleware that reads the user-agent, and changes the template directories dynamically. I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation [discourages changing settings on the fly](http://docs.djangoproject.com/en/dev/topics/settings/). I found a [snippet](http://www.djangosnippets.org/snippets/1098/) that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user. Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites? **Update** I went with a combination of middleware and tweaking the template call. For the middleware, I used [minidetector](http://code.google.com/p/minidetector/). I like it because it detects a [plethora](http://www.youtube.com/watch?v=b6E682C7Jj4) of mobile user-agents. All I have to do is check request.mobile in my views. For the template call tweak: ``` def check_mobile(request, template_name): if request.mobile: return 'mobile-%s'%template_name return template_name ``` I use this for any view that I know I have both versions. **TODO:** * Figure out how to access *request.mobile* in an extended version of render\_to\_response so I don't have to use check\_mobile('template\_name.html') * Using the previous automagically fallback to the regular template if no mobile version exists.
Rather than changing the template directories dynamically you could modify the request and add a value that lets your view know if the user is on an iphone or not. Then wrap render\_to\_response (or whatever you are using for creating HttpResponse objects) to grab the iphone version of the template instead of the standard html version if they are using an iphone.
164,460
<p>The standalone flashplayer takes no arguments other than a .swf file when you launch it from the command line. I need the player to go full screen, no window borders and such. This can be accomplished by hitting ctrl+f once the program has started. I want to do this programmatically as I need it to launch into full screen without any human interaction.</p> <p>My guess is that I need to some how get a handle to the window and then send it an event that looks like the "ctrl+f" keystroke. </p> <p>If it makes any difference, it looks like flashplayer is a gtk application and I have python with pygtk installed.</p> <p><b>UPDATE</b> (the solution I used... thanks to ypnos' answer):</p> <pre><code>./flashplayer http://example.com/example.swf &amp; sleep 3 &amp;&amp; ~/xsendkey -window "Adobe Flash Player 10" Control+F </code></pre>
[ { "answer_id": 164681, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 1, "selected": false, "text": "<p>I've actually done this a long time ago, but it wasn't petty. What we did is use the <a href=\"http://sawfish.wikia.com/wiki/Main_Page\" rel=\"nofollow noreferrer\">Sawfish window manager</a> and wrote a hook to recognize the flashplayer window, then strip all the decorations and snap it full screen.</p>\n\n<p>This may be possible without using the window manager, by registering for X window creation events from an external application, but I'm not familiar enough with X11 to tell you how that would be done.</p>\n\n<p>Another option would be to write a pygtk application that embedded the standalone flash player inside a gtk.Socket and then resized itself. After a bit of thought, this might be your best bet.</p>\n" }, { "answer_id": 165089, "author": "ypnos", "author_id": 21974, "author_profile": "https://Stackoverflow.com/users/21974", "pm_score": 4, "selected": true, "text": "<p>You can use a dedicated application which sends the keystroke to the window manager, which should then pass it to flash, if the window starts as being the active window on the screen. This is quite error prone, though, due to delays between starting flash and when the window will show up.</p>\n\n<p>For example, your script could do something like this:\nflashplayer *.swf\nsleep 3 &amp;&amp; xsendkey Control+F</p>\n\n<p>The application xsendkey can be found here: <a href=\"http://people.csail.mit.edu/adonovan/hacks/xsendkey.html\" rel=\"nofollow noreferrer\">http://people.csail.mit.edu/adonovan/hacks/xsendkey.html</a>\nWithout given a specific window, it will send it to the root window, which is handled by your window manager. You could also try to figure out the Window id first, using xprop or something related to it.</p>\n\n<p>Another option is a Window manager, which is able to remember your settings and automatically apply them. Fluxbos for example provides this feature. You could set fluxbox to make the Window decor-less and stretch it over the whole screen, if flashplayer supports being resized. This is also not-so-nice, as it would probably affect all the flashplayer windows you open ever.</p>\n" }, { "answer_id": 277865, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>nspluginplayer --fullscreen src=path/to/flashfile.swf\n</code></pre>\n\n<p>which is from the [<a href=\"http://gwenole.beauchesne.info//en/projects/nspluginwrapper](nspluginwrapper\" rel=\"nofollow noreferrer\">http://gwenole.beauchesne.info//en/projects/nspluginwrapper](nspluginwrapper</a> project)</p>\n" }, { "answer_id": 2276508, "author": "Lerc", "author_id": 217637, "author_profile": "https://Stackoverflow.com/users/217637", "pm_score": 0, "selected": false, "text": "<p>I've done this using openbox using a similar mechanism to the one that bmdhacks mentions. The thing that I did note from this was that the standalone flash player performed considerably worse fullscreen than the same player in a maximised undecorated window. (that, annoyingly is not properly fullscreen because of the menubar). I was wondering about running it with a custom gtk theme to make the menu invisible. That's just a performance issue though. If fullscreen currently works ok, then it's unneccisarily complicated. I was running on an OLPC XO, performance is more of an issue there.</p>\n\n<p>I didn't have much luck with nspluginplayer (too buggy I think).</p>\n\n<p>Ultimately I had the luxury of making the flash that was running so I could simply place code into the flash itself. By a similar token, Since you can embed flash within flash, it should be possible to make a little stub swf that goes fullscreen automatically and contains the target sfw.</p>\n" }, { "answer_id": 3994891, "author": "Daniel", "author_id": 483952, "author_profile": "https://Stackoverflow.com/users/483952", "pm_score": 0, "selected": false, "text": "<p>You have to use Acton script 3 cmd:</p>\n\n<pre><code>stage.displayState = StageDisplayState.FULL_SCREEN;\n</code></pre>\n\n<p>See Adobe Action script 3 programming.</p>\n\n<p>But be careful : in full screen, you will lose display performances!</p>\n\n<p>I've got this problem ... more under Linux!!!</p>\n" }, { "answer_id": 10877411, "author": "Jens", "author_id": 1434549, "author_profile": "https://Stackoverflow.com/users/1434549", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Another option would be to write a pygtk application that embedded the standalone flash player inside a gtk.Socket and then resized itself. After a bit of thought, this might be your best bet.</p>\n</blockquote>\n\n<p>This is exactly what I did. In addition to that, my player scales flash content via Xcomposite, Xfixes and Cairo. A .deb including python source be found here:\n<a href=\"http://www.crutzi.info/crutziplayer\" rel=\"nofollow\">http://www.crutzi.info/crutziplayer</a></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11176/" ]
The standalone flashplayer takes no arguments other than a .swf file when you launch it from the command line. I need the player to go full screen, no window borders and such. This can be accomplished by hitting ctrl+f once the program has started. I want to do this programmatically as I need it to launch into full screen without any human interaction. My guess is that I need to some how get a handle to the window and then send it an event that looks like the "ctrl+f" keystroke. If it makes any difference, it looks like flashplayer is a gtk application and I have python with pygtk installed. **UPDATE** (the solution I used... thanks to ypnos' answer): ``` ./flashplayer http://example.com/example.swf & sleep 3 && ~/xsendkey -window "Adobe Flash Player 10" Control+F ```
You can use a dedicated application which sends the keystroke to the window manager, which should then pass it to flash, if the window starts as being the active window on the screen. This is quite error prone, though, due to delays between starting flash and when the window will show up. For example, your script could do something like this: flashplayer \*.swf sleep 3 && xsendkey Control+F The application xsendkey can be found here: <http://people.csail.mit.edu/adonovan/hacks/xsendkey.html> Without given a specific window, it will send it to the root window, which is handled by your window manager. You could also try to figure out the Window id first, using xprop or something related to it. Another option is a Window manager, which is able to remember your settings and automatically apply them. Fluxbos for example provides this feature. You could set fluxbox to make the Window decor-less and stretch it over the whole screen, if flashplayer supports being resized. This is also not-so-nice, as it would probably affect all the flashplayer windows you open ever.
164,468
<p>The IT department of a subsidiary of ours had a consulting company write them an ASP.NET application. Now it's having intermittent problems with mixing up who the current user is and has been known to show Joe some of Bob's data by mistake.</p> <p>The consultants were brought back to troubleshoot and we were invited to listen in on their explanation. Two things stuck out.</p> <p>First, the consultant lead provided this pseudo-code:</p> <pre><code>void MyFunction() { Session["UserID"] = SomeProprietarySessionManagementLookup(); Response.Redirect("SomeOtherPage.aspx"); } </code></pre> <p>He went on to say that the assignment of the session variable is asynchronous, which seemed untrue. Granted the call into the lookup function could do something asynchronously, but this seems unwise.</p> <p>Given that alleged asynchronousness, his theory was that the session variable was not being assigned before the redirect's inevitable ThreadAbort exception was raised. This faulure then prevented SomeOtherPage from displaying the correct user's data.</p> <p>Second, he gave an example of a coding best practice he recommends. Rather than writing:</p> <pre><code>int MyFunction(int x, int x) { try { return x / y; } catch(Exception ex) { // log it throw; } } </code></pre> <p>the technique he recommended was:</p> <pre><code> int MyFunction(int x, int y, out bool isSuccessful) { isSuccessful = false; if (y == 0) return 0; isSuccessful = true; return x / y; } </code></pre> <p>This will certainly work and could be better from a performance perspective in some situations.</p> <p>However, from these and other discussion points it just seemed to us that this team was not well-versed technically.</p> <p>Opinions?</p>
[ { "answer_id": 164478, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 4, "selected": false, "text": "<p>Rule of thumb: If you need to ask if a consultant knows what he's doing, he probably doesn't ;)</p>\n\n<p>And I tend to agree here. Obviously you haven't provided much, but they don't seem terribly competent.</p>\n" }, { "answer_id": 164484, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>For the first point, that does indeed seem bizarre.</p>\n\n<p>On the second one, it's reasonable to try to avoid division by 0 - it's entirely avoidable and that avoidance is simple. However, using an out parameter to indicate success is only reasonable in certain cases, such as int.TryParse and DateTime.TryParseExact - where the caller can't easily determine whether or not their arguments are reasonable. Even then, the return value is usually the success/failure and the out parameter is the result of the method.</p>\n" }, { "answer_id": 164490, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 4, "selected": false, "text": "<p>If the consultant has written an application that's supposed to be able to keep track of users and only show the correct data to the correct users and it doesn't do that, then clearly something's wrong. A good consultant would find the problem and fix it. A bad consultant would tell you that it was asynchronicity.</p>\n" }, { "answer_id": 164497, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 5, "selected": true, "text": "<p>I would agree. These guys seem quite incompetent.</p>\n\n<p>(BTW, I'd check to see if in \"SomeProprietarySessionManagementLookup,\" they're using static data. Saw this -- with behavior <em>exactly as you describe</em> on a project I inherited several months ago. It was a total head-slap moment when we finally saw it ... And wished we could get face to face with the guys who wrote it ... )</p>\n" }, { "answer_id": 164499, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 2, "selected": false, "text": "<p>I agree with him in part -- it's definitely better to check y for zero rather than catching the (expensive) exception. The out bool isSuccessful seems really dated to me, but whatever.</p>\n\n<p>re: the asynchronous sessionid buffoonery -- may or may not be true, but it sounds like the consultant is blowing smoke for cover.</p>\n" }, { "answer_id": 164508, "author": "Steve Duitsman", "author_id": 4575, "author_profile": "https://Stackoverflow.com/users/4575", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/164468/does-this-consultant-know-what-hes-doing#164478\">Cody's rule of thumb is dead right.</a> If you have to ask, he probably doesn't.</p>\n\n<p>It seems like point two its patently incorrect. .NET's standards explain that if a method fails it should throw an exception, which seems closer to the original; not the consulstant's suggestion. Assuming the exception is accurately &amp; specifically describing the failure.</p>\n" }, { "answer_id": 164521, "author": "Simon", "author_id": 24039, "author_profile": "https://Stackoverflow.com/users/24039", "pm_score": 1, "selected": false, "text": "<p>The consultants created the code in the first place right? And it doesn't work. I think you have quite a bit of dirt on them already. </p>\n\n<p>The asynchronous answer sounds like BS, but there may be something in it. Presumably they have offered a suitable solution as well as pseudo-code describing the problem they themselves created. I would be more tempted to judge them on their solution rather than their expression of the problem. If their understanding is flawed their new solution won't work either. Then you'll know they are idiots. (In fact look round to see if you have a similar proof in any other areas of their code already)</p>\n\n<p>The other one is a code style issue. There are a lot of different ways to cope with that. I personally don't like that style, but there will be circumstances under which it is suitable.</p>\n" }, { "answer_id": 164526, "author": "Alf Zimmerman", "author_id": 24612, "author_profile": "https://Stackoverflow.com/users/24612", "pm_score": -1, "selected": false, "text": "<p>On the second point, I would not use exceptions here. Exceptions are reserved for exceptional cases.<br>\nHowever, division of anything by zero certainly does not equal zero (in math, at least), so this would be case specific.</p>\n" }, { "answer_id": 164530, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 0, "selected": false, "text": "<p>Typical \"consultant\" bollocks:</p>\n\n<ol>\n<li>The problem is with whatever SomeProprietarySessionManagementLookup is doing</li>\n<li>Exceptions are only expensive if they're thrown. Don't be afraid of <code>try..catch</code>, but throws should only occur in <em>exceptional</em> circumstances. If variable <code>y</code> <strong>shouldn't</strong> be zero then an <code>ArgumentOutOfRangeException</code> would be appropriate.</li>\n</ol>\n" }, { "answer_id": 164532, "author": "phreakre", "author_id": 12051, "author_profile": "https://Stackoverflow.com/users/12051", "pm_score": 0, "selected": false, "text": "<p>I have to agree with John Rudy. My gut tells me the problem is in SomeProprietarySessionManagementLookup(). </p>\n\n<p>.. and your consultants do not sound to sure of themselves.</p>\n" }, { "answer_id": 164545, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "<p>They're wrong on the async.</p>\n\n<p>The assignment happens and then the page redirects. The function can start something asynchronously and return (and could even conceivably alter the Session in its own way), but whatever it does return has to be assigned in the code you gave before the redirect.</p>\n\n<p>They're wrong on that defensive coding style in any low-level code and even in a higher-level function unless it's a specific business case that the 0 or NULL or empty string or whatever should be handled that way - in which case, it's always successful (that successful flag is a nasty code smell) and not an exception. Exceptions are for exceptions. You don't want to mask behaviors like this by coddling the callers of the functions. Catch things early and throw exceptions. I think Maguire covered this in Writing Solid Code or McConnell in Code Complete. Either way, it smells.</p>\n" }, { "answer_id": 164552, "author": "Tom", "author_id": 24227, "author_profile": "https://Stackoverflow.com/users/24227", "pm_score": 0, "selected": false, "text": "<p>Storing in Session in not async. So that isn't true unless that function is async. But even so, since it isn't calling a BeginCall and have something to call on completion, the next line of code wouldn't execute until the Session line is complete.</p>\n\n<p>For the second statement, while that could be used, it isn't exactly a best practice and you have a few things to note with it. You save the cost of throwing an exception, but wouldn't you want to know that you are trying to divide by zero instead of just moving past it?</p>\n\n<p>I don't think that is a solid suggestion at all.</p>\n" }, { "answer_id": 164565, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 3, "selected": false, "text": "<p>On the asynchronous part, the only way that could be true is if the assignment going on there is actually an indexer setter on Session that is hiding an asynchronous call with no callback indicating success/failure. This would seem to be a HORRIBLE design choice, and it looks like a core class in your framework, so I find it highly unlikely.</p>\n\n<p>Usually asynchronous calls have a way to specify a callback so you can determine what the result is, or if the operation was successful. The documentation for Session should be pretty clear though on if it is actually hiding an asynchronous call, but yeah... doesn't look like the consultant knows what he is talking about...</p>\n\n<hr>\n\n<p>The method call that is being assigned to the Session indexer cannot be asynch, because to get a value asynchronously, you HAVE to use a callback... no way around that, so if there is no explicit callback, it's definitely not asynch (well, internally there could be an asynchronous call, but the caller of the method would perceive it as synchronous, so it is irrelevant if the method internally for example invokes a web service asynchronously).</p>\n\n<hr>\n\n<p>For the second point, I think this would be much better, and keep the same functionality essentially:</p>\n\n<pre><code>int MyFunction(int x, int y)\n{\n if (y == 0)\n {\n // log it\n throw new DivideByZeroException(\"Divide by zero attempted!\");\n }\n\n return x / y; \n}\n</code></pre>\n" }, { "answer_id": 164584, "author": "BlackWasp", "author_id": 21862, "author_profile": "https://Stackoverflow.com/users/21862", "pm_score": 0, "selected": false, "text": "<p>Quite strange. On the second item it may or may not be faster. It certainly isn't the same functionality though.</p>\n" }, { "answer_id": 164652, "author": "Alvin", "author_id": 23637, "author_profile": "https://Stackoverflow.com/users/23637", "pm_score": 0, "selected": false, "text": "<p>I'm guessing your consultant is suggesting use a status variable instead of exception for error handling is a better practice? I don't agree. How often does people forgot or too lazy to do error checking for return values? Also, pass/fail variable is not informative. There are more things can go wrong other than divide by zero like integer x/y is too big or x is NaN. When things go wrong, status variable cannot tell you what went wrong, but exception can. Exception is for exceptional case, and divide by zero or NaN are definitely exceptional cases. </p>\n" }, { "answer_id": 164665, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 1, "selected": false, "text": "<p><strong>This guy does not know what he is doing</strong>. The obvious culprit is right here:</p>\n\n<pre><code>Session[\"UserID\"] = SomeProprietarySessionManagementLookup();\n</code></pre>\n" }, { "answer_id": 164723, "author": "Thom", "author_id": 24618, "author_profile": "https://Stackoverflow.com/users/24618", "pm_score": 0, "selected": false, "text": "<p>The session thing is possible. It's a bug, beyond doubt, but it could be that the write arrives at whatever custom session state provider you're using after the next read. The session state provider API accommodates locking to prevent this sort of thing, but if the implementor has just ignored all that, your consultant could be telling the truth.</p>\n\n<p>The second issue is also kinda valid. It's not quite idiomatic - it's a slightly reversed version of things like int.TryParse, which are there to avoid performance issues caused by throwing lots of exceptions. But unless you're calling that code an awful lot, it's unlikely it'll make a noticeable difference (compared to say, one less database query per page etc). It's certainly not something you should do by default.</p>\n" }, { "answer_id": 164750, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 2, "selected": false, "text": "<p>Asp.net sessions, if you're using the built-in providers, won't accidentally give you someone else's session. <code>SomeProprietarySessionManagementLookup()</code> is the likely culprit and is returning bad values or just not working.</p>\n\n<blockquote>\n<pre><code>Session[\"UserID\"] = SomeProprietarySessionManagementLookup();\n</code></pre>\n</blockquote>\n\n<p>First of all assigning the return value from an asynchronously SomeProprietarySessionManagementLookup() just wont work. The consultants code probably looks like:</p>\n\n<pre><code>public void SomeProprietarySessionManagementLookup()\n{\n // do some async lookup\n Action&lt;object&gt; d = delegate(object val)\n {\n LookupSession(); // long running thing that looks up the user.\n Session[\"UserID\"] = 1234; // Setting session manually\n };\n\n d.BeginInvoke(null,null,null); \n}\n</code></pre>\n\n<p>The consultant isn't totally full of BS, but they have written some buggy code. Response.Redirect() does throw a ThreadAbort, and if the proprietary method is asynchronous, asp.net <em>doesn't know to wait</em> for the asynchronous method to write back to the session before asp.net itself saves the session. This is probably why it sometimes works and sometimes doesn't. </p>\n\n<p>Their code might work if the asp.net session is in-process, but a state server or db server wouldn't. It's timing dependent.</p>\n\n<p>I tested the following. We use state server in development. This code works because the session is written to before the main thread finishes.</p>\n\n<pre><code>Action&lt;object&gt; d = delegate(object val)\n{\n System.Threading.Thread.Sleep(1000); // waits a little\n Session[\"rubbish\"] = DateTime.Now;\n};\n\nd.BeginInvoke(null, null, null);\nSystem.Threading.Thread.Sleep(5000); // waits a lot\n\nobject stuff = Session[\"rubbish\"];\nif( stuff == null ) stuff = \"not there\";\ndivStuff.InnerHtml = Convert.ToString(stuff);\n</code></pre>\n\n<p>This next snippet of code <strong>doesn't work</strong> because the session was already saved back to state server by the time the asynchronous method gets around to setting a session value.</p>\n\n<pre><code>Action&lt;object&gt; d = delegate(object val)\n{\n System.Threading.Thread.Sleep(5000); // waits a lot\n Session[\"rubbish\"] = DateTime.Now;\n};\n\nd.BeginInvoke(null, null, null);\n\n// wait removed - ends immediately.\nobject stuff = Session[\"rubbish\"];\nif( stuff == null ) stuff = \"not there\";\ndivStuff.InnerHtml = Convert.ToString(stuff);\n</code></pre>\n\n<p>The first step is for the consultant to make their code synchronous because their <em>performance trick</em> didn't work at all. If that fixes it, have the consultant properly implement using the <a href=\"http://msdn.microsoft.com/en-us/library/aa719599(VS.71).aspx\" rel=\"nofollow noreferrer\">Asynchronous Programming Design Pattern</a></p>\n" }, { "answer_id": 166928, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 0, "selected": false, "text": "<p>If SomeProprietarySessionManagementLookup(); is doing an asynchronous assignment it would more likely look like this:</p>\n\n<pre><code>SomeProprietarySessionManagementLookup(Session[\"UserID\"]);\n</code></pre>\n\n<p>The very fact that the code is assigning the result to Session[\"UserID\"] would suggest that it is not supposed to be asynchronous and the result should be obtained before Response.Redirect is called. If SomeProprietarySessionManagementLookup is returning before its result is calculated they have a design flaw anyway.</p>\n\n<p>The throw an exception or use an out parameter is a matter of opinion and circumstance and in actual practice won't amount to a hill of beans which ever way you do it. For the performance hit of exceptions to become an issue you would need to be calling the function a huge number of times which would probably be a problem in itself. </p>\n" }, { "answer_id": 176564, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "<p>If the consultants deployed their ASP.NET application on your server(s), then they may have deployed it in uncompiled form, which means there would be a bunch of *.cs files floating around that you could look at.</p>\n\n<p>If all you can find is compiled .NET assemblies (DLLs and EXEs) of theirs, then you should still be able to decompile them into somewhat readable source code. I'll bet if you look through the code you'll find them using static variables in their proprietary lookup code. You'd then have something very concrete to show your bosses.</p>\n" }, { "answer_id": 478692, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 0, "selected": false, "text": "<p>This entire answer stream is full of typical programmer attitudes. It reminds me of Joel's 'Things you should never do' article (rewrite from scratch.) We don't really know anything about the system, other than there's a bug, and some guy posted some code online. There are so many unknowns that it is ridiculous to say \"This guy does not know what he is doing.\" </p>\n" }, { "answer_id": 2404541, "author": "Keith Adler", "author_id": 135952, "author_profile": "https://Stackoverflow.com/users/135952", "pm_score": 0, "selected": false, "text": "<p>Rather than pile on the Consultant, you could just as easily pile on the person who procured their services. No consultant is perfect, nor is a hiring manager ... but at the end of the day the real direction you should be taking is very clear: <strong>instead of trying to find fault you should expend energy into working collaboratively to find solutions</strong>. No matter how skilled someone is at their roles and responsibilities they will certainly have deficiencies. If you determine there is a pattern of incompentencies then you may choose to transition to another resource going forward, but assigning blame has never solved a single problem in history.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12260/" ]
The IT department of a subsidiary of ours had a consulting company write them an ASP.NET application. Now it's having intermittent problems with mixing up who the current user is and has been known to show Joe some of Bob's data by mistake. The consultants were brought back to troubleshoot and we were invited to listen in on their explanation. Two things stuck out. First, the consultant lead provided this pseudo-code: ``` void MyFunction() { Session["UserID"] = SomeProprietarySessionManagementLookup(); Response.Redirect("SomeOtherPage.aspx"); } ``` He went on to say that the assignment of the session variable is asynchronous, which seemed untrue. Granted the call into the lookup function could do something asynchronously, but this seems unwise. Given that alleged asynchronousness, his theory was that the session variable was not being assigned before the redirect's inevitable ThreadAbort exception was raised. This faulure then prevented SomeOtherPage from displaying the correct user's data. Second, he gave an example of a coding best practice he recommends. Rather than writing: ``` int MyFunction(int x, int x) { try { return x / y; } catch(Exception ex) { // log it throw; } } ``` the technique he recommended was: ``` int MyFunction(int x, int y, out bool isSuccessful) { isSuccessful = false; if (y == 0) return 0; isSuccessful = true; return x / y; } ``` This will certainly work and could be better from a performance perspective in some situations. However, from these and other discussion points it just seemed to us that this team was not well-versed technically. Opinions?
I would agree. These guys seem quite incompetent. (BTW, I'd check to see if in "SomeProprietarySessionManagementLookup," they're using static data. Saw this -- with behavior *exactly as you describe* on a project I inherited several months ago. It was a total head-slap moment when we finally saw it ... And wished we could get face to face with the guys who wrote it ... )
164,496
<p>I've been reading about thread-safe singleton patterns here:</p> <p><a href="http://en.wikipedia.org/wiki/Singleton_pattern#C.2B.2B_.28using_pthreads.29" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Singleton_pattern#C.2B.2B_.28using_pthreads.29</a></p> <p>And it says at the bottom that the only safe way is to use pthread_once - which isn't available on Windows.</p> <p>Is that the <strong>only</strong> way of guaranteeing thread safe initialisation?</p> <p>I've read this thread on SO:</p> <p><a href="https://stackoverflow.com/questions/6915/thread-safe-lazy-contruction-of-a-singleton-in-c">Thread safe lazy construction of a singleton in C++</a></p> <p>And seems to hint at an atomic OS level swap and compare function, which I assume on Windows is:</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms683568.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms683568.aspx</a></p> <p>Can this do what I want?</p> <p><strong>Edit:</strong> I would like lazy initialisation and for there to only ever be one instance of the class.</p> <p>Someone on another site mentioned using a global inside a namespace (and he described a singleton as an anti-pattern) - how can it be an "anti-pattern"?</p> <p><strong>Accepted Answer:</strong><br> I've accepted <a href="https://stackoverflow.com/questions/164496/how-can-i-create-a-thread-safe-singleton-pattern-in-windows#164640">Josh's answer</a> as I'm using Visual Studio 2008 - NB: For future readers, if you aren't using this compiler (or 2005) - Don't use the accepted answer!!</p> <p><strong>Edit:</strong> <strong>The code works fine except the return statement - I get an error: error C2440: 'return' : cannot convert from 'volatile Singleton *' to 'Singleton *'. Should I modify the return value to be volatile Singleton *?</strong></p> <p><strong>Edit:</strong> Apparently const_cast&lt;> will remove the volatile qualifier. Thanks again to Josh.</p>
[ { "answer_id": 164517, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": -1, "selected": false, "text": "<p>There are many ways to do thread safe Singleton* initialization on windows. In fact some of them are even cross-platform. In the SO thread that you linked to, they were looking for a Singleton that is lazily constructed in C, which is a bit more specific, and can be a bit trickier to do right, given the intricacies of the memory model you are working under.</p>\n\n<ul>\n<li>which you should never use</li>\n</ul>\n" }, { "answer_id": 164534, "author": "Matthew Murdoch", "author_id": 4023, "author_profile": "https://Stackoverflow.com/users/4023", "pm_score": 4, "selected": false, "text": "<p>A simple way to guarantee <strong>cross-platform thread safe initialization of a singleton</strong> is to perform it explicitly (via a call to a static member function on the singleton) in the main thread of your application <strong>before</strong> your application starts any other threads (or at least any other threads that will access the singleton).</p>\n\n<p>Ensuring thread safe access to the singleton is then achieved in the usual way with mutexes/critical sections.</p>\n\n<p><strong>Lazy initialization</strong> can also be achieved using a similar mechanism. The usual problem encountered with this is that the mutex required to provide thread-safety is often initialized in the singleton itself which just pushes the thread-safety issue to initialization of the mutex/critical section. One way to overcome this issue is to create and initialize a mutex/critical section in the main thread of your application then pass it to the singleton via a call to a static member function. The heavyweight initialization of the singleton can then occur in a thread-safe manner using this pre-initialized mutex/critical section. For example:</p>\n\n<pre><code>// A critical section guard - create on the stack to provide \n// automatic locking/unlocking even in the face of uncaught exceptions\nclass Guard {\n private:\n LPCRITICAL_SECTION CriticalSection;\n\n public:\n Guard(LPCRITICAL_SECTION CS) : CriticalSection(CS) {\n EnterCriticalSection(CriticalSection);\n }\n\n ~Guard() {\n LeaveCriticalSection(CriticalSection);\n }\n};\n\n// A thread-safe singleton\nclass Singleton {\n private:\n static Singleton* Instance;\n static CRITICAL_SECTION InitLock;\n CRITICIAL_SECTION InstanceLock;\n\n Singleton() {\n // Time consuming initialization here ...\n\n InitializeCriticalSection(&amp;InstanceLock);\n }\n\n ~Singleton() {\n DeleteCriticalSection(&amp;InstanceLock);\n }\n\n public:\n // Not thread-safe - to be called from the main application thread\n static void Create() {\n InitializeCriticalSection(&amp;InitLock);\n Instance = NULL;\n }\n\n // Not thread-safe - to be called from the main application thread\n static void Destroy() {\n delete Instance;\n DeleteCriticalSection(&amp;InitLock);\n }\n\n // Thread-safe lazy initializer\n static Singleton* GetInstance() {\n Guard(&amp;InitLock);\n\n if (Instance == NULL) {\n Instance = new Singleton;\n }\n\n return Instance;\n }\n\n // Thread-safe operation\n void doThreadSafeOperation() {\n Guard(&amp;InstanceLock);\n\n // Perform thread-safe operation\n }\n};\n</code></pre>\n\n<p>However, there are good reasons to avoid the use of singletons altogether (and why they are sometimes referred to as an <strong>anti-pattern</strong>):</p>\n\n<ul>\n<li>They are essentially glorified global variables</li>\n<li>They can lead to high coupling between disparate parts of an application</li>\n<li>They can make unit testing more complicated or impossible (due to the difficultly in swapping real singletons with fake implementations)</li>\n</ul>\n\n<p>An alternative is to make use of a 'logical singleton' whereby you create and initialise a single instance of a class in the main thread and pass it to the objects which require it. This approach can become unwieldy where there are many objects which you want to create as singletons. In this case the disparate objects can be bundled into a single 'Context' object which is then passed around where necessary.</p>\n" }, { "answer_id": 164537, "author": "Henk", "author_id": 4613, "author_profile": "https://Stackoverflow.com/users/4613", "pm_score": 1, "selected": false, "text": "<p>You can use an OS primitive such as mutex or critical section to ensure thread safe initialization however this will incur an overhead each time your singleton pointer is accessed (due to acquiring a lock). It's also non portable.</p>\n" }, { "answer_id": 164550, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 1, "selected": false, "text": "<p>There is one clarifying point you need to consider for this question. Do you require ...</p>\n\n<ol>\n<li>That one and only one instance of a class is ever actually created</li>\n<li>Many instances of a class can be created but there should only be one true definitive instance of the class</li>\n</ol>\n\n<p>There are many samples on the web to implement these patterns in C++. Here's a <a href=\"http://www.codeproject.com/KB/cpp/singletonrvs.aspx\" rel=\"nofollow noreferrer\">Code Project Sample</a></p>\n" }, { "answer_id": 164588, "author": "Eric", "author_id": 6367, "author_profile": "https://Stackoverflow.com/users/6367", "pm_score": 0, "selected": false, "text": "<p>The following explains how to do it in C#, but the exact same concept applies to any programming language that would support the singleton pattern</p>\n\n<p><a href=\"http://www.yoda.arachsys.com/csharp/singleton.html\" rel=\"nofollow noreferrer\">http://www.yoda.arachsys.com/csharp/singleton.html</a></p>\n\n<p>What you need to decide is wheter you want lazy initialization or not. Lazy initialization means that the object contained inside the singleton is created on the first call to it\nex : </p>\n\n<pre><code>MySingleton::getInstance()-&gt;doWork();\n</code></pre>\n\n<p>if that call isnt made until later on, there is a danger of a race condition between the threads as explained in the article. However, if you put</p>\n\n<pre><code>MySingleton::getInstance()-&gt;initSingleton();\n</code></pre>\n\n<p>at the very beginning of your code where you assume it would be thread safe, then you are no longer lazy initializing, you will require \"some\" more processing power when your application starts. However it will solve a lot of headaches about race conditions if you do so.</p>\n" }, { "answer_id": 164640, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 5, "selected": true, "text": "<p>If you are are using Visual C++ 2005/2008 you can use the double checked locking pattern, since \"<a href=\"http://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Microsoft_Visual_C.2B.2B\" rel=\"noreferrer\">volatile variables behave as fences</a>\". This is the most efficient way to implement a lazy-initialized singleton.</p>\n\n<p>From <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163405.aspx\" rel=\"noreferrer\">MSDN Magazine:</a></p>\n\n<pre><code>Singleton* GetSingleton()\n{\n volatile static Singleton* pSingleton = 0;\n\n if (pSingleton == NULL)\n {\n EnterCriticalSection(&amp;cs);\n\n if (pSingleton == NULL)\n {\n try\n {\n pSingleton = new Singleton();\n }\n catch (...)\n {\n // Something went wrong.\n }\n }\n\n LeaveCriticalSection(&amp;cs);\n }\n\n return const_cast&lt;Singleton*&gt;(pSingleton);\n}\n</code></pre>\n\n<p>Whenever you need access to the singleton, just call GetSingleton(). The first time it is called, the static pointer will be initialized. After it's initialized, the NULL check will prevent locking for just reading the pointer.</p>\n\n<p><em>DO NOT</em> use this on just any compiler, as it's not portable. The standard makes no guarantees on how this will work. Visual C++ 2005 explicitly adds to the semantics of volatile to make this possible.</p>\n\n<p>You'll have to declare and <a href=\"http://msdn.microsoft.com/en-us/library/ms683472(VS.85).aspx\" rel=\"noreferrer\">initialize the CRITICAL SECTION</a> elsewhere in code. But that initialization is cheap, so lazy initialization is usually not important.</p>\n" }, { "answer_id": 223198, "author": "mmocny", "author_id": 29701, "author_profile": "https://Stackoverflow.com/users/29701", "pm_score": 0, "selected": false, "text": "<p>If you are looking for a more portable, and easier solution, you could turn to boost.</p>\n\n<p><a href=\"http://www.boost.org/doc/libs/1_32_0/doc/html/call_once.html\" rel=\"nofollow noreferrer\">boost::call_once</a> can be used for thread safe initialization.</p>\n\n<p>Its pretty simple to use, and will be part of the next C++0x standard.</p>\n" }, { "answer_id": 10252928, "author": "TripShock", "author_id": 179895, "author_profile": "https://Stackoverflow.com/users/179895", "pm_score": 2, "selected": false, "text": "<p>While I like the accepted solution, I just found another promising lead and thought I should share it here: <a href=\"http://msdn.microsoft.com/en-us/library/aa363808%28v=VS.85%29.aspx\" rel=\"nofollow\" title=\"One-Time Initialization &#40;Windows&#41;\">One-Time Initialization (Windows)</a></p>\n" }, { "answer_id": 11131957, "author": "zhaorufei", "author_id": 64469, "author_profile": "https://Stackoverflow.com/users/64469", "pm_score": 0, "selected": false, "text": "<p>The question does not require the singleton is lazy-constructed or not. \nSince many answers assume that, I assume that for the first phrase discuss:</p>\n\n<p>Given the fact that the language itself is not thread-awareness, and plus the optimization technique, writing a portable reliable c++ singleton is very hard (if not impossible), see \"<a href=\"http://erdani.org/publications/DDJ_Jul_Aug_2004_revised.pdf\" rel=\"nofollow\">C++ and the Perils of Double-Checked Locking</a>\" by Scott Meyers and Andrei Alexandrescu.</p>\n\n<p>I've seen many of the answer resort to sync object on windows platform by using CriticalSection, but CriticalSection is only thread-safe when all the threads is running on one single processor, today it's probably not true.</p>\n\n<p>MSDN cite: \"The threads of a single process can use a critical section object for mutual-exclusion synchronization. \".</p>\n\n<p>And <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms682530%28v=vs.85%29.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/windows/desktop/ms682530(v=vs.85).aspx</a></p>\n\n<p>clearify it further:</p>\n\n<p>A critical section object provides synchronization similar to that provided by a mutex object, except that a critical section can be used only by the threads of a single process.</p>\n\n<p>Now, if \"lazy-constructed\" is not a requirement, the following solution is both cross-module safe and thread-safe, and even portable:</p>\n\n<pre><code>struct X { };\n\nX * get_X_Instance()\n{\n static X x;\n return &amp;x;\n}\nextern int X_singleton_helper = (get_X_instance(), 1);\n</code></pre>\n\n<p>It's cross-module-safe because we use locally-scoped static object instead of file/namespace scoped global object.</p>\n\n<p>It's thread-safe because: X_singleton_helper must be assigned to the correct value before entering main or DllMain It's not lazy-constructed also because of this fact), in this expression the comma is an operator, not punctuation.</p>\n\n<p>Explicitly use \"extern\" here to prevent compiler optimize it out(Concerns about Scott Meyers article, the big enemy is optimizer.), and also make static-analyze tool such as pc-lint keep silent. \"Before main/DllMain\" is Scott meyer called \"single-threaded startup part\" in \"Effective C++ 3rd\" item 4.</p>\n\n<p>However, I'm not very sure about whether compiler is allowed to optimize the call the get_X_instance() out according to the language standard, please comment.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
I've been reading about thread-safe singleton patterns here: <http://en.wikipedia.org/wiki/Singleton_pattern#C.2B.2B_.28using_pthreads.29> And it says at the bottom that the only safe way is to use pthread\_once - which isn't available on Windows. Is that the **only** way of guaranteeing thread safe initialisation? I've read this thread on SO: [Thread safe lazy construction of a singleton in C++](https://stackoverflow.com/questions/6915/thread-safe-lazy-contruction-of-a-singleton-in-c) And seems to hint at an atomic OS level swap and compare function, which I assume on Windows is: <http://msdn.microsoft.com/en-us/library/ms683568.aspx> Can this do what I want? **Edit:** I would like lazy initialisation and for there to only ever be one instance of the class. Someone on another site mentioned using a global inside a namespace (and he described a singleton as an anti-pattern) - how can it be an "anti-pattern"? **Accepted Answer:** I've accepted [Josh's answer](https://stackoverflow.com/questions/164496/how-can-i-create-a-thread-safe-singleton-pattern-in-windows#164640) as I'm using Visual Studio 2008 - NB: For future readers, if you aren't using this compiler (or 2005) - Don't use the accepted answer!! **Edit:** **The code works fine except the return statement - I get an error: error C2440: 'return' : cannot convert from 'volatile Singleton \*' to 'Singleton \*'. Should I modify the return value to be volatile Singleton \*?** **Edit:** Apparently const\_cast<> will remove the volatile qualifier. Thanks again to Josh.
If you are are using Visual C++ 2005/2008 you can use the double checked locking pattern, since "[volatile variables behave as fences](http://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Microsoft_Visual_C.2B.2B)". This is the most efficient way to implement a lazy-initialized singleton. From [MSDN Magazine:](http://msdn.microsoft.com/en-us/magazine/cc163405.aspx) ``` Singleton* GetSingleton() { volatile static Singleton* pSingleton = 0; if (pSingleton == NULL) { EnterCriticalSection(&cs); if (pSingleton == NULL) { try { pSingleton = new Singleton(); } catch (...) { // Something went wrong. } } LeaveCriticalSection(&cs); } return const_cast<Singleton*>(pSingleton); } ``` Whenever you need access to the singleton, just call GetSingleton(). The first time it is called, the static pointer will be initialized. After it's initialized, the NULL check will prevent locking for just reading the pointer. *DO NOT* use this on just any compiler, as it's not portable. The standard makes no guarantees on how this will work. Visual C++ 2005 explicitly adds to the semantics of volatile to make this possible. You'll have to declare and [initialize the CRITICAL SECTION](http://msdn.microsoft.com/en-us/library/ms683472(VS.85).aspx) elsewhere in code. But that initialization is cheap, so lazy initialization is usually not important.
164,575
<p>I'm writing out XML files using the MSXML parser, with a wrapper I downloaded from here: <a href="http://www.codeproject.com/KB/XML/JW_CXml.aspx" rel="noreferrer">http://www.codeproject.com/KB/XML/JW_CXml.aspx</a>. Works great except that when I create a new document from code (so not load from file and modify), the result is all in one big line. I'd like elements to be indented nicely so that I can read it easily in a text editor.</p> <p>Googling shows many people with the same question - asked around 2001 or so. Replies usually say 'apply an XSL transformation' or 'add your own whitespace nodes'. Especially the last one makes me go %( so I'm hoping that in 2008 there's an easier way to pretty MSXML output. So my question; is there, and how do I use it?</p>
[ { "answer_id": 164610, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 0, "selected": false, "text": "<p>Unless the library has a format option then the only other way is to use XSLT, or an external pretty printer ( I think htmltidy can also do xml)\nThere doen't seem to be an option in the codeproject lib but you can specify an XSLT stylesheet to MSXML.</p>\n" }, { "answer_id": 164662, "author": "Torlack", "author_id": 5243, "author_profile": "https://Stackoverflow.com/users/5243", "pm_score": 3, "selected": true, "text": "<p>Try this, I found this years ago on the web.</p>\n\n<pre><code>#include &lt;msxml2.h&gt;\n\nbool FormatDOMDocument (IXMLDOMDocument *pDoc, IStream *pStream)\n{\n\n // Create the writer\n\n CComPtr &lt;IMXWriter&gt; pMXWriter;\n if (FAILED (pMXWriter.CoCreateInstance(__uuidof (MXXMLWriter), NULL, CLSCTX_ALL)))\n {\n return false;\n }\n CComPtr &lt;ISAXContentHandler&gt; pISAXContentHandler;\n if (FAILED (pMXWriter.QueryInterface(&amp;pISAXContentHandler)))\n {\n return false;\n }\n CComPtr &lt;ISAXErrorHandler&gt; pISAXErrorHandler;\n if (FAILED (pMXWriter.QueryInterface (&amp;pISAXErrorHandler)))\n {\n return false;\n }\n CComPtr &lt;ISAXDTDHandler&gt; pISAXDTDHandler;\n if (FAILED (pMXWriter.QueryInterface (&amp;pISAXDTDHandler)))\n {\n return false;\n }\n\n if (FAILED (pMXWriter -&gt;put_omitXMLDeclaration (VARIANT_FALSE)) ||\n FAILED (pMXWriter -&gt;put_standalone (VARIANT_TRUE)) ||\n FAILED (pMXWriter -&gt;put_indent (VARIANT_TRUE)) ||\n FAILED (pMXWriter -&gt;put_encoding (L\"UTF-8\")))\n {\n return false;\n }\n\n // Create the SAX reader\n\n CComPtr &lt;ISAXXMLReader&gt; pSAXReader;\n if (FAILED (pSAXReader.CoCreateInstance (__uuidof (SAXXMLReader), NULL, CLSCTX_ALL)))\n {\n return false;\n }\n\n if (FAILED (pSAXReader -&gt;putContentHandler (pISAXContentHandler)) ||\n FAILED (pSAXReader -&gt;putDTDHandler (pISAXDTDHandler)) ||\n FAILED (pSAXReader -&gt;putErrorHandler (pISAXErrorHandler)) ||\n FAILED (pSAXReader -&gt;putProperty (\n L\"http://xml.org/sax/properties/lexical-handler\", CComVariant (pMXWriter))) ||\n FAILED (pSAXReader -&gt;putProperty (\n L\"http://xml.org/sax/properties/declaration-handler\", CComVariant (pMXWriter))))\n {\n return false;\n }\n\n // Perform the write\n\n return \n SUCCEEDED (pMXWriter -&gt;put_output (CComVariant (pStream))) &amp;&amp;\n SUCCEEDED (pSAXReader -&gt;parse (CComVariant (pDoc)));\n}\n</code></pre>\n" }, { "answer_id": 164747, "author": "Roel", "author_id": 11449, "author_profile": "https://Stackoverflow.com/users/11449", "pm_score": 2, "selected": false, "text": "<p>Here's a modified version of the accepted answer that will transform in-memory (changes only in the last few lines but I'm posting the whole block for the convenience of future readers):</p>\n\n<pre><code>bool CXml::FormatDOMDocument(IXMLDOMDocument *pDoc)\n{\n // Create the writer\n CComPtr &lt;IMXWriter&gt; pMXWriter;\n if (FAILED (pMXWriter.CoCreateInstance(__uuidof (MXXMLWriter), NULL, CLSCTX_ALL))) {\n return false;\n }\n CComPtr &lt;ISAXContentHandler&gt; pISAXContentHandler;\n if (FAILED (pMXWriter.QueryInterface(&amp;pISAXContentHandler))) {\n return false;\n }\n CComPtr &lt;ISAXErrorHandler&gt; pISAXErrorHandler;\n if (FAILED (pMXWriter.QueryInterface (&amp;pISAXErrorHandler))) {\n return false;\n }\n CComPtr &lt;ISAXDTDHandler&gt; pISAXDTDHandler;\n if (FAILED (pMXWriter.QueryInterface (&amp;pISAXDTDHandler))) {\n return false;\n }\n\n if (FAILED (pMXWriter-&gt;put_omitXMLDeclaration (VARIANT_FALSE)) ||\n FAILED (pMXWriter-&gt;put_standalone (VARIANT_TRUE)) ||\n FAILED (pMXWriter-&gt;put_indent (VARIANT_TRUE)) ||\n FAILED (pMXWriter-&gt;put_encoding (L\"UTF-8\")))\n {\n return false;\n }\n\n // Create the SAX reader\n CComPtr &lt;ISAXXMLReader&gt; pSAXReader;\n if (FAILED(pSAXReader.CoCreateInstance(__uuidof (SAXXMLReader), NULL, CLSCTX_ALL))) {\n return false;\n }\n\n if (FAILED(pSAXReader-&gt;putContentHandler (pISAXContentHandler)) ||\n FAILED(pSAXReader-&gt;putDTDHandler (pISAXDTDHandler)) ||\n FAILED(pSAXReader-&gt;putErrorHandler (pISAXErrorHandler)) ||\n FAILED(pSAXReader-&gt;putProperty (L\"http://xml.org/sax/properties/lexical-handler\", CComVariant (pMXWriter))) ||\n FAILED(pSAXReader-&gt;putProperty (L\"http://xml.org/sax/properties/declaration-handler\", CComVariant (pMXWriter))))\n {\n return false;\n }\n\n // Perform the write\n bool success1 = SUCCEEDED(pMXWriter-&gt;put_output(CComVariant(pDoc.GetInterfacePtr())));\n bool success2 = SUCCEEDED(pSAXReader-&gt;parse(CComVariant(pDoc.GetInterfacePtr())));\n\n return success1 &amp;&amp; success2;\n}\n</code></pre>\n" }, { "answer_id": 164749, "author": "mitchnull", "author_id": 18645, "author_profile": "https://Stackoverflow.com/users/18645", "pm_score": 0, "selected": false, "text": "<p>I've written a sed script a while back for basic xml indenting. You can use it as an external indenter if all else fails (save this to xmlindent.sed, and process your xml with <em>sed -f xmlindent.sed &lt;filename&gt;</em>). You might need cygwin or some other posix environment to use it though.</p>\n\n<p>Here's the source:</p>\n\n<pre><code>:a\n/&gt;/!N;s/\\n/ /;ta\ns/ / /g;s/^ *//;s/ */ /g\n/^&lt;!--/{\n:e\n/--&gt;/!N;s/\\n//;te\ns/--&gt;/\\n/;D;\n}\n/^&lt;[?!][^&gt;]*&gt;/{\nH;x;s/\\n//;s/&gt;.*$/&gt;/;p;bb\n}\n/^&lt;\\/[^&gt;]*&gt;/{\nH;x;s/\\n//;s/&gt;.*$/&gt;/;s/^ //;p;bb\n}\n/^&lt;[^&gt;]*\\/&gt;/{\nH;x;s/\\n//;s/&gt;.*$/&gt;/;p;bb\n}\n/^&lt;[^&gt;]*[^\\/]&gt;/{\nH;x;s/\\n//;s/&gt;.*$/&gt;/;p;s/^/ /;bb\n}\n/&lt;/!ba\n{\nH;x;s/\\n//;s/ *&lt;.*$//;p;s/[^ ].*$//;x;s/^[^&lt;]*//;ba\n}\n:b\n{\ns/[^ ].*$//;x;s/^&lt;[^&gt;]*&gt;//;ba\n}\n</code></pre>\n\n<p>Hrmp, tabs seem to be garbled... You can copy-waste from here instead: <a href=\"http://mitchnull.blogspot.com/2008/09/xml-indenting-with-sed1.html\" rel=\"nofollow noreferrer\">XML indenting with sed(1)</a></p>\n" }, { "answer_id": 36982487, "author": "klaus triendl", "author_id": 279251, "author_profile": "https://Stackoverflow.com/users/279251", "pm_score": 2, "selected": false, "text": "<p>Even my 2 cents arrive 7 years later I think the question still deserves a simple answer wrapped in just a few lines of code, which is possible by using Visual C++'s <code>#import</code> directive and the native C++ COM support library (offering smart pointers and encapsulating error handling).</p>\n\n<p>Note that like the accepted answer it doesn't try to fit into the <code>CXml</code> class the OP is using but rather shows the core idea. Also I assume <code>msxml6</code>.</p>\n\n<p><strong>Pretty-printing to any stream</strong></p>\n\n<pre><code>void PrettyWriteXmlDocument(MSXML2::IXMLDOMDocument* xmlDoc, IStream* stream)\n{\n MSXML2::IMXWriterPtr writer(__uuidof(MSXML2::MXXMLWriter60));\n writer-&gt;encoding = L\"utf-8\";\n writer-&gt;indent = _variant_t(true);\n writer-&gt;standalone = _variant_t(true);\n writer-&gt;output = stream;\n\n MSXML2::ISAXXMLReaderPtr saxReader(__uuidof(MSXML2::SAXXMLReader60));\n saxReader-&gt;putContentHandler(MSXML2::ISAXContentHandlerPtr(writer));\n saxReader-&gt;putProperty(PUSHORT(L\"http://xml.org/sax/properties/lexical-handler\"), writer.GetInterfacePtr());\n saxReader-&gt;parse(xmlDoc);\n}\n</code></pre>\n\n<p><strong>File stream</strong></p>\n\n<p>If you need a stream writing to a file you need an implementation of the <code>IStream</code> interface.<br>\n<a href=\"https://gitlab.com/FireDaemon/open-source/wtlext/blob/master/include/wtlext/filestream.h\" rel=\"nofollow noreferrer\">wtlext</a> has got a class, which you can use or from which you can deduce how you can write your own.</p>\n\n<p>Another simple solution that has worked well for me is utilising the Ado Stream class:</p>\n\n<pre><code>void PrettySaveXmlDocument(MSXML2::IXMLDOMDocument* xmlDoc, const wchar_t* filePath)\n{\n ADODB::_StreamPtr stream(__uuidof(ADODB::Stream));\n stream-&gt;Type = ADODB::adTypeBinary;\n stream-&gt;Open(vtMissing, ADODB::adModeUnknown, ADODB::adOpenStreamUnspecified, _bstr_t(), _bstr_t());\n PrettyWriteXmlDocument(xmlDoc, IStreamPtr(stream));\n stream-&gt;SaveToFile(filePath, ADODB::adSaveCreateOverWrite);\n}\n</code></pre>\n\n<p><strong>Glueing it together</strong></p>\n\n<p>A simplistic <code>main</code> function shows this in action:</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;objbase.h&gt;\n#include &lt;comutil.h&gt;\n#include &lt;comdef.h&gt;\n#include &lt;comdefsp.h&gt;\n#import &lt;msxml6.dll&gt;\n#import &lt;msado60.tlb&gt; rename(\"EOF\", \"EndOfFile\") // requires: /I $(CommonProgramFiles)\\System\\ado\n\n\nvoid PrettyWriteXmlDocument(MSXML2::IXMLDOMDocument* xmlDoc, IStream* stream);\nvoid PrettySaveXmlDocument(MSXML2::IXMLDOMDocument* xmlDoc, const wchar_t* filePath);\n\n\nint wmain()\n{\n CoInitializeEx(nullptr, COINIT_MULTITHREADED);\n\n try\n {\n MSXML2::IXMLDOMDocumentPtr xmlDoc(__uuidof(MSXML2::DOMDocument60));\n xmlDoc-&gt;appendChild(xmlDoc-&gt;createElement(L\"root\"));\n\n PrettySaveXmlDocument(xmlDoc, L\"xmldoc.xml\");\n }\n catch (const _com_error&amp;)\n {\n }\n\n CoUninitialize();\n\n return EXIT_SUCCESS;\n}\n\n\n// assume definitions of PrettyWriteXmlDocument and PrettySaveXmlDocument go here\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11449/" ]
I'm writing out XML files using the MSXML parser, with a wrapper I downloaded from here: <http://www.codeproject.com/KB/XML/JW_CXml.aspx>. Works great except that when I create a new document from code (so not load from file and modify), the result is all in one big line. I'd like elements to be indented nicely so that I can read it easily in a text editor. Googling shows many people with the same question - asked around 2001 or so. Replies usually say 'apply an XSL transformation' or 'add your own whitespace nodes'. Especially the last one makes me go %( so I'm hoping that in 2008 there's an easier way to pretty MSXML output. So my question; is there, and how do I use it?
Try this, I found this years ago on the web. ``` #include <msxml2.h> bool FormatDOMDocument (IXMLDOMDocument *pDoc, IStream *pStream) { // Create the writer CComPtr <IMXWriter> pMXWriter; if (FAILED (pMXWriter.CoCreateInstance(__uuidof (MXXMLWriter), NULL, CLSCTX_ALL))) { return false; } CComPtr <ISAXContentHandler> pISAXContentHandler; if (FAILED (pMXWriter.QueryInterface(&pISAXContentHandler))) { return false; } CComPtr <ISAXErrorHandler> pISAXErrorHandler; if (FAILED (pMXWriter.QueryInterface (&pISAXErrorHandler))) { return false; } CComPtr <ISAXDTDHandler> pISAXDTDHandler; if (FAILED (pMXWriter.QueryInterface (&pISAXDTDHandler))) { return false; } if (FAILED (pMXWriter ->put_omitXMLDeclaration (VARIANT_FALSE)) || FAILED (pMXWriter ->put_standalone (VARIANT_TRUE)) || FAILED (pMXWriter ->put_indent (VARIANT_TRUE)) || FAILED (pMXWriter ->put_encoding (L"UTF-8"))) { return false; } // Create the SAX reader CComPtr <ISAXXMLReader> pSAXReader; if (FAILED (pSAXReader.CoCreateInstance (__uuidof (SAXXMLReader), NULL, CLSCTX_ALL))) { return false; } if (FAILED (pSAXReader ->putContentHandler (pISAXContentHandler)) || FAILED (pSAXReader ->putDTDHandler (pISAXDTDHandler)) || FAILED (pSAXReader ->putErrorHandler (pISAXErrorHandler)) || FAILED (pSAXReader ->putProperty ( L"http://xml.org/sax/properties/lexical-handler", CComVariant (pMXWriter))) || FAILED (pSAXReader ->putProperty ( L"http://xml.org/sax/properties/declaration-handler", CComVariant (pMXWriter)))) { return false; } // Perform the write return SUCCEEDED (pMXWriter ->put_output (CComVariant (pStream))) && SUCCEEDED (pSAXReader ->parse (CComVariant (pDoc))); } ```
164,585
<p>I'm serializing an object in a C# VS2003 / .Net 1.1 application. I need it serialized without the processing instruction, however. The XmlSerializer class puts out something like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-16" ?&gt; &lt;MyObject&gt; &lt;Property1&gt;Data&lt;/Property1&gt; &lt;Property2&gt;More Data&lt;/Property2&gt; &lt;/MyObject&gt; </code></pre> <p>Is there any way to get something like the following, without processing the resulting text to remove the tag?</p> <pre><code>&lt;MyObject&gt; &lt;Property1&gt;Data&lt;/Property1&gt; &lt;Property2&gt;More Data&lt;/Property2&gt; &lt;/MyObject&gt; </code></pre> <p>For those that are curious, my code looks like this...</p> <pre><code>XmlSerializer serializer = new XmlSerializer(typeof(MyObject)); StringBuilder builder = new StringBuilder(); using ( TextWriter stringWriter = new StringWriter(builder) ) { serializer.Serialize(stringWriter, comments); return builder.ToString(); } </code></pre>
[ { "answer_id": 164599, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "<p>In 2.0, you would use <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.omitxmldeclaration.aspx\" rel=\"noreferrer\">XmLWriterSettings.OmitXmlDeclaration</a>, and serialize to an XmlWriter - however I don't think this exists in 1.1; so not <em>entirely</em> useful - but just one more \"consider upgrading\" thing... and yes, I realise it isn't always possible.</p>\n" }, { "answer_id": 164604, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 0, "selected": false, "text": "<p>If by \"processing instruction\" you mean the xml declaration, then you can avoid this by setting the OmitXmlDeclaration property of XmlWriterSettings. You'll need to serialize using an XmlWriter, to accomplish this.</p>\n\n<pre><code>XmlSerializer serializer = new XmlSerializer(typeof(MyObject));\nStringBuilder builder = new StringBuilder();\nXmlWriterSettings settings = new XmlWriterSettings();\nsettings.OmitXmlDeclaration = true;\n\nusing ( XmlWriter stringWriter = new StringWriter(builder, settings) )\n{\n serializer.Serialize(stringWriter, comments);\n return builder.ToString();\n}\n</code></pre>\n\n<p>But ah, this doesn't answer your question for 1.1. Well, for reference to others.</p>\n" }, { "answer_id": 164608, "author": "DaveK", "author_id": 4244, "author_profile": "https://Stackoverflow.com/users/4244", "pm_score": 3, "selected": true, "text": "<p>The following link will take you to a post where someone has a method of supressing the processing instruction by using an XmlWriter and getting into an 'Element' state rather than a 'Start' state. This causes the processing instruction to not be written.</p>\n\n<p><a href=\"http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.webservices/2004-03/0315.html\" rel=\"nofollow noreferrer\">Suppress Processing Instruction</a></p>\n\n<blockquote>\n <p>If you pass an XmlWriter to the serializer, it will only emit a processing \n instruction if the XmlWriter's state is 'Start' (i.e., has not had anything \n written to it yet). </p>\n</blockquote>\n\n<pre><code>// Assume we have a type named 'MyType' and a variable of this type named \n'myObject' \nSystem.Text.StringBuilder output = new System.Text.StringBuilder(); \nSystem.IO.StringWriter internalWriter = new System.IO.StringWriter(output); \nSystem.Xml.XmlWriter writer = new System.Xml.XmlTextWriter(internalWriter); \nSystem.Xml.Serialization.XmlSerializer serializer = new \nSystem.Xml.Serialization.XmlSerializer(typeof(MyType)); \n\n\nwriter.WriteStartElement(\"MyContainingElement\"); \nserializer.Serialize(writer, myObject); \nwriter.WriteEndElement(); \n</code></pre>\n\n<blockquote>\n <p>In this case, the writer will be in a state of 'Element' (inside an element) \n so no processing instruction will be written. One you finish writing the \n XML, you can extract the text from the underlying stream and process it to \n your heart's content.</p>\n</blockquote>\n" }, { "answer_id": 322091, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I made a small correction </p>\n\n<pre><code>XmlSerializer serializer = new XmlSerializer(typeof(MyObject));\nStringBuilder builder = new StringBuilder();\nXmlWriterSettings settings = new XmlWriterSettings();\nsettings.OmitXmlDeclaration = true;\nusing ( XmlWriter stringWriter = XmlWriter.Create(builder, settings) )\n{ \n serializer.Serialize(stringWriter, comments); \n return builder.ToString();\n}\n</code></pre>\n" }, { "answer_id": 590036, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 0, "selected": false, "text": "<p>This works in .NET 1.1. (But you should still consider upgrading)</p>\n\n<pre><code> XmlSerializer s1= new XmlSerializer(typeof(MyClass)); \n XmlSerializerNamespaces ns = new XmlSerializerNamespaces();\n ns.Add( \"\", \"\" );\n\n\n MyClass c= new MyClass();\n c.PropertyFromDerivedClass= \"Hallo\";\n\n sw = new System.IO.StringWriter();\n s1.Serialize(new XTWND(sw), c, ns);\n ....\n\n /// XmlTextWriterFormattedNoDeclaration\n /// helper class : eliminates the XML Documentation at the\n /// start of a XML doc. \n /// XTWFND = XmlTextWriterFormattedNoDeclaration\n public class XTWFND : System.Xml.XmlTextWriter\n {\n public XTWFND(System.IO.TextWriter w) : base(w) { Formatting = System.Xml.Formatting.Indented; }\n public override void WriteStartDocument() { }\n }\n</code></pre>\n" }, { "answer_id": 625915, "author": "NetSide", "author_id": 66018, "author_profile": "https://Stackoverflow.com/users/66018", "pm_score": 1, "selected": false, "text": "<p>What about omitting namespaces ?</p>\n\n<p>instead of using </p>\n\n<pre><code>XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();\n namespaces.Add(\"\", \"\");\n</code></pre>\n\n<p>ex:</p>\n\n<pre><code>&lt;message xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:xsd=\\\"http://www.w3.org/2001/XMLSchema\\\"&gt;\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24222/" ]
I'm serializing an object in a C# VS2003 / .Net 1.1 application. I need it serialized without the processing instruction, however. The XmlSerializer class puts out something like this: ``` <?xml version="1.0" encoding="utf-16" ?> <MyObject> <Property1>Data</Property1> <Property2>More Data</Property2> </MyObject> ``` Is there any way to get something like the following, without processing the resulting text to remove the tag? ``` <MyObject> <Property1>Data</Property1> <Property2>More Data</Property2> </MyObject> ``` For those that are curious, my code looks like this... ``` XmlSerializer serializer = new XmlSerializer(typeof(MyObject)); StringBuilder builder = new StringBuilder(); using ( TextWriter stringWriter = new StringWriter(builder) ) { serializer.Serialize(stringWriter, comments); return builder.ToString(); } ```
The following link will take you to a post where someone has a method of supressing the processing instruction by using an XmlWriter and getting into an 'Element' state rather than a 'Start' state. This causes the processing instruction to not be written. [Suppress Processing Instruction](http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.webservices/2004-03/0315.html) > > If you pass an XmlWriter to the serializer, it will only emit a processing > instruction if the XmlWriter's state is 'Start' (i.e., has not had anything > written to it yet). > > > ``` // Assume we have a type named 'MyType' and a variable of this type named 'myObject' System.Text.StringBuilder output = new System.Text.StringBuilder(); System.IO.StringWriter internalWriter = new System.IO.StringWriter(output); System.Xml.XmlWriter writer = new System.Xml.XmlTextWriter(internalWriter); System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(MyType)); writer.WriteStartElement("MyContainingElement"); serializer.Serialize(writer, myObject); writer.WriteEndElement(); ``` > > In this case, the writer will be in a state of 'Element' (inside an element) > so no processing instruction will be written. One you finish writing the > XML, you can extract the text from the underlying stream and process it to > your heart's content. > > >
164,597
<p>My server has both Subversion and Apache installed, and the Apache web directory is also a Subversion working copy. The reason for this is that the simple command <code>svn update /server/staging</code> will deploy the latest source to the staging server.</p> <p>Apache public web directory: <code>/server/staging</code> <em>— (This is an SVN working copy.)</em></p> <p>I have two users on my server, 'richard' and 'austin'. They both are members of the 'developers' group. I recursively set permissions on the /server directory to richard:developers, using "sudo chown -R richard:developers /server".</p> <p>I then set the permissions to read, write and execute for both 'richard' and the 'developers' group.</p> <p>So surely, 'austin' should now be able to use the <code>svn update /server/staging</code> command? However, when he tries, he gets the error:</p> <pre><code>svn: Can't open file '/server/staging/.svn/lock': Permission denied </code></pre> <p>If I recursively change the owner of /server to austin:developers, he can run the command just fine, but then 'richard' can't.</p> <p>How do I fix the problem? I want to create a post-commit hook with to automatically deploy the staging site when files are committed, but I can't see a way for that to work for both users. The hook would be:</p> <pre><code>/usr/bin/svn update /server/staging </code></pre> <p>Using the same user account for both of them wouldn't really be an acceptable solution, and I'm not aware of any way to run the command inside the hook as 'root'.</p> <p>Any help is appreciated!</p>
[ { "answer_id": 164646, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "<p>I would set up <code>svnserve</code> which is a simple Subversion server using the <code>svn://</code> protocol. You can set this up so it runs under its own user account, then the repository would only be accessed by that one user. This user could then have the correct privileges to run <code>svn update /server/staging</code> on a post-commit hook.</p>\n" }, { "answer_id": 164654, "author": "zappan", "author_id": 4723, "author_profile": "https://Stackoverflow.com/users/4723", "pm_score": 0, "selected": false, "text": "<p>in your svn repo, you can find a 'conf' directory where you set permissions. you have 3 files there:</p>\n\n<ul>\n<li>authz</li>\n<li>passwd</li>\n<li>svnserve.conf</li>\n</ul>\n\n<p>you set in the authz file which users have which kind of acces, per user or per group. you set groups there, SVN groups not linux user groups (hashed lines are comments):</p>\n\n<pre><code>[groups]\n# harry_and_sally = harry,sally\nprojectgroup = richard,austin\n\n# [/foo/bar]\n# harry = rw -- user harry has read/write access\n# * = -- everybody have no access\n\n# [repository:/baz/fuz]\n# @harry_and_sally = rw -- harry_and_sally group members have read/write access\n# * = r -- everyone has read access\n\n[/server/staging]\n@projectgroup = rw\n* = r\n</code></pre>\n\n<p>work around this example and set your config. in the 'passwd' file you set up users passwords. execute</p>\n\n<pre><code>cat passwd\n</code></pre>\n\n<p>you'll get commented file with explanation how to set it up.</p>\n" }, { "answer_id": 164670, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 4, "selected": true, "text": "<p>Directory Set Group ID</p>\n\n<p>If the setgid bit on a directory entry is set, files in that directory will have the group ownership as the directory, instead of than the group of the user that created the file.</p>\n\n<p>This attribute is helpful when several users need access to certain files. If the users work in a directory with the setgid attribute set then any files created in the directory by any of the users will have the permission of the group. For example, the administrator can create a group called spcprj and add the users Kathy and Mark to the group spcprj. The directory spcprjdir can be created with the set GID bit set and Kathy and Mark although in different primary groups can work in the directory and have full access to all files in that directory, but still not be able to access files in each other's primary group.</p>\n\n<p>The following command will set the GID bit on a directory:</p>\n\n<pre><code>chmod g+s spcprjdir\n</code></pre>\n\n<p>The directory listing of the directory \"spcprjdir\":</p>\n\n<pre><code>drwxrwsr-x 2 kathy spcprj 1674 Sep 17 1999 spcprjdir\n</code></pre>\n\n<p>The \"s'' in place of the execute bit in the group permissions causes all files written to the directory \"spcprjdir\" to belong to the group \"spcprj\" . </p>\n\n<p>edit: source = <a href=\"http://www.comptechdoc.org/os/linux/usersguide/linux_ugfilesp.html\" rel=\"nofollow noreferrer\">Linux Files and File Permissions</a></p>\n" }, { "answer_id": 164985, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 0, "selected": false, "text": "<p>I use WebDAV - all SVN updates and commits are handled via apache and I never have such problems.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326176/" ]
My server has both Subversion and Apache installed, and the Apache web directory is also a Subversion working copy. The reason for this is that the simple command `svn update /server/staging` will deploy the latest source to the staging server. Apache public web directory: `/server/staging` *— (This is an SVN working copy.)* I have two users on my server, 'richard' and 'austin'. They both are members of the 'developers' group. I recursively set permissions on the /server directory to richard:developers, using "sudo chown -R richard:developers /server". I then set the permissions to read, write and execute for both 'richard' and the 'developers' group. So surely, 'austin' should now be able to use the `svn update /server/staging` command? However, when he tries, he gets the error: ``` svn: Can't open file '/server/staging/.svn/lock': Permission denied ``` If I recursively change the owner of /server to austin:developers, he can run the command just fine, but then 'richard' can't. How do I fix the problem? I want to create a post-commit hook with to automatically deploy the staging site when files are committed, but I can't see a way for that to work for both users. The hook would be: ``` /usr/bin/svn update /server/staging ``` Using the same user account for both of them wouldn't really be an acceptable solution, and I'm not aware of any way to run the command inside the hook as 'root'. Any help is appreciated!
Directory Set Group ID If the setgid bit on a directory entry is set, files in that directory will have the group ownership as the directory, instead of than the group of the user that created the file. This attribute is helpful when several users need access to certain files. If the users work in a directory with the setgid attribute set then any files created in the directory by any of the users will have the permission of the group. For example, the administrator can create a group called spcprj and add the users Kathy and Mark to the group spcprj. The directory spcprjdir can be created with the set GID bit set and Kathy and Mark although in different primary groups can work in the directory and have full access to all files in that directory, but still not be able to access files in each other's primary group. The following command will set the GID bit on a directory: ``` chmod g+s spcprjdir ``` The directory listing of the directory "spcprjdir": ``` drwxrwsr-x 2 kathy spcprj 1674 Sep 17 1999 spcprjdir ``` The "s'' in place of the execute bit in the group permissions causes all files written to the directory "spcprjdir" to belong to the group "spcprj" . edit: source = [Linux Files and File Permissions](http://www.comptechdoc.org/os/linux/usersguide/linux_ugfilesp.html)
164,621
<p>I need to create reports in a C# .NET Windows app. I've got an SQL Server 2005 database, Visual Studio 2005 and am quite OK with creating stored procedures and datasets.</p> <p>Can someone please point me in the right direction for creating reports? I just can't seem work it out. Some examples would be a good start, or a simple How-to tutorial... anything really that is a bit better explained than the MSDN docs.</p> <p>I'm using the CrystalDecisions.Windows.Forms.CrystalReportViewer control to display the reports, I presume this is correct.</p> <p>If I'm about to embark on a long and complex journey, what's the simplest way to create and display reports that can also be printed?</p>
[ { "answer_id": 164666, "author": "alexmac", "author_id": 23066, "author_profile": "https://Stackoverflow.com/users/23066", "pm_score": 2, "selected": false, "text": "<p>Crystal is one possible option for creating reports. It has been around a long time and a lot of people seem to like it. </p>\n\n<p>You might want to take a look at SQL reporting services. I have used both but my preferance is SQL reporting services. Its pretty well integrated into studio and works similar to the other microsoft projects. Its also free with the sql express etc.</p>\n\n<p>This is a good article on beginning reporting services:\n<a href=\"http://www.simple-talk.com/sql/learn-sql-server/beginning-sql-server-2005-reporting-services-part-1/\" rel=\"nofollow noreferrer\">http://www.simple-talk.com/sql/learn-sql-server/beginning-sql-server-2005-reporting-services-part-1/</a></p>\n" }, { "answer_id": 164674, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "<p>I second alex's recommendation to look at sql reporting services - if you have a sql developer license, then you probably already have reporting services</p>\n\n<p>i don't like crystal reports, too much tedium in the designer (editing expressions all the time) too many server-deployment issues (check those license files!)</p>\n" }, { "answer_id": 165003, "author": "SeaDrive", "author_id": 19267, "author_profile": "https://Stackoverflow.com/users/19267", "pm_score": 1, "selected": false, "text": "<p>I use Crystal. I will outline my method briefly, but be aware that I'm a one man shop and it may not translate to your environment.</p>\n\n<p>First, create a form with a CR Viewer. Then:</p>\n\n<p>1) Figure out what data you need, and create a view that retrieves the desired columns.\n2) Create a new Crystal report using the wizard giving your view as the source of the data.\n3) Drag, drop, insert, delete, and whatever to rough your report into shape. Yes, it's tedious.\n4) Create the necessary button click or whatever, and create the function in which to generate the report.\n5) Retrieve the data to a DataTable (probably in a DataSet). You do not have to use the view.\n6) Create the report object. Set the DataTable to be the DataSource. Assign the report object to the CR Viewer. This is one part for which there are examples.</p>\n\n<p>Comments: </p>\n\n<p>If you lose the window with the database fields, etc (Field Explorer), go to View/Document Outline. (It's my fantasy to have Bill Gates on a stage and ask him to find it.)</p>\n\n<p>The reason for setting up the view is that if you want to add a column, you revise the view, and the Field Explorer will update automatically. I've had all sorts of trouble doing it other ways. This method also is a work-around for a bug that requires scanning through all the tables resetting which table they point to. You want to hand Crystal a single table. You do not want to try to get Crystal to join tables, etc. I don't say it doesn't work; I say it's harder.</p>\n\n<p>There is (or was) documentation for the VS implementation of Crystal on the Business Objects web site, but I believe that it has disappeared behind a register/login screen. (I could stand more info on that myself.) </p>\n\n<p>I've had trouble getting Crystal to page break when I want, and not page break when I don't want, etc. It's far from the best report writer I've ever used and I do not understand why it seems to have put so many others out of business. In addition, their licensing policies are very difficult to deal with in a small, fluid organization. </p>\n\n<p>Edited to add example:</p>\n\n<pre><code>AcctStatement oRpt = new AcctStatement() ;\noRpt.Database.Tables[0].SetDataSource(dsRpt.Tables[0]);\noRpt.SetParameterValue(\"plan_title\",sPlanName) ;\ncrViewer.ReportSource = oRpt ;\n</code></pre>\n" }, { "answer_id": 165794, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "<p>You can use the report viewer with client side reporting built into vs.net (ReportBuilder/ReportViewer control). You can create reports the same way as you do for sql reporting services, except you dont need sql server(nor asp.net). Plus you have complete control over them(how you present, how you collect data, what layer they are generated in, what you do with them after generating, such as mailing them, sending to ftp, etc). You can also export as PDF and excel. </p>\n\n<p>And in your case building up a report from data and user input, this may work great as you can build up your own datasource and data as you go along. Once your data is ready to be reported on, bind it to your report.</p>\n\n<p>The reports can easily be built in Visual Studio 2005 (Add a report to your project), and be shown in a Winforms app using the ReportViewer control.</p>\n\n<p>Here is a great book i recommend to everyone to look at if interested in client side reports. It gives a lot of great info and many different scenarios and ways to use client side reporting.</p>\n\n<p><a href=\"http://www.apress.com/book/view/9781590598542\" rel=\"nofollow noreferrer\">http://www.apress.com/book/view/9781590598542</a></p>\n" }, { "answer_id": 198738, "author": "Piku", "author_id": 18854, "author_profile": "https://Stackoverflow.com/users/18854", "pm_score": 1, "selected": false, "text": "<p>I found the following websites solved my problems. Included here for future reference.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms227490(VS.80).aspx\" rel=\"nofollow noreferrer\">CrystalReportViewer Object Model Tutorials</a> for the tutorial on how to make the whole thing work. And also <a href=\"http://msdn.microsoft.com/en-us/library/ms227453(VS.80).aspx\" rel=\"nofollow noreferrer\">Setting up a project to use Crystal Reports</a>\nand specifically <a href=\"http://msdn.microsoft.com/en-us/library/ms227525(VS.80).aspx\" rel=\"nofollow noreferrer\">preparing the form</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms227507(VS.80).aspx\" rel=\"nofollow noreferrer\">adding the control</a></p>\n" }, { "answer_id": 233111, "author": "Kramii", "author_id": 11514, "author_profile": "https://Stackoverflow.com/users/11514", "pm_score": 0, "selected": false, "text": "<p>I strongly recommend trying an alternative reporting solution - I have a lot of experience with Crystal, and have managed to do some funky things with it in .Net, but quite honestly the integration of Crystal and .Net is an absolute pig for anything but the simplest cases.</p>\n" }, { "answer_id": 278916, "author": "Piku", "author_id": 18854, "author_profile": "https://Stackoverflow.com/users/18854", "pm_score": 3, "selected": true, "text": "<p>I have managed to make this work now.</p>\n\n<p><strong>Brief Overview</strong></p>\n\n<p>It works by having a 'data class' which is just a regular C# class containing variables and no code. This is then instantiated and filled with data and then placed inside an ArrayList. The ArrayList is bound to the report viewer, along with the name of the report to load. In the report designer '.Net Objects' are used, rather than communicating with the database.</p>\n\n<p><strong>Explanation</strong></p>\n\n<p>I created a class to hold the data for my report. This class is manually filled by me by manually retrieving data from the database. How you do this doesn't matter, but here's an example:</p>\n\n<pre><code>DataSet ds = GeneratePickingNoteDataSet(id);\nforeach (DataRow row in ds.Tables[0].Rows) {\n CPickingNoteData pickingNoteData = new CPickingNoteData();\n\n pickingNoteData.delivery_date = (DateTime)row[\"delivery_date\"];\n pickingNoteData.cust_po = (int)row[\"CustomerPONumber\"];\n pickingNoteData.address = row[\"CustomerAddress\"].ToString();\n // ... and so on ...\n\n rptData.Add(pickingNoteData);\n}\n</code></pre>\n\n<p>The class is then put inside an ArrayList. Each element in the arraylist corresponds to one 'row' in the finished report.</p>\n\n<p>The first element in the list can also hold the report header data, and the last element in the list can hold the report footer data. And because this is an ArrayList, normal Array access can be used to get at them:</p>\n\n<pre><code>((CPickingNoteData)rptData[0]).header_date = DateTime.Now;\n((CPickingNoteData)rptData[rptData.Count-1]).footer_serial = GenerateSerialNumber();\n</code></pre>\n\n<p>Once you have an arraylist full of data, bind it to your report viewer like this, where 'rptData' is of type 'ArrayList'</p>\n\n<pre><code>ReportDocument reportDoc = new ReportDocument();\nreportDoc.Load(reportPath);\nreportDoc.SetDataSource(rptData);\ncrystalReportViewer.ReportSource = reportDoc;\n</code></pre>\n\n<p>Now you will need to bind your data class to the report itself. You do this inside the designer:</p>\n\n<ol>\n<li>Open the Field Explorer tab (which might be under the 'View' menu), and right-click \"Database Fields\"</li>\n<li>Click on 'Project Data'</li>\n<li>Click on '.NET Objects'</li>\n<li>Scroll down the list to find your\ndata class (if it isn't there,\ncompile your application)</li>\n<li>Press '>>' and then OK</li>\n<li>You can now drag the class members\nonto the report and arrange them as\nyou want.</li>\n</ol>\n" }, { "answer_id": 3884583, "author": "kumar", "author_id": 469448, "author_profile": "https://Stackoverflow.com/users/469448", "pm_score": 1, "selected": false, "text": "<p>i think this may help you out\n<a href=\"http://infynet.wordpress.com/2010/10/06/crystal-report-in-c/\" rel=\"nofollow\">http://infynet.wordpress.com/2010/10/06/crystal-report-in-c/</a></p>\n" }, { "answer_id": 7415604, "author": "Mark Vick", "author_id": 944498, "author_profile": "https://Stackoverflow.com/users/944498", "pm_score": 0, "selected": false, "text": "<p>I have tried RS. I am converting from RS back to Crystal. RS is just too heavy and slow (or something). There is no reason to have to wait 30 seconds for a report to render is RS when Crystal does it in under a second.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18854/" ]
I need to create reports in a C# .NET Windows app. I've got an SQL Server 2005 database, Visual Studio 2005 and am quite OK with creating stored procedures and datasets. Can someone please point me in the right direction for creating reports? I just can't seem work it out. Some examples would be a good start, or a simple How-to tutorial... anything really that is a bit better explained than the MSDN docs. I'm using the CrystalDecisions.Windows.Forms.CrystalReportViewer control to display the reports, I presume this is correct. If I'm about to embark on a long and complex journey, what's the simplest way to create and display reports that can also be printed?
I have managed to make this work now. **Brief Overview** It works by having a 'data class' which is just a regular C# class containing variables and no code. This is then instantiated and filled with data and then placed inside an ArrayList. The ArrayList is bound to the report viewer, along with the name of the report to load. In the report designer '.Net Objects' are used, rather than communicating with the database. **Explanation** I created a class to hold the data for my report. This class is manually filled by me by manually retrieving data from the database. How you do this doesn't matter, but here's an example: ``` DataSet ds = GeneratePickingNoteDataSet(id); foreach (DataRow row in ds.Tables[0].Rows) { CPickingNoteData pickingNoteData = new CPickingNoteData(); pickingNoteData.delivery_date = (DateTime)row["delivery_date"]; pickingNoteData.cust_po = (int)row["CustomerPONumber"]; pickingNoteData.address = row["CustomerAddress"].ToString(); // ... and so on ... rptData.Add(pickingNoteData); } ``` The class is then put inside an ArrayList. Each element in the arraylist corresponds to one 'row' in the finished report. The first element in the list can also hold the report header data, and the last element in the list can hold the report footer data. And because this is an ArrayList, normal Array access can be used to get at them: ``` ((CPickingNoteData)rptData[0]).header_date = DateTime.Now; ((CPickingNoteData)rptData[rptData.Count-1]).footer_serial = GenerateSerialNumber(); ``` Once you have an arraylist full of data, bind it to your report viewer like this, where 'rptData' is of type 'ArrayList' ``` ReportDocument reportDoc = new ReportDocument(); reportDoc.Load(reportPath); reportDoc.SetDataSource(rptData); crystalReportViewer.ReportSource = reportDoc; ``` Now you will need to bind your data class to the report itself. You do this inside the designer: 1. Open the Field Explorer tab (which might be under the 'View' menu), and right-click "Database Fields" 2. Click on 'Project Data' 3. Click on '.NET Objects' 4. Scroll down the list to find your data class (if it isn't there, compile your application) 5. Press '>>' and then OK 6. You can now drag the class members onto the report and arrange them as you want.
164,630
<p>My app open file in subdirectory of directory where it is executed, subdirectory is called <code>sample</code> and it contains files:</p> <ul> <li><code>example.raf</code> (example extension, non significant)</li> <li><code>background.gif</code></li> </ul> <p><code>example.raf</code> contains relative path to <code>background.gif</code> (in this case only file name cause the files is in same directory as raf) and opening of RAF causes application to read and display <code>background.gif</code>.</p> <p>When I use <code>OpenFileDialog</code> to load RAF file everything is alright, image loads correctly. I know that open file dialog changes in some way current working directory but i was unable to recreate this without calling open file dialog</p> <p>Unfortunately in case when i call <strong>raf reading</strong> method directly from code, without supplying path to file form <code>OpenFileDialog</code> like this</p> <pre><code>LoadRAF("sample\\example.raf"); </code></pre> <p>in this case i got problem, app try to load image from <strong>ExecutablePath</strong> and not from subdirectory which contains <strong>RAF</strong> file and <strong>image</strong>. Ofcourse it is normal behavior but in this case it is highkly unwanted. It is required to handle both relative and absolute type of paths in my app, so what should i do to solve this, how to <strong>change ExecutablePath</strong> or what other thing i can do to make this work at least as in case of <code>OpenFileDialog</code>?</p>
[ { "answer_id": 164667, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 1, "selected": false, "text": "<p>The OpenFileDialog is spitting out an absolute path behind the scenes.</p>\n\n<p>If you know the location of raf file you can do something like:</p>\n\n<pre><code>string parentPath = Directory.GetParent(rafFilePath);\nstring imagePath = Path.Combine(parentPath, imageFileNameFromRaf);\n</code></pre>\n\n<p>imagePath will now contain the absolute path to your image derived from the image name contained in the raf file, and the directory the raf file was in.</p>\n" }, { "answer_id": 1747737, "author": "Siarhei Kuchuk", "author_id": 212746, "author_profile": "https://Stackoverflow.com/users/212746", "pm_score": 2, "selected": false, "text": "<p>Next code from my project ZipSolution (<a href=\"http://zipsolution.codeplex.com/\" rel=\"nofollow noreferrer\">http://zipsolution.codeplex.com/</a>)\nshows how to resolve and create relative pathes in .net</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.IO;\n\nnamespace ZipSolution\n{\n internal static class RelativePathDiscovery\n {\n /// &lt;summary&gt;\n /// Produces relative path when possible to go from baseLocation to targetLocation\n /// &lt;/summary&gt;\n /// &lt;param name=\"baseLocation\"&gt;The root folder&lt;/param&gt;\n /// &lt;param name=\"targetLocation\"&gt;The target folder&lt;/param&gt;\n /// &lt;returns&gt;The relative path relative to baseLocation&lt;/returns&gt;\n /// &lt;exception cref=\"ArgumentNullException\"&gt;base or target locations are null or empty&lt;/exception&gt;\n public static string ProduceRelativePath(string baseLocation, string targetLocation)\n {\n if (string.IsNullOrEmpty(baseLocation))\n {\n throw new ArgumentNullException(\"baseLocation\");\n }\n\n if (string.IsNullOrEmpty(targetLocation))\n {\n throw new ArgumentNullException(\"targetLocation\");\n }\n\n if (!Path.IsPathRooted(baseLocation))\n {\n return baseLocation;\n }\n\n if (!Path.IsPathRooted(targetLocation))\n {\n return targetLocation;\n }\n\n if (string.Compare(Path.GetPathRoot(baseLocation), Path.GetPathRoot(targetLocation), true) != 0)\n {\n return targetLocation;\n }\n\n if (string.Compare(baseLocation, targetLocation, true) == 0)\n {\n return \".\";\n }\n\n string resultPath = \".\";\n\n if (!targetLocation.EndsWith(@\"\\\"))\n {\n targetLocation = targetLocation + @\"\\\";\n }\n\n if (baseLocation.EndsWith(@\"\\\"))\n {\n baseLocation = baseLocation.Substring(0, baseLocation.Length - 1);\n }\n\n while (!targetLocation.StartsWith(baseLocation + @\"\\\", StringComparison.OrdinalIgnoreCase))\n {\n resultPath = resultPath + @\"\\..\";\n baseLocation = Path.GetDirectoryName(baseLocation);\n\n if (baseLocation.EndsWith(@\"\\\"))\n {\n baseLocation = baseLocation.Substring(0, baseLocation.Length - 1);\n }\n }\n\n resultPath = resultPath + targetLocation.Substring(baseLocation.Length);\n\n // preprocess .\\ case\n return resultPath.Substring(2, resultPath.Length - 3);\n }\n\n /// &lt;summary&gt;\n /// Resolves the relative pathes\n /// &lt;/summary&gt;\n /// &lt;param name=\"relativePath\"&gt;Relative path&lt;/param&gt;\n /// &lt;param name=\"basePath\"&gt;base path for discovering&lt;/param&gt;\n /// &lt;returns&gt;Resolved path&lt;/returns&gt;\n public static string ResolveRelativePath(string relativePath, string basePath)\n {\n if (string.IsNullOrEmpty(basePath))\n {\n throw new ArgumentNullException(\"basePath\");\n }\n\n if (string.IsNullOrEmpty(relativePath))\n {\n throw new ArgumentNullException(\"relativePath\");\n }\n\n var result = basePath;\n\n if (Path.IsPathRooted(relativePath))\n {\n return relativePath;\n }\n\n if (relativePath.EndsWith(@\"\\\"))\n {\n relativePath = relativePath.Substring(0, relativePath.Length - 1);\n }\n\n if (relativePath == \".\")\n {\n return basePath;\n }\n\n if (relativePath.StartsWith(@\".\\\"))\n {\n relativePath = relativePath.Substring(2);\n }\n\n relativePath = relativePath.Replace(@\"\\.\\\", @\"\\\");\n if (!relativePath.EndsWith(@\"\\\"))\n {\n relativePath = relativePath + @\"\\\";\n }\n\n while (!string.IsNullOrEmpty(relativePath))\n {\n int lengthOfOperation = relativePath.IndexOf(@\"\\\") + 1;\n var operation = relativePath.Substring(0, lengthOfOperation - 1);\n relativePath = relativePath.Remove(0, lengthOfOperation);\n\n if (operation == @\"..\")\n {\n result = Path.GetDirectoryName(result);\n }\n else\n {\n result = Path.Combine(result, operation);\n }\n }\n\n return result;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 1747795, "author": "munissor", "author_id": 91128, "author_profile": "https://Stackoverflow.com/users/91128", "pm_score": 0, "selected": false, "text": "<p>You can try to change the current directory to the directory containing your executable using Environment.CurrentDirectory before reading from relative paths. Or instead if you have a relative path (Path.IsPathRooted) you can combine (Path.Combine) your root directory with the relative path to have an absolute one.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My app open file in subdirectory of directory where it is executed, subdirectory is called `sample` and it contains files: * `example.raf` (example extension, non significant) * `background.gif` `example.raf` contains relative path to `background.gif` (in this case only file name cause the files is in same directory as raf) and opening of RAF causes application to read and display `background.gif`. When I use `OpenFileDialog` to load RAF file everything is alright, image loads correctly. I know that open file dialog changes in some way current working directory but i was unable to recreate this without calling open file dialog Unfortunately in case when i call **raf reading** method directly from code, without supplying path to file form `OpenFileDialog` like this ``` LoadRAF("sample\\example.raf"); ``` in this case i got problem, app try to load image from **ExecutablePath** and not from subdirectory which contains **RAF** file and **image**. Ofcourse it is normal behavior but in this case it is highkly unwanted. It is required to handle both relative and absolute type of paths in my app, so what should i do to solve this, how to **change ExecutablePath** or what other thing i can do to make this work at least as in case of `OpenFileDialog`?
Next code from my project ZipSolution (<http://zipsolution.codeplex.com/>) shows how to resolve and create relative pathes in .net ``` using System; using System.Collections.Generic; using System.Text; using System.IO; namespace ZipSolution { internal static class RelativePathDiscovery { /// <summary> /// Produces relative path when possible to go from baseLocation to targetLocation /// </summary> /// <param name="baseLocation">The root folder</param> /// <param name="targetLocation">The target folder</param> /// <returns>The relative path relative to baseLocation</returns> /// <exception cref="ArgumentNullException">base or target locations are null or empty</exception> public static string ProduceRelativePath(string baseLocation, string targetLocation) { if (string.IsNullOrEmpty(baseLocation)) { throw new ArgumentNullException("baseLocation"); } if (string.IsNullOrEmpty(targetLocation)) { throw new ArgumentNullException("targetLocation"); } if (!Path.IsPathRooted(baseLocation)) { return baseLocation; } if (!Path.IsPathRooted(targetLocation)) { return targetLocation; } if (string.Compare(Path.GetPathRoot(baseLocation), Path.GetPathRoot(targetLocation), true) != 0) { return targetLocation; } if (string.Compare(baseLocation, targetLocation, true) == 0) { return "."; } string resultPath = "."; if (!targetLocation.EndsWith(@"\")) { targetLocation = targetLocation + @"\"; } if (baseLocation.EndsWith(@"\")) { baseLocation = baseLocation.Substring(0, baseLocation.Length - 1); } while (!targetLocation.StartsWith(baseLocation + @"\", StringComparison.OrdinalIgnoreCase)) { resultPath = resultPath + @"\.."; baseLocation = Path.GetDirectoryName(baseLocation); if (baseLocation.EndsWith(@"\")) { baseLocation = baseLocation.Substring(0, baseLocation.Length - 1); } } resultPath = resultPath + targetLocation.Substring(baseLocation.Length); // preprocess .\ case return resultPath.Substring(2, resultPath.Length - 3); } /// <summary> /// Resolves the relative pathes /// </summary> /// <param name="relativePath">Relative path</param> /// <param name="basePath">base path for discovering</param> /// <returns>Resolved path</returns> public static string ResolveRelativePath(string relativePath, string basePath) { if (string.IsNullOrEmpty(basePath)) { throw new ArgumentNullException("basePath"); } if (string.IsNullOrEmpty(relativePath)) { throw new ArgumentNullException("relativePath"); } var result = basePath; if (Path.IsPathRooted(relativePath)) { return relativePath; } if (relativePath.EndsWith(@"\")) { relativePath = relativePath.Substring(0, relativePath.Length - 1); } if (relativePath == ".") { return basePath; } if (relativePath.StartsWith(@".\")) { relativePath = relativePath.Substring(2); } relativePath = relativePath.Replace(@"\.\", @"\"); if (!relativePath.EndsWith(@"\")) { relativePath = relativePath + @"\"; } while (!string.IsNullOrEmpty(relativePath)) { int lengthOfOperation = relativePath.IndexOf(@"\") + 1; var operation = relativePath.Substring(0, lengthOfOperation - 1); relativePath = relativePath.Remove(0, lengthOfOperation); if (operation == @"..") { result = Path.GetDirectoryName(result); } else { result = Path.Combine(result, operation); } } return result; } } } ```
164,642
<p>How do I create a grails war file so that it doesn't have the version number</p> <p>(e.g. foo-0.1.war) </p> <p>attached to the end when I execute the 'grails war' command?</p>
[ { "answer_id": 164702, "author": "Instantsoup", "author_id": 9861, "author_profile": "https://Stackoverflow.com/users/9861", "pm_score": 6, "selected": true, "text": "<p>I think you can specify the war name in the war command.</p>\n\n<pre><code>grails war foo.war\n</code></pre>\n\n<p>Also check the latest Grails documentation for where to set this as a configuration option. See the other answers for details.</p>\n" }, { "answer_id": 223603, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 3, "selected": false, "text": "<p>From the <a href=\"http://grails.org/doc/1.0.x/\" rel=\"noreferrer\">Grails Documentation</a>, <strong><em>Chapter 17, Deployment</em></strong></p>\n\n<blockquote>\n <p>There are also many ways in which you can customise the WAR file that is\n created. For example, you can specify\n a path (either absolute or relative)\n to the command that instructs it where\n to place the file and what name to\n give it:</p>\n\n<pre><code>grails war /opt/java/tomcat-5.5.24/foobar.war\n</code></pre>\n \n <p>Alternatively, you can add a line to\n Config.groovy that changes the default\n location and filename:</p>\n\n<pre><code>grails.war.destFile = \"foobar-prod.war\"\n</code></pre>\n \n <p>Of course, any command line argument\n that you provide overrides this\n setting.</p>\n</blockquote>\n" }, { "answer_id": 252373, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Another way to generate war files without version number is to keep the property, <strong>app.version</strong>, empty in the <strong>application.properties</strong></p>\n" }, { "answer_id": 855659, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Rolling up the other excellent answers. There are several options:</p>\n\n<p>Explicitly set it on the command line: <code>grails war foo.war</code></p>\n\n<p>Set the <code>app.version</code> property to empty in application.properties will cause the war to be named <code>foo.war</code>.</p>\n\n<p>Explicitly set the name of the war using the <code>grails.war.destFile</code> property in Config.groovy</p>\n" }, { "answer_id": 4892530, "author": "Phuong LeCong", "author_id": 1243628, "author_profile": "https://Stackoverflow.com/users/1243628", "pm_score": 5, "selected": false, "text": "<p>In case anybody comes upon this article and is using Grails 1.3.x, the configuration option has changed from <code>grails.war.destFile</code> in <code>Config.groovy</code> to being <code>grails.project.war.file</code> in <code>BuildConfig.groovy</code>. </p>\n\n<p>Also the file name is relative to the project workspace, so it should have a value like:</p>\n\n<p><code>\ngrails.project.war.file = \"target/${appName}.war\"\n</code></p>\n\n<p>This is according to the latest <a href=\"http://grails.org/doc/latest/guide/17.%20Deployment.html\">Grails documentation</a>.</p>\n" }, { "answer_id": 39277804, "author": "Jay Prall", "author_id": 56083, "author_profile": "https://Stackoverflow.com/users/56083", "pm_score": 2, "selected": false, "text": "<p>Grails 3.x has switched to gradle and uses the <a href=\"https://docs.gradle.org/current/userguide/war_plugin.html\" rel=\"nofollow noreferrer\">war</a> plugin. You can just specify name like this in the <code>build.gradle</code> file:</p>\n\n<pre><code>war {\n archiveName 'foo.war'\n}\n</code></pre>\n" }, { "answer_id": 56781213, "author": "Glushiator", "author_id": 1284183, "author_profile": "https://Stackoverflow.com/users/1284183", "pm_score": 0, "selected": false, "text": "<p>I am kind of late to the party... but anyway:</p>\n\n<p>I think the reason behind removing the version number is to eliminate the need to rename the war file so it deploys on \"<em>correct</em>\" context path <strong>/appName</strong>. If that's the case then a better option is to use a versioned war filename so you can deploy multiple versions at the same time on tomcat using the following naming pattern in <strong>grails-app/conf/BuildConfig.groovy</strong>:</p>\n\n<pre><code>grails.project.war.file = \"target/${appName}##${appVersion}.war\"\n</code></pre>\n\n<p>As explained in <a href=\"http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Parallel_deployment\" rel=\"nofollow noreferrer\">http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Parallel_deployment</a></p>\n\n<p>This method applies to wars in general, not only grails' wars.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I create a grails war file so that it doesn't have the version number (e.g. foo-0.1.war) attached to the end when I execute the 'grails war' command?
I think you can specify the war name in the war command. ``` grails war foo.war ``` Also check the latest Grails documentation for where to set this as a configuration option. See the other answers for details.
164,643
<p>In my C# source code I may have declared integers as:</p> <pre><code>int i = 5; </code></pre> <p>or</p> <pre><code>Int32 i = 5; </code></pre> <p>In the currently prevalent 32-bit world they are equivalent. However, as we move into a 64-bit world, am I correct in saying that the following will become the same?</p> <pre><code>int i = 5; Int64 i = 5; </code></pre>
[ { "answer_id": 164650, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "<p>No. The C# specification rigidly defines that <code>int</code> is an alias for <code>System.Int32</code> with exactly 32 bits. Changing this would be a <em>major</em> breaking change.</p>\n" }, { "answer_id": 164672, "author": "zappan", "author_id": 4723, "author_profile": "https://Stackoverflow.com/users/4723", "pm_score": 0, "selected": false, "text": "<p>Yes, as Jon said, and unlike the 'C/C++ world', Java and C# aren't dependent on the system they're running on. They have strictly defined lengths for byte/short/int/long and single/double precision floats, equal on every system.</p>\n" }, { "answer_id": 164692, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>No matter whether you're using the 32-bit version or 64-bit version of the CLR, in C# an <code>int</code> will always mean <code>System.Int32</code> and <code>long</code> will always mean <code>System.Int64</code>.</p>\n" }, { "answer_id": 3249355, "author": "BlueRaja - Danny Pflughoeft", "author_id": 238419, "author_profile": "https://Stackoverflow.com/users/238419", "pm_score": 4, "selected": false, "text": "<p><code>int</code> is always synonymous with <code>Int32</code> on all platforms.</p>\n\n<p>It's very unlikely that Microsoft will change that in the future, as it would break lots of existing code that assumes <code>int</code> is 32-bits.</p>\n" }, { "answer_id": 3249357, "author": "Tomas Petricek", "author_id": 33518, "author_profile": "https://Stackoverflow.com/users/33518", "pm_score": 5, "selected": false, "text": "<p>The <code>int</code> keyword in C# is defined as an alias for the <code>System.Int32</code> type and this is (judging by the name) meant to be a 32-bit integer. To the specification:</p>\n<blockquote>\n<p><a href=\"http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-335.pdf\" rel=\"noreferrer\">CLI specification</a> section 8.2.2 (Built-in value and reference types) has a table with the following:</p>\n<ul>\n<li><code>System.Int32</code> - Signed 32-bit integer</li>\n</ul>\n<p><a href=\"http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf\" rel=\"noreferrer\">C# specification</a> section 8.2.1 (Predefined types) has a similar table:</p>\n<ul>\n<li><code>int</code> - 32-bit signed integral type</li>\n</ul>\n</blockquote>\n<p>This guarantees that both <code>System.Int32</code> in CLR and <code>int</code> in C# will always be 32-bit.</p>\n" }, { "answer_id": 3249393, "author": "Jess", "author_id": 151495, "author_profile": "https://Stackoverflow.com/users/151495", "pm_score": 2, "selected": false, "text": "<p>According to the C# specification <a href=\"http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf\" rel=\"nofollow noreferrer\">ECMA-334</A>, section \"11.1.4 Simple Types\", the reserved word <code>int</code> will be aliased to <code>System.Int32</code>. Since this is in the specification it is very unlikely to change.</p>\n" }, { "answer_id": 3249501, "author": "Brian Gideon", "author_id": 158779, "author_profile": "https://Stackoverflow.com/users/158779", "pm_score": 3, "selected": false, "text": "<p>I think what you may be confused by is that <code>int</code> is an alias for <code>Int32</code> so it will always be 4 bytes, but <code>IntPtr</code> is suppose to match the word size of the CPU architecture so it will be 4 bytes on a 32-bit system and 8 bytes on a 64-bit system.</p>\n" }, { "answer_id": 3250411, "author": "Eric Lippert", "author_id": 88656, "author_profile": "https://Stackoverflow.com/users/88656", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>Will sizeof(testInt) ever be 8? </p>\n</blockquote>\n\n<p>No, sizeof(testInt) is an error. testInt is a local variable. The sizeof operator requires a type as its argument. This will never be 8 because it will always be an error.</p>\n\n<blockquote>\n <p>VS2010 compiles a c# managed integer as 4 bytes, even on a 64 bit machine. </p>\n</blockquote>\n\n<p>Correct. I note that section 18.5.8 of the C# specification defines <code>sizeof(int)</code> as being the compile-time constant 4. That is, when you say <code>sizeof(int)</code> the compiler simply replaces that with 4; it is just as if you'd said \"4\" in the source code.</p>\n\n<blockquote>\n <p>Does anyone know if/when the time will come that a standard \"int\" in C# will be 64 bits?</p>\n</blockquote>\n\n<p>Never. Section 4.1.4 of the C# specification states that \"int\" is a synonym for \"System.Int32\". </p>\n\n<p>If what you want is a \"pointer-sized integer\" then use IntPtr. An IntPtr changes its size on different architectures.</p>\n" }, { "answer_id": 32130086, "author": "House.Lee", "author_id": 1279946, "author_profile": "https://Stackoverflow.com/users/1279946", "pm_score": -1, "selected": false, "text": "<p>int without suffix can be either 32bit or 64bit, it depends on the value it represents.</p>\n\n<p>as defined in MSDN:</p>\n\n<blockquote>\n <p>When an integer literal has no suffix, its type is the first of these types in which its value can be represented: int, uint, long, ulong.</p>\n</blockquote>\n\n<p>Here is the address:\n<a href=\"https://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx</a></p>\n" }, { "answer_id": 38176696, "author": "PreventRage", "author_id": 6543067, "author_profile": "https://Stackoverflow.com/users/6543067", "pm_score": 2, "selected": false, "text": "<p>The following will <a href=\"https://msdn.microsoft.com/en-us/library/exx3b86w.aspx\" rel=\"nofollow\">always be true</a> in C#:</p>\n\n<p><strong>sbyte</strong> signed 8 bits, 1 byte</p>\n\n<p><strong>byte</strong> unsigned 8 bits, 1 byte</p>\n\n<p><strong>short</strong> signed 16 bits, 2 bytes</p>\n\n<p><strong>ushort</strong> unsigned 16 bits, 2 bytes</p>\n\n<p><strong>int</strong> signed 32 bits, 4 bytes</p>\n\n<p><strong>uint</strong> unsigned 32 bits, 4 bytes</p>\n\n<p><strong>long</strong> signed 64 bits, 8 bytes</p>\n\n<p><strong>ulong</strong> unsigned 64 bits, 8 bytes</p>\n\n<p>An integer <em>literal</em> is just a sequence of digits (eg <code>314159</code>) <em>without</em> any of these explicit types. C# assigns it the first type in the sequence (<strong>int</strong>, <strong>uint</strong>, <strong>long</strong>, <strong>ulong</strong>) in which it fits. This seems to have been slightly muddled in at least one of the responses above.</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/aa664674(v=vs.71).aspx\" rel=\"nofollow\">Weirdly</a> the <em>unary minus operator</em> (minus sign) showing up before a string of digits does <em>not</em> reduce the choice to (<strong>int</strong>, <strong>long</strong>). The literal is always positive; the minus sign really is an operator. So presumably <code>-314159</code> is <em>exactly</em> the same thing as <code>-((int)314159)</code>. Except apparently there's a special case to get <code>-2147483648</code> straight into an <strong>int</strong>; otherwise it'd be <code>-((uint)2147483648)</code>. Which I presume does something unpleasant.</p>\n\n<p>Somehow it seems safe to predict that C# (and friends) will never bother with \"squishy name\" types for >=128 bit integers. We'll get nice support for <em>arbitrarily</em> large integers and super-precise support for UInt128, UInt256, etc. as soon as processors support doing math that wide, and hardly ever use any of it. 64-bit address spaces are <em>really</em> big. If they're ever too small it'll be for some esoteric reason like ASLR or a more efficient MapReduce or something.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
In my C# source code I may have declared integers as: ``` int i = 5; ``` or ``` Int32 i = 5; ``` In the currently prevalent 32-bit world they are equivalent. However, as we move into a 64-bit world, am I correct in saying that the following will become the same? ``` int i = 5; Int64 i = 5; ```
No. The C# specification rigidly defines that `int` is an alias for `System.Int32` with exactly 32 bits. Changing this would be a *major* breaking change.
164,697
<p>I am a little confused about null values and variables in .NET. (VB preferred)</p> <p>Is there any way to check the "nullness" of ANY given variable regardless of whether it was an object or a value type? Or does my null check have to always anticipate whether it's checking a value type (e.g. System.Integer) or an object? </p> <p>I guess what I'm looking for is a function that checks all possible kind of null-ness. That is, any type of variables that </p> <p>a) were never assigned a value since declared</p> <p>b) were assigned a null value from a data object (that came from a database)</p> <p>c) were set equals to another variable value which was null</p> <p>d) were set to an ASP.NET session/application variable that was never set or expired.</p> <p>Is there a general best-practice when it comes to handling null scenarios in .NET?</p> <p><strong>UPDATE:</strong> When I talk about a value type being "null", what I really mean is a value type that was either never set or was at some point set equal to or cast from a null object. </p>
[ { "answer_id": 164706, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 2, "selected": false, "text": "<p>Value Types can't be null. It violates what it means to be a Value Type. You can wrap Value Types as Nullable(Of T) which gives you a great set of methods, and checks for Nothing do work. But you do have a lot of overhead with that wrapper. Perhaps you can clarify what you're trying to do?</p>\n\n<p>For completeness the VB syntax for Nullable wrappers is:</p>\n\n<pre><code>Dim i as Nullable(Of Integer) = Nothing '.NET 2.0/3.0'\nDim j as Integer? = Nothing '.NET 3.5'\n</code></pre>\n\n<p>EDIT: Value Type are always preinitialized to a default value, 0 for numerics, false for Booleans, etc.</p>\n" }, { "answer_id": 164709, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 0, "selected": false, "text": "<p>Value type variables can't contain null, that's because what null means, null means that the references points nowhere. I don't know on VB.net but on c# you can wrap value types to be nullables using the \"?\", like:</p>\n\n<pre><code>int? a = null;\n</code></pre>\n" }, { "answer_id": 164728, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 2, "selected": false, "text": "<p>Is this what you're after?</p>\n\n<pre><code>if IsNothing(foo) OrElse IsDbNull(foo) Then\n ' Do Something Because foo Is Either Nothing or DBNull.Value\nEnd If\n</code></pre>\n\n<p>In truth I'm not certain why you'd wish for this structure. The Only time I'd check for DBNULL.Value is when I'm using values that came from a database, and before I assign said value from a DATA Namespace class to some other class [i.e. dim b as string = dataReader(0)]. </p>\n\n<p>Typically, if you're concerned about an object having not been instantiated, or needing it to be re-instantiated, then just an IsNothing check will suffice.</p>\n" }, { "answer_id": 164757, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 1, "selected": false, "text": "<p>In .Net that are only two types of null that I am aware of, null (nothing in VB) and DbNull. If you are using a System.Nullable, you can use the same null checking syntax as you would with an object. If if your nullable object is boxed the .Net 2.0 CLR is smart enough to figure out the right way to handle this.</p>\n\n<p>The only case I have run into both types is in the data tier of an application where I might be accessing database data directly. For example, I have run into DbNull in a DataTable. To check for both of these null types in this situration, you could write an extension method like (sorry, in C#):</p>\n\n<pre><code>static public bool IsNull(this object obj)\n{\n return obj != null &amp;&amp; obj != DbNull.Value;\n}\n\n...\n\nif(dataTable[0][\"MyColumn\"].IsNull())\n{\n //do something\n}\n</code></pre>\n" }, { "answer_id": 164763, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 0, "selected": false, "text": "<p>As long as you're developing with Option Strict On, (a) shouldn't be an issue. The compiler will yell at you. If you're worried about checking for parameters, just use</p>\n\n<pre><code>Public Sub MySub(ByVal param1 as MyObject, ByVal param2 as Integer)\n if param1 is nothing then\n Throw New ArgumentException(\"param1 cannot be null!\")\n end if\n 'param2 cannot be null\nEnd Sub\n</code></pre>\n\n<p>For (b), your database interaction layer should handle this. If you're using LINQ, there are ways to handle this. If you're using typed data sets, there an .IsMyVariableNull property on the row that gets auto-generated.</p>\n\n<p>For (c), you don't need to worry about value types, but reference types can be checked with a simple Is Nothing (or IsNot Nothing).</p>\n\n<p>For (d), you can apply the same logic after the read. Test the receiving variable against Nothing.</p>\n\n<p>For the most part, a simple check of Is Nothing will get you by. Your database interaction layer will help you handle the stickier case of null values in your data, but it's up to you to handle them appropriately.</p>\n" }, { "answer_id": 165172, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 3, "selected": true, "text": "<p>Normal value types (booleans, ints, longs, float, double, enum and structs) are not nullable.</p>\n\n<p>The default value for all value types is 0.</p>\n\n<p>The CLR won't let you access variables unless they have been set. You may think this isn't always the case, but sometimes the CLR steps in and initializes them for you. At a method level you must explicitly initialize all variables before they are used.</p>\n\n<p>Further, as others point out, since .net 2.0 there is a new generic type called <code>Nullable&lt;T&gt;</code>. There are some compiler shorthands in C# like int? means <code>Nullable&lt;int&gt;</code>, double? means <code>Nullable&lt;double&gt;</code> etc.</p>\n\n<p>You can only wrap <code>Nullable&lt;T&gt;</code> over non-nullable value types, which is fine since references already have the ability to be null.</p>\n\n<pre><code>int? x = null;\n</code></pre>\n\n<p>For an int?, while you can test against null, it's sometimes nicer to call <code>x.HasValue()</code>.</p>\n\n<p>In C# there's also the <a href=\"http://msdn.microsoft.com/en-us/library/ms173224.aspx\" rel=\"nofollow noreferrer\">nullable coalescing operator</a> ?? when you want to assign a nullable to a non-nullable value type. But if you don't have the operator, you can call GetValueOrDefault().</p>\n\n<pre><code>int y = x ?? 2; // y becomes 2 if x is null.\nint z = x.GetValueOrDefault(2); // same as y\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17235/" ]
I am a little confused about null values and variables in .NET. (VB preferred) Is there any way to check the "nullness" of ANY given variable regardless of whether it was an object or a value type? Or does my null check have to always anticipate whether it's checking a value type (e.g. System.Integer) or an object? I guess what I'm looking for is a function that checks all possible kind of null-ness. That is, any type of variables that a) were never assigned a value since declared b) were assigned a null value from a data object (that came from a database) c) were set equals to another variable value which was null d) were set to an ASP.NET session/application variable that was never set or expired. Is there a general best-practice when it comes to handling null scenarios in .NET? **UPDATE:** When I talk about a value type being "null", what I really mean is a value type that was either never set or was at some point set equal to or cast from a null object.
Normal value types (booleans, ints, longs, float, double, enum and structs) are not nullable. The default value for all value types is 0. The CLR won't let you access variables unless they have been set. You may think this isn't always the case, but sometimes the CLR steps in and initializes them for you. At a method level you must explicitly initialize all variables before they are used. Further, as others point out, since .net 2.0 there is a new generic type called `Nullable<T>`. There are some compiler shorthands in C# like int? means `Nullable<int>`, double? means `Nullable<double>` etc. You can only wrap `Nullable<T>` over non-nullable value types, which is fine since references already have the ability to be null. ``` int? x = null; ``` For an int?, while you can test against null, it's sometimes nicer to call `x.HasValue()`. In C# there's also the [nullable coalescing operator](http://msdn.microsoft.com/en-us/library/ms173224.aspx) ?? when you want to assign a nullable to a non-nullable value type. But if you don't have the operator, you can call GetValueOrDefault(). ``` int y = x ?? 2; // y becomes 2 if x is null. int z = x.GetValueOrDefault(2); // same as y ```
164,714
<p>I just want to know the best way to emulate a C# style enumeration in Ruby.</p>
[ { "answer_id": 164738, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 2, "selected": false, "text": "<p>I don't think Ruby supports true enums -- though, there are still solutions available.</p>\n\n<p><a href=\"http://www.rubyfleebie.com/enumerations-and-ruby/\" rel=\"nofollow noreferrer\">Enumerations and Ruby</a></p>\n" }, { "answer_id": 164810, "author": "Ris Adams", "author_id": 15683, "author_profile": "https://Stackoverflow.com/users/15683", "pm_score": 2, "selected": false, "text": "<p>The easiest way to define an Enum in ruby to use a class with constant variables.</p>\n\n<pre><code>class WindowState\n Open = 1\n Closed = 2\n Max = 3\n Min = 4\nend\n</code></pre>\n" }, { "answer_id": 164833, "author": "Nate", "author_id": 12779, "author_profile": "https://Stackoverflow.com/users/12779", "pm_score": 3, "selected": false, "text": "<p>It's not quite the same, but I'll often build a hash for this kind of thing:</p>\n\n<pre><code>STATES = {:open =&gt; 1, :closed =&gt; 2, :max =&gt; 3, :min =&gt; 4}.freeze()\n</code></pre>\n\n<p>Freezing the hash keeps me from accidentally modifying its contents.</p>\n\n<p>Moreover, if you want to raise an error when accessing something that doesn't exist, you can use a defualt Proc to do this:</p>\n\n<pre><code>STATES = Hash.new { |hash, key| raise NameError, \"#{key} is not allowed\" }\nSTATES.merge!({:open =&gt; 1, :closed =&gt; 2, :max =&gt; 3, :min =&gt; 4}).freeze()\n\nSTATES[:other] # raises NameError\n</code></pre>\n" }, { "answer_id": 164852, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 1, "selected": false, "text": "<p>Making a class or hash as others have said will work. However, the Ruby thing to do is to use <a href=\"http://www.rubytips.org/2008/01/26/what-is-a-ruby-symbol-symbols-explained/\" rel=\"nofollow noreferrer\">symbols</a>. Symbols in Ruby start with a colon and look like this:</p>\n\n<pre><code>greetingtype = :hello\n</code></pre>\n\n<p>They are kind of like objects that consist only of a name.</p>\n" }, { "answer_id": 164891, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 4, "selected": true, "text": "<blockquote>\n<p>Specifically, I would like to be able to perform logical tests against the set of values given some variable. Example would be the state of a window: &quot;minimized, maximized, closed, open&quot;</p>\n</blockquote>\n<p>If you need the enumerations to map to values (eg, you need minimized to equal 0, maximised to equal 100, etc) I'd use a hash of symbols to values, like this:</p>\n<pre><code>WINDOW_STATES = { :minimized =&gt; 0, :maximized =&gt; 100 }.freeze\n</code></pre>\n<p>The freeze (like nate says) stops you from breaking things in future by accident.\nYou can check if something is valid by doing this</p>\n<pre><code>WINDOW_STATES.keys.include?(window_state)\n</code></pre>\n<p>Alternatively, if you don't need any values, and just need to check 'membership' then an array is fine</p>\n<pre><code>WINDOW_STATES = [:minimized, :maximized].freeze\n</code></pre>\n<p>Use it like this</p>\n<pre><code>WINDOW_STATES.include?(window_state)\n</code></pre>\n<p>If your keys are going to be strings (like for example a 'state' field in a RoR app), then you can use an array of strings. I do this ALL THE TIME in many of our rails apps.</p>\n<pre><code>WINDOW_STATES = %w(minimized maximized open closed).freeze\n</code></pre>\n<p>This is pretty much what rails <code>validates_inclusion_of</code> validator is purpose built for :-)</p>\n<h3>Personal Note:</h3>\n<p>I don't like typing include? all the time, so I have this (it's only complicated because of the .in?(1, 2, 3) case:</p>\n<pre><code>class Object\n\n # Lets us write array.include?(x) the other way round\n # Also accepts multiple args, so we can do 2.in?( 1,2,3 ) without bothering with arrays\n def in?( *args )\n # if we have 1 arg, and it is a collection, act as if it were passed as a single value, UNLESS we are an array ourselves.\n # The mismatch between checking for respond_to on the args vs checking for self.kind_of?Array is deliberate, otherwise\n # arrays of strings break and ranges don't work right\n args.length == 1 &amp;&amp; args.first.respond_to?(:include?) &amp;&amp; !self.kind_of?(Array) ?\n args.first.include?( self ) :\n args.include?( self )\n end\n end\nend\n</code></pre>\n<p>This lets you type</p>\n<pre><code>window_state.in? WINDOW_STATES\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20714/" ]
I just want to know the best way to emulate a C# style enumeration in Ruby.
> > Specifically, I would like to be able to perform logical tests against the set of values given some variable. Example would be the state of a window: "minimized, maximized, closed, open" > > > If you need the enumerations to map to values (eg, you need minimized to equal 0, maximised to equal 100, etc) I'd use a hash of symbols to values, like this: ``` WINDOW_STATES = { :minimized => 0, :maximized => 100 }.freeze ``` The freeze (like nate says) stops you from breaking things in future by accident. You can check if something is valid by doing this ``` WINDOW_STATES.keys.include?(window_state) ``` Alternatively, if you don't need any values, and just need to check 'membership' then an array is fine ``` WINDOW_STATES = [:minimized, :maximized].freeze ``` Use it like this ``` WINDOW_STATES.include?(window_state) ``` If your keys are going to be strings (like for example a 'state' field in a RoR app), then you can use an array of strings. I do this ALL THE TIME in many of our rails apps. ``` WINDOW_STATES = %w(minimized maximized open closed).freeze ``` This is pretty much what rails `validates_inclusion_of` validator is purpose built for :-) ### Personal Note: I don't like typing include? all the time, so I have this (it's only complicated because of the .in?(1, 2, 3) case: ``` class Object # Lets us write array.include?(x) the other way round # Also accepts multiple args, so we can do 2.in?( 1,2,3 ) without bothering with arrays def in?( *args ) # if we have 1 arg, and it is a collection, act as if it were passed as a single value, UNLESS we are an array ourselves. # The mismatch between checking for respond_to on the args vs checking for self.kind_of?Array is deliberate, otherwise # arrays of strings break and ranges don't work right args.length == 1 && args.first.respond_to?(:include?) && !self.kind_of?(Array) ? args.first.include?( self ) : args.include?( self ) end end end ``` This lets you type ``` window_state.in? WINDOW_STATES ```
164,727
<p>How do you return values or structures from a Popup window in Powerbuilder 9.0? The CloseWithReturn is only valid for Response windows and thus is not available. When I set a value to the Message.PowerObjectParm, the value becomes null when the Popup window closes. I need to use a Popup window so the user can click back to the caller window and scroll through rows. </p> <p>Program flow: 1) Window A OpenWithParm 2) Window B is now open 3) User interacts with both windows 3) User closes Window B 4) Window B needs to pass a structure back to window A</p>
[ { "answer_id": 165584, "author": "Doug Porter", "author_id": 4311, "author_profile": "https://Stackoverflow.com/users/4311", "pm_score": 3, "selected": true, "text": "<p>You won't be able to accomplish this the way you are thinking. Since the window you are opening from the parent is not a Response window, the two aren't explicitly linked together. </p>\n\n<p>But you could accomplish this by having a public instance variable in the parent window that is of the type of your custom structure. Then from the child window before you close it, explicitly set the variable in the parent window via something like this:</p>\n\n<pre><code>w_my_parent_window_name.istr_my_structure = lstr_my_structure\n</code></pre>\n\n<p>This should only be done if there will only be one instance of w_my_parent_window_name instantiated.</p>\n" }, { "answer_id": 165676, "author": "Terry", "author_id": 22509, "author_profile": "https://Stackoverflow.com/users/22509", "pm_score": 2, "selected": false, "text": "<p>You can get around the \"one instance\" of parent limitation by passing in a reference to the parent window when opening the popup, and storing the reference in an instance variable. This also ensures you're talking to the right version of w_my_parent_window_name.</p>\n" }, { "answer_id": 202710, "author": "Jason V", "author_id": 27912, "author_profile": "https://Stackoverflow.com/users/27912", "pm_score": 0, "selected": false, "text": "<p>If you're using the PFC, if I remember right there was a service that you could use as well.</p>\n" }, { "answer_id": 234962, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Message.PowerObjectParm would work for passing an <em>object</em>. The reason it becomes NULL when the popup is closed is because structures are auto-instantiated and auto-destroyed. They are only valid within the scope that they are declared. For example, if it's declared within a function, it will be destroyed upon completion of the function; if it's an instance variable of the popup, it will be destroyed along with the popup when it's closed.</p>\n\n<p>You can copy the structure back into a variable of the same type on the parent window before closing the popup as Dougman suggests, or alternatively, you could use an object instead of a structure. E.g. just create custom object and declare public instance variables in it as you would the variables of the structure. </p>\n\n<p>You of course need to explicitly create and destroy the object. An object created by the popup will remain instantiated until explicitly destroyed, even after the popup itself is destroyed.</p>\n" }, { "answer_id": 841013, "author": "Jason 'Bug' Fenter", "author_id": 103701, "author_profile": "https://Stackoverflow.com/users/103701", "pm_score": 0, "selected": false, "text": "<p>There are always multiple ways to solve a problem. I'll propose another, even though the question is old...</p>\n\n<p>When you close the popup window, you can trigger a custom event on the parent window. Well, technically, you can trigger <em>any</em> event on the parent window, but I'd suggest creating a custom event specifically for this so that you can pass the structure as an argument to that event.</p>\n" }, { "answer_id": 62795445, "author": "user13892009", "author_id": 13892009, "author_profile": "https://Stackoverflow.com/users/13892009", "pm_score": 0, "selected": false, "text": "<p>Use a local structure variable to return the values selected and Just use Message.PowerObjectParm in the parent window and Validate the existence of the structure variable if closed the response window without any selection.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4466/" ]
How do you return values or structures from a Popup window in Powerbuilder 9.0? The CloseWithReturn is only valid for Response windows and thus is not available. When I set a value to the Message.PowerObjectParm, the value becomes null when the Popup window closes. I need to use a Popup window so the user can click back to the caller window and scroll through rows. Program flow: 1) Window A OpenWithParm 2) Window B is now open 3) User interacts with both windows 3) User closes Window B 4) Window B needs to pass a structure back to window A
You won't be able to accomplish this the way you are thinking. Since the window you are opening from the parent is not a Response window, the two aren't explicitly linked together. But you could accomplish this by having a public instance variable in the parent window that is of the type of your custom structure. Then from the child window before you close it, explicitly set the variable in the parent window via something like this: ``` w_my_parent_window_name.istr_my_structure = lstr_my_structure ``` This should only be done if there will only be one instance of w\_my\_parent\_window\_name instantiated.
164,736
<p>I am trying to call php-cgi.exe from a .NET program. I use RedirectStandardOutput to get the output back as a stream but the whole thing is very slow.</p> <p>Do you have any idea on how I can make that faster? Any other technique?</p> <pre><code> Dim oCGI As ProcessStartInfo = New ProcessStartInfo() oCGI.WorkingDirectory = "C:\Program Files\Application\php" oCGI.FileName = "php-cgi.exe" oCGI.RedirectStandardOutput = True oCGI.RedirectStandardInput = True oCGI.UseShellExecute = False oCGI.CreateNoWindow = True Dim oProcess As Process = New Process() oProcess.StartInfo = oCGI oProcess.Start() oProcess.StandardOutput.ReadToEnd() </code></pre>
[ { "answer_id": 164791, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 4, "selected": true, "text": "<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx\" rel=\"noreferrer\">OutputDataReceived event</a> to receive data as it's pumped to StdOut.</p>\n" }, { "answer_id": 2268137, "author": "Jader Dias", "author_id": 48465, "author_profile": "https://Stackoverflow.com/users/48465", "pm_score": 4, "selected": false, "text": "<p>The best solution I have found is: </p>\n\n<pre><code>private void Redirect(StreamReader input, TextBox output)\n{\n new Thread(a =&gt;\n {\n var buffer = new char[1];\n while (input.Read(buffer, 0, 1) &gt; 0)\n {\n output.Dispatcher.Invoke(new Action(delegate\n {\n output.Text += new string(buffer);\n }));\n };\n }).Start();\n}\n\nprivate void Window_Loaded(object sender, RoutedEventArgs e)\n{\n process = new Process\n {\n StartInfo = new ProcessStartInfo\n {\n CreateNoWindow = true,\n FileName = \"php-cgi.exe\",\n RedirectStandardOutput = true,\n UseShellExecute = false,\n WorkingDirectory = @\"C:\\Program Files\\Application\\php\",\n }\n };\n if (process.Start())\n {\n Redirect(process.StandardOutput, textBox1);\n }\n}\n</code></pre>\n" }, { "answer_id": 4443077, "author": "Martin.Martinsson", "author_id": 434209, "author_profile": "https://Stackoverflow.com/users/434209", "pm_score": 2, "selected": false, "text": "<p>The problem is due a bad php.ini config. I had the same problem and i downloaded the Windows installer from: <a href=\"http://windows.php.net/download/\" rel=\"nofollow\">http://windows.php.net/download/</a>.</p>\n\n<p>After that and commenting out not needed extensions, the conversion process is alà Speedy Gonzales, converting 20 php per second.</p>\n\n<p>You can safely use \"oProcess.StandardOutput.ReadToEnd()\". It's more readable and alomost as fast as using the thread solution. To use the thread solution in conjunction with a string you need to introduce an event or something.</p>\n\n<p>Cheers</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508/" ]
I am trying to call php-cgi.exe from a .NET program. I use RedirectStandardOutput to get the output back as a stream but the whole thing is very slow. Do you have any idea on how I can make that faster? Any other technique? ``` Dim oCGI As ProcessStartInfo = New ProcessStartInfo() oCGI.WorkingDirectory = "C:\Program Files\Application\php" oCGI.FileName = "php-cgi.exe" oCGI.RedirectStandardOutput = True oCGI.RedirectStandardInput = True oCGI.UseShellExecute = False oCGI.CreateNoWindow = True Dim oProcess As Process = New Process() oProcess.StartInfo = oCGI oProcess.Start() oProcess.StandardOutput.ReadToEnd() ```
You can use the [OutputDataReceived event](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx) to receive data as it's pumped to StdOut.
164,751
<p>I have a dialog that resizes. It also has a custom background which I paint in response to a WM_ERASEBKGND call (currently a simple call to FillSolidRect). </p> <p>When the dialog is resized, there is tremendous flickering going on. To try and reduce the flickering I enumerate all child windows and add them to the clipping region. That seems to help a little -- now the flickering is mostly evident in all of the child controls as they repaint.</p> <p>How can I make the dialog flicker-free while resizing? I suspect double-buffering must play a part, but I'm not sure how to do that with a dialog with child controls (without making all child controls owner-draw or something like that).</p> <p>I should note that I'm using C++ (not .NET), and MFC, although pure Win32-based solutions are welcomed :)</p> <p>NOTE: One thing I tried but which didn't work (not sure why) was:</p> <pre><code>CDC memDC; memDC.CreateCompatibleDC(pDC); memDC.FillSolidRect(rect, backgroundColor); pDC-&gt;BitBlt(0, 0, rect.Width(), rect.Height(), &amp;memDC, 0, 0, SRCCOPY); </code></pre>
[ { "answer_id": 164766, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": false, "text": "<p>Double buffering is indeed the only way to make this work.</p>\n\n<p>Child controls will take care of themselves so long as you make sure <code>CLIPCHILDREN</code>.</p>\n" }, { "answer_id": 164803, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 3, "selected": false, "text": "<p>Do nothing in the WM_ERASEBKGND handling and do the erase as part of your main WM_PAINT. You can either paint smarter so that you only redraw the invalid areas, or more easily, double-buffer the drawing.</p>\n\n<p>By not doing anything in the erase background, you have all your drawing code in one location which should make it easier for others to follow and maintain.</p>\n" }, { "answer_id": 164977, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 3, "selected": false, "text": "<p>Try adding the following line to your OnInitDialog function:</p>\n\n<pre><code> ModifyStyle(0, WS_CLIPCHILDREN, 0);\n</code></pre>\n" }, { "answer_id": 216223, "author": "David L Morris", "author_id": 3137, "author_profile": "https://Stackoverflow.com/users/3137", "pm_score": 4, "selected": true, "text": "<p>Assuming that \"FillSolidRect\" is the erase of your background then return TRUE from the WM_ERASEBKGND.</p>\n\n<p>To do the double buffering that you are almost doing in your code fragment, you will need to use CreateCompatibleBitmap and select that into your memDC.</p>\n" }, { "answer_id": 403939, "author": "adzm", "author_id": 43784, "author_profile": "https://Stackoverflow.com/users/43784", "pm_score": 3, "selected": false, "text": "<p>If you are targeting WinXP or higher, you can also use the WS_EX_COMPOSITED style to enable double-buffering by default for top-level windows with this style. Bear in mind this has its own set of limitations -- specifically, no more drawing out of OnPaint cycles using GetDC, etc.</p>\n" }, { "answer_id": 14829752, "author": "Imrank", "author_id": 1164714, "author_profile": "https://Stackoverflow.com/users/1164714", "pm_score": 2, "selected": false, "text": "<p>you can set parameter of your call to InvalidateRect method as false. This will prevent you to send WM_ERASEBKGND when the window will redraw.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7442/" ]
I have a dialog that resizes. It also has a custom background which I paint in response to a WM\_ERASEBKGND call (currently a simple call to FillSolidRect). When the dialog is resized, there is tremendous flickering going on. To try and reduce the flickering I enumerate all child windows and add them to the clipping region. That seems to help a little -- now the flickering is mostly evident in all of the child controls as they repaint. How can I make the dialog flicker-free while resizing? I suspect double-buffering must play a part, but I'm not sure how to do that with a dialog with child controls (without making all child controls owner-draw or something like that). I should note that I'm using C++ (not .NET), and MFC, although pure Win32-based solutions are welcomed :) NOTE: One thing I tried but which didn't work (not sure why) was: ``` CDC memDC; memDC.CreateCompatibleDC(pDC); memDC.FillSolidRect(rect, backgroundColor); pDC->BitBlt(0, 0, rect.Width(), rect.Height(), &memDC, 0, 0, SRCCOPY); ```
Assuming that "FillSolidRect" is the erase of your background then return TRUE from the WM\_ERASEBKGND. To do the double buffering that you are almost doing in your code fragment, you will need to use CreateCompatibleBitmap and select that into your memDC.
164,767
<pre><code>$array = explode(&quot;.&quot;, $row[copy]); $a = $array.length -1; </code></pre> <p>I want to return the last element of this array but all i get from this is -1.</p>
[ { "answer_id": 164781, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 0, "selected": false, "text": "<p>I think your second line should be more like:</p>\n\n<pre><code>$index = count($array) - 1;\n$a = $array[$index];\n</code></pre>\n\n<p>If you want an element from an array you need to use square brackets.</p>\n" }, { "answer_id": 164785, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 3, "selected": false, "text": "<p>Try <a href=\"http://php.net/count\" rel=\"nofollow noreferrer\">count</a>:</p>\n\n<pre><code>$array = explode(\".\", $row[copy]);\n$a = count($array) - 1;\n$array[$a]; // last element\n</code></pre>\n" }, { "answer_id": 164788, "author": "Rick", "author_id": 14138, "author_profile": "https://Stackoverflow.com/users/14138", "pm_score": -1, "selected": false, "text": "<p>My PHP is a bit rusty, but shouldn't this be:</p>\n\n<pre><code>$array = explode(\".\", $row[$copy]);\n$a = $array[count($array)];\n</code></pre>\n\n<p>i.e.: isn't a \"$\" missing in front of \"copy\", and does .length actually work?</p>\n" }, { "answer_id": 164796, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 0, "selected": false, "text": "<p>As this is tag as PHP, I'll assume you are using PHP, if so then you'll want to do:</p>\n\n<pre><code>$array = explode(\".\", $row[copy]);\n$a = count($array) - 1;\n$value = $array[$a];\n</code></pre>\n\n<p>But this will only work if your keys are numeric and starting at 0.</p>\n\n<p>If you want to get the last element of an array, but don't have numeric keys or they don't start at 0, then:</p>\n\n<p>$array = explode(\".\", $row[copy]);\n$revArray = array_reverse($array, true);\n$value = $revArray[key($revArray)];</p>\n" }, { "answer_id": 164841, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "<p>You could also use <a href=\"http://php.net/array_pop\" rel=\"nofollow noreferrer\">array_pop()</a>. This function takes an array, removes the last element of the array and returns that element.</p>\n\n<pre><code>$array = explode(\".\", $row[copy]);\n$a = array_pop($array);\n</code></pre>\n\n<p>This will modify the $array, removing the last element, so don't use it if you still need the array for something.</p>\n" }, { "answer_id": 165062, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>You can also use:</p>\n\n<p>$a = end($array);</p>\n\n<p>This also sets the arrays internal pointer to the end of the array, but it does get you the last element easily.</p>\n" }, { "answer_id": 165078, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 1, "selected": false, "text": "<p>If you just want everythng after the final . you could try</p>\n\n<pre><code>$pos = strrpos($row['copy'], '.');\n$str=($pos!==false) ? substr($row['copy'],$pos+1) : '';\n</code></pre>\n\n<p>This saves generating an array if all you needed was the last element.</p>\n" }, { "answer_id": 165098, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Actually, there is a function that does exactly what you want: end()</p>\n\n<p>$res = end( explode('.', $row['copy']) );</p>\n" }, { "answer_id": 1048849, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>hi u can use this also : </p>\n\n<p>$stack = array(\"orange\", \"banana\", \"apple\", \"raspberry\");\n$fruit = array_pop($stack);\nprint_r($stack);</p>\n\n<p>After this, $stack will have only 3 elements:</p>\n\n<p>Array\n(\n [0] => orange\n [1] => banana\n [2] => apple\n)</p>\n\n<p>and raspberry will be assigned to $fruit. </p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` $array = explode(".", $row[copy]); $a = $array.length -1; ``` I want to return the last element of this array but all i get from this is -1.
You can also use: $a = end($array); This also sets the arrays internal pointer to the end of the array, but it does get you the last element easily.
164,789
<p>I am trying to do a Windows Forms application in an MVP style and - not having done much with threading before - am getting all confused.</p> <p>My UI is a set of very simple forms. Each of the forms implements an interface and contains a reference to a mediator class which lives in the Business Logic Layer and vice versa. So as simplified diagram looks like this:</p> <pre><code>CheckInForm : ICheckIn &lt;-------&gt; CheckInMediator : ICheckInMediator ---------------------------------------------------------------------------------------- CheckInForm.Show() &lt;-------- --------&gt; AttemptCheckIn(CheckInInfo) CheckInForm.DisplayCheckInInfo(DisplayInfo) &lt;-------- --------&gt; CompleteCheckIn(AdditionalCheckInInfo) PleaseWaitDialog.Show() &lt;-------- PleaseWaitDialog.Close() &lt;-------- CheckInForm.Close() &lt;-------- </code></pre> <p>As you can see, the mediator classes control the UI, telling it when to display data, start up, close, etc. They even signify when a modal dialog should appear and when it should close (ie the PleaseWaitDialog above) The only thing the UI does is show data on the screen and relay input back to the mediator. </p> <p>This architecture is nice and decoupled and has been super-easy to test and prototype. Now that I'm putting it all together however I'm starting to run into threading issues. For example, if I want my PleaseWaitDialog to appear as a modal form (using ShowDialog()) over the CheckInForm until a timer controlled by the mediator counts out 5 seconds (remember, this is a simplification) I will get a cross-threading error if I call PleaseWaitDialog.Close() from the timer's callback. In a similar vein, if I have a modal dialog block the user from interacting with the UI I don't want that to block activity in the business layer unless I specify otherwise (such as with a confirmation dialog).</p> <p>What I think I would like to do is to run the mediators and business logic on the main thread and the UI on a completely separate thread and my first question is does this make sense to do?</p> <p>My second question is, how do I do something like have a class run in a separate thread? And how do I have the two communicate? I am making my way through the reading on .NET threading but I have a deadline and some examples for how to have a class on the main thread spawn a thread containing the UI and have them objects talk to each other could really help.</p>
[ { "answer_id": 164835, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 2, "selected": false, "text": "<p>Have you looked into the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"nofollow noreferrer\">BackgroundWorker</a> class? It's great for doing a lot of the simplified processing in the background type procedures and gives events that can be listned to do have your GUI display progress.</p>\n" }, { "answer_id": 166782, "author": "McKenzieG1", "author_id": 3776, "author_profile": "https://Stackoverflow.com/users/3776", "pm_score": 0, "selected": false, "text": "<p>You <strong>can</strong> manipulate WinForms controls from another thread, but you need to use <code>Control.Invoke()</code>, and you will pay a considerable performance penalty for every cross-thread call, due to the context switch and associated behind-the-scenes CLR voodoo.</p>\n\n<p>If you want to segregate the GUI from the business logic and infrastructure code in a multi-threaded application, I recommend switching to a messaging model using thread-safe queues. Every time the lower layer(s) need to tell the GUI to do something, they drop a message object into a queue which the GUI elements poll periodically via a <code>Forms.Timer</code>. This works particularly well for large, processor-intensive applications, because you can throttle the processing needs of the GUI updates to some extent by adjusting the update timer frequencies. </p>\n\n<p>For the calls going back the other way (GUI -> lower layers), you can just call mediator methods from the GUI code, as long as those calls return reasonably quickly - you need to be very careful about delaying the GUI thread, because the responsiveness of the whole application will suffer. If you have some calls where it is difficult to return quickly enough, you can add a second queue going the other way.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I am trying to do a Windows Forms application in an MVP style and - not having done much with threading before - am getting all confused. My UI is a set of very simple forms. Each of the forms implements an interface and contains a reference to a mediator class which lives in the Business Logic Layer and vice versa. So as simplified diagram looks like this: ``` CheckInForm : ICheckIn <-------> CheckInMediator : ICheckInMediator ---------------------------------------------------------------------------------------- CheckInForm.Show() <-------- --------> AttemptCheckIn(CheckInInfo) CheckInForm.DisplayCheckInInfo(DisplayInfo) <-------- --------> CompleteCheckIn(AdditionalCheckInInfo) PleaseWaitDialog.Show() <-------- PleaseWaitDialog.Close() <-------- CheckInForm.Close() <-------- ``` As you can see, the mediator classes control the UI, telling it when to display data, start up, close, etc. They even signify when a modal dialog should appear and when it should close (ie the PleaseWaitDialog above) The only thing the UI does is show data on the screen and relay input back to the mediator. This architecture is nice and decoupled and has been super-easy to test and prototype. Now that I'm putting it all together however I'm starting to run into threading issues. For example, if I want my PleaseWaitDialog to appear as a modal form (using ShowDialog()) over the CheckInForm until a timer controlled by the mediator counts out 5 seconds (remember, this is a simplification) I will get a cross-threading error if I call PleaseWaitDialog.Close() from the timer's callback. In a similar vein, if I have a modal dialog block the user from interacting with the UI I don't want that to block activity in the business layer unless I specify otherwise (such as with a confirmation dialog). What I think I would like to do is to run the mediators and business logic on the main thread and the UI on a completely separate thread and my first question is does this make sense to do? My second question is, how do I do something like have a class run in a separate thread? And how do I have the two communicate? I am making my way through the reading on .NET threading but I have a deadline and some examples for how to have a class on the main thread spawn a thread containing the UI and have them objects talk to each other could really help.
Have you looked into the [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) class? It's great for doing a lot of the simplified processing in the background type procedures and gives events that can be listned to do have your GUI display progress.
164,808
<p>I've got an issue when accessing a web site, I can access it by using the NetBIOS name, but when accessing with the FQDN i get an error. </p> <p>Any ideas on how to troubleshoot this?</p> <p>(There is no DNS configured yet, we have modified the Hosts file to enter the related names and IP.)</p>
[ { "answer_id": 164907, "author": "dragonmantank", "author_id": 204, "author_profile": "https://Stackoverflow.com/users/204", "pm_score": 0, "selected": false, "text": "<p>Just to make sure, you have something like this</p>\n\n<pre><code>192.168.100.5 othermachine othermachine.mydomain.local\n</code></pre>\n\n<p>with both the netbios and the FQDN in it and not just the IP and netbios name?</p>\n" }, { "answer_id": 679861, "author": "ℳ  .", "author_id": 10660, "author_profile": "https://Stackoverflow.com/users/10660", "pm_score": 0, "selected": false, "text": "<p>Assuming, as dragonmantank mentioned above, that the FQDN is in your hosts file, I'd look at whether the web server software itself is configured to accept requests with the FQDN in the Host field.</p>\n" }, { "answer_id": 1207527, "author": "Jason Musgrove", "author_id": 94838, "author_profile": "https://Stackoverflow.com/users/94838", "pm_score": 2, "selected": false, "text": "<p>First, check the obvious: are there any typos in the file?</p>\n\n<p>Next, test out the name resolution. Something simple like pinging the web server by it's FQDN will do. See if the right IP is mentioned.</p>\n\n<ul>\n<li>If you get \"unknown host\", your client's hosts file does not have an entry for the FQDN you entered (check for typos in the host name), or, for some reason, your computer isn't reading your hosts file.</li>\n<li>If you get the wrong IP address, then you have the wrong IP in your hosts file (check for typos in the IP address), your computer's DNS cache is polluted (try: <code>ipconfig /flushdns</code> on a Windows machine), or something else is overriding the lookup (duplicate entries in the hosts file?).</li>\n</ul>\n\n<p>Next up, try communicating with your web server. Using Telnet, speak HTTP to it, and see how it responds:</p>\n\n<pre><code>telnet 192.168.0.1 80\n</code></pre>\n\n<p>Substitute your web server's IP address instead of <code>192.168.0.1</code>. Provide the following lines:</p>\n\n<pre><code>GET / HTTP/1.1\nHost: fqdn.mywebserver.com\n</code></pre>\n\n<p>Try the server's IP, server's netbios name, and finally the server's FQDN in place of <code>fqdn.mywebserver.com</code>. Be sure to press return <em>twice</em> after entering the host header.</p>\n\n<p>If the response is different between the netbios name and the FQDN, then it's a web server configuration issue; you need to adjust you virtual host settings (in Apache, the <code>ServerAlias</code> directive should be used to add additonal names. In IIS its in Web Site (tab) -> Advanced (button)).</p>\n\n<p>After that... I'm really out of ideas.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19159/" ]
I've got an issue when accessing a web site, I can access it by using the NetBIOS name, but when accessing with the FQDN i get an error. Any ideas on how to troubleshoot this? (There is no DNS configured yet, we have modified the Hosts file to enter the related names and IP.)
First, check the obvious: are there any typos in the file? Next, test out the name resolution. Something simple like pinging the web server by it's FQDN will do. See if the right IP is mentioned. * If you get "unknown host", your client's hosts file does not have an entry for the FQDN you entered (check for typos in the host name), or, for some reason, your computer isn't reading your hosts file. * If you get the wrong IP address, then you have the wrong IP in your hosts file (check for typos in the IP address), your computer's DNS cache is polluted (try: `ipconfig /flushdns` on a Windows machine), or something else is overriding the lookup (duplicate entries in the hosts file?). Next up, try communicating with your web server. Using Telnet, speak HTTP to it, and see how it responds: ``` telnet 192.168.0.1 80 ``` Substitute your web server's IP address instead of `192.168.0.1`. Provide the following lines: ``` GET / HTTP/1.1 Host: fqdn.mywebserver.com ``` Try the server's IP, server's netbios name, and finally the server's FQDN in place of `fqdn.mywebserver.com`. Be sure to press return *twice* after entering the host header. If the response is different between the netbios name and the FQDN, then it's a web server configuration issue; you need to adjust you virtual host settings (in Apache, the `ServerAlias` directive should be used to add additonal names. In IIS its in Web Site (tab) -> Advanced (button)). After that... I'm really out of ideas.
164,839
<p>Every time I try to create a new project or solution in visual studio (2005 and 2008), I get an error saying, "Project Creation failed." I even tried running vs in administrative mode, but I still get the same answer. Anyone have any suggestions, in short of uninstalling all of VS and reinstalling it?</p>
[ { "answer_id": 164860, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 1, "selected": false, "text": "<p>It sounds like an Add-in behaving badly. Can you launch it in safe mode?</p>\n\n<pre><code>devenv.exe /SafeMode\n</code></pre>\n" }, { "answer_id": 164863, "author": "steffenj", "author_id": 15328, "author_profile": "https://Stackoverflow.com/users/15328", "pm_score": 0, "selected": false, "text": "<p>Out of the blue i would guess a security/rights issue, eg. trying to create the solution on a drive/folder you don't have write access to, or has otherwise restricted rights.</p>\n" }, { "answer_id": 164877, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": 0, "selected": false, "text": "<p>Is it in Vista, I know 2005 is known to have compatibility issues in Vista, dunno about 2008, but do they both have current updates?</p>\n" }, { "answer_id": 164947, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": 0, "selected": false, "text": "<p>If you are running in administrator mode, and click run as administrator and have all the latest updates and no add-ins, I think you might have to reinstall it. Make sure you select all the development types you plan to use to get the sdks and not just the redistributables.</p>\n\n<p>If that doesn't work, you might talk to the microsoft reps. With some quick online research people really only had probelms like this before Visual Studio SP1, anything with 64 bit Vista has just been unable to compile ASP.</p>\n\n<p>Good luck.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21745/" ]
Every time I try to create a new project or solution in visual studio (2005 and 2008), I get an error saying, "Project Creation failed." I even tried running vs in administrative mode, but I still get the same answer. Anyone have any suggestions, in short of uninstalling all of VS and reinstalling it?
It sounds like an Add-in behaving badly. Can you launch it in safe mode? ``` devenv.exe /SafeMode ```
164,847
<p>Vi and Vim allow for really awesome customization, typically stored inside a <code>.vimrc</code> file. Typical features for a programmer would be syntax highlighting, smart indenting and so on.</p> <p><strong>What other tricks for productive programming have you got, hidden in your .vimrc?</strong></p> <p>I am mostly interested in refactorings, auto classes and similar productivity macros, especially for C#.</p>
[ { "answer_id": 164866, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": false, "text": "<p>This isn't in my .vimrc file, but yesterday I learned about the <code>]p</code> command. This pastes the contents of a buffer just like <code>p</code> does, but it automatically adjusts the indent to match the line the cursor is on! This is excellent for moving code around.</p>\n" }, { "answer_id": 164867, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 6, "selected": false, "text": "<p>I use the following to keep all the temporary and backup files in one place:</p>\n\n<pre><code>set backup\nset backupdir=~/.vim/backup\nset directory=~/.vim/tmp\n</code></pre>\n\n<p>Saves cluttering working directories all over the place.</p>\n\n<p>You will have to create these directories first, vim will <strong>not</strong> create them for you.</p>\n" }, { "answer_id": 164884, "author": "Trenton", "author_id": 2601671, "author_profile": "https://Stackoverflow.com/users/2601671", "pm_score": 2, "selected": false, "text": "<p>I'm on OS X, so some of these might have better defaults on other platforms, but regardless:</p>\n\n<pre><code>syntax on\nset tabstop=4\nset expandtab\nset shiftwidth=4\n</code></pre>\n" }, { "answer_id": 164889, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 2, "selected": false, "text": "<pre><code>\nset nobackup \nset nocp\nset tabstop=4\nset shiftwidth=4\nset et\nset ignorecase\n\nset ai\nset ruler\nset showcmd\nset incsearch\nset dir=$temp \" Make swap live in the %TEMP% directory\nsyn on\n\n\" Load the color scheme\ncolo inkpot\n</code></pre>\n" }, { "answer_id": 164923, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 2, "selected": false, "text": "<p>There isn't much actually in <a href=\"http://code.google.com/p/lh-vim/source/browse#svn/misc/trunk\" rel=\"nofollow noreferrer\">my .vimrc</a> (even if it has 850 lines). Mostly settings and a few common and simple mappings that I was too lazy to extract into plugins.</p>\n\n<p>If you mean \"template-files\" by \"auto-classes\", I'm using a <a href=\"http://code.google.com/p/lh-vim/wiki/muTemplate\" rel=\"nofollow noreferrer\">template-expander plugin</a> -- on this same site, you'll find the ftplugins I've defined for C&amp;C++ editing, some may be adapted to C# I guess.</p>\n\n<p>Regarding the refactoring aspect, there is a tip dedicated to this subject on <a href=\"http://vim.wikia.com\" rel=\"nofollow noreferrer\">http://vim.wikia.com</a> ; IIRC the example code is for C#. It inspired me a <a href=\"http://code.google.com/p/lh-vim/wiki/lhRefactor\" rel=\"nofollow noreferrer\">refactoring plugin</a> that still needs of lot of work (it needs to be refactored actually).</p>\n\n<p>You should have a look at the archives of vim mailing-list, specially the subjects about using vim as an effective IDE. Don't forget to have a look at :make, tags, ...</p>\n\n<p>HTH,</p>\n" }, { "answer_id": 164935, "author": "Aleksandar Dimitrov", "author_id": 11797, "author_profile": "https://Stackoverflow.com/users/11797", "pm_score": 2, "selected": false, "text": "<p>Well, you'll have to scavenge my <a href=\"http://github.com/adimit/config\" rel=\"nofollow noreferrer\">configs</a> yourself. Have fun. Mostly it's just my desired setup, including mappings and random syntax-relevant stuff, as well as folding setup and some plugin configuration, a tex-compilation parser etc.</p>\n\n<p>BTW, something I found extremely useful is \"highlight word under cursor\":</p>\n\n<pre><code> highlight flicker cterm=bold ctermfg=white\n au CursorMoved &lt;buffer&gt; exe 'match flicker /\\V\\&lt;'.escape(expand('&lt;cword&gt;'), '/').'\\&gt;/'\n</code></pre>\n\n<p>Note that only <code>cterm</code> and <code>termfg</code> are used, because I don't use <code>gvim</code>. If you want that to work in <code>gvim</code> just replac them with <code>gui</code> and <code>guifg</code>, respectively.</p>\n" }, { "answer_id": 164961, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": false, "text": "<pre><code>map = }{!}fmt^M}\nmap + }{!}fmt -p '&gt; '^M}\nset showmatch\n</code></pre>\n\n<p>= is for reformatting normal paragraphs. + is for reformatting paragraphs in quoted emails. showmatch is for flashing the matching parenthesis/bracket when I type a close parenthesis or bracket.</p>\n" }, { "answer_id": 165002, "author": "pixelbeat", "author_id": 4421, "author_profile": "https://Stackoverflow.com/users/4421", "pm_score": 2, "selected": false, "text": "<p>I've tried to keep <a href=\"http://www.pixelbeat.org/settings/.vimrc\" rel=\"nofollow noreferrer\" title=\"my .vimrc\">my .vimrc</a> as generally useful as possible.</p>\n\n<p>A handy trick in there is a handler for .gpg files to edit them securely:</p>\n\n<pre><code>au BufNewFile,BufReadPre *.gpg :set secure vimi= noswap noback nowriteback hist=0 binary\nau BufReadPost *.gpg :%!gpg -d 2&gt;/dev/null\nau BufWritePre *.gpg :%!gpg -e -r '[email protected]' 2&gt;/dev/null\nau BufWritePost *.gpg u\n</code></pre>\n" }, { "answer_id": 165247, "author": "shank", "author_id": 24697, "author_profile": "https://Stackoverflow.com/users/24697", "pm_score": 2, "selected": false, "text": "<p>I use cscope from within vim (making great use of the multiple buffers). I use control-K to initiate most of the commands (stolen from ctags as I recall). Also, I've already generated the .cscope.out file.</p>\n\n<p>if has(\"cscope\")</p>\n\n<pre><code>set cscopeprg=/usr/local/bin/cscope\nset cscopetagorder=0\nset cscopetag\nset cscopepathcomp=3\nset nocscopeverbose\ncs add .cscope.out\nset csverb\n\n\"\n\" cscope find\n\"\n\" 0 or s: Find this C symbol\n\" 1 or d: Find this definition\n\" 2 or g: Find functions called by this function\n\" 3 or c: Find functions calling this function\n\" 4 or t: Find assignments to\n\" 6 or e: Find this egrep pattern\n\" 7 or f: Find this file\n\" 8 or i: Find files #including this file\n\" \nmap ^Ks :cs find 0 &lt;C-R&gt;=expand(\"&lt;cword&gt;\")&lt;CR&gt;&lt;CR&gt;\nmap ^Kd :cs find 1 &lt;C-R&gt;=expand(\"&lt;cword&gt;\")&lt;CR&gt;&lt;CR&gt;\nmap ^Kg :cs find 2 &lt;C-R&gt;=expand(\"&lt;cword&gt;\")&lt;CR&gt;&lt;CR&gt;\nmap ^Kc :cs find 3 &lt;C-R&gt;=expand(\"&lt;cword&gt;\")&lt;CR&gt;&lt;CR&gt;\nmap ^Kt :cs find 4 &lt;C-R&gt;=expand(\"&lt;cword&gt;\")&lt;CR&gt;&lt;CR&gt;\nmap ^Ke :cs find 6 &lt;C-R&gt;=expand(\"&lt;cword&gt;\")&lt;CR&gt;&lt;CR&gt;\nmap ^Kf :cs find 7 &lt;C-R&gt;=expand(\"&lt;cfile&gt;\")&lt;CR&gt;&lt;CR&gt;\nmap ^Ki :cs find 8 &lt;C-R&gt;=expand(\"%\")&lt;CR&gt;&lt;CR&gt;\n</code></pre>\n\n<p>endif</p>\n" }, { "answer_id": 165257, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 2, "selected": false, "text": "<p>Use the first available 'tags' file in the directory tree:</p>\n\n<pre><code>:set tags=tags;/\n</code></pre>\n\n<p>Left and right are for switching buffers, not moving the cursor:</p>\n\n<pre><code>map &lt;right&gt; &lt;ESC&gt;:bn&lt;RETURN&gt;\nmap &lt;left&gt; &lt;ESC&gt;:bp&lt;RETURN&gt;\n</code></pre>\n\n<p>Disable search highlighting with a single keypress:</p>\n\n<pre><code>map - :nohls&lt;cr&gt;\n</code></pre>\n" }, { "answer_id": 165267, "author": "Alex B", "author_id": 23643, "author_profile": "https://Stackoverflow.com/users/23643", "pm_score": 4, "selected": false, "text": "<p>Misc. settings:</p>\n\n<ol>\n<li><p>Turn off annoying error bells:</p>\n\n<pre><code>set noerrorbells\nset visualbell\nset t_vb=\n</code></pre></li>\n<li><p>Make cursor move as expected with wrapped lines:</p>\n\n<pre><code>inoremap &lt;Down&gt; &lt;C-o&gt;gj\ninoremap &lt;Up&gt; &lt;C-o&gt;gk\n</code></pre></li>\n<li><p>Lookup <code>ctags</code> \"tags\" file up the directory, until one is found:</p>\n\n<pre><code>set tags=tags;/\n</code></pre></li>\n<li><p>Display SCons files wiith Python syntax:</p>\n\n<pre><code>autocmd BufReadPre,BufNewFile SConstruct set filetype=python\nautocmd BufReadPre,BufNewFile SConscript set filetype=python\n</code></pre></li>\n</ol>\n" }, { "answer_id": 165271, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 0, "selected": false, "text": "<p>I put my .vimrc at <a href=\"http://dotfiles.org/~petdance/.vimrc\" rel=\"nofollow noreferrer\">http://dotfiles.org/~petdance/.vimrc</a>, and I have <a href=\"http://dotfiles.org/~petdance/\" rel=\"nofollow noreferrer\">some other files at dotfiles.org, too</a>.</p>\n" }, { "answer_id": 165289, "author": "Nick Parker", "author_id": 7296, "author_profile": "https://Stackoverflow.com/users/7296", "pm_score": 2, "selected": false, "text": "<p>I keep my vimrc file up on github. You can find it here:</p>\n\n<p><a href=\"http://github.com/developernotes/vim-setup/tree/master\" rel=\"nofollow noreferrer\">http://github.com/developernotes/vim-setup/tree/master</a></p>\n" }, { "answer_id": 166562, "author": "Kris Kumler", "author_id": 4281, "author_profile": "https://Stackoverflow.com/users/4281", "pm_score": 2, "selected": false, "text": "<p>1) I like a statusline (with the filename, ascii value (decimal), hex value, and the standard lines, cols, and %):</p>\n\n<pre><code>set statusline=%t%h%m%r%=[%b\\ 0x%02B]\\ \\ \\ %l,%c%V\\ %P\n\" Always show a status line\nset laststatus=2\n\"make the command line 1 line high\nset cmdheight=1\n</code></pre>\n\n<p>2) I also like mappings for split windows.</p>\n\n<pre><code>\" &lt;space&gt; switches to the next window (give it a second)\n\" &lt;space&gt;n switches to the next window\n\" &lt;space&gt;&lt;space&gt; switches to the next window and maximizes it\n\" &lt;space&gt;= Equalizes the size of all windows\n\" + Increases the size of the current window\n\" - Decreases the size of the current window\n\n :map &lt;space&gt; &lt;c-W&gt;w\n:map &lt;space&gt;n &lt;c-W&gt;w\n:map &lt;space&gt;&lt;space&gt; &lt;c-W&gt;w&lt;c-W&gt;_\n:map &lt;space&gt;= &lt;c-W&gt;=\nif bufwinnr(1)\n map + &lt;c-W&gt;+\n map - &lt;c-W&gt;-\nendif\n</code></pre>\n" }, { "answer_id": 166636, "author": "Dominic Dos Santos", "author_id": 5379, "author_profile": "https://Stackoverflow.com/users/5379", "pm_score": 3, "selected": false, "text": "<p>Some fixes for common typos have saved me a surprising amount of time:</p>\n\n<pre><code>:command WQ wq\n:command Wq wq\n:command W w\n:command Q q\n\niab anf and\niab adn and\niab ans and\niab teh the\niab thre there\n</code></pre>\n" }, { "answer_id": 167261, "author": "rampion", "author_id": 9859, "author_profile": "https://Stackoverflow.com/users/9859", "pm_score": 0, "selected": false, "text": "<p>My <code>~/.vimrc</code> is pretty standard (mostly the <code>$VIMRUNTIME/vimrc_example.vim</code>), but I use my <code>~/.vim</code> directory extensively, with custom scripts in <code>~/.vim/ftplugin</code> and <code>~/.vim/syntax</code>.</p>\n" }, { "answer_id": 171558, "author": "Frew Schmidt", "author_id": 12448, "author_profile": "https://Stackoverflow.com/users/12448", "pm_score": 7, "selected": false, "text": "<p>You asked for it :-)</p>\n\n<pre><code>\"{{{Auto Commands\n\n\" Automatically cd into the directory that the file is in\nautocmd BufEnter * execute \"chdir \".escape(expand(\"%:p:h\"), ' ')\n\n\" Remove any trailing whitespace that is in the file\nautocmd BufRead,BufWrite * if ! &amp;bin | silent! %s/\\s\\+$//ge | endif\n\n\" Restore cursor position to where it was before\naugroup JumpCursorOnEdit\n au!\n autocmd BufReadPost *\n \\ if expand(\"&lt;afile&gt;:p:h\") !=? $TEMP |\n \\ if line(\"'\\\"\") &gt; 1 &amp;&amp; line(\"'\\\"\") &lt;= line(\"$\") |\n \\ let JumpCursorOnEdit_foo = line(\"'\\\"\") |\n \\ let b:doopenfold = 1 |\n \\ if (foldlevel(JumpCursorOnEdit_foo) &gt; foldlevel(JumpCursorOnEdit_foo - 1)) |\n \\ let JumpCursorOnEdit_foo = JumpCursorOnEdit_foo - 1 |\n \\ let b:doopenfold = 2 |\n \\ endif |\n \\ exe JumpCursorOnEdit_foo |\n \\ endif |\n \\ endif\n \" Need to postpone using \"zv\" until after reading the modelines.\n autocmd BufWinEnter *\n \\ if exists(\"b:doopenfold\") |\n \\ exe \"normal zv\" |\n \\ if(b:doopenfold &gt; 1) |\n \\ exe \"+\".1 |\n \\ endif |\n \\ unlet b:doopenfold |\n \\ endif\naugroup END\n\n\"}}}\n\n\"{{{Misc Settings\n\n\" Necesary for lots of cool vim things\nset nocompatible\n\n\" This shows what you are typing as a command. I love this!\nset showcmd\n\n\" Folding Stuffs\nset foldmethod=marker\n\n\" Needed for Syntax Highlighting and stuff\nfiletype on\nfiletype plugin on\nsyntax enable\nset grepprg=grep\\ -nH\\ $*\n\n\" Who doesn't like autoindent?\nset autoindent\n\n\" Spaces are better than a tab character\nset expandtab\nset smarttab\n\n\" Who wants an 8 character tab? Not me!\nset shiftwidth=3\nset softtabstop=3\n\n\" Use english for spellchecking, but don't spellcheck by default\nif version &gt;= 700\n set spl=en spell\n set nospell\nendif\n\n\" Real men use gcc\n\"compiler gcc\n\n\" Cool tab completion stuff\nset wildmenu\nset wildmode=list:longest,full\n\n\" Enable mouse support in console\nset mouse=a\n\n\" Got backspace?\nset backspace=2\n\n\" Line Numbers PWN!\nset number\n\n\" Ignoring case is a fun trick\nset ignorecase\n\n\" And so is Artificial Intellegence!\nset smartcase\n\n\" This is totally awesome - remap jj to escape in insert mode. You'll never type jj anyway, so it's great!\ninoremap jj &lt;Esc&gt;\n\nnnoremap JJJJ &lt;Nop&gt;\n\n\" Incremental searching is sexy\nset incsearch\n\n\" Highlight things that we find with the search\nset hlsearch\n\n\" Since I use linux, I want this\nlet g:clipbrdDefaultReg = '+'\n\n\" When I close a tab, remove the buffer\nset nohidden\n\n\" Set off the other paren\nhighlight MatchParen ctermbg=4\n\" }}}\n\n\"{{{Look and Feel\n\n\" Favorite Color Scheme\nif has(\"gui_running\")\n colorscheme inkpot\n \" Remove Toolbar\n set guioptions-=T\n \"Terminus is AWESOME\n set guifont=Terminus\\ 9\nelse\n colorscheme metacosm\nendif\n\n\"Status line gnarliness\nset laststatus=2\nset statusline=%F%m%r%h%w\\ (%{&amp;ff}){%Y}\\ [%l,%v][%p%%]\n\n\" }}}\n\n\"{{{ Functions\n\n\"{{{ Open URL in browser\n\nfunction! Browser ()\n let line = getline (\".\")\n let line = matchstr (line, \"http[^ ]*\")\n exec \"!konqueror \".line\nendfunction\n\n\"}}}\n\n\"{{{Theme Rotating\nlet themeindex=0\nfunction! RotateColorTheme()\n let y = -1\n while y == -1\n let colorstring = \"inkpot#ron#blue#elflord#evening#koehler#murphy#pablo#desert#torte#\"\n let x = match( colorstring, \"#\", g:themeindex )\n let y = match( colorstring, \"#\", x + 1 )\n let g:themeindex = x + 1\n if y == -1\n let g:themeindex = 0\n else\n let themestring = strpart(colorstring, x + 1, y - x - 1)\n return \":colorscheme \".themestring\n endif\n endwhile\nendfunction\n\" }}}\n\n\"{{{ Paste Toggle\nlet paste_mode = 0 \" 0 = normal, 1 = paste\n\nfunc! Paste_on_off()\n if g:paste_mode == 0\n set paste\n let g:paste_mode = 1\n else\n set nopaste\n let g:paste_mode = 0\n endif\n return\nendfunc\n\"}}}\n\n\"{{{ Todo List Mode\n\nfunction! TodoListMode()\n e ~/.todo.otl\n Calendar\n wincmd l\n set foldlevel=1\n tabnew ~/.notes.txt\n tabfirst\n \" or 'norm! zMzr'\nendfunction\n\n\"}}}\n\n\"}}}\n\n\"{{{ Mappings\n\n\" Open Url on this line with the browser \\w\nmap &lt;Leader&gt;w :call Browser ()&lt;CR&gt;\n\n\" Open the Project Plugin &lt;F2&gt;\nnnoremap &lt;silent&gt; &lt;F2&gt; :Project&lt;CR&gt;\n\n\" Open the Project Plugin\nnnoremap &lt;silent&gt; &lt;Leader&gt;pal :Project .vimproject&lt;CR&gt;\n\n\" TODO Mode\nnnoremap &lt;silent&gt; &lt;Leader&gt;todo :execute TodoListMode()&lt;CR&gt;\n\n\" Open the TagList Plugin &lt;F3&gt;\nnnoremap &lt;silent&gt; &lt;F3&gt; :Tlist&lt;CR&gt;\n\n\" Next Tab\nnnoremap &lt;silent&gt; &lt;C-Right&gt; :tabnext&lt;CR&gt;\n\n\" Previous Tab\nnnoremap &lt;silent&gt; &lt;C-Left&gt; :tabprevious&lt;CR&gt;\n\n\" New Tab\nnnoremap &lt;silent&gt; &lt;C-t&gt; :tabnew&lt;CR&gt;\n\n\" Rotate Color Scheme &lt;F8&gt;\nnnoremap &lt;silent&gt; &lt;F8&gt; :execute RotateColorTheme()&lt;CR&gt;\n\n\" DOS is for fools.\nnnoremap &lt;silent&gt; &lt;F9&gt; :%s/$//g&lt;CR&gt;:%s// /g&lt;CR&gt;\n\n\" Paste Mode! Dang! &lt;F10&gt;\nnnoremap &lt;silent&gt; &lt;F10&gt; :call Paste_on_off()&lt;CR&gt;\nset pastetoggle=&lt;F10&gt;\n\n\" Edit vimrc \\ev\nnnoremap &lt;silent&gt; &lt;Leader&gt;ev :tabnew&lt;CR&gt;:e ~/.vimrc&lt;CR&gt;\n\n\" Edit gvimrc \\gv\nnnoremap &lt;silent&gt; &lt;Leader&gt;gv :tabnew&lt;CR&gt;:e ~/.gvimrc&lt;CR&gt;\n\n\" Up and down are more logical with g..\nnnoremap &lt;silent&gt; k gk\nnnoremap &lt;silent&gt; j gj\ninoremap &lt;silent&gt; &lt;Up&gt; &lt;Esc&gt;gka\ninoremap &lt;silent&gt; &lt;Down&gt; &lt;Esc&gt;gja\n\n\" Good call Benjie (r for i)\nnnoremap &lt;silent&gt; &lt;Home&gt; i &lt;Esc&gt;r\nnnoremap &lt;silent&gt; &lt;End&gt; a &lt;Esc&gt;r\n\n\" Create Blank Newlines and stay in Normal mode\nnnoremap &lt;silent&gt; zj o&lt;Esc&gt;\nnnoremap &lt;silent&gt; zk O&lt;Esc&gt;\n\n\" Space will toggle folds!\nnnoremap &lt;space&gt; za\n\n\" Search mappings: These will make it so that going to the next one in a\n\" search will center on the line it's found in.\nmap N Nzz\nmap n nzz\n\n\" Testing\nset completeopt=longest,menuone,preview\n\ninoremap &lt;expr&gt; &lt;cr&gt; pumvisible() ? \"\\&lt;c-y&gt;\" : \"\\&lt;c-g&gt;u\\&lt;cr&gt;\"\ninoremap &lt;expr&gt; &lt;c-n&gt; pumvisible() ? \"\\&lt;lt&gt;c-n&gt;\" : \"\\&lt;lt&gt;c-n&gt;\\&lt;lt&gt;c-r&gt;=pumvisible() ? \\\"\\\\&lt;lt&gt;down&gt;\\\" : \\\"\\\"\\&lt;lt&gt;cr&gt;\"\ninoremap &lt;expr&gt; &lt;m-;&gt; pumvisible() ? \"\\&lt;lt&gt;c-n&gt;\" : \"\\&lt;lt&gt;c-x&gt;\\&lt;lt&gt;c-o&gt;\\&lt;lt&gt;c-n&gt;\\&lt;lt&gt;c-p&gt;\\&lt;lt&gt;c-r&gt;=pumvisible() ? \\\"\\\\&lt;lt&gt;down&gt;\\\" : \\\"\\\"\\&lt;lt&gt;cr&gt;\"\n\n\" Swap ; and : Convenient.\nnnoremap ; :\nnnoremap : ;\n\n\" Fix email paragraphs\nnnoremap &lt;leader&gt;par :%s/^&gt;$//&lt;CR&gt;\n\n\"ly$O#{{{ \"lpjjj_%A#}}}jjzajj\n\n\"}}}\n\n\"{{{Taglist configuration\nlet Tlist_Use_Right_Window = 1\nlet Tlist_Enable_Fold_Column = 0\nlet Tlist_Exit_OnlyWindow = 1\nlet Tlist_Use_SingleClick = 1\nlet Tlist_Inc_Winwidth = 0\n\"}}}\n\nlet g:rct_completion_use_fri = 1\n\"let g:Tex_DefaultTargetFormat = \"pdf\"\nlet g:Tex_ViewRule_pdf = \"kpdf\"\n\nfiletype plugin indent on\nsyntax on\n</code></pre>\n" }, { "answer_id": 185960, "author": "camflan", "author_id": 22445, "author_profile": "https://Stackoverflow.com/users/22445", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://media.camronflanders.com/.vimrc\" rel=\"nofollow noreferrer\">my .vimrc</a>. My word swap function is usually a big hit.</p>\n" }, { "answer_id": 201938, "author": "Jeremy Cantrell", "author_id": 18866, "author_profile": "https://Stackoverflow.com/users/18866", "pm_score": 0, "selected": false, "text": "<p>Here are mine. They've been evolving for a number of years and they work equally well in Linux/Windows/OSX (last time I checked):</p>\n\n<p><a href=\"https://github.com/jmcantrell/dotfiles-vim/blob/master/vimrc\" rel=\"nofollow noreferrer\">vimrc</a> and\n<a href=\"https://github.com/jmcantrell/dotfiles-vim/blob/master/gvimrc\" rel=\"nofollow noreferrer\">gvimrc</a></p>\n" }, { "answer_id": 219617, "author": "Julien Nephtali", "author_id": 5060, "author_profile": "https://Stackoverflow.com/users/5060", "pm_score": 1, "selected": false, "text": "<p>Here is my .vimrc. I use Gvim 7.2</p>\n\n<pre><code>set guioptions=em\nset showtabline=2\nset softtabstop=2\nset shiftwidth=2\nset tabstop=2\n\n\" Use spaces instead of tabs\nset expandtab\nset autoindent\n\n\" Colors and fonts\ncolorscheme inkpot\nset guifont=Consolas:h11:cANSI\n\n\"TAB navigation like firefox\n:nmap &lt;C-S-tab&gt; :tabprevious&lt;cr&gt;\n:nmap &lt;C-tab&gt; :tabnext&lt;cr&gt;\n:imap &lt;C-S-tab&gt; &lt;ESC&gt;:tabprevious&lt;cr&gt;i\n:imap &lt;C-tab&gt; &lt;ESC&gt;:tabnext&lt;cr&gt;i\n:nmap &lt;C-t&gt; :tabnew&lt;cr&gt;\n:imap &lt;C-t&gt; &lt;ESC&gt;:tabnew&lt;cr&gt;i\n:map &lt;C-w&gt; :tabclose&lt;cr&gt;\n\n\" No Backups and line numbers\nset nobackup\nset number\nset nuw=6\n\n\" swp files are saved to %Temp% folder\nset dir=$temp\n\" sets the default size of gvim on open\nset lines=40 columns=90\n</code></pre>\n" }, { "answer_id": 219693, "author": "rshdev", "author_id": 19961, "author_profile": "https://Stackoverflow.com/users/19961", "pm_score": 3, "selected": false, "text": "<p>I didn't realize how many of my 3200 .vimrc lines were just for my quirky needs and would be pretty uninspiring to list here. But maybe that's why Vim is so useful...</p>\n\n<pre><code>iab AlP ABCDEFGHIJKLMNOPQRSTUVWXYZ\niab MoN January February March April May June July August September October November December\niab MoO Jan Feb Mar Apr May Jun Jul Aug Sep Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\niab NuM 12345678901234567890123456789012345678901234567890123456789012345678901234567890 \niab RuL ----+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0\n\n\" Highlight every other line\nmap ,&lt;Tab&gt; :set hls&lt;CR&gt;/\\\\n.*\\\\n/&lt;CR&gt;\n\n\" This is for working across multiple xterms and/or gvims\n\" Transfer/read and write one block of text between vim sessions (capture whole line):\n\" Write\nnmap ;w :. w! ~/.vimxfer&lt;CR&gt;\n\" Read\nnmap ;r :r ~/.vimxfer&lt;CR&gt;\n\" Append \nnmap ;a :. w! &gt;&gt;~/.vimxfer&lt;CR&gt;\n</code></pre>\n" }, { "answer_id": 257356, "author": "ngn", "author_id": 23109, "author_profile": "https://Stackoverflow.com/users/23109", "pm_score": 1, "selected": false, "text": "<p>What's in my <code>.vimrc</code>?</p>\n\n<pre><code>ngn@macavity:~$ cat .vimrc\n\" This file intentionally left blank\n</code></pre>\n\n<p>The real config files lie under <code>~/.vim/ :)</code></p>\n\n<p>And most of the stuff there is parasiting on other people's efforts, blatantly adapted from <code>vim.org</code> to my editing advantage.</p>\n" }, { "answer_id": 257444, "author": "Whaledawg", "author_id": 23829, "author_profile": "https://Stackoverflow.com/users/23829", "pm_score": 3, "selected": false, "text": "<p>I'm not the most advanced vim'er in the world, but here's a few I've picked up</p>\n\n<pre><code>function! Mosh_Tab_Or_Complete()\n if col('.')&gt;1 &amp;&amp; strpart( getline('.'), col('.')-2, 3 ) =~ '^\\w'\n return \"\\&lt;C-N&gt;\"\n else\n return \"\\&lt;Tab&gt;\"\nendfunction\n\ninoremap &lt;Tab&gt; &lt;C-R&gt;=Mosh_Tab_Or_Complete()&lt;CR&gt;\n</code></pre>\n\n<p>Makes the tab-autocomplete figure out whether you want to place a word there or an actual\ntab(4 spaces).</p>\n\n<pre><code>map cc :.,$s/^ *//&lt;CR&gt;\n</code></pre>\n\n<p>Remove all opening whitespace from here to the end of the file. For some reason I find this useful a lot.</p>\n\n<pre><code>set nu! \nset nobackup\n</code></pre>\n\n<p>Show line numbers and don't create those annoying backup files. I've never restored anything from an old backup anyways.</p>\n\n<pre><code>imap ii &lt;C-[&gt;\n</code></pre>\n\n<p>While in insert, press i twice to go to command mode. I've never come across a word or variable with 2 i's in a row, and this way I don't have to have my fingers leave the home row or press multiple keys to switch back and forth.</p>\n" }, { "answer_id": 257445, "author": "Terminus", "author_id": 7053, "author_profile": "https://Stackoverflow.com/users/7053", "pm_score": 0, "selected": false, "text": "<pre><code>\" **************************\n\" * vim general options ****\n\" **************************\nset nocompatible\nset history=1000\nset mouse=a\n\n\" don't have files trying to override this .vimrc:\nset nomodeline\n\n\" have &lt;F1&gt; prompt for a help topic, rather than displaying the introduction\n\" page, and have it do this from any mode:\nnnoremap &lt;F1&gt; :help&lt;Space&gt;\nvmap &lt;F1&gt; &lt;C-C&gt;&lt;F1&gt;\nomap &lt;F1&gt; &lt;C-C&gt;&lt;F1&gt;\nmap! &lt;F1&gt; &lt;C-C&gt;&lt;F1&gt;\n\nset title\n\n\" **************************\n\" * set visual options *****\n\" **************************\nset nu\nset ruler\nsyntax on\n\n\" colorscheme oceandeep\nset background=dark\n\nset wildmenu\nset wildmode=list:longest,full\n\n\" use \"[RO]\" for \"[readonly]\"\nset shortmess+=r\n\nset scrolloff=3\n\n\" display the current mode and partially-typed commands in the status line:\nset showmode\nset showcmd\n\n\" don't make it look like there are line breaks where there aren't:\nset nowrap\n\n\" **************************\n\" * set editing options ****\n\" **************************\nset autoindent\nfiletype plugin indent on\nset backspace=eol,indent,start\nautocmd FileType text setlocal textwidth=80\nautocmd FileType make set noexpandtab shiftwidth=8\n\n\" * Search &amp; Replace\n\" make searches case-insensitive, unless they contain upper-case letters:\nset ignorecase\nset smartcase\n\" show the `best match so far' as search strings are typed:\nset incsearch\n\" assume the /g flag on :s substitutions to replace all matches in a line:\nset gdefault\n\n\" ***************************\n\" * tab completion **********\n\" ***************************\nsetlocal omnifunc=syntaxcomplete#Complete\nimap &lt;Tab&gt; &lt;C-x&gt;&lt;C-o&gt;\ninoremap &lt;tab&gt; &lt;c-r&gt;=InsertTabWrapper()&lt;cr&gt;\n\n\" ***************************\n\" * keyboard mapping ********\n\" ***************************\nimap &lt;A-1&gt; &lt;Esc&gt;:tabn 1&lt;CR&gt;i\nimap &lt;A-2&gt; &lt;Esc&gt;:tabn 2&lt;CR&gt;i\nimap &lt;A-3&gt; &lt;Esc&gt;:tabn 3&lt;CR&gt;i\nimap &lt;A-4&gt; &lt;Esc&gt;:tabn 4&lt;CR&gt;i\nimap &lt;A-5&gt; &lt;Esc&gt;:tabn 5&lt;CR&gt;i\nimap &lt;A-6&gt; &lt;Esc&gt;:tabn 6&lt;CR&gt;i\nimap &lt;A-7&gt; &lt;Esc&gt;:tabn 7&lt;CR&gt;i\nimap &lt;A-8&gt; &lt;Esc&gt;:tabn 8&lt;CR&gt;i\nimap &lt;A-9&gt; &lt;Esc&gt;:tabn 9&lt;CR&gt;i\n\nmap &lt;A-1&gt; :tabn 1&lt;CR&gt;\nmap &lt;A-2&gt; :tabn 2&lt;CR&gt;\nmap &lt;A-3&gt; :tabn 3&lt;CR&gt;\nmap &lt;A-4&gt; :tabn 4&lt;CR&gt;\nmap &lt;A-5&gt; :tabn 5&lt;CR&gt;\nmap &lt;A-6&gt; :tabn 6&lt;CR&gt;\nmap &lt;A-7&gt; :tabn 7&lt;CR&gt;\nmap &lt;A-8&gt; :tabn 8&lt;CR&gt;\nmap &lt;A-9&gt; :tabn 9&lt;CR&gt;\n\n\" ***************************\n\" * Utilities Needed ********\n\" ***************************\nfunction InsertTabWrapper()\n let col = col('.') - 1\n if !col || getline('.')[col - 1] !~ '\\k'\n return \"\\&lt;tab&gt;\"\n else\n return \"\\&lt;c-p&gt;\"\n endif\nendfunction\n\n\" end of .vimrc\n</code></pre>\n" }, { "answer_id": 342511, "author": "Jon DellOro", "author_id": 36456, "author_profile": "https://Stackoverflow.com/users/36456", "pm_score": 0, "selected": false, "text": "<p>Probably the most significant things below are the font choices and the colour schemes. Yes, I have spent far too long enjoyably fiddling with those things. :)</p>\n\n<pre><code>\"set tildeop\nset nosmartindent\n\" set guifont=courier\n\" awesome programming font\n\" set guifont=peep:h09:cANSI\n\" another nice looking font for programming and general use\nset guifont=Bitstream_Vera_Sans_MONO:h09:cANSI\nset lines=68\nset tabstop=2\nset shiftwidth=2\nset expandtab\nset ignorecase\nset nobackup\n\" set writebackup\n\n\" Some of my favourite colour schemes, lovingly crafted over the years :)\n\" very dark scarlet background, almost white text\n\" hi Normal guifg=#FFFFF0 guibg=#3F0000 ctermfg=white ctermbg=Black\n\" C64 colours\n\"hi Normal guifg=#8CA1EC guibg=#372DB4 ctermfg=white ctermbg=Black \n\" nice forest green background with bisque fg\nhi Normal guifg=#9CfCb1 guibg=#279A1D ctermfg=white ctermbg=Black \n\" dark green background with almost white text \n\"hi Normal guifg=#FFFFF0 guibg=#003F00 ctermfg=white ctermbg=Black\n\n\" french blue background, almost white text\n\"hi Normal guifg=#FFFFF0 guibg=#00003F ctermfg=white ctermbg=Black\n\n\" slate blue bg, grey text\n\"hi Normal guifg=#929Cb1 guibg=#20403F ctermfg=white ctermbg=Black \n\n\" yellow/orange bg, black text\nhi Normal guifg=#000000 guibg=#f8db3a ctermfg=white ctermbg=Black \n</code></pre>\n" }, { "answer_id": 369302, "author": "Ronny Brendel", "author_id": 14114, "author_profile": "https://Stackoverflow.com/users/14114", "pm_score": 0, "selected": false, "text": "<pre><code>set guifont=FreeMono\\ 12\n\ncolorscheme default\n\nset nocompatible\nset backspace=indent,eol,start\nset nobackup \"do not keep a backup file, use versions instead\nset history=10000 \"keep 10000 lines of command line history\nset ruler \"show the cursor position all the time\nset showcmd \"display incomplete commands\nset showmode\nset showmatch\nset nojoinspaces \"do not insert a space, when joining lines\nset whichwrap=\"\" \"do not jump to the next line when deleting\n\"set nowrap\nfiletype plugin indent on\nsyntax enable\nset hlsearch\nset incsearch \"do incremental searching\nset autoindent\nset noexpandtab\nset tabstop=4\nset shiftwidth=4\nset number\nset laststatus=2\nset visualbell \"do not beep\nset tabpagemax=100\nset statusline=%F\\ %h%m%r%=%l/%L\\ \\(%-03p%%\\)\\ %-03c\\ \n\n\"use listmode to make tabs visible and make them gray so they are not\n\"disctrating too much\nset listchars=tab:»\\ ,eol:¬,trail:.\nhighlight NonText ctermfg=gray guifg=gray\nhighlight SpecialKey ctermfg=gray guifg=gray\nhighlight clear MatchParen\nhighlight MatchParen cterm=bold\nset list\n\n\nmatch Todo /@todo/ \"highlight doxygen todos\n\n\n\"different tabbing settings for different file types\nif has(\"autocmd\")\n autocmd FileType c setlocal tabstop=4 softtabstop=4 shiftwidth=4 expandtab\n autocmd FileType cpp setlocal tabstop=4 softtabstop=4 shiftwidth=4 expandtab\n autocmd FileType go setlocal tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab\n autocmd FileType make setlocal tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab\n autocmd FileType python setlocal tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab\n\n \" doesnt work properly -- revise me\n autocmd CursorMoved * call RonnyHighlightWordUnderCursor()\n autocmd CursorMovedI * call RonnyHighlightWordUnderCursor()\n\n \"jump to the end of the file if it is a logfile\n autocmd BufReadPost *.log normal G\n\n autocmd BufRead,BufNewFile *.go set filetype=go\nendif\n\n\nhighlight Search ctermfg=white ctermbg=gray\nhighlight IncSearch ctermfg=white ctermbg=gray\nhighlight RonnyWordUnderCursorHighlight cterm=bold\n\n\nfunction! RonnyHighlightWordUnderCursor()\npython &lt;&lt; endpython\nimport vim\n\n# get the character under the cursor\nrow, col = vim.current.window.cursor\ncharacterUnderCursor = ''\ntry:\n characterUnderCursor = vim.current.buffer[row-1][col]\nexcept:\n pass\n\n# remove last search\nvim.command(\"match RonnyWordUnderCursorHighlight //\")\n\n# if the cursor is currently located on a real word, move on and highlight it\nif characterUnderCursor.isalpha() or characterUnderCursor.isdigit() or characterUnderCursor is '_':\n\n # expand cword to get the word under the cursor\n wordUnderCursor = vim.eval(\"expand(\\'&lt;cword&gt;\\')\")\n if wordUnderCursor is None :\n wordUnderCursor = \"\"\n\n # escape the word\n wordUnderCursor = vim.eval(\"RonnyEscapeString(\\\"\" + wordUnderCursor + \"\\\")\")\n wordUnderCursor = \"\\&lt;\" + wordUnderCursor + \"\\&gt;\"\n\n currentSearch = vim.eval(\"@/\")\n\n if currentSearch != wordUnderCursor :\n # highlight it, if it is not the currently searched word\n vim.command(\"match RonnyWordUnderCursorHighlight /\" + wordUnderCursor + \"/\")\n\nendpython\nendfunction\n\n\nfunction! RonnyEscapeString(s)\npython &lt;&lt; endpython\nimport vim\n\ns = vim.eval(\"a:s\")\n\nescapeMap = {\n '\"' : '\\\\\"',\n \"'\" : '\\\\''',\n \"*\" : '\\\\*',\n \"/\" : '\\\\/',\n #'' : ''\n}\n\ns = s.replace('\\\\', '\\\\\\\\')\n\nfor before, after in escapeMap.items() :\n s = s.replace(before, after)\n\nvim.command(\"return \\'\" + s + \"\\'\")\nendpython\nendfunction\n</code></pre>\n" }, { "answer_id": 475904, "author": "Martin", "author_id": 52986, "author_profile": "https://Stackoverflow.com/users/52986", "pm_score": 5, "selected": false, "text": "<p>My latest addition is for <strong>highlighting of the current line</strong></p>\n\n<pre><code>set cul # highlight current line\nhi CursorLine term=none cterm=none ctermbg=3 # adjust color\n</code></pre>\n" }, { "answer_id": 652532, "author": "Adam Gibbins", "author_id": 20528, "author_profile": "https://Stackoverflow.com/users/20528", "pm_score": 4, "selected": false, "text": "<p>My mini version:</p>\n\n<pre><code>syntax on\nset background=dark\nset shiftwidth=2\nset tabstop=2\n\nif has(\"autocmd\")\n filetype plugin indent on\nendif\n\nset showcmd \" Show (partial) command in status line.\nset showmatch \" Show matching brackets.\nset ignorecase \" Do case insensitive matching\nset smartcase \" Do smart case matching\nset incsearch \" Incremental search\nset hidden \" Hide buffers when they are abandoned\n</code></pre>\n\n<p>The big version, collected from various places:</p>\n\n<pre><code>syntax on\nset background=dark\nset ruler \" show the line number on the bar\nset more \" use more prompt\nset autoread \" watch for file changes\nset number \" line numbers\nset hidden\nset noautowrite \" don't automagically write on :next\nset lazyredraw \" don't redraw when don't have to\nset showmode\nset showcmd\nset nocompatible \" vim, not vi\nset autoindent smartindent \" auto/smart indent\nset smarttab \" tab and backspace are smart\nset tabstop=2 \" 6 spaces\nset shiftwidth=2\nset scrolloff=5 \" keep at least 5 lines above/below\nset sidescrolloff=5 \" keep at least 5 lines left/right\nset history=200\nset backspace=indent,eol,start\nset linebreak\nset cmdheight=2 \" command line two lines high\nset undolevels=1000 \" 1000 undos\nset updatecount=100 \" switch every 100 chars\nset complete=.,w,b,u,U,t,i,d \" do lots of scanning on tab completion\nset ttyfast \" we have a fast terminal\nset noerrorbells \" No error bells please\nset shell=bash\nset fileformats=unix\nset ff=unix\nfiletype on \" Enable filetype detection\nfiletype indent on \" Enable filetype-specific indenting\nfiletype plugin on \" Enable filetype-specific plugins\nset wildmode=longest:full\nset wildmenu \" menu has tab completion\nlet maplocalleader=',' \" all my macros start with ,\nset laststatus=2\n\n\" searching\nset incsearch \" incremental search\nset ignorecase \" search ignoring case\nset hlsearch \" highlight the search\nset showmatch \" show matching bracket\nset diffopt=filler,iwhite \" ignore all whitespace and sync\n\n\" backup\nset backup\nset backupdir=~/.vim_backup\nset viminfo=%100,'100,/100,h,\\\"500,:100,n~/.viminfo\n\"set viminfo='100,f1\n\n\" spelling\nif v:version &gt;= 700\n \" Enable spell check for text files\n autocmd BufNewFile,BufRead *.txt setlocal spell spelllang=en\nendif\n\n\" mappings\n\" toggle list mode\nnmap &lt;LocalLeader&gt;tl :set list!&lt;cr&gt;\n\" toggle paste mode\nnmap &lt;LocalLeader&gt;pp :set paste!&lt;cr&gt;\n</code></pre>\n" }, { "answer_id": 652632, "author": "Herbert Sitz", "author_id": 76434, "author_profile": "https://Stackoverflow.com/users/76434", "pm_score": 5, "selected": false, "text": "<p>Someone (viz. Frew) who posted above had this line:</p>\n\n<p>\"Automatically cd into the directory that the file is in:\"</p>\n\n<pre><code>autocmd BufEnter * execute \"chdir \".escape(expand(\"%:p:h\"), ' ')\n</code></pre>\n\n<p>I was doing something like that myself until I discovered the same thing could be accomplished with a built in setting:</p>\n\n<pre><code>set autochdir\n</code></pre>\n\n<p>I think something similar has happened to me a few different times. Vim has so many different built-in settings and options that it's sometimes quicker and easier to roll-your-own than search the docs for the built-in way to do it.</p>\n" }, { "answer_id": 701319, "author": "Fire Crow", "author_id": 80479, "author_profile": "https://Stackoverflow.com/users/80479", "pm_score": 0, "selected": false, "text": "<p>I've created my own syntax for my to do or checklist documents which highlights things like</p>\n\n<p>-> do this (in bold)</p>\n\n<p>!-> do this now (in orange)</p>\n\n<p>++> doing this in process (in green)</p>\n\n<p>=> this is done (in gray)</p>\n\n<p>I have the document in ./syntax/ as fc_comdoc.vim</p>\n\n<p>in vimrc to set this syntax for anything with my custom extension .txtcd or .txtap</p>\n\n<pre><code>au BufNewFile,BufRead *.txtap,*.txtcd setf fc_comdoc\n</code></pre>\n" }, { "answer_id": 702644, "author": "Nick Bolton", "author_id": 47775, "author_profile": "https://Stackoverflow.com/users/47775", "pm_score": 1, "selected": false, "text": "<p>Line numbers and syntax highlighting.</p>\n\n<pre><code>set number\nsyntax on\n</code></pre>\n" }, { "answer_id": 789272, "author": "Don Reba", "author_id": 49329, "author_profile": "https://Stackoverflow.com/users/49329", "pm_score": 0, "selected": false, "text": "<p>I show fold contents and syntax groups on mouse-over:</p>\n\n<pre><code>function! SyntaxBallon()\n let synID = synID(v:beval_lnum, v:beval_col, 0)\n let groupID = synIDtrans(synID)\n let name = synIDattr(synID, \"name\")\n let group = synIDattr(groupID, \"name\")\n return name . \"\\n\" . group\nendfunction\n\nfunction! FoldBalloon()\n let foldStart = foldclosed(v:beval_lnum)\n let foldEnd = foldclosedend(v:beval_lnum)\n let lines = []\n if foldStart &gt;= 0\n \" we are in a fold\n let numLines = foldEnd - foldStart + 1\n if (numLines &gt; 17)\n \" show only the first 8 and the last 8 lines\n let lines += getline(foldStart, foldStart + 8)\n let lines += [ '-- Snipped ' . (numLines - 16) . ' lines --']\n let lines += getline(foldEnd - 8, foldEnd)\n else\n \" show all lines\n let lines += getline(foldStart, foldEnd)\n endif\n endif\n \" return result\n return join(lines, has(\"balloon_multiline\") ? \"\\n\" : \" \")\nendfunction\n\nfunction! Balloon()\n if foldclosed(v:beval_lnum) &gt;= 0\n return FoldBalloon()\n else\n return SyntaxBallon()\nendfunction\n\nset balloonexpr=Balloon()\nset ballooneval\n</code></pre>\n" }, { "answer_id": 789284, "author": "Nick Presta", "author_id": 40906, "author_profile": "https://Stackoverflow.com/users/40906", "pm_score": 0, "selected": false, "text": "<pre><code>set nocompatible\nsyntax on\nset number\nset autoindent\nset smartindent\nset background=dark\nset tabstop=4 shiftwidth=4\nset tw=80\nset expandtab\nset mousehide\nset cindent\nset list listchars=tab:»·,trail:·\nset autoread\nfiletype on\nfiletype indent on\nfiletype plugin on\n\n\" abbreviations for c programming\nfunc LoadCAbbrevs()\n \" iabbr do do {&lt;CR&gt;} while ();&lt;C-O&gt;3h&lt;C-O&gt;\n \" iabbr for for (;;) {&lt;CR&gt;}&lt;C-O&gt;k&lt;C-O&gt;3l&lt;C-O&gt;\n \" iabbr switch switch () {&lt;CR&gt;}&lt;C-O&gt;k&lt;C-O&gt;6l&lt;C-O&gt;\n \" iabbr while while () {&lt;CR&gt;}&lt;C-O&gt;k&lt;C-O&gt;5l&lt;C-O&gt;\n \" iabbr if if () {&lt;CR&gt;}&lt;C-O&gt;k&lt;C-O&gt;2l&lt;C-O&gt;\n iabbr #d #define\n iabbr #i #include\nendfunc\nau FileType c,cpp call LoadCAbbrevs()\n\nau BufReadPost * if line(\"'\\\"\") &gt; 0 &amp;&amp; line(\"'\\\"\") &lt;= line(\"$\") |\n \\ exe \"normal g'\\\"\" | endif\n\nautocmd FileType python set nocindent shiftwidth=4 ts=4 foldmethod=indent\n</code></pre>\n\n<p>Not much there.</p>\n" }, { "answer_id": 1219104, "author": "Gavin Gilmour", "author_id": 126893, "author_profile": "https://Stackoverflow.com/users/126893", "pm_score": 5, "selected": false, "text": "<p><strong>Update 2012</strong>: I'd now really recommend checking out <a href=\"https://github.com/Lokaltog/vim-powerline\" rel=\"nofollow noreferrer\">vim-powerline</a> which has replaced my old statusline script, albeit currently missing a few features I miss.</p>\n\n<hr>\n\n<p>I'd say that the statusline stuff in <a href=\"https://github.com/gaving/dotfiles/blob/master/.vimrc\" rel=\"nofollow noreferrer\">my vimrc</a> was probably most interesting/useful out of the lot (ripped from the authors vimrc <a href=\"http://github.com/scrooloose/vimfiles/blob/52b9810195dc571a87eb8ef6af5ae821184b1baa/vimrc\" rel=\"nofollow noreferrer\">here</a> and corresponding blog post <a href=\"http://got-ravings.blogspot.com/2009/07/vim-pr0n-combating-long-lines.html\" rel=\"nofollow noreferrer\">here</a>).</p>\n\n<p>Screenshot:</p>\n\n<p><a href=\"http://img34.imageshack.us/img34/849/statusline.png\" rel=\"nofollow noreferrer\">status line http://img34.imageshack.us/img34/849/statusline.png</a></p>\n\n<p>Code:</p>\n\n<pre><code>\"recalculate the trailing whitespace warning when idle, and after saving\nautocmd cursorhold,bufwritepost * unlet! b:statusline_trailing_space_warning\n\n\"return '[\\s]' if trailing white space is detected\n\"return '' otherwise\nfunction! StatuslineTrailingSpaceWarning()\n if !exists(\"b:statusline_trailing_space_warning\")\n\n if !&amp;modifiable\n let b:statusline_trailing_space_warning = ''\n return b:statusline_trailing_space_warning\n endif\n\n if search('\\s\\+$', 'nw') != 0\n let b:statusline_trailing_space_warning = '[\\s]'\n else\n let b:statusline_trailing_space_warning = ''\n endif\n endif\n return b:statusline_trailing_space_warning\nendfunction\n\n\n\"return the syntax highlight group under the cursor ''\nfunction! StatuslineCurrentHighlight()\n let name = synIDattr(synID(line('.'),col('.'),1),'name')\n if name == ''\n return ''\n else\n return '[' . name . ']'\n endif\nendfunction\n\n\"recalculate the tab warning flag when idle and after writing\nautocmd cursorhold,bufwritepost * unlet! b:statusline_tab_warning\n\n\"return '[&amp;et]' if &amp;et is set wrong\n\"return '[mixed-indenting]' if spaces and tabs are used to indent\n\"return an empty string if everything is fine\nfunction! StatuslineTabWarning()\n if !exists(\"b:statusline_tab_warning\")\n let b:statusline_tab_warning = ''\n\n if !&amp;modifiable\n return b:statusline_tab_warning\n endif\n\n let tabs = search('^\\t', 'nw') != 0\n\n \"find spaces that arent used as alignment in the first indent column\n let spaces = search('^ \\{' . &amp;ts . ',}[^\\t]', 'nw') != 0\n\n if tabs &amp;&amp; spaces\n let b:statusline_tab_warning = '[mixed-indenting]'\n elseif (spaces &amp;&amp; !&amp;et) || (tabs &amp;&amp; &amp;et)\n let b:statusline_tab_warning = '[&amp;et]'\n endif\n endif\n return b:statusline_tab_warning\nendfunction\n\n\"recalculate the long line warning when idle and after saving\nautocmd cursorhold,bufwritepost * unlet! b:statusline_long_line_warning\n\n\"return a warning for \"long lines\" where \"long\" is either &amp;textwidth or 80 (if\n\"no &amp;textwidth is set)\n\"\n\"return '' if no long lines\n\"return '[#x,my,$z] if long lines are found, were x is the number of long\n\"lines, y is the median length of the long lines and z is the length of the\n\"longest line\nfunction! StatuslineLongLineWarning()\n if !exists(\"b:statusline_long_line_warning\")\n\n if !&amp;modifiable\n let b:statusline_long_line_warning = ''\n return b:statusline_long_line_warning\n endif\n\n let long_line_lens = s:LongLines()\n\n if len(long_line_lens) &gt; 0\n let b:statusline_long_line_warning = \"[\" .\n \\ '#' . len(long_line_lens) . \",\" .\n \\ 'm' . s:Median(long_line_lens) . \",\" .\n \\ '$' . max(long_line_lens) . \"]\"\n else\n let b:statusline_long_line_warning = \"\"\n endif\n endif\n return b:statusline_long_line_warning\nendfunction\n\n\"return a list containing the lengths of the long lines in this buffer\nfunction! s:LongLines()\n let threshold = (&amp;tw ? &amp;tw : 80)\n let spaces = repeat(\" \", &amp;ts)\n\n let long_line_lens = []\n\n let i = 1\n while i &lt;= line(\"$\")\n let len = strlen(substitute(getline(i), '\\t', spaces, 'g'))\n if len &gt; threshold\n call add(long_line_lens, len)\n endif\n let i += 1\n endwhile\n\n return long_line_lens\nendfunction\n\n\"find the median of the given array of numbers\nfunction! s:Median(nums)\n let nums = sort(a:nums)\n let l = len(nums)\n\n if l % 2 == 1\n let i = (l-1) / 2\n return nums[i]\n else\n return (nums[l/2] + nums[(l/2)-1]) / 2\n endif\nendfunction\n\n\n\"statusline setup\nset statusline=%f \"tail of the filename\n\n\"display a warning if fileformat isnt unix\nset statusline+=%#warningmsg#\nset statusline+=%{&amp;ff!='unix'?'['.&amp;ff.']':''}\nset statusline+=%*\n\n\"display a warning if file encoding isnt utf-8\nset statusline+=%#warningmsg#\nset statusline+=%{(&amp;fenc!='utf-8'&amp;&amp;&amp;fenc!='')?'['.&amp;fenc.']':''}\nset statusline+=%*\n\nset statusline+=%h \"help file flag\nset statusline+=%y \"filetype\nset statusline+=%r \"read only flag\nset statusline+=%m \"modified flag\n\n\"display a warning if &amp;et is wrong, or we have mixed-indenting\nset statusline+=%#error#\nset statusline+=%{StatuslineTabWarning()}\nset statusline+=%*\n\nset statusline+=%{StatuslineTrailingSpaceWarning()}\n\nset statusline+=%{StatuslineLongLineWarning()}\n\nset statusline+=%#warningmsg#\nset statusline+=%{SyntasticStatuslineFlag()}\nset statusline+=%*\n\n\"display a warning if &amp;paste is set\nset statusline+=%#error#\nset statusline+=%{&amp;paste?'[paste]':''}\nset statusline+=%*\n\nset statusline+=%= \"left/right separator\n\nfunction! SlSpace()\n if exists(\"*GetSpaceMovement\")\n return \"[\" . GetSpaceMovement() . \"]\"\n else\n return \"\"\n endif\nendfunc\nset statusline+=%{SlSpace()}\n\nset statusline+=%{StatuslineCurrentHighlight()}\\ \\ \"current highlight\nset statusline+=%c, \"cursor column\nset statusline+=%l/%L \"cursor line/total lines\nset statusline+=\\ %P \"percent through file\nset laststatus=2\n</code></pre>\n\n<p>Amongst other things, it informs on the status line of the usual standard file information but\nalso includes additional things like warnings for :set paste, mixed indenting, trailing\nwhite space etc. Pretty useful if you're particularly anal about your\ncode formatting.</p>\n\n<p>Furthermore and as shown in the screenshot, combining it with\n<a href=\"http://github.com/scrooloose/syntastic/tree/master\" rel=\"nofollow noreferrer\">syntastic</a> allows any syntax errors to\nbe highlighted on it (assuming your language of choice has an associated syntax checker\nbundled.</p>\n" }, { "answer_id": 1219114, "author": "Tadeusz A. Kadłubowski", "author_id": 122460, "author_profile": "https://Stackoverflow.com/users/122460", "pm_score": 2, "selected": false, "text": "<p>My .vimrc includes (among other, more usefull things) the following line:</p>\n\n<pre><code>set statusline=%2*%n\\|%&lt;%*%-.40F%2*\\|\\ %2*%M\\ %3*%=%1*\\ %1*%2.6l%2*x%1*%1.9(%c%V%)%2*[%1*%P%2*]%1*%2B\n</code></pre>\n\n<p>I got bored while learning for my high school finals.</p>\n" }, { "answer_id": 1296038, "author": "William Pursell", "author_id": 140750, "author_profile": "https://Stackoverflow.com/users/140750", "pm_score": 4, "selected": false, "text": "<p>Sometimes the simplest things are the most valuable. The 2 lines in my .vimrc that are totally indispensable:</p>\n\n<pre>\nnore ; :\nnore , ;\n</pre>\n" }, { "answer_id": 1330572, "author": "Mosh", "author_id": 161609, "author_profile": "https://Stackoverflow.com/users/161609", "pm_score": 0, "selected": false, "text": "<p>Just saw this now:</p>\n\n<pre><code>:nnoremap &lt;esc&gt; :noh&lt;return&gt;&lt;esc&gt;\n</code></pre>\n\n<p>I found it in <a href=\"http://www.viemu.com/blog/2009/06/16/a-vim-and-viemu-mapping-you-really-cant-miss-never-type-noh-again/\" rel=\"nofollow noreferrer\">ViEmu Blog</a> and I really dig this. A short explanation - It makes Esc turn off search highlight in normal mode.</p>\n" }, { "answer_id": 1330577, "author": "chaos", "author_id": 47529, "author_profile": "https://Stackoverflow.com/users/47529", "pm_score": 0, "selected": false, "text": "<pre><code>set tabstop=4\nset shiftwidth=4\nset cindent\nset noautoindent\nset noexpandtab\nset nocompatible\nset cino=:0(4u0\nset backspace=indent,start\nset term=ansi\nlet lpc_syntax_for_c=1\nsyntax enable\n\nautocmd FileType c set cin noai nosi\nautocmd FileType lpc set cin noai nosi\nautocmd FileType css set nocin ai noet\nautocmd FileType js set nocin ai noet\nautocmd FileType php set nocin ai noet\n\nfunction! DeleteFile(...)\n if(exists('a:1'))\n let theFile=a:1\n elseif ( &amp;ft == 'help' )\n echohl Error\n echo \"Cannot delete a help buffer!\"\n echohl None\n return -1\n else\n let theFile=expand('%:p')\n endif\n let delStatus=delete(theFile)\n if(delStatus == 0)\n echo \"Deleted \" . theFile\n else\n echohl WarningMsg\n echo \"Failed to delete \" . theFile\n echohl None\n endif\n return delStatus\nendfunction\n\"delete the current file\ncom! Rm call DeleteFile()\n\"delete the file and quit the buffer (quits vim if this was the last file)\ncom! RM call DeleteFile() &lt;Bar&gt; q!\n</code></pre>\n" }, { "answer_id": 1606045, "author": "Michael Foukarakis", "author_id": 149530, "author_profile": "https://Stackoverflow.com/users/149530", "pm_score": 0, "selected": false, "text": "<p>The results of years of my meddling with vim are all <a href=\"http://pastebin.com/f82bd697\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 1606206, "author": "DaedalusFall", "author_id": 74013, "author_profile": "https://Stackoverflow.com/users/74013", "pm_score": 0, "selected": false, "text": "<p>Useful stuff for C/C++ and svn usage (could be easily modified for git/hg/whatever).\nI set them to my F-keys.</p>\n\n<p>Not C#, but useful nonetheless.</p>\n\n<pre><code>function! SwapFilesKeep()\n \" Open a new window next to the current one with the matching .cpp/.h pair\"\n let command = \"echo \" . bufname(\"%\") . \"|sed s,\\h$,\\H,|sed s,cpp,h,|sed s,H$,cpp,\"\n let newfilename = system(command)\n silent execute(\"vs \" . newfilename)\nendfunction\n\nfunction! SwapFiles()\n \" swap between .cpp and .h \"\n let command = \"echo \" . bufname(\"%\") . \"|sed s,\\h$,\\H,|sed s,cpp,h,|sed s,H$,cpp,\"\n let newfilename = system(command)\n silent execute(\"e \" . newfilename)\nendfunction\n\nfunction! SvnDiffAll()\n let tempfile = system(\"tempfile\")\n silent execute \":!svn diff .&gt;\" . tempfile\n execute \":sf \".tempfile\n return\nendfunction\n\nfunction! SvnLog()\n let fn = expand('%')\n let tempfile = system(\"tempfile\")\n silent execute \":!svn log -v \" . fn . \"&gt;\" . tempfile\n execute \":sf \".tempfile\n return\nendfunction\n\nfunction! SvnStatus()\n let tempfile = system(\"tempfile\")\n silent execute \":!svn status .&gt;\" . tempfile\n execute \":sf \".tempfile\n return\nendfunction\n\nfunction! SvnDiff()\n \" diff with BASE \"\n let dir = expand('%:p:h')\n let fn = expand('%')\n let fn = substitute(fn,\".*\\\\\",\"\",\"\")\n let fn = substitute(fn,\".*/\",\"\",\"\")\n silent execute \":vert diffsplit \" . dir . \"/.svn/text-base/\" . fn . \".svn-base\"\n silent execute \":set ft=cpp\"\n unlet fn dir\n return\nendfunction\n</code></pre>\n" }, { "answer_id": 1636961, "author": "Maxim Sloyko", "author_id": 141906, "author_profile": "https://Stackoverflow.com/users/141906", "pm_score": 3, "selected": false, "text": "<pre><code>syntax on\nset cindent\nset ts=4\nset sw=4\nset backspace=2\nset laststatus=2\nset nohlsearch\nset modeline\nset modelines=3\nset ai\nmap Q gq\n\nset vb t_vb=\n\nset nowrap\nset ss=5\nset is\nset scs\nset ru\n\nmap &lt;F2&gt; &lt;Esc&gt;:w&lt;CR&gt;\nmap! &lt;F2&gt; &lt;Esc&gt;:w&lt;CR&gt;\n\nmap &lt;F10&gt; &lt;Esc&gt;:qa&lt;CR&gt;\nmap! &lt;F10&gt; &lt;Esc&gt;:qa&lt;CR&gt;\n\nmap &lt;F9&gt; &lt;Esc&gt;:wqa&lt;CR&gt;\nmap! &lt;F9&gt; &lt;Esc&gt;:wqa&lt;CR&gt;\n\ninoremap &lt;s-up&gt; &lt;Esc&gt;&lt;c-w&gt;W&lt;Ins&gt;\ninoremap &lt;s-down&gt; &lt;Esc&gt;&lt;c-w&gt;w&lt;Ins&gt;\n\nnnoremap &lt;s-up&gt; &lt;c-w&gt;W\nnnoremap &lt;s-down&gt; &lt;c-w&gt;w\n\n\" Fancy middle-line &lt;CR&gt;\ninoremap &lt;C-CR&gt; &lt;Esc&gt;o\nnnoremap &lt;C-CR&gt; o\n\n\" This is the way I like my quotation marks and various braces\ninoremap '' ''&lt;Left&gt;\ninoremap \"\" \"\"&lt;Left&gt;\ninoremap () ()&lt;Left&gt;\ninoremap &lt;&gt; &lt;&gt;&lt;Left&gt;\ninoremap {} {}&lt;Left&gt;\ninoremap [] []&lt;Left&gt;\ninoremap () ()&lt;Left&gt;\n\n\" Quickly set comma or semicolon at the end of the string\ninoremap ,, &lt;End&gt;,\ninoremap ;; &lt;End&gt;;\nau FileType python inoremap :: &lt;End&gt;:\n\n\nau FileType perl,python set foldlevel=0\nau FileType perl,python set foldcolumn=4\nau FileType perl,python set fen\nau FileType perl set fdm=syntax\nau FileType python set fdm=indent\nau FileType perl,python set fdn=4\nau FileType perl,python set fml=10\nau FileType perl,python set fdo=block,hor,mark,percent,quickfix,search,tag,undo,search\n\nau FileType perl,python abbr sefl self\nau FileType perl abbr sjoft shift\nau FileType perl abbr DUmper Dumper\n\nfunction! ToggleNumberRow()\n if !exists(\"g:NumberRow\") || 0 == g:NumberRow\n let g:NumberRow = 1\n call ReverseNumberRow()\n else\n let g:NumberRow = 0\n call NormalizeNumberRow()\n endif\nendfunction\n\n\n\" Reverse the number row characters\nfunction! ReverseNumberRow()\n \" map each number to its shift-key character\n inoremap 1 !\n inoremap 2 @\n inoremap 3 #\n inoremap 4 $\n inoremap 5 %\n inoremap 6 ^\n inoremap 7 &amp;\n inoremap 8 *\n inoremap 9 (\n inoremap 0 )\n inoremap - _\n inoremap 90 ()&lt;Left&gt;\n \" and then the opposite\n inoremap ! 1\n inoremap @ 2\n inoremap # 3\n inoremap $ 4\n inoremap % 5\n inoremap ^ 6\n inoremap &amp; 7\n inoremap * 8\n inoremap ( 9\n inoremap ) 0\n inoremap _ -\nendfunction\n\n\" DO the opposite to ReverseNumberRow -- give everything back\nfunction! NormalizeNumberRow()\n iunmap 1\n iunmap 2\n iunmap 3\n iunmap 4\n iunmap 5\n iunmap 6\n iunmap 7\n iunmap 8\n iunmap 9\n iunmap 0\n iunmap -\n \"------\n iunmap !\n iunmap @\n iunmap #\n iunmap $\n iunmap %\n iunmap ^\n iunmap &amp;\n iunmap *\n iunmap (\n iunmap )\n iunmap _\n inoremap () ()&lt;Left&gt;\nendfunction\n\n\"call ToggleNumberRow()\nnnoremap &lt;M-n&gt; :call ToggleNumberRow()&lt;CR&gt;\n\n\" Add use &lt;CWORD&gt; at the top of the file\nfunction! UseWord(word)\n let spec_cases = {'Dumper': 'Data::Dumper'}\n let my_word = a:word\n if has_key(spec_cases, my_word)\n let my_word = spec_cases[my_word]\n endif\n\n let was_used = search(\"^use.*\" . my_word, \"bw\")\n\n if was_used &gt; 0\n echo \"Used already\"\n return 0\n endif\n\n let last_use = search(\"^use\", \"bW\")\n if 0 == last_use\n last_use = search(\"^package\", \"bW\")\n if 0 == last_use\n last_use = 1\n endif\n endif\n\n let use_string = \"use \" . my_word . \";\"\n let res = append(last_use, use_string)\n return 1\nendfunction\n\nfunction! UseCWord()\n let cline = line(\".\")\n let ccol = col(\".\")\n let ch = UseWord(expand(\"&lt;cword&gt;\"))\n normal mu\n call cursor(cline + ch, ccol)\n\nendfunction\n\nfunction! GetWords(pattern)\n let cline = line(\".\")\n let ccol = col(\".\")\n call cursor(1,1)\n\n let temp_dict = {}\n let cpos = searchpos(a:pattern)\n while cpos[0] != 0\n let temp_dict[expand(\"&lt;cword&gt;\")] = 1\n let cpos = searchpos(a:pattern, 'W')\n endwhile\n\n call cursor(cline, ccol)\n return keys(temp_dict)\nendfunction\n\n\" Append the list of words, that match the pattern after cursor\nfunction! AppendWordsLike(pattern)\n let word_list = sort(GetWords(a:pattern))\n call append(line(\".\"), word_list)\nendfunction\n\n\nnnoremap &lt;F7&gt; :call UseCWord()&lt;CR&gt;\n\n\" Useful to mark some code lines as debug statements\nfunction! MarkDebug()\n let cline = line(\".\")\n let ctext = getline(cline)\n call setline(cline, ctext . \"##_DEBUG_\")\nendfunction\n\n\" Easily remove debug statements\nfunction! RemoveDebug()\n %g/#_DEBUG_/d\nendfunction\n\nau FileType perl,python inoremap &lt;M-d&gt; &lt;Esc&gt;:call MarkDebug()&lt;CR&gt;&lt;Ins&gt;\nau FileType perl,python inoremap &lt;F6&gt; &lt;Esc&gt;:call RemoveDebug()&lt;CR&gt;&lt;Ins&gt;\nau FileType perl,python nnoremap &lt;F6&gt; :call RemoveDebug()&lt;CR&gt;\n\n\" end Perl settings\n\nnnoremap &lt;silent&gt; &lt;F8&gt; :TlistToggle&lt;CR&gt;\ninoremap &lt;silent&gt; &lt;F8&gt; &lt;Esc&gt;:TlistToggle&lt;CR&gt;&lt;Esc&gt;\n\nfunction! AlwaysCD()\n if bufname(\"\") !~ \"^scp://\" &amp;&amp; bufname(\"\") !~ \"^sftp://\" &amp;&amp; bufname(\"\") !~ \"^ftp://\"\n lcd %:p:h\n endif\nendfunction\nautocmd BufEnter * call AlwaysCD()\n\nfunction! DeleteRedundantSpaces()\n let cline = line(\".\")\n let ccol = col(\".\")\n silent! %s/\\s\\+$//g\n call cursor(cline, ccol)\nendfunction\nau BufWrite * call DeleteRedundantSpaces()\n\nset nobackup\nset nowritebackup\nset cul\n\ncolorscheme evening\n\nautocmd FileType python set formatoptions=wcrq2l\nautocmd FileType python set inc=\"^\\s*from\"\nautocmd FileType python so /usr/share/vim/vim72/indent/python.vim\n\nautocmd FileType c set si\nautocmd FileType mail set noai\nautocmd FileType mail set ts=3\nautocmd FileType mail set tw=78\nautocmd FileType mail set shiftwidth=3\nautocmd FileType mail set expandtab\nautocmd FileType xslt set ts=4\nautocmd FileType xslt set shiftwidth=4\nautocmd FileType txt set ts=3\nautocmd FileType txt set tw=78\nautocmd FileType txt set expandtab\n\n\" Move cursor together with the screen\nnoremap &lt;c-j&gt; j&lt;c-e&gt;\nnoremap &lt;c-k&gt; k&lt;c-y&gt;\n\n\" Better Marks\nnnoremap ' `\n</code></pre>\n" }, { "answer_id": 1636974, "author": "subbul", "author_id": 164780, "author_profile": "https://Stackoverflow.com/users/164780", "pm_score": 0, "selected": false, "text": "<p><strong><em>:map + v%zf</em></strong> # hit \"+\" to fold a function/loop anything within a paranthesis.</p>\n\n<p><strong><em>:set expandtab</em></strong> # tab will be expanded as spaces as per the setting of ts (tabspace)</p>\n" }, { "answer_id": 1637003, "author": "Lucas Gabriel Sánchez", "author_id": 20601, "author_profile": "https://Stackoverflow.com/users/20601", "pm_score": 0, "selected": false, "text": "<pre><code>set ai \nset si \nset sm \nset sta \nset ts=3 \nset sw=3 \nset co=130 \nset lines=50 \nset nowrap \nset ruler \nset showcmd \nset showmode \nset showmatch \nset incsearch \nset hlsearch \nset gfn=Consolas:h11\nset guioptions-=T\nset clipboard=unnamed\nset expandtab\nset nobackup\n\nsyntax on \ncolors torte\n</code></pre>\n" }, { "answer_id": 1637004, "author": "hasen", "author_id": 35364, "author_profile": "https://Stackoverflow.com/users/35364", "pm_score": 2, "selected": false, "text": "<pre><code>set tabstop=4 softtabstop=4 shiftwidth=4 expandtab autoindent cindent \nset encoding=utf-8 fileencoding=utf-8\nset nobackup nowritebackup noswapfile autoread\nset number\nset hlsearch incsearch ignorecase smartcase\n\nif has(\"gui_running\")\n set lines=35 columns=140\n colorscheme ir_black\nelse\n colorscheme darkblue\nendif\n\n\" bash like auto-completion\nset wildmenu\nset wildmode=list:longest\n\ninoremap &lt;C-j&gt; &lt;Esc&gt;\n\n\" for lusty explorer\nnoremap glr \\lr\nnoremap glf \\lf\nnoremap glb \\lb\n\n\" use ctrl-h/j/k/l to switch between splits\nmap &lt;c-j&gt; &lt;c-w&gt;j\nmap &lt;c-k&gt; &lt;c-w&gt;k\nmap &lt;c-l&gt; &lt;c-w&gt;l\nmap &lt;c-h&gt; &lt;c-w&gt;h\n\n\" Nerd tree stuff\nlet NERDTreeIgnore = ['\\.pyc$', '\\.pyo$']\nnoremap gn :NERDTree&lt;Cr&gt;\n\n\" cd to the current file's directory\nnoremap gc :lcd %:h&lt;Cr&gt;\n</code></pre>\n" }, { "answer_id": 1637544, "author": "Benj", "author_id": 193128, "author_profile": "https://Stackoverflow.com/users/193128", "pm_score": 0, "selected": false, "text": "<p>I tend to split my .vimrc into different sections so that I can turn different sections on and off on all the different machines I run on, i.e. some bits on windows some on linux etc:</p>\n\n<pre><code>\n\"*****************************************\n\"* SECTION 1 - THINGS JUST FOR GVIM *\n\"*****************************************\nif v:version >= 700\n\n \"Note: Other plugin files\n source ~/.vim/ben_init/bens_pscripts.vim\n \"source ~/.vim/ben_init/stim_projects.vim\n \"source ~/.vim/ben_init/temp_commands.vim\n \"source ~/.vim/ben_init/wwatch.vim\n\n \"Extract sections of code as a function (works in C, C++, Perl, Java)\n source ~/.vim/ben_init/functify.vim\n\n \"Settings that relate to the look/feel of vim in the GUI\n source ~/.vim/ben_init/gui_settings.vim\n\n \"General VIM settings\n source ~/.vim/ben_init/general_settings.vim\n\n \"Settings for programming\n source ~/.vim/ben_init/c_programming.vim\n\n \"Settings for completion\n source ~/.vim/ben_init/completion.vim\n\n \"My own templating system\n source ~/.vim/ben_init/templates.vim\n\n \"Abbreviations and interesting key mappings\n source ~/.vim/ben_init/abbrev.vim\n\n \"Plugin configuration\n source ~/.vim/ben_init/plugin_config.vim\n\n \"Wiki configuration\n source ~/.vim/ben_init/wiki_config.vim\n\n \"Key mappings\n source ~/.vim/ben_init/key_mappings.vim\n\n \"Auto commands\n source ~/.vim/ben_init/autocmds.vim\n\n \"Handy Functions written by other people\n source ~/.vim/ben_init/handy_functions.vim\n\n \"My own omni_completions\n source ~/.vim/ben_init/bens_omni.vim\n\nendif\n</code></pre>\n" }, { "answer_id": 1639333, "author": "Mosh", "author_id": 161609, "author_profile": "https://Stackoverflow.com/users/161609", "pm_score": 1, "selected": false, "text": "<p>This is my humble .vimrc.\nIt is a work in progress (As it should always be), so forgive the messy layout and the commented out lines.</p>\n\n<pre><code>\" =====Key mapping\n\" Insert empty line.\nnmap &lt;A-o&gt; o&lt;ESC&gt;k\nnmap &lt;A-O&gt; O&lt;ESC&gt;j\n\" Insert one character.\nnmap &lt;A-i&gt; i &lt;Esc&gt;r\nnmap &lt;A-a&gt; a &lt;Esc&gt;r\n\" Move on display lines in normal and visual mode.\nnnoremap j gj\nnnoremap k gk\nvnoremap j gj\nvnoremap k gk\n\" Do not lose * register when pasting on visual selection.\nvmap p \"zxP\n\" Clear highlight search results with &lt;esc&gt;\nnnoremap &lt;esc&gt; :noh&lt;return&gt;&lt;esc&gt;\n\" Center screen on next/previous selection.\nmap n nzz\nmap N Nzz\n\" &lt;Esc&gt; with jj.\ninoremap jj &lt;Esc&gt;\n\" Switch jump to mark.\nnnoremap ' `\nnnoremap ` '\n\" Last and next jump should center too.\nnnoremap &lt;C-o&gt; &lt;C-o&gt;zz\nnnoremap &lt;C-i&gt; &lt;C-i&gt;zz\n\" Paste on new line.\nnnoremap &lt;A-p&gt; :pu&lt;CR&gt;\nnnoremap &lt;A-S-p&gt; :pu!&lt;CR&gt;\n\" Quick paste on insert mode.\ninoremap &lt;C-F&gt; &lt;C-R&gt;\"\n\" Indent cursor on empty line.\nnnoremap &lt;A-c&gt; ddO\nnnoremap &lt;leader&gt;c ddO\n\" Save and quit quickly.\nnnoremap &lt;leader&gt;s :w&lt;CR&gt;\nnnoremap &lt;leader&gt;q :q&lt;CR&gt;\nnnoremap &lt;leader&gt;Q :q!&lt;CR&gt;\n\" The way it should have been.\nnoremap Y y$\n\" Moving in buffers.\nnnoremap &lt;C-S-tab&gt; :bprev&lt;CR&gt;\nnnoremap &lt;C-tab&gt; :bnext&lt;CR&gt;\n\" Using bufkill plugin.\nnnoremap &lt;leader&gt;b :BD&lt;CR&gt;\nnnoremap &lt;leader&gt;B :BD!&lt;CR&gt;\nnnoremap &lt;leader&gt;ZZ :w&lt;CR&gt;:BD&lt;CR&gt;\n\" Moving and resizing in windows.\nnnoremap + &lt;C-W&gt;+\nnnoremap _ &lt;C-W&gt;-\nnnoremap &lt;C-h&gt; &lt;C-w&gt;h\nnnoremap &lt;C-j&gt; &lt;C-w&gt;j\nnnoremap &lt;C-k&gt; &lt;C-w&gt;k\nnnoremap &lt;C-l&gt; &lt;C-w&gt;l\nnnoremap &lt;leader&gt;w &lt;C-w&gt;c\n\" Moving in tabs\nnoremap &lt;c-right&gt; gt\nnoremap &lt;c-left&gt; gT\nnnoremap &lt;leader&gt;t :tabc&lt;CR&gt;\n\" Moving around in insert mode.\ninoremap &lt;A-j&gt; &lt;C-O&gt;gj\ninoremap &lt;A-k&gt; &lt;C-O&gt;gk\ninoremap &lt;A-h&gt; &lt;Left&gt;\ninoremap &lt;A-l&gt; &lt;Right&gt;\n\n\" =====General options\n\" I copy a lot from external apps.\nset clipboard=unnamed\n\" Don't let swap and backup files fill my working directory.\nset backupdir=c:\\\\temp,. \" Backup files\nset directory=c:\\\\temp,. \" Swap files\nset nocompatible\nset showmatch\nset hidden\nset showcmd \" This shows what you are typing as a command.\nset scrolloff=3\n\" Allow backspacing over everything in insert mode\nset backspace=indent,eol,start\n\" Syntax highlight\nsyntax on \nfiletype plugin on\nfiletype indent on\n\n\" =====Searching\nset ignorecase\nset hlsearch\nset incsearch\n\n\" =====Indentation settings\n\" autoindent just copies the indentation from the line above.\n\"set autoindent\n\" smartindent automatically inserts one extra level of indentation in some cases.\nset smartindent\n\" cindent is more customizable, but also more strict.\n\"set cindent\nset tabstop=4\nset shiftwidth=4\n\n\" =====GUI options.\n\" Just Vim without any gui.\nset guioptions-=m\nset guioptions-=T\nset lines=40\nset columns=150\n\" Consolas is better, but Courier new is everywhere.\n\"set guifont=Courier\\ New:h9\nset guifont=Consolas:h9\n\" Cool status line.\nset statusline=%&lt;%1*===\\ %5*%f%1*%(\\ ===\\ %4*%h%1*%)%(\\ ===\\ %4*%m%1*%)%(\\ ===\\ %4*%r%1*%)\\ ===%====\\ %2*%b(0x%B)%1*\\ ===\\ %3*%l,%c%V%1*\\ ===\\ %5*%P%1*\\ ===%0* laststatus=2\ncolorscheme mildblack\nlet g:sienna_style = 'dark'\n\n\" =====Plugins\n\n\" ===BufPos\nnnoremap &lt;leader&gt;ob :call BufWipeout()&lt;CR&gt;\n\" ===SuperTab\n\" Map SuperTab to space key.\nlet g:SuperTabMappingForward = '&lt;c-space&gt;'\nlet g:SuperTabMappingBackward = '&lt;s-c-space&gt;'\nlet g:SuperTabDefaultCompletionType = 'context'\n\" ===miniBufExpl\n\" let g:miniBufExplMapWindowNavVim = 1\n\" let g:miniBufExplMapCTabSwitchBufs = 1\n\" let g:miniBufExplorerMoreThanOne = 0\n\" ===AutoClose\n\" let g:AutoClosePairs = {'(': ')', '{': '}', '[': ']', '\"': '\"', \"'\": \"'\"}\n\" ===NERDTree\nnnoremap &lt;leader&gt;n :NERDTreeToggle&lt;CR&gt;\n\" ===delimitMate\nlet delimitMate = \"(:),[:],{:}\"\n</code></pre>\n" }, { "answer_id": 1639391, "author": "guns", "author_id": 76288, "author_profile": "https://Stackoverflow.com/users/76288", "pm_score": 3, "selected": false, "text": "<p>My heavily commented vimrc, with readline-esque (emacs) keybindings:</p>\n\n<pre><code>if version &gt;= 700\n\n\"------ Meta ------\"\n\n\" clear all autocommands! (this comment must be on its own line)\nautocmd!\n\nset nocompatible \" break away from old vi compatibility\nset fileformats=unix,dos,mac \" support all three newline formats\nset viminfo= \" don't use or save viminfo files\n\n\"------ Console UI &amp; Text display ------\"\n\nset cmdheight=1 \" explicitly set the height of the command line\nset showcmd \" Show (partial) command in status line.\nset number \" yay line numbers\nset ruler \" show current position at bottom\nset noerrorbells \" don't whine\nset visualbell t_vb= \" and don't make faces\nset lazyredraw \" don't redraw while in macros\nset scrolloff=5 \" keep at least 5 lines around the cursor\nset wrap \" soft wrap long lines\nset list \" show invisible characters\nset listchars=tab:&gt;·,trail:· \" but only show tabs and trailing whitespace\nset report=0 \" report back on all changes\nset shortmess=atI \" shorten messages and don't show intro\nset wildmenu \" turn on wild menu :e &lt;Tab&gt;\nset wildmode=list:longest \" set wildmenu to list choice\nif has('syntax')\n syntax on\n \" Remember that rxvt-unicode has 88 colors by default; enable this only if\n \" you are using the 256-color patch\n if &amp;term == 'rxvt-unicode'\n set t_Co=256\n endif\n\n if &amp;t_Co == 256\n colorscheme xoria256\n else\n colorscheme peachpuff\n endif\nendif\n\n\"------ Text editing and searching behavior ------\"\n\nset nohlsearch \" turn off highlighting for searched expressions\nset incsearch \" highlight as we search however\nset matchtime=5 \" blink matching chars for .x seconds\nset mouse=a \" try to use a mouse in the console (wimp!)\nset ignorecase \" set case insensitivity\nset smartcase \" unless there's a capital letter\nset completeopt=menu,longest,preview \" more autocomplete &lt;Ctrl&gt;-P options\nset nostartofline \" leave my cursor position alone!\nset backspace=2 \" equiv to :set backspace=indent,eol,start\nset textwidth=80 \" we like 80 columns\nset showmatch \" show matching brackets\nset formatoptions=tcrql \" t - autowrap to textwidth\n \" c - autowrap comments to textwidth\n \" r - autoinsert comment leader with &lt;Enter&gt;\n \" q - allow formatting of comments with :gq\n \" l - don't format already long lines\n\n\"------ Indents and tabs ------\"\n\nset autoindent \" set the cursor at same indent as line above\nset smartindent \" try to be smart about indenting (C-style)\nset expandtab \" expand &lt;Tab&gt;s with spaces; death to tabs!\nset shiftwidth=4 \" spaces for each step of (auto)indent\nset softtabstop=4 \" set virtual tab stop (compat for 8-wide tabs)\nset tabstop=8 \" for proper display of files with tabs\nset shiftround \" always round indents to multiple of shiftwidth\nset copyindent \" use existing indents for new indents\nset preserveindent \" save as much indent structure as possible\nfiletype plugin indent on \" load filetype plugins and indent settings\n\n\"------ Key bindings ------\"\n\n\" Remap broken meta-keys that send ^[\nfor n in range(97,122) \" ASCII a-z\n let c = nr2char(n)\n exec \"set &lt;M-\". c .\"&gt;=\\e\". c\n exec \"map \\e\". c .\" &lt;M-\". c .\"&gt;\"\n exec \"map! \\e\". c .\" &lt;M-\". c .\"&gt;\"\nendfor\n\n\"\"\" Emacs keybindings\n\" first move the window command because we'll be taking it over\nnoremap &lt;C-x&gt; &lt;C-w&gt;\n\" Movement left/right\nnoremap! &lt;C-b&gt; &lt;Left&gt;\nnoremap! &lt;C-f&gt; &lt;Right&gt;\n\" word left/right\nnoremap &lt;M-b&gt; b\nnoremap! &lt;M-b&gt; &lt;C-o&gt;b\nnoremap &lt;M-f&gt; w\nnoremap! &lt;M-f&gt; &lt;C-o&gt;w\n\" line start/end\nnoremap &lt;C-a&gt; ^\nnoremap! &lt;C-a&gt; &lt;Esc&gt;I\nnoremap &lt;C-e&gt; $\nnoremap! &lt;C-e&gt; &lt;Esc&gt;A\n\" Rubout word / line and enter insert mode\nnoremap &lt;C-w&gt; i&lt;C-w&gt;\nnoremap &lt;C-u&gt; i&lt;C-u&gt;\n\" Forward delete char / word / line and enter insert mode\nnoremap! &lt;C-d&gt; &lt;C-o&gt;x\nnoremap &lt;M-d&gt; dw\nnoremap! &lt;M-d&gt; &lt;C-o&gt;dw\nnoremap &lt;C-k&gt; Da\nnoremap! &lt;C-k&gt; &lt;C-o&gt;D\n\" Undo / Redo and enter normal mode\nnoremap &lt;C-_&gt; u\nnoremap! &lt;C-_&gt; &lt;C-o&gt;u&lt;Esc&gt;&lt;Right&gt;\nnoremap! &lt;C-r&gt; &lt;C-o&gt;&lt;C-r&gt;&lt;Esc&gt;\n\n\" Remap &lt;C-space&gt; to word completion\nnoremap! &lt;Nul&gt; &lt;C-n&gt;\n\n\" OS X paste (pretty poor implementation)\nif has('mac')\n noremap √ :r!pbpaste&lt;CR&gt;\n noremap! √ &lt;Esc&gt;√\nendif\n\n\"\"\" screen.vim REPL: http://github.com/ervandew/vimfiles\n\" send paragraph to parallel process\nvmap &lt;C-c&gt;&lt;C-c&gt; :ScreenSend&lt;CR&gt;\nnmap &lt;C-c&gt;&lt;C-c&gt; mCvip&lt;C-c&gt;&lt;C-c&gt;`C\nimap &lt;C-c&gt;&lt;C-c&gt; &lt;Esc&gt;&lt;C-c&gt;&lt;C-c&gt;&lt;Right&gt;\n\" set shell region height\nlet g:ScreenShellHeight = 12\n\n\n\"------ Filetypes ------\"\n\n\" Vimscript\nautocmd FileType vim setlocal expandtab shiftwidth=4 tabstop=8 softtabstop=4\n\n\" Shell\nautocmd FileType sh setlocal expandtab shiftwidth=4 tabstop=8 softtabstop=4\n\n\" Lisp\nautocmd Filetype lisp,scheme setlocal equalprg=~/.vim/bin/lispindent.lisp expandtab shiftwidth=2 tabstop=8 softtabstop=2\n\n\" Ruby\nautocmd FileType ruby setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2\n\n\" PHP\nautocmd FileType php setlocal expandtab shiftwidth=4 tabstop=4 softtabstop=4\n\n\" X?HTML &amp; XML\nautocmd FileType html,xhtml,xml setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2\n\n\" CSS\nautocmd FileType css setlocal expandtab shiftwidth=4 tabstop=4 softtabstop=4\n\n\" JavaScript\n\" autocmd BufRead,BufNewFile *.json setfiletype javascript\nautocmd FileType javascript setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2\nlet javascript_enable_domhtmlcss=1\n\n\"------ END VIM-500 ------\"\n\nendif \" version &gt;= 500\n</code></pre>\n" }, { "answer_id": 1639762, "author": "Jan Christoph", "author_id": 198414, "author_profile": "https://Stackoverflow.com/users/198414", "pm_score": 0, "selected": false, "text": "<p>In addition to my vimrc I have a bigger collection of plugins. Everything is stored in a git repository at <a href=\"http://github.com/jceb/vimrc\" rel=\"nofollow noreferrer\">http://github.com/jceb/vimrc</a>.</p>\n\n<pre><code>\" Author: Jan Christoph Ebersbach jceb AT e-jc DOT de\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\" ---------- Settings ----------\n\"\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n\" Prevent modelines in files from being evaluated (avoids a potential\n\" security problem wherein a malicious user could write a hazardous\n\" modeline into a file) (override default value of 5)\nset modeline\nset modelines=5\n\n\" ########## miscellaneous options ##########\nset nocompatible \" Use Vim defaults instead of 100% vi compatibility\nset whichwrap=&lt;,&gt; \" Cursor key move the cursor to the next/previous line if pressed at the end/beginning of a line\nset backspace=indent,eol,start \" more powerful backspacing\nset viminfo='20,\\\"50 \" read/write a .viminfo file, don't store more than\nset history=100 \" keep 50 lines of command line history\nset incsearch \" Incremental search\nset hidden \" hidden allows to have modified buffers in background\nset noswapfile \" turn off backups and files\nset nobackup \" Don't keep a backup file\nset magic \" special characters that can be used in search patterns\nset grepprg=grep\\ --exclude='*.svn-base'\\ -n\\ $*\\ /dev/null \" don't grep through svn-base files\n\" Try do use the ack program when available\nlet tmp = ''\nfor i in ['ack', 'ack-grep']\n let tmp = substitute (system ('which '.i), '\\n.*', '', '')\n if v:shell_error == 0\n exec \"set grepprg=\".tmp.\"\\\\ -a\\\\ -H\\\\ --nocolor\\\\ --nogroup\"\n break\n endif\nendfor\nunlet tmp\n\"set autowrite \" Automatically save before commands like :next and :make\n\" Suffixes that get lower priority when doing tab completion for filenames.\n\" These are files we are not likely to want to edit or read.\nset suffixes=.bak,~,.swp,.o,.info,.aux,.log,.dvi,.bbl,.blg,.brf,.cb,.ind,.idx,.ilg,.inx,.out,.toc,.pdf,.exe\n\"set autochdir \" move to the directory of the edited file\nset ssop-=options \" do not store global and local values in a session\nset ssop-=folds \" do not store folds\n\n\" ########## visual options ##########\nset wildmenu \" When 'wildmenu' is on, command-line completion operates in an enhanced mode.\nset wildcharm=&lt;C-Z&gt;\nset showmode \" If in Insert, Replace or Visual mode put a message on the last line.\nset guifont=monospace\\ 8 \" guifont + fontsize\nset guicursor=a:blinkon0 \" cursor-blinking off!!\nset ruler \" show the cursor position all the time\nset nowrap \" kein Zeilenumbruch\nset foldmethod=indent \" Standardfaltungsmethode\nset foldlevel=99 \" default fold level\nset winminheight=0 \" Minimal Windowheight\nset showcmd \" Show (partial) command in status line.\nset showmatch \" Show matching brackets.\nset matchtime=2 \" time to show the matching bracket\nset hlsearch \" highlight search\nset linebreak\nset lazyredraw \" no readraw when running macros\nset scrolloff=3 \" set X lines to the curors - when moving vertical..\nset laststatus=2 \" statusline is always visible\nset statusline=(%{bufnr('%')})\\ %t\\ \\ %r%m\\ #%{expand('#:t')}\\ (%{bufnr('#')})%=[%{&amp;fileformat}:%{&amp;fileencoding}:%{&amp;filetype}]\\ %l,%c\\ %P \" statusline\n\"set mouse=n \" mouse only in normal mode support in vim\n\"set foldcolumn=1 \" show folds\nset number \" draw linenumbers\nset nolist \" list nonprintable characters\nset sidescroll=0 \" scroll X columns to the side instead of centering the cursor on another screen\nset completeopt=menuone \" show the complete menu even if there is just one entry\nset listchars+=precedes:&lt;,extends:&gt; \" display the following nonprintable characters\nif $LANG =~ \".*\\.UTF-8$\" || $LANG =~ \".*utf8$\" || $LANG =~ \".*utf-8$\"\n set listchars+=tab:»·,trail:·\" display the following nonprintable characters\nendif\nset guioptions=aegitcm \" disabled menu in gui mode\n\"set guioptions=aegimrLtT\nset cpoptions=aABceFsq$ \" q: When joining multiple lines leave the cursor at the position where it would be when joining two lines.\n\" $: When making a change to one line, don't redisplay the line, but put a '$' at the end of the changed text.\n\" v: Backspaced characters remain visible on the screen in Insert mode.\n\ncolorscheme peaksea \" default color scheme\n\n\" default color scheme\n\" if &amp;term == '' || &amp;term == 'builtin_gui' || &amp;term == 'dumb'\nif has('gui_running')\n set background=light \" use colors that fit to a light background\nelse\n set background=light \" use colors that fit to a light background\n \"set background=dark \" use colors that fit to a dark background\nendif\n\nsyntax on \" syntax highlighting\n\n\" ########## text options ##########\nset smartindent \" always set smartindenting on\nset autoindent \" always set autoindenting on\nset backspace=2 \" Influences the working of &lt;BS&gt;, &lt;Del&gt;, CTRL-W and CTRL-U in Insert mode.\nset textwidth=0 \" Don't wrap words by default\nset shiftwidth=4 \" number of spaces to use for each step of indent\nset tabstop=4 \" number of spaces a tab counts for\nset noexpandtab \" insert spaces instead of tab\nset smarttab \" insert spaces only at the beginning of the line\nset ignorecase \" Do case insensitive matching\nset smartcase \" overwrite ignorecase if pattern contains uppercase characters\nset formatoptions=lcrqn \" no automatic linebreak\nset pastetoggle=&lt;F11&gt; \" put vim in pastemode - usefull for pasting in console-mode\nset fileformats=unix,dos,mac \" favorite fileformats\nset encoding=utf-8 \" set default-encoding to utf-8\nset iskeyword+=_,- \" these characters also belong to a word\nset matchpairs+=&lt;:&gt;\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\" ---------- Special Configuration ----------\n\"\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n\" ########## determine terminal encoding ##########\n\"if has(\"multi_byte\") &amp;&amp; &amp;term != 'builtin_gui'\n\" set termencoding=utf-8\n\"\n\" \" unfortunately the normal xterm supports only latin1\n\" if $TERM == \"xterm\" || $TERM == \"xterm-color\" || $TERM == \"screen\" || $TERM == \"linux\" || $TERM_PROGRAM == \"GLterm\"\n\" let propv = system(\"xprop -id $WINDOWID -f WM_LOCALE_NAME 8s ' $0' -notype WM_LOCALE_NAME\")\n\" if propv !~ \"WM_LOCALE_NAME .*UTF.*8\"\n\" set termencoding=latin1\n\" endif\n\" endif\n\" \" for the possibility of using a terminal to input and read chinese\n\" \" characters\n\" if $LANG == \"zh_CN.GB2312\"\n\" set termencoding=euc-cn\n\" endif\n\"endif\n\n\" Set paper size from /etc/papersize if available (Debian-specific)\nif filereadable('/etc/papersize')\n let s:papersize = matchstr(system('/bin/cat /etc/papersize'), '\\p*')\n if strlen(s:papersize)\n let &amp;printoptions = \"paper:\" . s:papersize\n endif\n unlet! s:papersize\nendif\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\" ---------- Autocommands ----------\n\"\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nfiletype plugin on \" automatically load filetypeplugins\nfiletype indent on \" indent according to the filetype\n\nif !exists(\"autocommands_loaded\")\n let autocommands_loaded = 1\n\n augroup templates\n \" read templates\n \" au BufNewFile ?akefile,*.mk TSkeletonSetup Makefile\n \" au BufNewFile *.tex TSkeletonSetup latex.tex\n \" au BufNewFile build*.xml TSkeletonSetup antbuild.xml\n \" au BufNewFile test*.py,*Test.py TSkeletonSetup pyunit.py\n \" au BufNewFile *.py TSkeletonSetup python.py\n augroup END\n\n augroup filetypesettings\n \" Do word completion automatically\n au FileType debchangelog setl expandtab\n au FileType asciidoc,mkd,txt,mail call DoFastWordComplete()\n au FileType tex,plaintex setlocal makeprg=pdflatex\\ \\\"%:p\\\"\n au FileType mkd setlocal autoindent\n au FileType java,c,cpp setlocal noexpandtab nosmarttab\n au FileType mail setlocal textwidth=70\n au FileType mail call FormatMail()\n au FileType mail setlocal formatoptions=tcrqan\n au FileType mail setlocal comments+=b:--\n au FileType txt setlocal formatoptions=tcrqn textwidth=72\n au FileType asciidoc,mkd,tex setlocal formatoptions=tcrq textwidth=72\n au FileType xml,docbk,xhtml,jsp setlocal formatoptions=tcrqn\n au FileType ruby setlocal shiftwidth=2\n\n au BufReadPost,BufNewFile * set formatoptions-=o \" o is really annoying\n au BufReadPost,BufNewFile * call ReadIncludePath()\n\n \" Special Makefilehandling\n au FileType automake,make setlocal list noexpandtab\n\n au FileType xsl,xslt,xml,html,xhtml runtime! scripts/closetag.vim\n\n \" Omni completion settings\n \"au FileType c setlocal completefunc=ccomplete#Complete\n au FileType css setlocal omnifunc=csscomplete#CompleteCSS\n \"au FileType html setlocal completefunc=htmlcomplete#CompleteTags\n \"au FileType js setlocal completefunc=javascriptcomplete#CompleteJS\n \"au FileType php setlocal completefunc=phpcomplete#CompletePHP\n \"au FileType python setlocal completefunc=pythoncomplete#Complete\n \"au FileType ruby setlocal completefunc=rubycomplete#Complete\n \"au FileType sql setlocal completefunc=sqlcomplete#Complete\n \"au FileType * setlocal completefunc=syntaxcomplete#Complete\n \"au FileType xml setlocal completefunc=xmlcomplete#CompleteTags\n\n au FileType help setlocal nolist\n\n \" insert a prompt for every changed file in the commit message\n \"au FileType svn :1![ -f \"%\" ] &amp;&amp; awk '/^[MDA]/ { print $2 \":\\n - \" }' %\n augroup END\n\n augroup hooks\n \" replace \"Last Modified: with the current time\"\n au BufWritePre,FileWritePre * call LastMod()\n\n \" line highlighting in insert mode\n autocmd InsertLeave * set nocul\n autocmd InsertEnter * set cul\n\n \" move to the directory of the edited file\n \"au BufEnter * if isdirectory (expand ('%:p:h')) | cd %:p:h | endif\n\n \" jump to last position in the file\n au BufRead * if line(\"'\\\"\") &gt; 0 &amp;&amp; line(\"'\\\"\") &lt;= line(\"$\") &amp;&amp; &amp;filetype != \"mail\" | exe \"normal g`\\\"\" | endif\n \" jump to last position every time a buffer is entered\n \"au BufEnter * if line(\"'x\") &gt; 0 &amp;&amp; line(\"'x\") &lt;= line(\"$\") &amp;&amp; line(\"'y\") &gt; 0 &amp;&amp; line(\"'y\") &lt;= line(\"$\") &amp;&amp; &amp;filetype != \"mail\" | exe \"normal g'yztg`x\" | endif\n \"au BufLeave * if &amp;modifiable | exec \"normal mxHmy\"\n augroup END\n\n augroup highlight\n \" make visual mode dark cyan\n au FileType * hi Visual ctermfg=Black ctermbg=DarkCyan gui=bold guibg=#a6caf0\n \" make cursor red\n au BufEnter,BufRead,WinEnter * :call SetCursorColor()\n\n \" hightlight trailing spaces and tabs and the defined print margin\n \"au FileType * hi WhiteSpaceEOL_Printmargin ctermfg=black ctermbg=White guifg=Black guibg=White\n au FileType * hi WhiteSpaceEOL_Printmargin ctermbg=White guibg=White\n au FileType * let m='' | if &amp;textwidth &gt; 0 | let m='\\|\\%' . &amp;textwidth . 'v.' | endif | exec 'match WhiteSpaceEOL_Printmargin /\\s\\+$' . m .'/'\n augroup END\nendif\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\" ---------- Functions ----------\n\"\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n\" set cursor color\nfunction! SetCursorColor()\n hi Cursor ctermfg=black ctermbg=red guifg=Black guibg=Red\nendfunction\ncall SetCursorColor()\n\n\" change dir the root of a debian package\nfunction! GetPackageRoot()\n let sd = getcwd()\n let owd = sd\n let cwd = owd\n let dest = sd\n while !isdirectory('debian')\n lcd ..\n let owd = cwd\n let cwd = getcwd()\n if cwd == owd\n break\n endif\n endwhile\n if cwd != sd &amp;&amp; isdirectory('debian')\n let dest = cwd\n endif\n return dest\nendfunction\n\n\" vim tip: Opening multiple files from a single command-line\nfunction! Sp(dir, ...)\n let split = 'sp'\n if a:dir == '1'\n let split = 'vsp'\n endif\n if(a:0 == 0)\n execute split\n else\n let i = a:0\n while(i &gt; 0)\n execute 'let files = glob (a:' . i . ')'\n for f in split (files, \"\\n\")\n execute split . ' ' . f\n endfor\n let i = i - 1\n endwhile\n windo if expand('%') == '' | q | endif\n endif\nendfunction\ncom! -nargs=* -complete=file Sp call Sp(0, &lt;f-args&gt;)\ncom! -nargs=* -complete=file Vsp call Sp(1, &lt;f-args&gt;)\n\n\" reads the file .include_path - useful for C programming\nfunction! ReadIncludePath()\n let include_path = expand(\"%:p:h\") . '/.include_path'\n if filereadable(include_path)\n for line in readfile(include_path, '')\n exec \"setl path +=,\" . line\n endfor\n endif\nendfunction\n\n\" update last modified line in file\nfun! LastMod()\n let line = line(\".\")\n let column = col(\".\")\n let search = @/\n\n \" replace Last Modified in the first 20 lines\n if line(\"$\") &gt; 20\n let l = 20\n else\n let l = line(\"$\")\n endif\n \" replace only if the buffer was modified\n if &amp;mod == 1\n silent exe \"1,\" . l . \"g/Last Modified:/s/Last Modified:.*/Last Modified: \" .\n \\ strftime(\"%a %d. %b %Y %T %z %Z\") . \"/\"\n endif\n let @/ = search\n\n \" set cursor to last position before substitution\n call cursor(line, column)\nendfun\n\n\" toggles show marks plugin\n\"fun! ToggleShowMarks()\n\" if exists('b:sm') &amp;&amp; b:sm == 1\n\" let b:sm=0\n\" NoShowMarks\n\" setl updatetime=4000\n\" else\n\" let b:sm=1\n\" setl updatetime=200\n\" DoShowMarks\n\" endif\n\"endfun\n\n\" reformats an email\nfun! FormatMail()\n \" workaround for the annoying mutt send-hook behavoir\n silent! 1,/^$/g/^X-To: .*/exec 'normal gg'|exec '/^To: /,/^Cc: /-1d'|1,/^$/s/^X-To: /To: /|exec 'normal dd'|exec '?Cc'|normal P\n silent! 1,/^$/g/^X-Cc: .*/exec 'normal gg'|exec '/^Cc: /,/^Bcc: /-1d'|1,/^$/s/^X-Cc: /Cc: /|exec 'normal dd'|exec '?Bcc'|normal P\n silent! 1,/^$/g/^X-Bcc: .*/exec 'normal gg'|exec '/^Bcc: /,/^Subject: /-1d'|1,/^$/s/^X-Bcc: /Bcc: /|exec 'normal dd'|exec '?Subject'|normal P\n\n \" delete signature\n silent! /^&gt; --[\\t ]*$/,/^-- $/-2d\n \" fix quotation\n silent! /^\\(On\\|In\\) .*$/,/^-- $/-1:s/&gt;&gt;/&gt; &gt;/g\n silent! /^\\(On\\|In\\) .*$/,/^-- $/-1:s/&gt;\\([^\\ \\t]\\)/&gt; \\1/g\n \" delete inner and trailing spaces\n normal :%s/[\\xa0\\x0d\\t ]\\+$//g\n normal :%s/\\([^\\xa0\\x0d\\t ]\\)[\\xa0\\x0d\\t ]\\+\\([^\\xa0\\x0d\\t ]\\)/\\1 \\2/g\n \" format text\n normal gg\n \" convert bad formated umlauts to real characters\n normal :%s/\\\\\\([0-9]*\\)/\\=nr2char(submatch(1))/g\n normal :%s/&amp;#\\([0-9]*\\);/\\=nr2char(submatch(1))/g\n \" break undo sequence\n normal iu\n exec 'silent! /\\(^\\(On\\|In\\) .*$\\|\\(schrieb\\|wrote\\):$\\)/,/^-- $/-1!par '.&amp;tw.'gqs0'\n \" place the cursor before my signature\n silent! /^-- $/-1\n \" clear search buffer\n let @/ = \"\"\nendfun\n\n\" insert selection at mark a\nfun! Insert() range\n exe \"normal vgvmzomy\\&lt;Esc&gt;\"\n normal `y\n let lineA = line(\".\")\n let columnA = col(\".\")\n\n normal `z\n let lineB = line(\".\")\n let columnB = col(\".\")\n\n \" exchange marks\n if lineA &gt; lineB || lineA &lt;= lineB &amp;&amp; columnA &gt; columnB\n \" save z in c\n normal mc\n \" store y in z\n normal `ymz\n \" set y to old z\n normal `cmy\n endif\n\n exe \"normal! gvd`ap`y\"\nendfun\n\n\" search with the selection of the visual mode\nfun! VisualSearch(direction) range\n let l:saved_reg = @\"\n execute \"normal! vgvy\"\n let l:pattern = escape(@\", '\\\\/.*$^~[]')\n let l:pattern = substitute(l:pattern, \"\\n$\", \"\", \"\")\n if a:direction == '#'\n execute \"normal! ?\" . l:pattern . \"^M\"\n elseif a:direction == '*'\n execute \"normal! /\" . l:pattern . \"^M\"\n elseif a:direction == '/'\n execute \"normal! /\" . l:pattern\n else\n execute \"normal! ?\" . l:pattern\n endif\n let @/ = l:pattern\n let @\" = l:saved_reg\nendfun\n\n\" 'Expandvar' expands the variable under the cursor\nfun! &lt;SID&gt;Expandvar()\n let origreg = @\"\n normal yiW\n if (@\" == \"@\\\"\")\n let @\" = origreg\n else\n let @\" = eval(@\")\n endif\n normal diW\"0p\n let @\" = origreg\nendfun\n\n\" execute the bc calculator\nfun! &lt;SID&gt;Bc(exp)\n setlocal paste\n normal mao\n exe \":.!echo 'scale=2; \" . a:exp . \"' | bc\"\n normal 0i \"bDdd`a\"bp\n setlocal nopaste\nendfun\n\nfun! &lt;SID&gt;RFC(number)\n silent exe \":e http://www.ietf.org/rfc/rfc\" . a:number . \".txt\"\nendfun\n\n\" The function Nr2Hex() returns the Hex string of a number.\nfunc! Nr2Hex(nr)\n let n = a:nr\n let r = \"\"\n while n\n let r = '0123456789ABCDEF'[n % 16] . r\n let n = n / 16\n endwhile\n return r\nendfunc\n\n\" The function String2Hex() converts each character in a string to a two\n\" character Hex string.\nfunc! String2Hex(str)\n let out = ''\n let ix = 0\n while ix &lt; strlen(a:str)\n let out = out . Nr2Hex(char2nr(a:str[ix]))\n let ix = ix + 1\n endwhile\n return out\nendfunc\n\n\" translates hex value to the corresponding number\nfun! Hex2Nr(hex)\n let r = 0\n let ix = strlen(a:hex) - 1\n while ix &gt;= 0\n let val = 0\n if a:hex[ix] == '1'\n let val = 1\n elseif a:hex[ix] == '2'\n let val = 2\n elseif a:hex[ix] == '3'\n let val = 3\n elseif a:hex[ix] == '4'\n let val = 4\n elseif a:hex[ix] == '5'\n let val = 5\n elseif a:hex[ix] == '6'\n let val = 6\n elseif a:hex[ix] == '7'\n let val = 7\n elseif a:hex[ix] == '8'\n let val = 8\n elseif a:hex[ix] == '9'\n let val = 9\n elseif a:hex[ix] == 'a' || a:hex[ix] == 'A'\n let val = 10\n elseif a:hex[ix] == 'b' || a:hex[ix] == 'B'\n let val = 11\n elseif a:hex[ix] == 'c' || a:hex[ix] == 'C'\n let val = 12\n elseif a:hex[ix] == 'd' || a:hex[ix] == 'D'\n let val = 13\n elseif a:hex[ix] == 'e' || a:hex[ix] == 'E'\n let val = 14\n elseif a:hex[ix] == 'f' || a:hex[ix] == 'F'\n let val = 15\n endif\n let r = r + val * Power(16, strlen(a:hex) - ix - 1)\n let ix = ix - 1\n endwhile\n return r\nendfun\n\n\" mathematical power function\nfun! Power(base, exp)\n let r = 1\n let exp = a:exp\n while exp &gt; 0\n let r = r * a:base\n let exp = exp - 1\n endwhile\n return r\nendfun\n\n\" Captialize movent/selection\nfunction! Capitalize(type, ...)\n let sel_save = &amp;selection\n let &amp;selection = \"inclusive\"\n let reg_save = @@\n\n if a:0 \" Invoked from Visual mode, use '&lt; and '&gt; marks.\n silent exe \"normal! `&lt;\" . a:type . \"`&gt;y\"\n elseif a:type == 'line'\n silent exe \"normal! '[V']y\"\n elseif a:type == 'block'\n silent exe \"normal! `[\\&lt;C-V&gt;`]y\"\n else\n silent exe \"normal! `[v`]y\"\n endif\n\n silent exe \"normal! `[gu`]~`]\"\n\n let &amp;selection = sel_save\n let @@ = reg_save\nendfunction\n\n\" Find file in current directory and edit it.\nfunction! Find(...)\n let path=\".\"\n if a:0==2\n let path=a:2\n endif\n let l:list=system(\"find \".path. \" -name '\".a:1.\"' | grep -v .svn \")\n let l:num=strlen(substitute(l:list, \"[^\\n]\", \"\", \"g\"))\n if l:num &lt; 1\n echo \"'\".a:1.\"' not found\"\n return\n endif\n if l:num != 1\n let tmpfile = tempname()\n exe \"redir! &gt; \" . tmpfile\n silent echon l:list\n redir END\n let old_efm = &amp;efm\n set efm=%f\n\n if exists(\":cgetfile\")\n execute \"silent! cgetfile \" . tmpfile\n else\n execute \"silent! cfile \" . tmpfile\n endif\n\n let &amp;efm = old_efm\n\n \" Open the quickfix window below the current window\n botright copen\n\n call delete(tmpfile)\n endif\nendfunction\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\" ---------- Plugin Settings ----------\n\"\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n\" hide dotfiles by default - the gh mapping quickly changes this behavior\nlet g:netrw_list_hide = '\\(^\\|\\s\\s\\)\\zs\\.\\S\\+'\n\n\" Do not go to active window.\n\"let g:bufExplorerFindActive = 0\n\" Don't show directories.\n\"let g:bufExplorerShowDirectories = 0\n\" Sort by full file path name.\n\"let g:bufExplorerSortBy = 'fullpath'\n\" Show relative paths.\n\"let g:bufExplorerShowRelativePath = 1\n\n\" don't allow autoinstalling of scripts\nlet g:GetLatestVimScripts_allowautoinstall = 0\n\n\" load manpage-plugin\nruntime! ftplugin/man.vim\n\n\" load matchit-plugin\nruntime! macros/matchit.vim\n\n\" minibuf explorer\n\"let g:miniBufExplModSelTarget = 1\n\"let g:miniBufExplorerMoreThanOne = 0\n\"let g:miniBufExplModSelTarget = 0\n\"let g:miniBufExplUseSingleClick = 1\n\"let g:miniBufExplMapWindowNavVim = 1\n\"let g:miniBufExplVSplit = 25\n\"let g:miniBufExplSplitBelow = 1\n\"let g:miniBufExplForceSyntaxEnable = 1\n\"let g:miniBufExplTabWrap = 1\n\n\" calendar plugin\n\" let g:calendar_weeknm = 4\n\n\" xml-ftplugin configuration\nlet xml_use_xhtml = 1\n\n\" :ToHTML\nlet html_number_lines = 1\nlet html_use_css = 1\nlet use_xhtml = 1\n\n\" LatexSuite\n\"let g:Tex_DefaultTargetFormat = 'pdf'\n\"let g:Tex_Diacritics = 1\n\n\" python-highlightings\nlet python_highlight_all = 1\n\n\" Eclim settings\n\"let org.eclim.user.name = g:tskelUserName\n\"let org.eclim.user.email = g:tskelUserEmail\n\"let g:EclimLogLevel = 4 \" info\n\"let g:EclimBrowser = \"x-www-browser\"\n\"let g:EclimShowCurrentError = 1\n\" nnoremap &lt;silent&gt; &lt;buffer&gt; &lt;tab&gt; :call eclim#util#FillTemplate(\"${\", \"}\")&lt;CR&gt;\n\" nnoremap &lt;silent&gt; &lt;buffer&gt; &lt;leader&gt;i :JavaImport&lt;CR&gt;\n\" nnoremap &lt;silent&gt; &lt;buffer&gt; &lt;leader&gt;d :JavaDocSearch -x declarations&lt;CR&gt;\n\" nnoremap &lt;silent&gt; &lt;buffer&gt; &lt;CR&gt; :JavaSearchContext&lt;CR&gt;\n\" nnoremap &lt;silent&gt; &lt;buffer&gt; &lt;CR&gt; :AntDoc&lt;CR&gt;\n\n\" quickfix notes plugin\nmap &lt;Leader&gt;n &lt;Plug&gt;QuickFixNote\nnnoremap &lt;F6&gt; :QFNSave ~/.vimquickfix/\nnnoremap &lt;S-F6&gt; :e ~/.vimquickfix/\nnnoremap &lt;F7&gt; :cgetfile ~/.vimquickfix/\nnnoremap &lt;S-F7&gt; :caddfile ~/.vimquickfix/\nnnoremap &lt;S-F8&gt; :!rm ~/.vimquickfix/\n\n\" EnhancedCommentify updated keybindings\nvmap &lt;Leader&gt;&lt;Space&gt; &lt;Plug&gt;VisualTraditional\nnmap &lt;Leader&gt;&lt;Space&gt; &lt;Plug&gt;Traditional\nlet g:EnhCommentifyTraditionalMode = 'No'\nlet g:EnhCommentifyPretty = 'No'\nlet g:EnhCommentifyRespectIndent = 'Yes'\n\n\" FuzzyFinder keybinding\nnnoremap &lt;leader&gt;fb :FufBuffer&lt;CR&gt;\nnnoremap &lt;leader&gt;fd :FufDir&lt;CR&gt;\nnnoremap &lt;leader&gt;fD :FufDir &lt;C-r&gt;=expand('%:~:.:h').'/'&lt;CR&gt;&lt;CR&gt;\nnmap &lt;leader&gt;Fd &lt;leader&gt;fD\nnmap &lt;leader&gt;FD &lt;leader&gt;fD\nnnoremap &lt;leader&gt;ff :FufFile&lt;CR&gt;\nnnoremap &lt;leader&gt;fF :FufFile &lt;C-r&gt;=expand('%:~:.:h').'/'&lt;CR&gt;&lt;CR&gt;\nnmap &lt;leader&gt;FF &lt;leader&gt;fF\nnnoremap &lt;leader&gt;ft :FufTextMate&lt;CR&gt;\nnnoremap &lt;leader&gt;fr :FufRenewCache&lt;CR&gt;\n\"let g:FuzzyFinderOptions = {}\n\"let g:FuzzyFinderOptions = { 'Base':{}, 'Buffer':{}, 'File':{}, 'Dir':{},\n \"\\ 'MruFile':{}, 'MruCmd':{}, 'Bookmark':{},\n \"\\ 'Tag':{}, 'TaggedFile':{},\n \"\\ 'GivenFile':{}, 'GivenDir':{}, 'GivenCmd':{},\n \"\\ 'CallbackFile':{}, 'CallbackItem':{}, }\nlet g:fuf_onelinebuf_location = 'botright'\nlet g:fuf_maxMenuWidth = 300\nlet g:fuf_file_exclude = '\\v\\~$|\\.o$|\\.exe$|\\.bak$|\\.swp$|((^|[/\\\\])\\.[/\\\\]$)|\\.pyo|\\.pyc|autom4te\\.cache|blib|_build|\\.bzr|\\.cdv|cover_db|CVS|_darcs|\\~\\.dep|\\~\\.dot|\\.git|\\.hg|\\~\\.nib|\\.pc|\\~\\.plst|RCS|SCCS|_sgbak|\\.svn'\n\n\" YankRing\nnnoremap &lt;silent&gt; &lt;F8&gt; :YRShow&lt;CR&gt;\nlet g:yankring_history_file = '.yankring_history_file'\nlet g:yankring_replace_n_pkey = '&lt;c-\\&gt;'\nlet g:yankring_replace_n_nkey = '&lt;c-m&gt;'\n\n\" supertab\nlet g:SuperTabDefaultCompletionType = \"&lt;c-n&gt;\"\n\n\" TagList\nlet Tlist_Show_One_File = 1\n\n\" UltiSnips\n\"let g:UltiSnipsJumpForwardTrigger = \"&lt;tab&gt;\"\n\"let g:UltiSnipsJumpBackwardTrigger = \"&lt;S-tab&gt;\"\n\n\" NERD Commenter\nnmap &lt;leader&gt;&lt;space&gt; &lt;plug&gt;NERDCommenterToggle\nvmap &lt;leader&gt;&lt;space&gt; &lt;plug&gt;NERDCommenterToggle\nimap &lt;C-c&gt; &lt;ESC&gt;:call NERDComment(0, \"insert\")&lt;CR&gt;\n\n\" disable unused Mark mappings\nnmap &lt;leader&gt;_r &lt;plug&gt;MarkRegex\nvmap &lt;leader&gt;_r &lt;plug&gt;MarkRegex\nnmap &lt;leader&gt;_n &lt;plug&gt;MarkClear\nvmap &lt;leader&gt;_n &lt;plug&gt;MarkClear\nnmap &lt;leader&gt;_* &lt;plug&gt;MarkSearchCurrentNext\nnmap &lt;leader&gt;_# &lt;plug&gt;MarkSearchCurrentPrev\nnmap &lt;leader&gt;_/ &lt;plug&gt;MarkSearchAnyNext\nnmap &lt;leader&gt;_# &lt;plug&gt;MarkSearchAnyPrev\nnmap &lt;leader&gt;__* &lt;plug&gt;MarkSearchNext\nnmap &lt;leader&gt;__# &lt;plug&gt;MarkSearchPrev\n\n\" Nerd Tree explorer mapping\nnmap &lt;leader&gt;e :NERDTree&lt;CR&gt;\n\n\" TaskList settings\nlet g:tlWindowPosition = 1\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\" ---------- Keymappings ----------\n\"\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n\" edit/reload .vimrc-Configuration\nnnoremap gce :e $HOME/.vimrc&lt;CR&gt;\nnnoremap gcl :source $HOME/.vimrc&lt;CR&gt;:echo \"Configuration reloaded\"&lt;CR&gt;\n\n\" un/hightlight current line\nnnoremap &lt;silent&gt; &lt;Leader&gt;H :match&lt;CR&gt;\nnnoremap &lt;silent&gt; &lt;Leader&gt;h mk:exe 'match Search /&lt;Bslash&gt;%'.line(\".\").'l/'&lt;CR&gt;\n\n\" spellcheck off, german, englisch\nnnoremap gsg :setlocal invspell spelllang=de&lt;CR&gt;\nnnoremap gse :setlocal invspell spelllang=en&lt;CR&gt;\n\n\" switch to previous/next buffer\nnnoremap &lt;silent&gt; &lt;c-p&gt; :bprevious&lt;CR&gt;\nnnoremap &lt;silent&gt; &lt;c-n&gt; :bnext&lt;CR&gt;\n\n\" kill/delete trailing spaces and tabs\nnnoremap &lt;Leader&gt;kt msHmt:silent! %s/[\\t \\x0d]\\+$//g&lt;CR&gt;:let @/ = \"\"&lt;CR&gt;:echo \"Deleted trailing spaces\"&lt;CR&gt;'tzt`s\nvnoremap &lt;Leader&gt;kt :s/[\\t \\x0d]\\+$//g&lt;CR&gt;:let @/ = \"\"&lt;CR&gt;:echo \"Deleted trailing, spaces\"&lt;CR&gt;\n\n\" kill/reduce inner spaces and tabs to a single space/tab\nnnoremap &lt;Leader&gt;ki msHmt:silent! %s/\\([^\\xa0\\x0d\\t ]\\)[\\xa0\\x0d\\t ]\\+\\([^\\xa0\\x0d\\t ]\\)/\\1 \\2/g&lt;CR&gt;:let @/ = \"\"&lt;CR&gt;:echo \"Deleted inner spaces\"&lt;CR&gt;'tzt`s\nvnoremap &lt;Leader&gt;ki :s/\\([^\\xa0\\x0d\\t ]\\)[\\xa0\\x0d\\t ]\\+\\([^\\xa0\\x0d\\t ]\\)/\\1 \\2/g&lt;CR&gt;:let @/ = \"\"&lt;CR&gt;:echo \"Deleted inner spaces\"&lt;CR&gt;\n\n\" start new undo sequences when using certain commands in insert mode\ninoremap &lt;C-U&gt; &lt;C-G&gt;u&lt;C-U&gt;\ninoremap &lt;C-W&gt; &lt;C-G&gt;u&lt;C-W&gt;\ninoremap &lt;BS&gt; &lt;C-G&gt;u&lt;BS&gt;\ninoremap &lt;C-H&gt; &lt;C-G&gt;u&lt;C-H&gt;\ninoremap &lt;Del&gt; &lt;C-G&gt;u&lt;Del&gt;\n\n\" swap two words\n\" http://www.vim.org/tips/tip.php?tip_id=329\nnmap &lt;silent&gt; gw \"_yiw:s/\\(\\%#[ÄÖÜäöüßa-zA-Z0-9]\\+\\)\\(\\_W\\+\\)\\([ÄÖÜäöüßa-zA-Z0-9]\\+\\)/\\3\\2\\1/&lt;CR&gt;&lt;C-o&gt;&lt;C-l&gt;:let @/ = \"\"&lt;CR&gt;\nnmap &lt;silent&gt; gW \"_yiW:s/\\(\\%#[ÄÖÜäöüßa-zA-Z0-9-+*_]\\+\\)\\(\\_W\\+\\)\\([ÄÖÜäöüßa-zA-Z0-9-+*_]\\+\\)/\\3\\2\\1/&lt;CR&gt;&lt;C-o&gt;&lt;C-l&gt;:let @/ = \"\"&lt;CR&gt;\n\n\" Capitalize movement\nnnoremap &lt;silent&gt; gC :set opfunc=Capitalize&lt;CR&gt;g@\nvnoremap &lt;silent&gt; gC :&lt;C-U&gt;call Capitalize(visualmode(), 1)&lt;CR&gt;\n\n\" delete search-register\nnnoremap &lt;silent&gt; &lt;leader&gt;/ :let @/ = \"\"&lt;CR&gt;\n\n\" browse current buffer/selection in www-browser\nnnoremap &lt;Leader&gt;b :!x-www-browser %:p&lt;CR&gt;:echo \"WWW-Browser started\"&lt;CR&gt;\nvnoremap &lt;Leader&gt;b y:!x-www-browser &lt;C-R&gt;\"&lt;CR&gt;:echo \"WWW-Browser started\"&lt;CR&gt;\n\n\" lookup/translate inner/selected word in dictionary\n\" recode is only needed for non-utf-8-text\n\" nnoremap &lt;Leader&gt;T mayiw`a:exe \"!dict -P - -- $(echo \" . @\" . \"\\| recode latin1..utf-8)\"&lt;CR&gt;\n\"nnoremap &lt;Leader&gt;t mayiw`a:exe \"!dict -P - -- \" . @\"&lt;CR&gt;\n\" vnoremap &lt;Leader&gt;T may`a:exe \"!dict -P - -- $(echo \" . @\" . \"\\| recode latin1..utf-8)\"&lt;CR&gt;\n\"vnoremap &lt;Leader&gt;t may`a:exe \"!dict -P - -- \" . @\"&lt;CR&gt;\n\n\" delete words in insert mode like expected - doesn't work properly at\n\" the end of the line\ninoremap &lt;C-BS&gt; &lt;C-w&gt;\n\n\" Switch buffers\nnnoremap &lt;silent&gt; [b :ls&lt;Bar&gt;let nr = input(\"Buffer: \")&lt;Bar&gt;if nr != ''&lt;Bar&gt;exe \":b \" . nr&lt;Bar&gt;endif&lt;CR&gt;\n\" Search for the occurence of the word under the cursor\nnnoremap &lt;silent&gt; [I [I:le\n</code></pre>\n" }, { "answer_id": 1642132, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 1, "selected": false, "text": "<p>Almost everything is <a href=\"http://code.google.com/p/lh-vim/\" rel=\"nofollow noreferrer\">here</a>. It is mainly programming oriented, in C++ in particular.</p>\n" }, { "answer_id": 1646203, "author": "elvy", "author_id": 199158, "author_profile": "https://Stackoverflow.com/users/199158", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://github.com/elventails/vim/blob/master/vimrc\" rel=\"nofollow noreferrer\">http://github.com/elventails/vim/blob/master/vimrc</a></p>\n\n<p>Has extras for CakePHP/PHP/Git</p>\n\n<p>enjoy!</p>\n\n<p>Will add nice options you guys are using to it and update the repo;</p>\n\n<p>Cheers,</p>\n" }, { "answer_id": 1647401, "author": "Richard", "author_id": 110772, "author_profile": "https://Stackoverflow.com/users/110772", "pm_score": 0, "selected": false, "text": "<p>A lot of this comes from the <a href=\"http://vim.wikia.com/wiki/Vim_Tips_Wiki\" rel=\"nofollow noreferrer\">wiki</a> btw. </p>\n\n<pre><code>set nocompatible\nsource $VIMRUNTIME/mswin.vim\nbehave mswin\nset nobackup\nset tabstop=4\nset nowrap\n\nset guifont=Droid_Sans_Mono:h9:cANSI\ncolorscheme torte\nset shiftwidth=4\nset ic\nsyn off\nset nohls\nset acd\nset autowrite\nnoremap \\c \"+yy\nnoremap \\x \"+dd\nnoremap \\t :tabnew&lt;CR&gt;\nnoremap \\2 I\"&lt;Esc&gt;A\"&lt;Esc&gt;\nnoremap \\3 bi'&lt;Esc&gt;ea'&lt;Esc&gt;\nnoremap \\\" i\"&lt;Esc&gt;ea\"&lt;Esc&gt;\nnoremap ?2 Bi\"&lt;Esc&gt;Ea\"&lt;Esc&gt;\nset matchpairs+=&lt;:&gt;\nnnoremap &lt;C-N&gt; :next&lt;CR&gt;\nnnoremap &lt;C-P&gt; :prev&lt;CR&gt;\nnnoremap &lt;Tab&gt; :bnext&lt;CR&gt;\nnnoremap &lt;S-Tab&gt; :bprevious&lt;CR&gt;\nnnoremap \\w :let @/=expand(\"&lt;cword&gt;\")&lt;Bar&gt;split&lt;Bar&gt;normal n&lt;CR&gt;\nnnoremap \\W :let @/='\\&lt;'.expand(\"&lt;cword&gt;\").'\\&gt;'&lt;Bar&gt;split&lt;Bar&gt;normal n&lt;CR&gt;\n\nautocmd FileType xml exe \":silent %!xmllint --format --recover - \"\nautocmd FileType cpp set tabstop=2 shiftwidth=2 expandtab autoindent smarttab\nautocmd FileType sql set tabstop=2 shiftwidth=2 expandtab autoindent smarttab\n\n\" Map key to toggle opt\nfunction MapToggle(key, opt)\n let cmd = ':set '.a:opt.'! \\| set '.a:opt.\"?\\&lt;CR&gt;\"\n exec 'nnoremap '.a:key.' '.cmd\n exec 'inoremap '.a:key.\" \\&lt;C-O&gt;\".cmd\nendfunction\ncommand -nargs=+ MapToggle call MapToggle(&lt;f-args&gt;)\n\nmap &lt;F6&gt; :if exists(\"syntax_on\") &lt;Bar&gt; syntax off &lt;Bar&gt; else &lt;Bar&gt; syntax enable &lt;Bar&gt; endif &lt;CR&gt;\n\n\" Display-altering option toggles\nMapToggle &lt;F7&gt; hlsearch\nMapToggle &lt;F8&gt; wrap\nMapToggle &lt;F9&gt; list\n\n\" Behavior-altering option toggles\nMapToggle &lt;F10&gt; scrollbind\nMapToggle &lt;F11&gt; ignorecase\nMapToggle &lt;F12&gt; paste\nset pastetoggle=&lt;F12&gt;\n</code></pre>\n" }, { "answer_id": 1656156, "author": "Pierre-Antoine LaFayette", "author_id": 135360, "author_profile": "https://Stackoverflow.com/users/135360", "pm_score": 1, "selected": false, "text": "<p>My .vimrc and .bashrc plus my entire .vim folder (with all the plugins) are available at:\n<a href=\"http://code.google.com/p/pal-nix/\" rel=\"nofollow noreferrer\">http://code.google.com/p/pal-nix/</a>.</p>\n\n<p>Here's my .vimrc for quick review:\n<pre><code>\n\" .vimrc \n\"\n\" $Author$\n\" $Date$\n\" $Revision$ </p>\n\n<p>\" * Initial Configuration * {{{1 \"\n\" change directory on open file, buffer switch etc. {{{2\nset autochdir</p>\n\n<p>\" turn on filetype detection and indentation {{{2\nfiletype indent plugin on</p>\n\n<p>\" set tags file to search in parent directories with tags; {{{2\nset tags=tags;</p>\n\n<p>\" reload vimrc on update {{{2\nautocmd BufWritePost .vimrc source %</p>\n\n<p>\" set folds to look for markers {{{2\n:set foldmethod=marker</p>\n\n<p>\" automatically save view and reload folds {{{2\n\"au BufWinLeave * mkview\n\"au BufWinEnter * silent loadview</p>\n\n<p>\" behave like windows {{{2\n\"source $VIMRUNTIME/mswin.vim \" can't use if on (use with gvim only)\n\"behave mswin</p>\n\n<p>\" load dictionary files for complete suggestion with Ctrl-n {{{2\nset complete+=k\nautocmd FileType * exec('set dictionary+=~/.vim/dict/' . &amp;filetype)</p>\n\n<p>\" * User Interface * {{{1 \"\n\" turn on coloring {{{2\nif has('syntax')\n syntax on\nendif</p>\n\n<p>\" gvim color scheme of choice {{{2\nif has('gui')\n so $VIMRUNTIME/colors/desert.vim\nendif</p>\n\n<p>\" turn off annoying bell {{{2\nset vb</p>\n\n<p>\" set the directory for swp files {{{2\nif(isdirectory(expand(\"$VIMRUNTIME/swp\")))\n set dir=$VIMRUNTIME/swp\nendif</p>\n\n<p>\" have fifty lines of cmdline (etc) history {{{2\nset history=50</p>\n\n<p>\" have cmdline completion (for filenames, help topics, option names) {{{2\n\" first list the available options and complete the longest common part, then\n\" have further s cycle through the possibilities:\nset wildmode=list:longest,full</p>\n\n<p>\" use \"[RO]\" for \"[readonly]\" to save space in the message line: {{{2\nset shortmess+=r</p>\n\n<p>\" display current mode and partially typed commands in status line {{{2\nset showmode\nset showcmd</p>\n\n<p>\" Text Formatting -- General {{{2\nset nocompatible \"prevents vim from emulating vi's original bugs\nset backspace=2 \"make backspace work normal (indent, eol, start)\nset autoindent\nset smartindent \"makes vim smartly guess indent level\nset tabstop=2 \"sets up 2 space tabs\nset shiftwidth=2 \"tells vim to use 2 spaces when text is indented\nset smarttab \"uses shiftwidth for inserting s\nset expandtab \"insert spaces instead of \nset softtabstop=2 \"makes vim see multiple space characters as tabstops\nset showmatch \"causes cursor to jump to bracket match\nset mat=5 \"how many tenths of a second to blink matches\nset guioptions-=T \"removes toolbar from gvim\nset ruler \"ensures each window contains a status line\nset incsearch \"vim will search for text as you type\nset hlsearch \"highlight search terms\nset hl=l:Visual \"use Visual mode's highlighting scheme --much better\nset ignorecase \"ignore case in searches --faster this way\nset virtualedit=all \"allows the cursor to stray beyond defined text\nset number \"show line numbers in left margin\nset path=$PWD/** \"recursively set the path of the project\n \"get more information from the status line \nset statusline=[%n]\\ %&lt;%.99f\\ %h%w%m%r%{exists('*CapsLockStatusline')?CapsLockStatusline():''}%y%=%-16(\\ %l,%c-%v\\ %)%P\nset laststatus=2 \"keep status line showing\nset cursorline \"highlight current line\nhighlight CursorLine guibg=lightblue guifg=white ctermbg=blue ctermfg=white\n\"set spell \"spell check\nset spellsuggest=3 \"suggest better spelling\nset spelllang=en \"set language\nset encoding=utf-8 \"set character encoding</p>\n\n<p>\" * Macros * {{{1 \"\n\" Function keys {{{2\n\" Don't you always find yourself hitting instead of ? {{{3\ninoremap \nnoremap </p>\n\n<p>\" turn off syntax highlighting {{{3\nnnoremap :nohlsearch\ninoremap :nohlsearcha</p>\n\n<p>\" NERD Tree Explorer {{{3\nnnoremap :NERDTreeToggle </p>\n\n<p>\" open tag list {{{3\nnnoremap :TlistToggle</p>\n\n<p>\" Spell check {{{3\nnnoremap :set spell</p>\n\n<p>\" No spell check {{{3\nnnoremap :set nospell</p>\n\n<p>\" refactor curly braces on keyword line {{{3\nmap :%s/) \\?\\n^\\s*{/) {/g</p>\n\n<p>\" useful mappings to paste and reformat/reindent {{{2\nnnoremap P P'[v']=\nnnoremap p P'[v']=</p>\n\n<p>\" * Scripts * {{{1 \"\n:au Filetype html,xml,xsl source ~/.vim/scripts/closetag.vim</p>\n\n<p>\" Modeline {{{1\n\" vim:set fdm=marker sw=4 ts=4:\n</pre></code></p>\n" }, { "answer_id": 1656158, "author": "John Kugelman", "author_id": 68587, "author_profile": "https://Stackoverflow.com/users/68587", "pm_score": 0, "selected": false, "text": "<p>The super money part from my .vimrc is how it shows a \"&raquo;\" character each place there's a tab, and how it highlights \"bad\" whitespace in red. Bad whitespace is stuff like tabs in the middle of a line or invisible spaces at the end.</p>\n\n<pre><code>syntax enable\n\n\" Incremental search without highlighting.\nset incsearch\nset nohlsearch\n\n\" Show ruler.\nset ruler\n\n\" Try to keep 2 lines above/below the current line in view for context.\nset scrolloff=2\n\n\" Other file types.\nautocmd BufReadPre,BufNew *.xml set filetype=xml\n\n\" Flag problematic whitespace (trailing spaces, spaces before tabs).\nhighlight BadWhitespace term=standout ctermbg=red guibg=red\nmatch BadWhitespace /[^* \\t]\\zs\\s\\+$\\| \\+\\ze\\t/\n\n\" If using ':set list' show things nicer.\nexecute 'set listchars=tab:' . nr2char(187) . '\\ '\nset list\nhighlight Tab ctermfg=lightgray guifg=lightgray\n2match Tab /\\t/\n\n\" Indent settings for code: 4 spaces, do not use tab character.\n\"set tabstop=4 shiftwidth=4 autoindent smartindent shiftround\n\"autocmd FileType c,cpp,java,xml,python,cs setlocal expandtab softtabstop=4\n\"autocmd FileType c,cpp,java,xml,python,cs 2match BadWhitespace /[^\\t]\\zs\\t/\nset tabstop=8 shiftwidth=4 autoindent smartindent shiftround\nset expandtab softtabstop=4\n2match BadWhitespace /[^\\t]\\zs\\t\\+/\n\n\" Automatically show matching brackets.\nset showmatch\n\n\" Auto-complete file names after &lt;TAB&gt; like bash does.\nset wildmode=longest,list\nset wildignore=.svn,CVS,*.swp\n\n\" Show current mode and currently-typed command.\nset showmode\nset showcmd\n\n\" Use mouse if possible.\n\" set mouse=a\n\n\" Use Ctrl-N and Ctrl-P to move between files.\nnnoremap &lt;C-N&gt; :confirm next&lt;Enter&gt;\nnnoremap &lt;C-P&gt; :confirm prev&lt;Enter&gt;\n\n\" Confirm saving and quitting.\nset confirm\n\n\" So yank behaves like delete, i.e. Y = D.\nmap Y y$\n\n\" Toggle paste mode with F5.\nset pastetoggle=&lt;F5&gt;\n\n\" Don't exit visual mode when shifting.\nvnoremap &lt; &lt;gv\nvnoremap &gt; &gt;gv\n\n\" Move up and down by visual lines not buffer lines.\nnnoremap &lt;Up&gt; gk\nvnoremap &lt;Up&gt; gk\nnnoremap &lt;Down&gt; gj\nvnoremap &lt;Down&gt; gj\n</code></pre>\n" }, { "answer_id": 1773289, "author": "Yada", "author_id": 45066, "author_profile": "https://Stackoverflow.com/users/45066", "pm_score": 0, "selected": false, "text": "<p>I can't live without TAB Completion</p>\n\n<pre><code>\" Intelligent tab completion\ninoremap &lt;silent&gt; &lt;Tab&gt; &lt;C-r&gt;=&lt;SID&gt;InsertTabWrapper(1)&lt;CR&gt;\ninoremap &lt;silent&gt; &lt;S-Tab&gt; &lt;C-r&gt;=&lt;SID&gt;InsertTabWrapper(-1)&lt;CR&gt;\n\nfunction! &lt;SID&gt;InsertTabWrapper(direction)\n let idx = col('.') - 1\n let str = getline('.')\n\n if a:direction &gt; 0 &amp;&amp; idx &gt;= 2 &amp;&amp; str[idx - 1] == ' '\n \\&amp;&amp; str[idx - 2] =~? '[a-z]'\n if &amp;softtabstop &amp;&amp; idx % &amp;softtabstop == 0\n return \"\\&lt;BS&gt;\\&lt;Tab&gt;\\&lt;Tab&gt;\"\n else\n return \"\\&lt;BS&gt;\\&lt;Tab&gt;\"\n endif\n elseif idx == 0 || str[idx - 1] !~? '[a-z]'\n return \"\\&lt;Tab&gt;\"\n elseif a:direction &gt; 0\n return \"\\&lt;C-p&gt;\"\n else\n return \"\\&lt;C-n&gt;\"\n endif\nendfunction\n</code></pre>\n" }, { "answer_id": 1817199, "author": "Roberto Bonvallet", "author_id": 13169, "author_profile": "https://Stackoverflow.com/users/13169", "pm_score": 1, "selected": false, "text": "<p>The return, backspace, spacebar and hyphen keys aren't bound to anything useful, so I map them to navigate more conveniently through the document:</p>\n\n<pre><code>\" Page down, page up, scroll down, scroll up\nnoremap &lt;Space&gt; &lt;C-f&gt;\nnoremap - &lt;C-b&gt;\nnoremap &lt;Backspace&gt; &lt;C-y&gt;\nnoremap &lt;Return&gt; &lt;C-e&gt;\n</code></pre>\n" }, { "answer_id": 2079364, "author": "fferen", "author_id": 243503, "author_profile": "https://Stackoverflow.com/users/243503", "pm_score": 0, "selected": false, "text": "<p>I made a function that automatically sends your text to a private pastebin.</p>\n\n<pre><code>let g:pfx='' \" prefix for private pastebin.\n\nfunction PBSubmit()\npython &lt;&lt; EOF\nimport vim\nimport urllib2 as url\nimport urllib\n\npfx = vim.eval( 'g:pfx' )\n\nURL = 'http://'\n\nif pfx == '':\n URL += 'pastebin.com/pastebin.php'\nelse:\n URL += pfx + '.pastebin.com/pastebin.php'\n\ndata = urllib.urlencode( { 'code2': '\\n'.join( vim.current.buffer ).decode( 'utf-8' ).encode( 'latin-1' ),\n 'email': '',\n 'expiry': 'd',\n 'format': 'text',\n 'parent_pid': '',\n 'paste': 'Send',\n 'poster': '' } )\n\nurl.urlopen( URL, data )\n\nprint 'Submitted to ' + URL\nEOF\nendfunction\n\nmap &lt;Leader&gt;pb :call PBSubmit()&lt;CR&gt;\n</code></pre>\n" }, { "answer_id": 2648674, "author": "ravett", "author_id": 317931, "author_profile": "https://Stackoverflow.com/users/317931", "pm_score": 0, "selected": false, "text": "<p>My favorite bit of my .vimrc is a set of mappings for working with macros:</p>\n\n<pre><code>nnoremap &lt;Leader&gt;qa mqGo&lt;Esc&gt;\"ap\nnnoremap &lt;Leader&gt;qb mqGo&lt;Esc&gt;\"bp\nnnoremap &lt;Leader&gt;qc mqGo&lt;Esc&gt;\"cp\n&lt;SNIP&gt;\nnnoremap &lt;Leader&gt;qz mqGo&lt;Esc&gt;\"zp\n\nnnoremap &lt;Leader&gt;Qa G0\"ad$dd'q\nnnoremap &lt;Leader&gt;Qb G0\"bd$dd'q\nnnoremap &lt;Leader&gt;Qc G0\"cd$dd'q\n&lt;SNIP&gt;\nnnoremap &lt;Leader&gt;Qz G0\"zd$dd'q\n</code></pre>\n\n<p>With this \\q[a-z] will mark your location, and print the contents of the given register at the bottom of the current file and \\Q[a-z] will put the contents of the last line into the given register and go back to your marked location. Makes it really easy to edit a macro or copy and tweak one macro into a new register.</p>\n" }, { "answer_id": 2746087, "author": "tilljoel", "author_id": 61296, "author_profile": "https://Stackoverflow.com/users/61296", "pm_score": 0, "selected": false, "text": "<p>My <a href=\"http://hackr.se/vim/vimrc\" rel=\"nofollow noreferrer\">.vimrc</a>, the plugins i use and other tweaks are customized to help me with the tasks i preform most frequently:</p>\n\n<ul>\n<li>Use Mutt/Vim to read/write emails</li>\n<li>Write C code under GNU/Linux, usually with glib, gobject, gstreamer</li>\n<li>Browse/Read C source code </li>\n<li>Work with Python, Ruby on Rails or Bash scripts</li>\n<li>Develop web applications with HTML, Javascript, CSS</li>\n</ul>\n\n<p>I have some more info about my <a href=\"http://hackr.se/vim/vim-configuration/\" rel=\"nofollow noreferrer\">Vim configuration here</a></p>\n" }, { "answer_id": 2746150, "author": "Siddhartha Reddy", "author_id": 130535, "author_profile": "https://Stackoverflow.com/users/130535", "pm_score": 0, "selected": false, "text": "<p>Some of my favorite customizations that I haven't found to be all too common:</p>\n\n<pre><code>\" Windows *********************************************************************\"\nset equalalways \" Multiple windows, when created, are equal in size\"\nset splitbelow splitright \" Put the new windows to the right/bottom\"\n\n\" Insert new line in command mode *********************************************\"\nmap &lt;S-Enter&gt; O&lt;ESC&gt; \" Insert above current line\"\nmap &lt;Enter&gt; o&lt;ESC&gt; \" Insert below current line\"\n\n\" After selecting something in visual mode and shifting, I still want that\"\n\" selection intact ************************************************************\"\nvmap &gt; &gt;gv\nvmap &lt; &lt;gv\n</code></pre>\n" }, { "answer_id": 2841066, "author": "sixtyfootersdude", "author_id": 251589, "author_profile": "https://Stackoverflow.com/users/251589", "pm_score": 0, "selected": false, "text": "<p>I have this in my <code>~/.vim/after/syntax/vim.vim</code> file:</p>\n\n<p>What it does is:</p>\n\n<ul>\n<li>highlights the word blue in the color blue</li>\n<li>highlights the wrod red in the color red</li>\n<li>etc</li>\n</ul>\n\n<p>Ie: so if you go:</p>\n\n<pre><code>highlight JakeRedKeywords cterm=bold term=bold ctermbg=black ctermfg=Red\n</code></pre>\n\n<p>The word red will be red and the word black will be black. </p>\n\n<p>Here is the code: </p>\n\n<pre><code>syn cluster vimHiCtermColors contains=vimHiCtermColorBlack,vimHiCtermColorBlue,vimHiCtermColorBrown,vimHiCtermColorCyan,vimHiCtermColorDarkBlue,vimHiCtermColorDarkcyan,vimHiCtermColorDarkgray,vimHiCtermColorDarkgreen,vimHiCtermColorDarkgrey,vimHiCtermColorDarkmagenta,vimHiCtermColorDarkred,vimHiCtermColorDarkyellow,vimHiCtermColorGray,vimHiCtermColorGreen,vimHiCtermColorGrey,vimHiCtermColorLightblue,vimHiCtermColorLightcyan,vimHiCtermColorLightgray,vimHiCtermColorLightgreen,vimHiCtermColorLightgrey,vimHiCtermColorLightmagenta,vimHiCtermColorLightred,vimHiCtermColorMagenta,vimHiCtermColorRed,vimHiCtermColorWhite,vimHiCtermColorYellow\n\nsyn case ignore\n\nsyn keyword vimHiCtermColorYellow yellow contained \nsyn keyword vimHiCtermColorBlack black contained\nsyn keyword vimHiCtermColorBlue blue contained\nsyn keyword vimHiCtermColorBrown brown contained\nsyn keyword vimHiCtermColorCyan cyan contained\nsyn keyword vimHiCtermColorDarkBlue darkBlue contained\nsyn keyword vimHiCtermColorDarkcyan darkcyan contained\nsyn keyword vimHiCtermColorDarkgray darkgray contained\nsyn keyword vimHiCtermColorDarkgreen darkgreen contained\nsyn keyword vimHiCtermColorDarkgrey darkgrey contained\nsyn keyword vimHiCtermColorDarkmagenta darkmagenta contained\nsyn keyword vimHiCtermColorDarkred darkred contained\nsyn keyword vimHiCtermColorDarkyellow darkyellow contained\nsyn keyword vimHiCtermColorGray gray contained\nsyn keyword vimHiCtermColorGreen green contained\nsyn keyword vimHiCtermColorGrey grey contained\nsyn keyword vimHiCtermColorLightblue lightblue contained\nsyn keyword vimHiCtermColorLightcyan lightcyan contained\nsyn keyword vimHiCtermColorLightgray lightgray contained\nsyn keyword vimHiCtermColorLightgreen lightgreen contained\nsyn keyword vimHiCtermColorLightgrey lightgrey contained\nsyn keyword vimHiCtermColorLightmagenta lightmagenta contained\nsyn keyword vimHiCtermColorLightred lightred contained\nsyn keyword vimHiCtermColorMagenta magenta contained\nsyn keyword vimHiCtermColorRed red contained\nsyn keyword vimHiCtermColorWhite white contained\nsyn keyword vimHiCtermColorYellow yellow contained\n\nsyn match vimHiCtermFgBg contained \"\\ccterm[fb]g=\"he=e-1 nextgroup=vimNumber,@vimHiCtermColors,vimFgBgAttrib,vimHiCtermError\n\nhighlight vimHiCtermColorBlack ctermfg=black ctermbg=white\nhighlight vimHiCtermColorBlue ctermfg=blue\nhighlight vimHiCtermColorBrown ctermfg=brown\nhighlight vimHiCtermColorCyan ctermfg=cyan\nhighlight vimHiCtermColorDarkBlue ctermfg=darkBlue\nhighlight vimHiCtermColorDarkcyan ctermfg=darkcyan\nhighlight vimHiCtermColorDarkgray ctermfg=darkgray\nhighlight vimHiCtermColorDarkgreen ctermfg=darkgreen\nhighlight vimHiCtermColorDarkgrey ctermfg=darkgrey\nhighlight vimHiCtermColorDarkmagenta ctermfg=darkmagenta\nhighlight vimHiCtermColorDarkred ctermfg=darkred\nhighlight vimHiCtermColorDarkyellow ctermfg=darkyellow\nhighlight vimHiCtermColorGray ctermfg=gray\nhighlight vimHiCtermColorGreen ctermfg=green\nhighlight vimHiCtermColorGrey ctermfg=grey\nhighlight vimHiCtermColorLightblue ctermfg=lightblue\nhighlight vimHiCtermColorLightcyan ctermfg=lightcyan\nhighlight vimHiCtermColorLightgray ctermfg=lightgray\nhighlight vimHiCtermColorLightgreen ctermfg=lightgreen\nhighlight vimHiCtermColorLightgrey ctermfg=lightgrey\nhighlight vimHiCtermColorLightmagenta ctermfg=lightmagenta\nhighlight vimHiCtermColorLightred ctermfg=lightred\nhighlight vimHiCtermColorMagenta ctermfg=magenta\nhighlight vimHiCtermColorRed ctermfg=red\nhighlight vimHiCtermColorWhite ctermfg=white\nhighlight vimHiCtermColorYellow ctermfg=yellow\n</code></pre>\n" }, { "answer_id": 2989503, "author": "Alexis Métaireau", "author_id": 147077, "author_profile": "https://Stackoverflow.com/users/147077", "pm_score": 0, "selected": false, "text": "<p>Here's mine ! Thanks for sharing. You can find other stuff about vim plugins here: <a href=\"http://github.com/ametaireau/dotfiles/\" rel=\"nofollow noreferrer\">http://github.com/ametaireau/dotfiles/</a></p>\n\n<p>Hope it helps.</p>\n\n<pre><code>\" My .vimrc configuration file.\n\" =============================\n\"\n\" Plugins\n\" -------\n\" Comes with a set of utilities to enhance the user experience.\n\" Django and python snippets are possible thanks to the snipmate\n\" plugin.\n\"\n\" A also uses taglist and NERDTree vim plugins.\n\"\n\" Shortcuts\n\" ----------\n\" Here are some shortcuts I like to use when editing text using VIM:\n\"\n\" &lt;alt-left/right&gt; to navigate trough tabs\n\" &lt;ctrl-e&gt; to display the explorator\n\" &lt;ctrl-p&gt; for the code explorator\n\" &lt;ctrl-space&gt; to autocomplete\n\" &lt;ctrl-n&gt; enter tabnew to open a new file\n\" &lt;alt-h&gt; highlight the lines of more than 80 columns\n\" &lt;ctrl-h&gt; set textwith to 80 cols\n\" &lt;maj-k&gt; when on a python file, open the related pydoc documentation\n\" ,v and ,V to show/edit and reload the vimrc configuration file\n\ncolorscheme evening \nsyntax on \" syntax highlighting\nfiletype on \" to consider filetypes ...\nfiletype plugin on \" ... and in plugins\nset directory=~/.vim/swp \" store the .swp files in a specific path\nset expandtab \" enter spaces when tab is pressed\nset tabstop=4 \" use 4 spaces to represent tab\nset softtabstop=4\nset shiftwidth=4 \" number of spaces to use for auto indent\nset autoindent \" copy indent from current line on new line\nset number \" show line numbers\nset backspace=indent,eol,start \" make backspaces more powerful \nset ruler \" show line and column number\nset showcmd \" show (partial) command in status line\nset incsearch \" highlight search\nset noignorecase\nset infercase\nset nowrap\n\n\" shortcuts\nmap &lt;c-n&gt; :tabnew \nmap &lt;silent&gt;&lt;c-e&gt; :NERDTreeToggle &lt;cr&gt;\nmap &lt;silent&gt;&lt;c-p&gt; :TlistToggle &lt;cr&gt;\nnnoremap &lt;a-right&gt; gt\nnnoremap &lt;a-left&gt; gT\ncommand W w !sudo tee % &gt; /dev/null\nmap &lt;buffer&gt; K :execute \"!pydoc \" . expand(\"&lt;cword&gt;\")&lt;CR&gt;\nmap &lt;F2&gt; :set textwidth=80 &lt;cr&gt;\n\" Replace trailing slashes\nmap &lt;F3&gt; :%s/\\s\\+$//&lt;CR&gt;:exe \":echo'trailing slashes removes'\"&lt;CR&gt;\nmap &lt;silent&gt;&lt;F6&gt; :QFix&lt;CR&gt;\n\n\" edit vim quickly\nmap ,v :sp ~/.vimrc&lt;CR&gt;&lt;C-W&gt;_\nmap &lt;silent&gt; ,V :source ~/.vimrc&lt;CR&gt;:filetype detect&lt;CR&gt;:exe \":echo'vimrc reloaded'\"&lt;CR&gt; \n\n\" configure expanding of tabs for various file types\nau BufRead,BufNewFile *.py set expandtab\nau BufRead,BufNewFile *.c set noexpandtab\nau BufRead,BufNewFile *.h set noexpandtab\nau BufRead,BufNewFile Makefile* set noexpandtab\n\n\" remap CTRL+N to CTRL + space\ninoremap &lt;Nul&gt; &lt;C-n&gt;\n\n\" Omnifunc completers\nautocmd FileType python set omnifunc=pythoncomplete#Complete\n\n\" Tlist configuration\nlet Tlist_GainFocus_On_ToggleOpen = 1\nlet Tlist_Close_On_Select = 0\nlet Tlist_Auto_Update = 1\nlet Tlist_Process_File_Always = 1\nlet Tlist_Use_Right_Window = 1\nlet Tlist_WinWidth = 40\nlet Tlist_Show_One_File = 1\nlet Tlist_Show_Menu = 0\nlet Tlist_File_Fold_Auto_Close = 0\nlet Tlist_Ctags_Cmd = '/usr/bin/ctags'\nlet tlist_css_settings = 'css;e:SECTIONS'\n\n\" NerdTree configuration\nlet NERDTreeIgnore = ['\\.pyc$', '\\.pyo$']\n\n\" Highlight more than 80 columns lines on demand\nnnoremap &lt;silent&gt;&lt;F1&gt;\n\\ :if exists('w:long_line_match') &lt;Bar&gt;\n\\ silent! call matchdelete(w:long_line_match) &lt;Bar&gt;\n\\ unlet w:long_line_match &lt;Bar&gt;\n\\ elseif &amp;textwidth &gt; 0 &lt;Bar&gt;\n\\ let w:long_line_match = matchadd('ErrorMsg', '\\%&gt;'.&amp;tw.'v.\\+', -1) &lt;Bar&gt;\n\\ else &lt;Bar&gt;\n\\ let w:long_line_match = matchadd('ErrorMsg', '\\%&gt;80v.\\+', -1) &lt;Bar&gt;\n\\ endif&lt;CR&gt;\n\ncommand -bang -nargs=? QFix call QFixToggle(&lt;bang&gt;0)\nfunction! QFixToggle(forced)\n if exists(\"g:qfix_win\") &amp;&amp; a:forced == 0\n cclose\n unlet g:qfix_win\n else\n copen 10\n let g:qfix_win = bufnr(\"$\")\n endif\nendfunction\n</code></pre>\n" }, { "answer_id": 2989673, "author": "ZyX", "author_id": 273566, "author_profile": "https://Stackoverflow.com/users/273566", "pm_score": 0, "selected": false, "text": "<pre><code>\"{{{1 Защита от множественных загрузок \nif exists(\"b:dollarHOMEslashdotvimrcFileLoaded\")\n finish\nendif\nlet b:dollarHOMEslashdotvimrcFileLoaded=1\n\" set t_Co=8\n\" set t_Sf=[3%p1%dm\n\" set t_Sb=[4%p1%dm\n\"{{{1 Options \n\"{{{2 set \nset nocompatible\nset background=dark\nset display+=lastline\n\"set iminsert=0\n\"set imsearch=0\nset grepprg=grep\\ -nH\\ $*\nset expandtab\nset tabstop=4\nset shiftwidth=4\nset softtabstop=4\nset backspace=indent,eol,start\nset autoindent\nset nosmartindent\nset backup\nset conskey\nset bioskey\nset browsedir=buffer\n\" bomb may work bad\nset nobomb\nexe \"set backupdir=\".$HOME.\"/.vimbackup,.\"\nset backupext=~\nset history=32\nset ruler\nset showcmd\nset hlsearch\nset incsearch\nset nocindent\nset textwidth=80\nset complete=.,i,d,t,w,b,u,k\n\" set conskey\nset noconfirm\nset cscopetag\nset cscopetagorder=1\n\" set copyindent\n\" !may be not safe\nset exrc\nset secure\n\" set foldclose\nset noswapfile\n\" set swapsync=sync\nset fsync\nset guicursor=\"a:block-blinkoff0\"\nset autowriteall\nset hidden\nset nojoinspaces\nset nostartofline\n\" set virtualedit+=onemore\nset lazyredraw\nset visualbell\nset makeef=make.##.err.log\nset modelines=16\nset more\nset virtualedit+=block\nset winaltkeys=no\nset fileencodings=utf-8,cp1251,koi8-r,default\nset encoding=utf-8\nset list\nset listchars=tab:&gt;-,trail:-,nbsp:_\nset magic\nset pastetoggle=&lt;F1&gt;\nset foldmethod=marker\nset wildmenu\nset wildcharm=&lt;Tab&gt;\nset formatoptions=arcoqn12w\n\"set formatoptions+=t\nset scrolloff=2\n\n\"{{{3 define keys\n\"{{{4 get keys from zkbd\nif isdirectory($HOME.\"/.zkbd\") &amp;&amp;\n \\filereadable($HOME.\"/.zkbd/\".$TERM.\"-pc-linux-gnu\")\n let s:keys=split(system(\"cat \".\n \\shellescape($HOME.\"/.zkbd/\".$TERM.\"-pc-linux-gnu\").\n \\\" | grep \\\"^key\\\\\\\\[\\\" | \".\n \\\"sed -re \\\"s/^key\\\\\\\\[([[:alnum:]]*)\\\\\\\\]='(.*)'\\\\$\".\n \\\"/\\\\\\\\1=\\\\\\\\2/g\\\"\"), \"\\\\n\")\n for key in s:keys\n let tmp=split(key, \"=\")\n if tmp[0]=~\"^F\\\\d\\\\+$\"\n execute \"set &lt;\".tmp[0].\"&gt;=\".\n \\substitute(tmp[1], \"\\\\^\\\\[\", \"\\&lt;ESC&gt;\", \"g\")\n endif\n endfor\nendif\n\" function g:DefineKeys()\n \"{{{4 screen\n if 0 &amp;&amp; $_SECONDLAUNCH\n set &lt;F1&gt;=[11~\n set &lt;F2&gt;=[12~\n set &lt;F3&gt;=[13~\n set &lt;F4&gt;=[14~\n set &lt;F5&gt;=[15~\n set &lt;F6&gt;=[17~\n set &lt;F7&gt;=[18~\n set &lt;F8&gt;=[19~\n set &lt;F9&gt;=[20~\n set &lt;F10&gt;=[21~\n set &lt;F11&gt;=[23~\n set &lt;F12&gt;=[24~\n set &lt;S-F1&gt;=[23~\n set &lt;S-F2&gt;=[24~\n set &lt;S-F3&gt;=[25~\n set &lt;S-F4&gt;=[26~\n set &lt;S-F5&gt;=[28~\n set &lt;S-F6&gt;=[29~\n set &lt;S-F7&gt;=[31~\n set &lt;S-F8&gt;=[32~\n set &lt;S-F9&gt;=[33~\n set &lt;S-F10&gt;=[34~\n set &lt;S-F11&gt;=[23$\n set &lt;S-F12&gt;=[24$\n set &lt;HOME&gt;=[7~\n set &lt;END&gt;=[8~\n \"{{{4 xterm \n elseif $TERM==\"xterm\"\n set &lt;M-a&gt;=a\n set &lt;M-b&gt;=b\n set &lt;M-c&gt;=c\n set &lt;M-d&gt;=d\n set &lt;M-e&gt;=e\n set &lt;M-f&gt;=f\n set &lt;M-g&gt;=g\n set &lt;M-h&gt;=h\n set &lt;M-i&gt;=i\n set &lt;M-j&gt;=j\n set &lt;M-k&gt;=k\n set &lt;M-l&gt;=l\n set &lt;M-m&gt;=m\n set &lt;M-n&gt;=n\n set &lt;M-o&gt;=o\n set &lt;M-p&gt;=p\n set &lt;M-q&gt;=q\n set &lt;M-r&gt;=r\n set &lt;M-s&gt;=s\n set &lt;M-t&gt;=t\n set &lt;M-u&gt;=u\n set &lt;M-v&gt;=v\n set &lt;M-w&gt;=w\n set &lt;M-x&gt;=x\n set &lt;M-y&gt;=y\n set &lt;M-z&gt;=z\n \"set &lt;M-SPACE&gt;= \n \"set &lt;Left&gt;=OD\n \"set &lt;S-Left&gt;=O2D\n \"set &lt;C-Left&gt;=O5D\n \"set &lt;Right&gt;=OC\n \"set &lt;S-Right&gt;=O2C\n \"set &lt;C-Right&gt;=O5C\n \"set &lt;Up&gt;=OA\n \"set &lt;S-Up&gt;=O2A\n \"set &lt;C-Up&gt;=O5A\n \"set &lt;Down&gt;=OB\n \"set &lt;S-Down&gt;=O2B\n \"set &lt;C-Down&gt;=O5B\n set &lt;F1&gt;=[11~\n set &lt;F2&gt;=[12~\n set &lt;F3&gt;=[13~\n set &lt;F4&gt;=[14~\n set &lt;F5&gt;=[15~\n set &lt;F6&gt;=[17~\n set &lt;F7&gt;=[18~\n set &lt;F8&gt;=[19~\n set &lt;F9&gt;=[20~\n set &lt;F10&gt;=[21~\n set &lt;F11&gt;=[23~\n set &lt;F12&gt;=[24~\n \"set &lt;C-F1&gt;=\n \"set &lt;C-F2&gt;=\n \"set &lt;C-F3&gt;=\n \"set &lt;C-F4&gt;=\n \"set &lt;C-F5&gt;=[15;5~\n \"set &lt;C-F6&gt;=[17;5~\n \"\n \"set &lt;C-F7&gt;=[18;5~\n \"set &lt;C-F8&gt;=[19;5~\n \"set &lt;C-F9&gt;=[20;5~\n \"set &lt;C-F10&gt;=[21;5~\n \"set &lt;C-F11&gt;=[23;5~\n \"set &lt;C-F12&gt;=[24;5~\n set &lt;S-F1&gt;=[11;2~\n set &lt;S-F2&gt;=[12;2~\n set &lt;S-F3&gt;=[13;2~\n set &lt;S-F4&gt;=[14;2~\n set &lt;S-F5&gt;=[15;2~\n set &lt;S-F6&gt;=[17;2~\n set &lt;S-F7&gt;=[18;2~\n set &lt;S-F8&gt;=[19;2~\n set &lt;S-F9&gt;=[20;2~\n set &lt;S-F10&gt;=[21;2~\n set &lt;S-F11&gt;=[23;2~\n set &lt;S-F12&gt;=[24;2~\n set &lt;END&gt;=OF\n set &lt;S-END&gt;=O2F\n set &lt;S-HOME&gt;=O2H\n set &lt;HOME&gt;=OH\n set &lt;DEL&gt;=\n \" set &lt;PageUp&gt;=[5~\n \" set &lt;PageDown&gt;=[6~\n \" noremap &lt;DEL&gt;\n \" inoremap &lt;DEL&gt;\n \" cnoremap &lt;DEL&gt;\n set &lt;S-Del&gt;=[3;2~\n \" set &lt;C-Del&gt;=[3;5~\n \" set &lt;M-Del&gt;=[3;3~\n \"{{{4 rxvt --- aterm\n elseif $TERM==\"rxvt\"\n set &lt;M-a&gt;=a\n set &lt;M-b&gt;=b\n set &lt;M-c&gt;=c\n set &lt;M-d&gt;=d\n set &lt;M-e&gt;=e\n set &lt;M-f&gt;=f\n set &lt;M-g&gt;=g\n set &lt;M-h&gt;=h\n set &lt;M-i&gt;=i\n set &lt;M-j&gt;=j\n set &lt;M-k&gt;=k\n set &lt;M-l&gt;=l\n set &lt;M-m&gt;=m\n set &lt;M-n&gt;=n\n set &lt;M-o&gt;=o\n set &lt;M-p&gt;=p\n set &lt;M-q&gt;=q\n set &lt;M-r&gt;=r\n set &lt;M-s&gt;=s\n set &lt;M-t&gt;=t\n set &lt;M-u&gt;=u\n set &lt;M-v&gt;=v\n set &lt;M-w&gt;=w\n set &lt;M-x&gt;=x\n set &lt;M-y&gt;=y\n set &lt;M-z&gt;=z\n set &lt;F1&gt;=OP\n set &lt;F2&gt;=OQ\n set &lt;F3&gt;=OR\n set &lt;F4&gt;=OS\n set &lt;F5&gt;=[15~\n set &lt;F6&gt;=[17~\n set &lt;F7&gt;=[18~\n set &lt;F8&gt;=[19~\n set &lt;F9&gt;=[20~\n set &lt;F10&gt;=[21~\n set &lt;F11&gt;=[23~\n set &lt;F12&gt;=[24~\n set &lt;S-F1&gt;=[23~\n set &lt;S-F2&gt;=[24~\n set &lt;S-F3&gt;=[25~\n set &lt;S-F4&gt;=[26~\n set &lt;S-F5&gt;=[28~\n set &lt;S-F6&gt;=[29~\n set &lt;S-F7&gt;=[31~\n set &lt;S-F8&gt;=[32~\n set &lt;S-F9&gt;=[33~\n set &lt;S-F10&gt;=[34~\n set &lt;S-F11&gt;=[23$\n set &lt;S-F12&gt;=[24$\n \" set &lt;C-S-F2&gt;=[24^\n \" set &lt;C-S-F3&gt;=[25^\n \" set &lt;C-S-F4&gt;=[26^\n \" set &lt;C-S-F5&gt;=[28^\n \" set &lt;C-S-F6&gt;=[29^\n \" set &lt;C-S-F7&gt;=[31^\n \" set &lt;C-S-F8&gt;=[32^\n \" set &lt;C-S-F9&gt;=[33^\n \" set &lt;C-S-F10&gt;=[34^\n \" set &lt;C-S-F11&gt;=[23@\n \" set &lt;C-S-F12&gt;=[24@\n \" set &lt;M-F5&gt;=&lt;F5&gt;\n \" set &lt;M-F6&gt;=&lt;F6&gt;\n \" set &lt;M-F7&gt;=&lt;F7&gt;\n \" set &lt;M-F8&gt;=&lt;F8&gt;\n \" set &lt;M-F9&gt;=&lt;F9&gt;\n \" set &lt;M-F10&gt;=&lt;F10&gt;\n \" set &lt;M-F11&gt;=&lt;F11&gt;\n \" set &lt;M-F12&gt;=&lt;F12&gt;\n \" set &lt;M-S-F5&gt;=&lt;S-F5&gt;\n \" set &lt;M-S-F6&gt;=&lt;S-F6&gt;\n \" set &lt;M-S-F7&gt;=&lt;S-F7&gt;\n \" set &lt;M-S-F8&gt;=&lt;S-F8&gt;\n \" set &lt;M-S-F9&gt;=&lt;S-F9&gt;\n \" set &lt;M-S-F10&gt;=&lt;S-F10&gt;\n \" set &lt;M-S-F11&gt;=&lt;S-F11&gt;\n \" set &lt;M-S-F12&gt;=&lt;S-F12&gt;\n \"{{{4 rxvt-unicode --- urxvt\n elseif $TERM==\"rxvt-unicode\"\n set &lt;M-a&gt;=a\n set &lt;M-b&gt;=b\n set &lt;M-c&gt;=c\n set &lt;M-d&gt;=d\n set &lt;M-e&gt;=e\n set &lt;M-f&gt;=f\n set &lt;M-g&gt;=g\n set &lt;M-h&gt;=h\n set &lt;M-i&gt;=i\n set &lt;M-j&gt;=j\n set &lt;M-k&gt;=k\n set &lt;M-l&gt;=l\n set &lt;M-m&gt;=m\n set &lt;M-n&gt;=n\n set &lt;M-o&gt;=o\n set &lt;M-p&gt;=p\n set &lt;M-q&gt;=q\n set &lt;M-r&gt;=r\n set &lt;M-s&gt;=s\n set &lt;M-t&gt;=t\n set &lt;M-u&gt;=u\n set &lt;M-v&gt;=v\n set &lt;M-w&gt;=w\n set &lt;M-x&gt;=x\n set &lt;M-y&gt;=y\n set &lt;M-z&gt;=z\n set &lt;F1&gt;=[11~\n set &lt;F2&gt;=[12~\n set &lt;F3&gt;=[13~\n set &lt;F4&gt;=[14~\n set &lt;F5&gt;=[15~\n set &lt;F6&gt;=[17~\n set &lt;F7&gt;=[18~\n set &lt;F8&gt;=[19~\n set &lt;F9&gt;=[20~\n set &lt;F10&gt;=[21~\n set &lt;F11&gt;=[23~\n set &lt;F12&gt;=[24~\n \" fluxbox!&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n set &lt;S-F1&gt;=[23~\n set &lt;S-F2&gt;=[24~\n set &lt;S-F3&gt;=[25~\n set &lt;S-F4&gt;=[26~\n set &lt;S-F5&gt;=[28~\n set &lt;S-F6&gt;=[29~\n set &lt;S-F7&gt;=[31~\n set &lt;S-F8&gt;=[32~\n set &lt;S-F9&gt;=[33~\n set &lt;S-F10&gt;=[34~\n set &lt;S-F11&gt;=[23$\n set &lt;S-F12&gt;=[24$\n \" set &lt;C-F1&gt;=[11^\n \" set &lt;C-F2&gt;=[12^\n \" set &lt;C-F3&gt;=[13^\n \" set &lt;C-F4&gt;=[14^\n \" set &lt;C-F5&gt;=[15^\n \" set &lt;C-F6&gt;=[17^\n \" set &lt;C-F7&gt;=[18^\n \" set &lt;C-F8&gt;=[19^\n \" set &lt;C-F9&gt;=[20^\n \" set &lt;C-F10&gt;=[21^\n \" set &lt;C-F11&gt;=[23^\n \" set &lt;C-F12&gt;=[24^\n \" openbox!&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n \" set &lt;S-F1&gt;=[23~\n \" set &lt;S-F2&gt;=[24~\n \" set &lt;S-F3&gt;=[25~\n \" set &lt;S-F4&gt;=[26~\n \" set &lt;S-F5&gt;=[28~\n \" set &lt;S-F6&gt;=[29~\n \" set &lt;S-F7&gt;=[31~\n \" set &lt;S-F8&gt;=[32~\n \" set &lt;S-F9&gt;=[33~\n \" set &lt;S-F10&gt;=[34~\n \" set &lt;S-F11&gt;=[23$\n \" set &lt;S-F12&gt;=[24$\n \" set &lt;C-S-F2&gt;=[24^\n \" set &lt;C-S-F3&gt;=[25^\n \" set &lt;C-S-F4&gt;=[26^\n \" set &lt;C-S-F5&gt;=[28^\n \" set &lt;C-S-F6&gt;=[29^\n \" set &lt;C-S-F7&gt;=[31^\n \" set &lt;C-S-F8&gt;=[32^\n \" set &lt;C-S-F9&gt;=[33^\n \" set &lt;C-S-F10&gt;=[34^\n \" set &lt;C-S-F11&gt;=[23@\n \" set &lt;C-S-F12&gt;=[24@\n \" set &lt;M-F5&gt;=&lt;F5&gt;\n \" set &lt;M-F6&gt;=&lt;F6&gt;\n \" set &lt;M-F7&gt;=&lt;F7&gt;\n \" set &lt;M-F8&gt;=&lt;F8&gt;\n \" set &lt;M-F9&gt;=&lt;F9&gt;\n \" set &lt;M-F10&gt;=&lt;F10&gt;\n \" set &lt;M-F11&gt;=&lt;F11&gt;\n \" set &lt;M-F12&gt;=&lt;F12&gt;\n \" set &lt;M-S-F5&gt;=&lt;S-F5&gt;\n \" set &lt;M-S-F6&gt;=&lt;S-F6&gt;\n \" set &lt;M-S-F7&gt;=&lt;S-F7&gt;\n \" set &lt;M-S-F8&gt;=&lt;S-F8&gt;\n \" set &lt;M-S-F9&gt;=&lt;S-F9&gt;\n \" set &lt;M-S-F10&gt;=&lt;S-F10&gt;\n \" set &lt;M-S-F11&gt;=&lt;S-F11&gt;\n \" set &lt;M-S-F12&gt;=&lt;S-F12&gt;\n endif\n \" autocmd! DefineKeys\n\" endfunction\n\" \"{{{4 autocmd \n\" augroup DefineKeys\n\" autocmd BufEnter * call g:DefineKeys()\n\" augroup END\n\n\"{{{2 filetipe \nfiletype plugin indent on\nsyntax on\n\n\"{{{2 let \n\"{{{ NERDCommenter \nlet NERDShutUp=1\nlet NERDSpaceDelims=1\n\"}}}\nlet g:c_syntax_for_h=1\nlet g:xml_syntax_folding=1\nlet paste_mode=0 \" 0 = normal, 1 = paste\n\"{{{3 keys if $TERM==\"rxvt-unicode\"\n \" \" fluxbox!&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n \" let g:C_F1=\"\\&lt;ESC&gt;[11^\"\n \" let g:C_F2=\"\\&lt;ESC&gt;[12^\"\n \" let g:C_F3=\"\\&lt;ESC&gt;[13^\"\n \" let g:C_F4=\"\\&lt;ESC&gt;[14^\"\n \" let g:C_F5=\"\\&lt;ESC&gt;[15^\"\n \" let g:C_F6=\"\\&lt;ESC&gt;[17^\"\n \" let g:C_F7=\"\\&lt;ESC&gt;[18^\"\n \" let g:C_F8=\"\\&lt;ESC&gt;[19^\"\n \" let g:C_F9=\"\\&lt;ESC&gt;[20^\"\n \" let g:C_F10=\"\\&lt;ESC&gt;[21^\"\n \" let g:C_F11=\"\\&lt;ESC&gt;[23^\"\n \" let g:C_F12=\"\\&lt;ESC&gt;[24^\"\n \" let g:M_S_F1=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[23$\"\n \" let g:M_S_F2=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[24$\"\n \" let g:M_S_F3=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[25$\"\n \" let g:M_S_F4=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[26$\"\n \" let g:M_S_F5=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[28$\"\n \" let g:M_S_F6=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[29$\"\n \" let g:M_S_F7=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[31$\"\n \" let g:M_S_F8=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[32$\"\n \" let g:M_S_F9=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[33$\"\n \" let g:M_S_F10=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[34$\"\n \" let g:M_S_F11=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[23$\"\n \" let g:M_S_F12=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[24$\"\n \" let g:M_C_F1=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[11^\"\n \" let g:M_C_F2=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[12^\"\n \" let g:M_C_F3=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[13^\"\n \" let g:M_C_F4=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[14^\"\n \" let g:M_C_F5=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[15^\"\n \" let g:M_C_F6=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[17^\"\n \" let g:M_C_F7=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[18^\"\n \" let g:M_C_F8=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[19^\"\n \" let g:M_C_F9=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[20^\"\n \" let g:M_C_F10=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[21^\"\n \" let g:M_C_F11=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[23^\"\n \" let g:M_C_F12=\"\\&lt;ESC&gt;\\&lt;ESC&gt;[24^\"\n\" endif\n\"{{{3 Настройки :TOhtml \nlet html_number_lines=1\n\" let html_ignore_folding=1\nlet html_use_css=1\nlet html_no_pre=0\nlet use_xhtml=1\n\"{{{3 Предотвратить загрузку \nlet loaded_cmdalias=0\n\"{{{3 Mine \n\" let g:kmaps={\"en\": \"\", \"ru\": \"russian-dvp\"}\n\n\"{{{1 Syntax \nhighlight TooLongLine term=reverse ctermfg=Yellow ctermbg=Red\n2match TooLongLine /\\S\\%&gt;81v/\n\n\"{{{1 Autocommands \nautocmd VimLeavePre * silent mksession! ~/.vim/lastSession.vim\nau BufWritePost * if getline(1) =~ \"^#!\" | execute \"silent! !chmod a+x %\" | \n \\endif\nautocmd BufRead,BufWinEnter * let &amp;l:modifiable=(!(&amp;ro &amp;&amp; !&amp;bt==\"quickfix\"))\n\n\"{{{1 Digraphs \ndigraphs ca 94 \"^\ndigraphs ga 96 \"`\ndigraphs ti 126 \"~\n\n\"{{{1 Menus \n\" menu Encoding.koi8-r :e ++enc=8bit-koi8-r&lt;CR&gt;\n\" menu Encoding.windows-1251 :e ++enc=8bit-cp1251&lt;CR&gt;\n\" menu Encoding.ibm-866 :e ++enc=8bit-ibm866&lt;CR&gt;\n\" menu Encoding.utf-8 :e ++enc=2byte-utf-8&lt;CR&gt;\n\" menu Encoding.ucs-2le :e ++enc=ucs-2le&lt;CR&gt;\n\n\"{{{1 Команды \nfunction s:Substitute(sstring, line1, line2)\n execute a:line1.\",\".a:line2.\"!perl -pi -e 'use encoding \\\"utf8\\\"; s'\".\n \\escape(shellescape(a:sstring), '%!').\n \\\" 2&gt;/dev/null\"\nendfunction\ncommand -range=% -nargs=+ S call s:Substitute(&lt;q-args&gt;, &lt;line1&gt;, &lt;line2&gt;)\n\n\"{{{1 Mappings \n\"{{{2 Menu mappings \n\n\"{{{2 function mappings \n\"\n\"{{{3 Function Eatchar \nfunction Eatchar(pat)\n let l:pat=((a:pat==\"\")?(\"*\"):(a:pat))\n let c = nr2char(getchar(0))\n return (c =~ l:pat) ? '' : c\nendfunction\n\"{{{3 CleverTab - tab to autocomplete and move indent \nfunction CleverTab()\n if strpart( getline('.'), col('.')-2, 1) =~ '^\\k$'\n return \"\\&lt;C-n&gt;\"\n else\n return \"\\&lt;Tab&gt;\"\n endif\nendfunction\ninoremap &lt;Tab&gt; &lt;C-R&gt;=CleverTab()&lt;CR&gt;\n\"{{{3 Keymap switch \nfunction! SwitchKeymap(kmaps, knum)\n let s:kmapvals=values(a:kmaps)\n if a:knum==\"+\"\n let s:ki=index(s:kmapvals, &amp;keymap)\n echo s:ki\n if s:ki==-1\n let &amp;keymap=s:kmapvals[0]\n return\n elseif s:ki&gt;=len(a:kmaps)-1\n let &amp;keymap=s:kmapvals[0]\n return\n endif\n let &amp;keymap=s:kmapvals[s:ki+1]\n return\n elseif has_key(a:kmaps, a:knum)\n let &amp;keymap=a:kmaps[a:knum]\n return\n endif\n let s:ki=0\n for val in s:kmapvals\n if s:ki==a:knum\n let &amp;keymap=val\n return\n endif\n let s:ki+=1\n endfor\n let &amp;keymap=s:kmapvals[0]\nendfunction\n\" inoremap &lt;S-Tab&gt; &lt;C-\\&gt;&lt;C-o&gt;:call&lt;SPACE&gt;SwitchKeymap(g:kmaps,&lt;SPACE&gt;\"+\")&lt;C-m&gt;\n\n\n\"{{{2 ToggleVerbose \nfunction! ToggleVerbose()\n let g:verboseflag = !g:verboseflag\n if g:verboseflag\n exe \"set verbosefile=\".$HOME.\"/.logs/vim/verbose.log\n set verbose=15\n else\n set verbose=0\n set verbosefile=\n endif\nendfunction\nnoremap &lt;F4&gt;sv :call&lt;SPACE&gt;ToggleVerbose()\ninoremap &lt;F4&gt;sv &lt;C-o&gt;:call&lt;SPACE&gt;ToggleVerbose()\n\n\"{{{2 Other mappings \n\"{{{3 &lt;.*F12&gt; mappings - for some browsing \n noremap &lt;F12&gt; :TlistToggle&lt;CR&gt;\ninoremap &lt;F12&gt; &lt;C-O&gt;:TlistToggle&lt;CR&gt;\ninoremap &lt;S-F12&gt; &lt;C-O&gt;:BufExplorer&lt;CR&gt;\n noremap &lt;S-F12&gt; :BufExplorer&lt;CR&gt;\ninoremap &lt;M-F12&gt; &lt;C-O&gt;:NERDTreeToggle&lt;CR&gt;\n noremap &lt;M-F12&gt; :NERDTreeToggle&lt;CR&gt;\n\"{{{3 yank/paste \nvnoremap &lt;C-Insert&gt; \"+y\nnnoremap &lt;S-Insert&gt; \"+p\ninoremap &lt;S-Insert&gt; &lt;C-o&gt;&lt;S-Insert&gt;\nvnoremap p \"_da&lt;C-r&gt;&lt;C-r&gt;\"&lt;CR&gt;&lt;ESC&gt;\n\"{{{3 Motions \n\"{{{4 Left/Right replace \ncnoremap &lt;C-b&gt; &lt;Left&gt;\ncnoremap &lt;C-f&gt; &lt;Right&gt;\ninoremap &lt;C-b&gt; &lt;C-\\&gt;&lt;C-o&gt;h\ninoremap &lt;C-f&gt; &lt;C-o&gt;a\n\ncnoremap &lt;M-b&gt; &lt;C-Right&gt;\ninoremap &lt;M-b&gt; &lt;C-o&gt;w\ninoremap &lt;M-f&gt; &lt;C-o&gt;b\ncnoremap &lt;M-f&gt; &lt;C-Left&gt;\n\"{{{4 Page Up/Down \nnnoremap &lt;C-b&gt; &lt;C-U&gt;&lt;C-U&gt;\ninoremap &lt;PageUp&gt; &lt;C-O&gt;&lt;C-U&gt;&lt;C-O&gt;&lt;C-U&gt;\nnnoremap &lt;C-f&gt; &lt;C-D&gt;&lt;C-D&gt;\ninoremap &lt;PageDown&gt; &lt;C-O&gt;&lt;C-D&gt;&lt;C-O&gt;&lt;C-D&gt;\n\"{{{4 Up/Down \ninoremap &lt;C-G&gt; &lt;C-\\&gt;&lt;C-o&gt;gk\ninoremap &lt;Up&gt; &lt;C-\\&gt;&lt;C-o&gt;gk\ninoremap &lt;Down&gt; &lt;C-\\&gt;&lt;C-o&gt;gj\ninoremap &lt;C-l&gt; &lt;C-\\&gt;&lt;C-o&gt;gj\nnnoremap &lt;Down&gt; gj\nvnoremap &lt;Down&gt; gj\nnnoremap j gj\nvnoremap j gj\nnnoremap gj j\nvnoremap gj j\nnnoremap gk k\nvnoremap gk k\nnnoremap k gk\nvnoremap k gk\nnnoremap &lt;Up&gt; gk\nvnoremap &lt;Up&gt; gk\n\"{{{4 Smart &lt;HOME&gt; and &lt;END&gt; \n\n \" imap &lt;HOME&gt; &lt;C-o&gt;g^\n \" imap &lt;C-O&gt;g^&lt;HOME&gt; &lt;C-o&gt;^\n\" inoremap &lt;C-o&gt;^&lt;HOME&gt; &lt;C-o&gt;0\n \" imap &lt;END&gt; &lt;C-o&gt;g$\n\" inoremap &lt;C-o&gt;g$&lt;END&gt; &lt;C-o&gt;$\n \" nmap &lt;HOME&gt; &lt;C-o&gt;g^\n \" nmap &lt;C-O&gt;g^&lt;HOME&gt; ^\n\" nnoremap &lt;C-o&gt;^&lt;HOME&gt; 0\n \" nmap &lt;END&gt; g$\n\" nnoremap &lt;C-o&gt;g$&lt;END&gt; $\n\"{{{3 &lt;F3&gt; and searching \n noremap &lt;F3&gt; :nohl&lt;CR&gt;\ninoremap &lt;S-F3&gt; &lt;C-o&gt;:nohl&lt;CR&gt;\ninoremap &lt;F3&gt; &lt;C-o&gt;n\n\"{{{3 &lt;F2&gt; for saving, &lt;F10&gt; for exiting \n noremap &lt;F2&gt; :up&lt;CR&gt;\ninoremap &lt;F2&gt; &lt;C-o&gt;:up&lt;CR&gt;\ninoremap &lt;F10&gt; &lt;ESC&gt;ZZ\n noremap &lt;F10&gt; &lt;ESC&gt;ZZ\ninoremap &lt;S-F10&gt; &lt;ESC&gt;:q!&lt;CR&gt;\n noremap &lt;S-F10&gt; :q!&lt;CR&gt;\ninoremap &lt;C-F10&gt; &lt;ESC&gt;:silent&lt;SPACE&gt;mksession&lt;SPACE&gt;session.vim&lt;CR&gt;:wq!\n noremap &lt;C-F10&gt; :silent&lt;SPACE&gt;mksession&lt;SPACE&gt;session.vim&lt;CR&gt;:wq!\n\"{{{3 Something \ninoremap &lt;C-z&gt; &lt;C-o&gt;u\n noremap &lt;F1&gt; :set paste!&lt;C-m&gt;\ninoremap &lt;C-^&gt; &lt;C-O&gt;&lt;C-^&gt;\ninoremap &lt;C-d&gt; &lt;Del&gt;\ncnoremap &lt;C-d&gt; &lt;Del&gt;\n\"{{{3 &lt;C-j&gt; \ninoremap &lt;C-j&gt;j &lt;C-o&gt;:bn&lt;CR&gt;\ninoremap &lt;C-j&gt;J &lt;C-o&gt;:bN&lt;CR&gt;\n noremap &lt;C-j&gt;j :bn&lt;CR&gt;\n noremap &lt;C-j&gt;J :bN&lt;CR&gt;\n\"{{{3 for visual \ninoremap &lt;S-Left&gt; &lt;C-o&gt;vge\ninoremap &lt;S-Up&gt; &lt;C-o&gt;vk\ninoremap &lt;S-Down&gt; &lt;C-o&gt;vj\ninoremap &lt;S-Right&gt; &lt;C-o&gt;ve\ninoremap &lt;S-End&gt; &lt;C-o&gt;v$\ninoremap &lt;S-Home&gt; &lt;C-o&gt;v$o^\nvnoremap A &lt;C-c&gt;i\n\"{{{3 &lt;F4&gt; \n\"{{{4 &lt;F4&gt; folds \n noremap &lt;F4&gt;{ a{{{&lt;ESC&gt;\ninoremap &lt;F4&gt;{ {{{\n noremap &lt;F4&gt;} a}}}&lt;ESC&gt;\ninoremap &lt;F4&gt;} }}}\ninoremap &lt;F4&gt;[ &lt;C-o&gt;o{{{&lt;C-o&gt;:call NERDComment(0,\"norm\")&lt;C-m&gt;\n noremap &lt;F4&gt;[ o{{{&lt;C-o&gt;:call NERDComment(0,\"norm\")&lt;C-m&gt;\ninoremap &lt;F4&gt;] &lt;C-o&gt;o}}}&lt;C-o&gt;:call NERDComment(0,\"norm\")&lt;C-m&gt;\n noremap &lt;F4&gt;] o}}}&lt;C-o&gt;:call NERDComment(0,\"norm\")&lt;C-m&gt;\n\"{{{4 &lt;F4&gt; folds \ninoremap &lt;F4&gt;f &lt;C-o&gt;za&lt;C-o&gt;j&lt;C-o&gt;^\n noremap &lt;F4&gt;f zaj\n\"{{{4 &lt;F4&gt; yank/paste/delete \ninoremap &lt;F4&gt;p &lt;C-o&gt;p\ninoremap &lt;F4&gt;gp &lt;C-o&gt;\"+p\ninoremap &lt;F4&gt;y( &lt;C-o&gt;ya)\ninoremap &lt;F4&gt;yl &lt;C-o&gt;yy\ninoremap &lt;F4&gt;gy( &lt;C-o&gt;\"+ya)\ninoremap &lt;F4&gt;gyl &lt;C-o&gt;\"+yy\ninoremap &lt;F4&gt;P &lt;C-o&gt;P\ninoremap &lt;F4&gt;d( &lt;C-o&gt;da)\ninoremap &lt;F4&gt;dl &lt;C-o&gt;dd\n\"{{{4 &lt;F4&gt; frequently used expressions \ninoremap &lt;F4&gt;c \\033[m&lt;C-/&gt;&lt;C-o&gt;h\n\"{{{4 &lt;F4&gt; alternate \n imap &lt;F4&gt;a &lt;C-o&gt;:A&lt;C-m&gt;\n map &lt;F4&gt;a :A&lt;C-m&gt;\n\"}}}\n\"}}}\n\"{{{3 «,» \n\"\n\" &amp;lower\n\" &amp;upper\n\" &amp;1st\n\" &amp;2nd\n\" &amp;both lower and upper (or both 1st and 2nd)\n\" prefixed with &amp;e\n\" prefixed with &amp;E\n\" is &amp;Prefix for smth\n\" &amp;prefixed with (([what]p(prefix)))\n\" -: nothing\n\" +: added\n\" /: replaced\n\" [invc]: for modes insert, normal, visual, command (for insert mode if\n\" omitted)\n\" | vimrc | | | | |\n\" | i n v c | tex | c | html | vim | other\n\" ----+-----------------+--------+--------+-------+-------+---------------------\n\" a | l l | | | | |\n\" b | b - - b | +Pu | +eb+Eb | | |\n\" c | l b | +u | | | |\n\" d | b b b | | | | |\n\" e | Pl Pl | | +l+Pu | | |\n\" f | b(eb) - - b | | | | /u | zsh:+el\n\" g | | | | | |\n\" h | b(el) - - b(el) | /u | | | | sh:/u+eu\n\" i | l l - l | | | | |\n\" j | | | | | |\n\" k | | | | | |\n\" l | l | +Pu | | | | make:+u\n\" m | l l | /[in]m | +u | | |\n\" n | l | /l+u | | /l | /l |\n\" o | l | | | | |\n\" p | - - - b | +el | | | |\n\" q | b(eb) | +Pl | | | |\n\" r | | +u | | | |\n\" s | l(el) - - b | +u | +u | | +u+eu | make,perl,zsh:+u\n\" t | b(el) - - l | +eu | | | |\n\" u | l - - b | | | +u | +u |\n\" v | | | | | |\n\" w | b - - b | | | | |\n\" x | | | | | |\n\" y | l l l | | | | |\n\" z | | | | | |\n\" ' \" | b | /b | | | |\n\" ; : | 1 | | | | |\n\" , . | b 2 - 1 | | | +e2 | |\n\" ? ! | | | | | |\n\" &lt; &gt; | | +b | | +b+eb | +1 |\n\" - _ | | +1 | | +b | |\n\" @ / | b | | | | |\n\" = | | | | | |\n\"\n\"{{{4 insert \ninoremap ,&lt;SPACE&gt; ,&lt;SPACE&gt;\ninoremap ,&lt;Esc&gt; ,\ninoremap ,&lt;BS&gt; &lt;Nop&gt;\ninoremap ,ef &lt;C-o&gt;I{&lt;C-m&gt;&lt;C-o&gt;o}&lt;C-o&gt;O\ninoremap ,eF &lt;C-m&gt;{&lt;C-m&gt;&lt;C-o&gt;o}&lt;C-o&gt;O\ninoremap ,F {&lt;C-o&gt;o}&lt;C-o&gt;O\ninoremap ,f {}&lt;C-\\&gt;&lt;C-o&gt;h\ninoremap ,h []&lt;C-\\&gt;&lt;C-o&gt;h\ninoremap ,s ()&lt;C-\\&gt;&lt;C-o&gt;h\ninoremap ,u &lt;LT&gt;&gt;&lt;C-\\&gt;&lt;C-o&gt;h\ninoremap ,es (&lt;C-\\&gt;&lt;C-o&gt;E&lt;C-o&gt;a)&lt;C-\\&gt;&lt;C-o&gt;h\ninoremap ,H [[::]]&lt;C-o&gt;F:\ninoremap ,eh [::]&lt;C-o&gt;F:\ninoremap ,, \\\ninoremap ,. &lt;C-o&gt;==\ninoremap ,w &lt;C-o&gt;w\ninoremap ,W &lt;C-o&gt;W\ninoremap ,b &lt;C-o&gt;b\ninoremap ,B &lt;C-o&gt;B\ninoremap ,a &lt;C-o&gt;A\ninoremap ,i &lt;C-o&gt;I\ninoremap ,l &lt;C-o&gt;o\ninoremap ,o &lt;C-o&gt;O\ninoremap ,dw &lt;C-o&gt;\"zdaw\ninoremap ,p &lt;C-o&gt;\"zp\ninoremap ,P &lt;C-o&gt;\"zP\ninoremap ,yw &lt;C-o&gt;\"zyaw\ninoremap ,y &lt;C-o&gt;\"zy\ninoremap ,d &lt;C-o&gt;\"zd\ninoremap ,D &lt;C-o&gt;\"_d\ninoremap ,c &lt;C-o&gt;:call&lt;SPACE&gt;NERDComment(0,\"toggle\")&lt;C-m&gt;\ninoremap ,ec &lt;C-o&gt;:call&lt;SPACE&gt;NERDComment(0,\"toEOL\")&lt;C-m&gt;\ninoremap ,t &lt;C-r&gt;=Tr3transliterate(input(\"Translit: \"))&lt;C-m&gt;\ninoremap ,T &lt;C-o&gt;b&lt;C-o&gt;\"tdiw&lt;C-r&gt;&lt;C-r&gt;=Tr3transliterate(@t)&lt;C-m&gt;\ninoremap ,et &lt;C-o&gt;B&lt;C-o&gt;\"tdiW&lt;C-r&gt;&lt;C-r&gt;=Tr3transliterate(@t)&lt;C-m&gt;\ninoremap ,/ &lt;C-x&gt;&lt;C-f&gt;\ninoremap ,@ &lt;C-o&gt;:w!&lt;C-m&gt;\ninoremap ,; &lt;C-o&gt;%\ninoremap ,m &lt;C-\\&gt;&lt;C-o&gt;:call system(\"make &amp;\")&lt;C-m&gt;\ninoremap ,n \\&lt;C-m&gt;\ninoremap ,q «»&lt;C-\\&gt;&lt;C-o&gt;h\ninoremap ,Q „“&lt;C-\\&gt;&lt;C-o&gt;h\ninoremap ,eq “”&lt;C-\\&gt;&lt;C-o&gt;h\ninoremap ,eQ ‘’&lt;C-\\&gt;&lt;C-o&gt;h\ninoremap ,\" \"\"&lt;C-\\&gt;&lt;C-o&gt;h\ninoremap ,' ''&lt;C-\\&gt;&lt;C-o&gt;h\n\n\"{{{4 visual \nvnoremap ,y \"zy\nvnoremap ,d \"zd\nvnoremap ,D \"_d\nvnoremap ,p \"zp\n\n\"{{{4 command \ncnoremap ,s ()&lt;Left&gt;\ncnoremap ,S \\(\\)&lt;Left&gt;&lt;Left&gt;\ncnoremap ,U \\&lt;LT&gt;\\&gt;&lt;Left&gt;&lt;Left&gt;\ncnoremap ,u &lt;LT&gt;&gt;&lt;Left&gt;\ncnoremap ,F \\{}&lt;Left&gt;\ncnoremap ,f {}&lt;Left&gt;\ncnoremap ,h []&lt;Left&gt;\ncnoremap ,H [[::]]&lt;Left&gt;&lt;Left&gt;&lt;Left&gt;\ncnoremap ,eh [::]&lt;Left&gt;&lt;Left&gt;\ncnoremap ,i &lt;Home&gt;\ncnoremap ,a &lt;End&gt;\ncnoremap ,, \\\ncnoremap ,. &lt;C-r&gt;:\ncnoremap ,p &lt;C-r&gt;\"\ncnoremap ,P &lt;C-r&gt;+\ncnoremap ,z &lt;C-r&gt;z\ncnoremap ,t &lt;C-r&gt;=Tr3transliterate(input(\"Translit: \"))&lt;C-m&gt;\ncnoremap ,b &lt;C-Left&gt;\ncnoremap ,w &lt;C-Right&gt;\ncnoremap ,B &lt;C-Left&gt;\ncnoremap ,W &lt;C-Right&gt;\n\n\"{{{4 normal \nnnoremap ,C :!\nnnoremap ,c :call&lt;SPACE&gt;NERDComment(0,\"toggle\")&lt;C-m&gt;\nnnoremap ,d \"_\nnnoremap ,D \"_d\nnnoremap ,m :call system(\"make &amp;\")&lt;C-m&gt;\nnnoremap ,a $\nnnoremap ,i ^\nnnoremap ,, ==\nnnoremap ,y \"zy\nnnoremap ,p \"zp\nnnoremap ,P \"zP\n\n\"{{{1 Functions \n\n\"{{{1 \nnohlsearch\n\" vim: ft=vim:fenc=utf-8:ts=4\n</code></pre>\n" }, { "answer_id": 3688637, "author": "dash-tom-bang", "author_id": 65845, "author_profile": "https://Stackoverflow.com/users/65845", "pm_score": 1, "selected": false, "text": "<p>When I launch gVim without arguments, I want it to open in my \"project\" directory, so that I can do <code>:find</code> etc. However, when I launch it with files, I don't want it to switch directory, I want it to stay right there (in part, so that it opens the file I want it to open!).</p>\n\n<pre><code>if argc() == 0\n cd $PROJECT_DIR\nendif\n</code></pre>\n\n<p>So that I can use <code>:find</code> from any file in the current project, I set up my path to look up the directory tree 'til it finds <code>src</code> or <code>scripts</code> and descends into those, at least until it hits <code>c:\\work</code> which is the root of all of my projects. This allows me to open files in a project that is not current (i.e. <code>PROJECT_DIR</code> above specifies a different directory).</p>\n\n<pre><code>set path+=src/**;c:/work,scripts/**;c:/work\n</code></pre>\n\n<p>So that I get automatic saving and reloading, and exiting of insert mode when gVim loses focus, as well as automatic checkout from Perforce when editing a readonly file...</p>\n\n<pre><code>augroup AutoSaveGroup\n autocmd!\n autocmd FocusLost *.cpp,*.h,*.cs,*.rad*,Jam*,*.py,*.bat,*.mel wa\n autocmd FileChangedRO *.cpp,*.h,*.cs,*.rad*,Jam*,*.py,*.bat,*.mel silent !p4 edit %:p\n autocmd FileChangedRO *.cpp,*.h,*.cs,*.rad*,Jam*,*.py,*.bat,*.mel w!\naugroup END\n\naugroup OutOfInsert\n autocmd!\n autocmd FocusLost * call feedkeys(\"\\&lt;C-\\&gt;\\&lt;C-N&gt;\")\naugroup END\n</code></pre>\n\n<p>And finally, switch to the directory of the file in the current buffer so that it's easy to <code>:e</code> other files in that directory.</p>\n\n<pre><code>augroup MiscellaneousTomStuff\n autocmd!\n \" make up for the deficiencies in 'autochdir'\n autocmd BufEnter * silent! lcd %:p:h:gs/ /\\\\ /\naugroup END\n</code></pre>\n" }, { "answer_id": 3791030, "author": "mike3996", "author_id": 308668, "author_profile": "https://Stackoverflow.com/users/308668", "pm_score": 3, "selected": false, "text": "<p>My 242-line <code>.vimrc</code> is not that interesting, but since nobody mentioned it, I felt like I must share the two most important mappings that have enhanced my workflow besides the default mappings:</p>\n\n<pre><code>map &lt;C-j&gt; :bprev&lt;CR&gt;\nmap &lt;C-k&gt; :bnext&lt;CR&gt;\nset hidden \" this will go along\n</code></pre>\n\n<p>Seriously, switching buffers is <strong>the</strong> thing to do very often. Windows, sure, but everything doesn't fit the screen so nicely.</p>\n\n<p>Similar set of maps for quick browsing of errors (see quickfix) and grep results:</p>\n\n<pre><code>map &lt;C-n&gt; :cn&lt;CR&gt;\nmap &lt;C-m&gt; :cp&lt;CR&gt;\n</code></pre>\n\n<p>Simple, effortless and efficient.</p>\n" }, { "answer_id": 3871787, "author": "Dummy00001", "author_id": 360695, "author_profile": "https://Stackoverflow.com/users/360695", "pm_score": 1, "selected": false, "text": "<p>The line I can't live without and generally first appearing in my <code>.vimrc</code>:</p>\n\n<pre><code>\" prevent switch to Replece mode if &lt;Insert&gt; pressed in insert mode\nimap &lt;Insert&gt; &lt;Nop&gt;\n</code></pre>\n\n<p>Another bit I can't live without is preserving the current line when hitting PgDown/PgUp:</p>\n\n<pre><code>map &lt;silent&gt; &lt;PageUp&gt; 1000&lt;C-U&gt;\nmap &lt;silent&gt; &lt;PageDown&gt; 1000&lt;C-D&gt;\nimap &lt;silent&gt; &lt;PageUp&gt; &lt;C-O&gt;1000&lt;C-U&gt;\nimap &lt;silent&gt; &lt;PageDown&gt; &lt;C-O&gt;1000&lt;C-D&gt;\nset nostartofline\n</code></pre>\n\n<p>Disable the annoying matching parentheses highlighting:</p>\n\n<pre><code>set noshowmatch\nlet loaded_matchparen = 1\n</code></pre>\n\n<p>Disable syntax highlighting when editing huge (>4MB) files:</p>\n\n<pre><code>au BufReadPost * if getfsize(bufname(\"%\")) &gt; 4*1024*1024 |\n\\ set syntax= |\n\\ endif\n</code></pre>\n\n<p>And finally <a href=\"http://vimrc-dissection.blogspot.com/2010/05/vim-inline-calculator.html\" rel=\"nofollow\">my simple in-line calculator</a>:</p>\n\n<pre><code>function CalcX(line_num)\n let l = getline(a:line_num)\n let expr = substitute( l, \" *=.*$\",\"\",\"\" )\n exec \":let g:tmp_calcx = \".expr\n call setline(a:line_num, expr.\" = \".g:tmp_calcx)\nendfunction\n:map &lt;silent&gt; &lt;F11&gt; :call CalcX(\".\")&lt;CR&gt;\n</code></pre>\n" }, { "answer_id": 3977974, "author": "SergioAraujo", "author_id": 2571881, "author_profile": "https://Stackoverflow.com/users/2571881", "pm_score": 1, "selected": false, "text": "<p>Two functions that I use extensively are placeholders to jump to files and InsertChangeLog (), jointly \"facilitate the creation of files with more friendly description </p>\n\n<pre><code>\" place holders snippets\n\" File Templates\n\" --------------\n\" &lt;leader&gt;j jumps to the next marker\n\" iabbr &lt;buffer&gt; for for &lt;+i+&gt; in &lt;+intervalo+&gt;:&lt;cr&gt;&lt;tab&gt;&lt;+i+&gt;\nfunction! LoadFileTemplate()\n \"silent! 0r ~/.vim/templates/%:e.tmpl\n syn match vimTemplateMarker \"&lt;+.\\++&gt;\" containedin=ALL\n hi vimTemplateMarker guifg=#67a42c guibg=#112300 gui=bold\nendfunction\nfunction! JumpToNextPlaceholder()\n let old_query = getreg('/')\n echo search(\"&lt;+.\\\\++&gt;\")\n exec \"norm! c/+&gt;/e\\&lt;CR&gt;\"\n call setreg('/', old_query)\nendfunction\nautocmd BufNewFile * :call LoadFileTemplate()\nnnoremap &lt;leader&gt;j :call JumpToNextPlaceholder()&lt;CR&gt;a\ninoremap &lt;leader&gt;j &lt;ESC&gt;:call JumpToNextPlaceholder()&lt;CR&gt;a\n\n\nfun! InsertChangeLog()\n normal(1G)\n call append(0, \"Arquivo: &lt;+Description+&gt;\")\n call append(1, \"Criado: \" . strftime(\"%a %d/%b/%Y hs %H:%M\"))\n call append(2, \"Last Change: \" . strftime(\"%a %d/%b/%Y hs %H:%M\"))\n call append(3, \"autor: &lt;+digite seu nome+&gt;\")\n call append(4, \"site: &lt;+digite o endereço de seu site+&gt;\")\n call append(5, \"twitter: &lt;+your twitter here+&gt;\")\n normal gg\nendfun\n</code></pre>\n" }, { "answer_id": 4177516, "author": "Benoit", "author_id": 457352, "author_profile": "https://Stackoverflow.com/users/457352", "pm_score": 0, "selected": false, "text": "<p>Here are some parts of my vimrc and files sourced from the vimrc:</p>\n\n<h2>Using <kbd>F10</kbd> to toggle common boolean settings:</h2>\n\n<pre><code>\" F10 inverts 'wrap'\nxnoremap &lt;F10&gt; :&lt;C-U&gt;set wrap! &lt;Bar&gt; set wrap? &lt;CR&gt;gv\nnnoremap &lt;F10&gt; :set wrap! &lt;Bar&gt; set wrap? &lt;CR&gt;\ninoremap &lt;F10&gt; &lt;C-O&gt;:set wrap! &lt;Bar&gt; set wrap? &lt;CR&gt;\n\" Shift-F10 inverts 'virtualedit'\nxnoremap &lt;S-F10&gt; :&lt;C-U&gt;set ve=&lt;C-R&gt;=(&amp;ve == 'all') ? '' : 'all'&lt;return&gt; ve?&lt;CR&gt;gv\nnnoremap &lt;S-F10&gt; :set ve=&lt;C-R&gt;=(&amp;ve == 'all') ? '' : 'all'&lt;return&gt; ve?&lt;CR&gt;\ninoremap &lt;S-F10&gt; &lt;C-O&gt;:set ve=&lt;C-R&gt;=(&amp;ve == 'all') ? '' : 'all'&lt;return&gt; ve?&lt;CR&gt;\n\" Ctrl-F10 inverts 'hidden'\nxnoremap &lt;C-F10&gt; :&lt;C-U&gt;set hidden! &lt;Bar&gt; set hidden? &lt;CR&gt;gv\nnnoremap &lt;C-F10&gt; :set hidden! &lt;Bar&gt; set hidden? &lt;CR&gt;\ninoremap &lt;C-F10&gt; &lt;C-O&gt;:set hidden! &lt;Bar&gt; set hidden? &lt;CR&gt;\n</code></pre>\n\n<h2>Using <kbd>F11</kbd> and <kbd>F12</kbd> to move around quickfix entries</h2>\n\n<pre><code>\" F11 and F12 to go to resp. previous and next item in quickfix entries\nnnoremap &lt;F11&gt; :silent! cc&lt;CR&gt;:silent! cp &lt;CR&gt;:call ErrBlink()&lt;CR&gt;\nnnoremap &lt;F12&gt; :silent! cc&lt;CR&gt;:silent! cn &lt;CR&gt;:call ErrBlink()&lt;CR&gt;\n\" Shift-F11 and Shift-F12 to go to resp prev. and next file in quickfix list\nnnoremap &lt;S-F11&gt; :silent! cc&lt;CR&gt;:silent! cpf&lt;CR&gt;:call ErrBlink()&lt;CR&gt;\nnnoremap &lt;S-F12&gt; :silent! cc&lt;CR&gt;:silent! cnf&lt;CR&gt;:call ErrBlink()&lt;CR&gt;\n\" Ctrl-F11 and Ctrl-F1 to recall older and newer quickfix lists\nnnoremap &lt;C-F11&gt; :silent! col &lt;CR&gt;:call ErrBlink()&lt;CR&gt;\nnnoremap &lt;C-F12&gt; :silent! cnew&lt;CR&gt;:call ErrBlink()&lt;CR&gt;\n</code></pre>\n\n<h2>Search visually selected text with <kbd>*</kbd> and <kbd>#</kbd> (prefix with <kbd>_</kbd> to keep old search also)</h2>\n\n<pre><code>xnoremap &lt;silent&gt; _* :&lt;C-U&gt;\n \\let old_reg=getreg('\"')&lt;Bar&gt;let old_regtype=getregtype('\"')&lt;CR&gt;\n \\gvy/&lt;C-R&gt;&lt;C-R&gt;/\\|&lt;C-R&gt;&lt;C-R&gt;=substitute(\n \\substitute(escape(@\", '/\\.*$^~['), '\\s\\+', '\\\\s\\\\+', 'g'), '\\_s\\+', '\\\\_s*', 'g')&lt;CR&gt;&lt;CR&gt;\n \\gV:call setreg('\"', old_reg, old_regtype)&lt;CR&gt;\n\nxnoremap &lt;silent&gt; _# :&lt;C-U&gt;\n \\let old_reg=getreg('\"')&lt;Bar&gt;let old_regtype=getregtype('\"')&lt;CR&gt;\n \\gvy?&lt;C-R&gt;&lt;C-R&gt;/\\|&lt;C-R&gt;&lt;C-R&gt;=substitute(\n \\substitute(escape(@\", '?\\.*$^~['), '\\s\\+', '\\\\s\\\\+', 'g'), '\\_s\\+', '\\\\_s*', 'g')&lt;CR&gt;&lt;CR&gt;\n \\gV:call setreg('\"', old_reg, old_regtype)&lt;CR&gt;\n\nxnoremap &lt;silent&gt; * :&lt;C-U&gt;\n \\let old_reg=getreg('\"')&lt;Bar&gt;let old_regtype=getregtype('\"')&lt;CR&gt;\n \\gvy/&lt;C-R&gt;&lt;C-R&gt;=substitute(\n \\substitute(escape(@\", '/\\.*$^~['), '\\s\\+', '\\\\s\\\\+', 'g'), '\\_s\\+', '\\\\_s*', 'g')&lt;CR&gt;&lt;CR&gt;\n \\gV:call setreg('\"', old_reg, old_regtype)&lt;CR&gt;\n\nxnoremap &lt;silent&gt; # :&lt;C-U&gt;\n \\let old_reg=getreg('\"')&lt;Bar&gt;let old_regtype=getregtype('\"')&lt;CR&gt;\n \\gvy?&lt;C-R&gt;&lt;C-R&gt;=substitute(\n \\substitute(escape(@\", '?\\.*$^~['), '\\s\\+', '\\\\s\\\\+', 'g'), '\\_s\\+', '\\\\_s*', 'g')&lt;CR&gt;&lt;CR&gt;\n \\gV:call setreg('\"', old_reg, old_regtype)&lt;CR&gt;\n</code></pre>\n\n<h2>Using <kbd>F1</kbd> and <kbd>F3</kbd> to search (shift to add results to current ones)</h2>\n\n<pre><code>set grepprg=ack\n\" F2 uses ack to search a Perl pattern\nnnoremap &lt;F2&gt; :grep&lt;space&gt;\nnnoremap &lt;S-F2&gt; :grepadd&lt;space&gt;\n\" F3 uses vim to search current pattern\nnnoremap &lt;F3&gt; :noautocmd vim // **/*&lt;C-F&gt;Bhhi\nnnoremap &lt;F3&gt;&lt;F3&gt; :noautocmd vim /&lt;C-R&gt;&lt;C-O&gt;// **/*&lt;Return&gt;\n\" F3 to search the current highlighted pattern\nxnoremap &lt;F3&gt; \"zy:noautocmd vim /\\M&lt;C-R&gt;=escape(@z,'\\/')&lt;CR&gt;/ **/*&lt;CR&gt;\nnnoremap &lt;S-F3&gt; :noautocmd vimgrepadd // **/*&lt;C-F&gt;Bhhi\nnnoremap &lt;S-F3&gt;&lt;S-F3&gt; :noautocmd vimgrepadd /&lt;C-R&gt;&lt;C-O&gt;// **/*&lt;Return&gt;\nxnoremap &lt;S-F3&gt; \"zy:noautocmd vimgrepadd /\\M&lt;C-R&gt;=escape(@z,'\\/')&lt;CR&gt;/ **/*&lt;CR&gt;\n</code></pre>\n\n<h2>Do not store replaced text when pasting in visual mode</h2>\n\n<pre><code>xnoremap p pgvy\n</code></pre>\n\n<h2>Help functions</h2>\n\n<pre><code>\" Have cursor line and column blink a bit\nfunction! BlinkHere()\n for i in range(1,6)\n set cursorline! cursorcolumn!\n redraw\n sleep 30m\n endfor\nendfunction\n\n\" Blink on mappings to quickfix commands\nfunction! ErrBlink()\n silent! cw\n silent! normal! z17\n silent! cc\n silent! normal! zz\n silent! call BlinkHere()\nendfunction\n</code></pre>\n\n<h2>Automatically sort quickfix list</h2>\n\n<pre><code>function! s:CompareQuickfixEntries(i1, i2)\n if bufname(a:i1.bufnr) == bufname(a:i2.bufnr)\n return a:i1.lnum == a:i2.lnum ? 0 : (a:i1.lnum &lt; a:i2.lnum ? -1 : 1)\n else\n return bufname(a:i1.bufnr) &lt; bufname(a:i2.bufnr) ? -1 : 1\n endif\nendfunction\n\nfunction! s:SortUniqQFList()\n let sortedList = sort(getqflist(), 's:CompareQuickfixEntries')\n let uniqedList = []\n let last = ''\n for item in sortedList\n let this = bufname(item.bufnr) . \"\\t\" . item.lnum\n if this !=# last\n call add(uniqedList, item)\n let last = this\n endif\n endfor\n call setqflist(uniqedList)\nendfunction\nautocmd! QuickfixCmdPost * call s:SortUniqQFList()\n</code></pre>\n" }, { "answer_id": 4200067, "author": "SergioAraujo", "author_id": 2571881, "author_profile": "https://Stackoverflow.com/users/2571881", "pm_score": 1, "selected": false, "text": "<pre><code> \" insert change log in files\n fun! InsertChangeLog()\n let l:flag=0\n for i in range(1,5)\n if getline(i) !~ '.*Last Change.*'\n let l:flag = l:flag + 1\n endif\n endfor\n if l:flag &gt;= 5\n normal(1G)\n call append(0, \"File: &lt;+Description+&gt;\")\n call append(1, \"Created: \" . strftime(\"%a %d/%b/%Y hs %H:%M\"))\n call append(2, \"Last Change: \" . strftime(\"%a %d/%b/%Y hs %H:%M\"))\n call append(3, \"author: &lt;+your name+&gt;\")\n call append(4, \"site: &lt;+site+&gt;\")\n call append(5, \"twitter: &lt;+your twitter here+&gt;\")\n normal gg\n endif\nendfun\nmap &lt;special&gt; &lt;F4&gt; &lt;esc&gt;:call InsertChangeLog()&lt;cr&gt;\n\n\" update changefile log\n\" http://tech.groups.yahoo.com/group/vim/message/51005\nfun! LastChange()\n let _s=@/\n let l = line(\".\")\n let c = col(\".\")\n if line(\"$\") &gt;= 5\n 1,5s/\\s*Last Change:\\s*\\zs.*/\\=\"\" . strftime(\"%Y %b %d %X\")/ge\n endif\n let @/=_s\n call cursor(l, c)\nendfun\nautocmd BufWritePre * keepjumps call LastChange()\n\n function! JumpToNextPlaceholder()\n let old_query = getreg('/')\n echo search(\"&lt;+.\\\\++&gt;\")\n exec \"norm! c/+&gt;/e\\&lt;CR&gt;\"\n call setreg('/', old_query)\nendfunction\nautocmd BufNewFile * :call LoadFileTemplate()\nnnoremap &lt;special&gt; &lt;leader&gt;j :call JumpToNextPlaceholder()&lt;CR&gt;a\ninoremap &lt;special&gt; &lt;leader&gt;j &lt;ESC&gt;:call JumpToNextPlaceholder()&lt;CR&gt;a\n\n\" Cientific calculator\ncommand! -nargs=+ Calc :py print &lt;args&gt;\npy from math import *\nmap ,c :Calc\n\n\nset statusline=%F%m%r%h%w\\\n\\ ft:%{&amp;ft}\\ \\\n\\ff:%{&amp;ff}\\ \\\n\\%{strftime(\\\"%a\\ %d/%m/%Y\\ \\\n\\%H:%M:%S\\\",getftime(expand(\\\"%:p\\\")))}%=\\ \\\n\\buf:%n\\ \\\n\\L:%04l\\ C:%04v\\ \\\n\\T:%04L\\ HEX:%03.3B\\ ASCII:%03.3b\\ %P\nset laststatus=2 \" Always show statusline\n</code></pre>\n" }, { "answer_id": 5293784, "author": "Jan Larres", "author_id": 102250, "author_profile": "https://Stackoverflow.com/users/102250", "pm_score": 0, "selected": false, "text": "<p>My (pretty heavily customized) vimrc is probably too long to post it here, so I'll just link to it instead:</p>\n\n<p><a href=\"https://github.com/majutsushi/etc/blob/master/vim/.vimrc\" rel=\"nofollow\">https://github.com/majutsushi/etc/blob/master/vim/.vimrc</a></p>\n\n<p>There are some useful tidbits in there that I either wrote myself or picked up somewhere like a statusbar with all kinds of information that I find useful. A screenshot is on the website of this plugin I wrote:</p>\n\n<p><a href=\"http://majutsushi.github.com/tagbar/\" rel=\"nofollow\">http://majutsushi.github.com/tagbar/</a></p>\n" }, { "answer_id": 5368078, "author": "expelledboy", "author_id": 644945, "author_profile": "https://Stackoverflow.com/users/644945", "pm_score": 1, "selected": false, "text": "<p>This isnt in my .vimrc but its related.</p>\n\n<p>In your .bashrc add this line\n<code>alias :q=exit</code></p>\n\n<p>Its amazing how much I have used this, sometimes without even realising!</p>\n" }, { "answer_id": 7135304, "author": "mikl", "author_id": 66851, "author_profile": "https://Stackoverflow.com/users/66851", "pm_score": 1, "selected": false, "text": "<p>My .vimrc is <a href=\"https://github.com/mikl/dotfiles/blob/master/vimrc\" rel=\"nofollow\">available on Github</a>. Lots of small tweaks and handy bindings in there :)</p>\n" }, { "answer_id": 7135371, "author": "dpogg1", "author_id": 327453, "author_profile": "https://Stackoverflow.com/users/327453", "pm_score": 2, "selected": false, "text": "<p>Put this in your vimrc:</p>\n\n<pre><code>imap &lt;C-l&gt; &lt;Space&gt;=&gt;&lt;Space&gt;\n</code></pre>\n\n<p>and never think about typing a hashrocket again. Yes, I know you don't need to in Ruby 1.9. But never mind that. </p>\n\n<p>My full vimrc is <a href=\"https://github.com/dpoggi/dotvim/blob/master/vimrc\" rel=\"nofollow\">here</a>.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7028/" ]
Vi and Vim allow for really awesome customization, typically stored inside a `.vimrc` file. Typical features for a programmer would be syntax highlighting, smart indenting and so on. **What other tricks for productive programming have you got, hidden in your .vimrc?** I am mostly interested in refactorings, auto classes and similar productivity macros, especially for C#.
You asked for it :-) ``` "{{{Auto Commands " Automatically cd into the directory that the file is in autocmd BufEnter * execute "chdir ".escape(expand("%:p:h"), ' ') " Remove any trailing whitespace that is in the file autocmd BufRead,BufWrite * if ! &bin | silent! %s/\s\+$//ge | endif " Restore cursor position to where it was before augroup JumpCursorOnEdit au! autocmd BufReadPost * \ if expand("<afile>:p:h") !=? $TEMP | \ if line("'\"") > 1 && line("'\"") <= line("$") | \ let JumpCursorOnEdit_foo = line("'\"") | \ let b:doopenfold = 1 | \ if (foldlevel(JumpCursorOnEdit_foo) > foldlevel(JumpCursorOnEdit_foo - 1)) | \ let JumpCursorOnEdit_foo = JumpCursorOnEdit_foo - 1 | \ let b:doopenfold = 2 | \ endif | \ exe JumpCursorOnEdit_foo | \ endif | \ endif " Need to postpone using "zv" until after reading the modelines. autocmd BufWinEnter * \ if exists("b:doopenfold") | \ exe "normal zv" | \ if(b:doopenfold > 1) | \ exe "+".1 | \ endif | \ unlet b:doopenfold | \ endif augroup END "}}} "{{{Misc Settings " Necesary for lots of cool vim things set nocompatible " This shows what you are typing as a command. I love this! set showcmd " Folding Stuffs set foldmethod=marker " Needed for Syntax Highlighting and stuff filetype on filetype plugin on syntax enable set grepprg=grep\ -nH\ $* " Who doesn't like autoindent? set autoindent " Spaces are better than a tab character set expandtab set smarttab " Who wants an 8 character tab? Not me! set shiftwidth=3 set softtabstop=3 " Use english for spellchecking, but don't spellcheck by default if version >= 700 set spl=en spell set nospell endif " Real men use gcc "compiler gcc " Cool tab completion stuff set wildmenu set wildmode=list:longest,full " Enable mouse support in console set mouse=a " Got backspace? set backspace=2 " Line Numbers PWN! set number " Ignoring case is a fun trick set ignorecase " And so is Artificial Intellegence! set smartcase " This is totally awesome - remap jj to escape in insert mode. You'll never type jj anyway, so it's great! inoremap jj <Esc> nnoremap JJJJ <Nop> " Incremental searching is sexy set incsearch " Highlight things that we find with the search set hlsearch " Since I use linux, I want this let g:clipbrdDefaultReg = '+' " When I close a tab, remove the buffer set nohidden " Set off the other paren highlight MatchParen ctermbg=4 " }}} "{{{Look and Feel " Favorite Color Scheme if has("gui_running") colorscheme inkpot " Remove Toolbar set guioptions-=T "Terminus is AWESOME set guifont=Terminus\ 9 else colorscheme metacosm endif "Status line gnarliness set laststatus=2 set statusline=%F%m%r%h%w\ (%{&ff}){%Y}\ [%l,%v][%p%%] " }}} "{{{ Functions "{{{ Open URL in browser function! Browser () let line = getline (".") let line = matchstr (line, "http[^ ]*") exec "!konqueror ".line endfunction "}}} "{{{Theme Rotating let themeindex=0 function! RotateColorTheme() let y = -1 while y == -1 let colorstring = "inkpot#ron#blue#elflord#evening#koehler#murphy#pablo#desert#torte#" let x = match( colorstring, "#", g:themeindex ) let y = match( colorstring, "#", x + 1 ) let g:themeindex = x + 1 if y == -1 let g:themeindex = 0 else let themestring = strpart(colorstring, x + 1, y - x - 1) return ":colorscheme ".themestring endif endwhile endfunction " }}} "{{{ Paste Toggle let paste_mode = 0 " 0 = normal, 1 = paste func! Paste_on_off() if g:paste_mode == 0 set paste let g:paste_mode = 1 else set nopaste let g:paste_mode = 0 endif return endfunc "}}} "{{{ Todo List Mode function! TodoListMode() e ~/.todo.otl Calendar wincmd l set foldlevel=1 tabnew ~/.notes.txt tabfirst " or 'norm! zMzr' endfunction "}}} "}}} "{{{ Mappings " Open Url on this line with the browser \w map <Leader>w :call Browser ()<CR> " Open the Project Plugin <F2> nnoremap <silent> <F2> :Project<CR> " Open the Project Plugin nnoremap <silent> <Leader>pal :Project .vimproject<CR> " TODO Mode nnoremap <silent> <Leader>todo :execute TodoListMode()<CR> " Open the TagList Plugin <F3> nnoremap <silent> <F3> :Tlist<CR> " Next Tab nnoremap <silent> <C-Right> :tabnext<CR> " Previous Tab nnoremap <silent> <C-Left> :tabprevious<CR> " New Tab nnoremap <silent> <C-t> :tabnew<CR> " Rotate Color Scheme <F8> nnoremap <silent> <F8> :execute RotateColorTheme()<CR> " DOS is for fools. nnoremap <silent> <F9> :%s/$//g<CR>:%s// /g<CR> " Paste Mode! Dang! <F10> nnoremap <silent> <F10> :call Paste_on_off()<CR> set pastetoggle=<F10> " Edit vimrc \ev nnoremap <silent> <Leader>ev :tabnew<CR>:e ~/.vimrc<CR> " Edit gvimrc \gv nnoremap <silent> <Leader>gv :tabnew<CR>:e ~/.gvimrc<CR> " Up and down are more logical with g.. nnoremap <silent> k gk nnoremap <silent> j gj inoremap <silent> <Up> <Esc>gka inoremap <silent> <Down> <Esc>gja " Good call Benjie (r for i) nnoremap <silent> <Home> i <Esc>r nnoremap <silent> <End> a <Esc>r " Create Blank Newlines and stay in Normal mode nnoremap <silent> zj o<Esc> nnoremap <silent> zk O<Esc> " Space will toggle folds! nnoremap <space> za " Search mappings: These will make it so that going to the next one in a " search will center on the line it's found in. map N Nzz map n nzz " Testing set completeopt=longest,menuone,preview inoremap <expr> <cr> pumvisible() ? "\<c-y>" : "\<c-g>u\<cr>" inoremap <expr> <c-n> pumvisible() ? "\<lt>c-n>" : "\<lt>c-n>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>" inoremap <expr> <m-;> pumvisible() ? "\<lt>c-n>" : "\<lt>c-x>\<lt>c-o>\<lt>c-n>\<lt>c-p>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>" " Swap ; and : Convenient. nnoremap ; : nnoremap : ; " Fix email paragraphs nnoremap <leader>par :%s/^>$//<CR> "ly$O#{{{ "lpjjj_%A#}}}jjzajj "}}} "{{{Taglist configuration let Tlist_Use_Right_Window = 1 let Tlist_Enable_Fold_Column = 0 let Tlist_Exit_OnlyWindow = 1 let Tlist_Use_SingleClick = 1 let Tlist_Inc_Winwidth = 0 "}}} let g:rct_completion_use_fri = 1 "let g:Tex_DefaultTargetFormat = "pdf" let g:Tex_ViewRule_pdf = "kpdf" filetype plugin indent on syntax on ```
164,858
<p>The following snippet of C# code:</p> <pre><code> int i = 1; string result = String.Format("{0},{1},{2}", i++, i++, i++); Console.WriteLine(result); </code></pre> <p>writes out: 1,2,3</p> <p>Before I tried this in the compiler I was expecting the assignments to take place and then the evaluations, so my expected output was: 1,1,1</p> <p>So my question is: Does this "pattern" (is it called a pattern?) of assign and then evaluate each parameter have a name?</p> <p>EDIT: I'm referring to the pattern of evaluating and assigning the parameters to the String.Format() function. Not the incrementing of i.</p> <p>(I may be incorrectly using the word evaluate in the question above because if the parameter was say (i + j) then we know that it would be evaluated before it was assigned. When using the word evaluate in that context I'm referring to the incrementing of i.)</p>
[ { "answer_id": 164908, "author": "Jacob Krall", "author_id": 3140, "author_profile": "https://Stackoverflow.com/users/3140", "pm_score": 3, "selected": true, "text": "<p>The <strong>order of evaluation</strong> of arguments is strictly left-to-right in C#. When you evaluate the expression <code>i++</code>, what happens is the value of <code>i</code> is calculated and pushed, then the value of <code>i</code> is incremented.</p>\n\n<p>The ++ operator on System.Int32 is effectively a function with the special name <code>++</code> and the special syntax of calling it by writing a reference to a variable and then the characters ++.</p>\n\n<p>So in effect, what you wrote is</p>\n\n<pre><code>// assume this function is defined:\nint Inc(ref int i)\n{\n var old = i;\n i = i + 1;\n return old;\n}\n\n...\nint i = 1;\nstring result = String.Format(\"{0},{1},{2}\", Inc(ref i), Inc(ref i), Inc(ref i));\nConsole.WriteLine(result);\n...\n</code></pre>\n\n<p>Since arguments are evaluated left-to-right, <code>Inc(ref i)</code> is called 3 times, each time incrementing <code>i</code> after passing the current value of <code>i</code> to <code>String.Format(...)</code>. This is exactly what happens in your code, as well.</p>\n" }, { "answer_id": 164912, "author": "Mike Ivanov", "author_id": 5126, "author_profile": "https://Stackoverflow.com/users/5126", "pm_score": 0, "selected": false, "text": "<p>The arguments of a function are evaluated <a href=\"http://msdn.microsoft.com/en-us/library/aa691335.aspx\" rel=\"nofollow noreferrer\">left-to-right in C#</a>. This is not the case in C/C++, where the standard says the order of evaluation is undefined.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
The following snippet of C# code: ``` int i = 1; string result = String.Format("{0},{1},{2}", i++, i++, i++); Console.WriteLine(result); ``` writes out: 1,2,3 Before I tried this in the compiler I was expecting the assignments to take place and then the evaluations, so my expected output was: 1,1,1 So my question is: Does this "pattern" (is it called a pattern?) of assign and then evaluate each parameter have a name? EDIT: I'm referring to the pattern of evaluating and assigning the parameters to the String.Format() function. Not the incrementing of i. (I may be incorrectly using the word evaluate in the question above because if the parameter was say (i + j) then we know that it would be evaluated before it was assigned. When using the word evaluate in that context I'm referring to the incrementing of i.)
The **order of evaluation** of arguments is strictly left-to-right in C#. When you evaluate the expression `i++`, what happens is the value of `i` is calculated and pushed, then the value of `i` is incremented. The ++ operator on System.Int32 is effectively a function with the special name `++` and the special syntax of calling it by writing a reference to a variable and then the characters ++. So in effect, what you wrote is ``` // assume this function is defined: int Inc(ref int i) { var old = i; i = i + 1; return old; } ... int i = 1; string result = String.Format("{0},{1},{2}", Inc(ref i), Inc(ref i), Inc(ref i)); Console.WriteLine(result); ... ``` Since arguments are evaluated left-to-right, `Inc(ref i)` is called 3 times, each time incrementing `i` after passing the current value of `i` to `String.Format(...)`. This is exactly what happens in your code, as well.
164,865
<p>Here at work, we are working on a newsletter system that our clients can use. As an intern one of my jobs is to help with the smaller pieces of the puzzle. In this case what I need to do is scan the logs of the email server for bounced messages and add the emails and the reason the email bounced to a "bad email database".</p> <p>The bad emails table has two columns: 'email' and 'reason' I use the following statement to get the information from the logs and send it to the Perl script</p> <pre><code>grep " 550 " /var/log/exim/main.log | awk '{print $5 "|" $23 " " $24 " " $25 " " $26 " " $27 " " $28 " " $29 " " $30 " " $31 " " $32 " " $33}' | perl /devl/bademails/getbademails.pl </code></pre> <p>If you have sugestions on a more efficient awk script, then I would be glad to hear those too but my main focus is the Perl script. The awk pipes "[email protected]|reason for bounce" to the Perl script. I want to take in these strings, split them at the | and put the two different parts into their respective columns in the database. Here's what I have:</p> <pre><code>#!usr/bin/perl use strict; use warnings; use DBI; my $dbpath = "dbi:mysql:database=system;host=localhost:3306"; my $dbh = DBI-&gt;connect($dbpath, "root", "******") or die "Can't open database: $DBI::errstr"; while(&lt;STDIN&gt;) { my $line = $_; my @list = # ? this is where i am confused for (my($i) = 0; $i &lt; 1; $i++) { if (defined($list[$i])) { my @val = split('|', $list[$i]); print "Email: $val[0]\n"; print "Reason: $val[1]"; my $sth = $dbh-&gt;prepare(qq{INSERT INTO bademails VALUES('$val[0]', '$val[1]')}); $sth-&gt;execute(); $sth-&gt;finish(); } } } exit 0; </code></pre>
[ { "answer_id": 164892, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 3, "selected": false, "text": "<p>I'm not sure what you want to put in @list? If the awk pipes one line per entry, you'll have that in $line, and you don't need the for loop on the @list.</p>\n\n<p>That said, if you're going to pipe it into Perl, why bother with the grep and AWK in the first place? </p>\n\n<pre><code>#!/ust/bin/perl -w\nuse strict;\n\nwhile (&lt;&gt;) {\n next unless / 550 /;\n my @tokens = split ' ', $_;\n my $addr = $tokens[4];\n my $reason = join \" \", @tokens[5..$#tokens];\n\n # ... DBI code\n}\n</code></pre>\n\n<p>Side note about the DBI calls: you should really use placeholders so that a \"bad email\" wouldn't be able to inject SQL into your database.</p>\n" }, { "answer_id": 164893, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 3, "selected": false, "text": "<p>Why not forgo the grep and awk and go straight to Perl?</p>\n\n<p>Disclaimer: I have not checked if the following code compiles:</p>\n\n<pre><code>while (&lt;STDIN&gt;) {\n next unless /550/; # skips over the rest of the while loop\n my @fields = split;\n my $email = $fields[4];\n my $reason = join(' ', @fields[22..32]);\n ...\n}\n</code></pre>\n\n<p>EDIT: See <a href=\"https://stackoverflow.com/users/18625/dland\">@dland's comment</a> for a further optimisation :-)</p>\n\n<p>Hope this helps?</p>\n" }, { "answer_id": 164906, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 5, "selected": true, "text": "<p>Something like this would work:</p>\n\n<pre><code>while(&lt;STDIN&gt;) {\n my $line = $_;\n chomp($line);\n my ($email,$reason) = split(/\\|/, $line);\n print \"Email: $email\\n\";\n print \"Reason: $reason\";\n my $sth = $dbh-&gt;prepare(qq{INSERT INTO bademails VALUES(?, ?)});\n $sth-&gt;execute($email, $reason); \n $sth-&gt;finish(); \n}\n</code></pre>\n\n<p>You might find it easier to just do the whole thing in Perl. \"next unless / 550 /\" could replace the grep and a regex could probably replace the awk.</p>\n" }, { "answer_id": 164909, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<pre><code>my(@list) = split /\\|/, $line;\n</code></pre>\n\n<p>This will generate more than two entries in @list if you have extra pipe symbols in the tail of the line. To avoid that, use:</p>\n\n<pre><code>$line =~ m/^([^|]+)\\|(.*)$/;\nmy(@list) = ($1, $2);\n</code></pre>\n\n<p>The dollar in the regex is arguably superfluous, but also documents 'end of line'.</p>\n" }, { "answer_id": 165932, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 3, "selected": false, "text": "<p>Have you considered using <a href=\"http://search.cpan.org/dist/ack/ack\" rel=\"nofollow noreferrer\">App::Ack</a> instead? Instead of shelling out to an external program, you can just use Perl instead. Unfortunately, you'll have to read through the <a href=\"http://search.cpan.org/src/PETDANCE/ack-1.86/ack\" rel=\"nofollow noreferrer\">ack</a> program code to really get a sense of how to do this, but you should get a more portable program as a result.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ]
Here at work, we are working on a newsletter system that our clients can use. As an intern one of my jobs is to help with the smaller pieces of the puzzle. In this case what I need to do is scan the logs of the email server for bounced messages and add the emails and the reason the email bounced to a "bad email database". The bad emails table has two columns: 'email' and 'reason' I use the following statement to get the information from the logs and send it to the Perl script ``` grep " 550 " /var/log/exim/main.log | awk '{print $5 "|" $23 " " $24 " " $25 " " $26 " " $27 " " $28 " " $29 " " $30 " " $31 " " $32 " " $33}' | perl /devl/bademails/getbademails.pl ``` If you have sugestions on a more efficient awk script, then I would be glad to hear those too but my main focus is the Perl script. The awk pipes "[email protected]|reason for bounce" to the Perl script. I want to take in these strings, split them at the | and put the two different parts into their respective columns in the database. Here's what I have: ``` #!usr/bin/perl use strict; use warnings; use DBI; my $dbpath = "dbi:mysql:database=system;host=localhost:3306"; my $dbh = DBI->connect($dbpath, "root", "******") or die "Can't open database: $DBI::errstr"; while(<STDIN>) { my $line = $_; my @list = # ? this is where i am confused for (my($i) = 0; $i < 1; $i++) { if (defined($list[$i])) { my @val = split('|', $list[$i]); print "Email: $val[0]\n"; print "Reason: $val[1]"; my $sth = $dbh->prepare(qq{INSERT INTO bademails VALUES('$val[0]', '$val[1]')}); $sth->execute(); $sth->finish(); } } } exit 0; ```
Something like this would work: ``` while(<STDIN>) { my $line = $_; chomp($line); my ($email,$reason) = split(/\|/, $line); print "Email: $email\n"; print "Reason: $reason"; my $sth = $dbh->prepare(qq{INSERT INTO bademails VALUES(?, ?)}); $sth->execute($email, $reason); $sth->finish(); } ``` You might find it easier to just do the whole thing in Perl. "next unless / 550 /" could replace the grep and a regex could probably replace the awk.
164,926
<p>When displaying the value of a decimal currently with <code>.ToString()</code>, it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places. </p> <p>Do I use a variation of <code>.ToString()</code> for this?</p>
[ { "answer_id": 164932, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 11, "selected": true, "text": "<pre><code>decimalVar.ToString(&quot;#.##&quot;); // returns &quot;.5&quot; when decimalVar == 0.5m\n</code></pre>\n<p>or</p>\n<pre><code>decimalVar.ToString(&quot;0.##&quot;); // returns &quot;0.5&quot; when decimalVar == 0.5m\n</code></pre>\n<p>or</p>\n<pre><code>decimalVar.ToString(&quot;0.00&quot;); // returns &quot;0.50&quot; when decimalVar == 0.5m\n</code></pre>\n" }, { "answer_id": 164934, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 7, "selected": false, "text": "<p>If you just need this for display use string.Format</p>\n\n<pre><code>String.Format(\"{0:0.00}\", 123.4567m); // \"123.46\"\n</code></pre>\n\n<p><a href=\"http://www.csharp-examples.net/string-format-double/\" rel=\"noreferrer\">http://www.csharp-examples.net/string-format-double/</a></p>\n\n<p>The \"m\" is a decimal suffix. About the decimal suffix:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/364x0z75.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/364x0z75.aspx</a></p>\n" }, { "answer_id": 164937, "author": "John Smith", "author_id": 24661, "author_profile": "https://Stackoverflow.com/users/24661", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/zy06z30k.aspx\" rel=\"noreferrer\">Math.Round Method (Decimal, Int32)</a></p>\n" }, { "answer_id": 164966, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 6, "selected": false, "text": "<p>Given <strong>decimal d=12.345;</strong> the expressions <strong>d.ToString(\"C\")</strong> or <strong>String.Format(\"{0:C}\", d)</strong> yield <strong>$12.35</strong> - note that the current culture's currency settings including the symbol are used.</p>\n\n<p>Note that <a href=\"http://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx#CFormatString\" rel=\"noreferrer\">\"C\"</a> uses number of digits from current culture. You can always override default to force necessary precision with <code>C{Precision specifier}</code> like <code>String.Format(\"{0:C2}\", 5.123d)</code>.</p>\n" }, { "answer_id": 775089, "author": "Joel Mueller", "author_id": 24380, "author_profile": "https://Stackoverflow.com/users/24380", "pm_score": 6, "selected": false, "text": "<p>If you want it formatted with commas as well as a decimal point (but no currency symbol), such as 3,456,789.12...</p>\n\n<pre><code>decimalVar.ToString(\"n2\");\n</code></pre>\n" }, { "answer_id": 1907832, "author": "Sofox", "author_id": 232147, "author_profile": "https://Stackoverflow.com/users/232147", "pm_score": 9, "selected": false, "text": "<pre><code>decimalVar.ToString(\"F\");\n</code></pre>\n\n<p>This will:</p>\n\n<ul>\n<li>Round off to 2 decimal places <em>eg.</em> <code>23.456</code> → <code>23.46</code></li>\n<li>Ensure that there\nare always 2 decimal places <em>eg.</em> <code>23</code> → <code>23.00</code>; <code>12.5</code> → <code>12.50</code></li>\n</ul>\n\n<p>Ideal for displaying currency.</p>\n\n<p>Check out the documentation on <a href=\"http://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx#FFormatString\" rel=\"noreferrer\">ToString(\"F\")</a> (thanks to Jon Schneider).</p>\n" }, { "answer_id": 5724542, "author": "Mike M.", "author_id": 358637, "author_profile": "https://Stackoverflow.com/users/358637", "pm_score": 9, "selected": false, "text": "<p>I know this is an old question, but I was surprised to see that no one seemed to post an answer that;</p>\n<ol>\n<li>Didn't use bankers rounding</li>\n<li>Keeps the value as a decimal.</li>\n</ol>\n<p>This is what I would use:</p>\n<pre><code>decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero);\n</code></pre>\n<p><a href=\"http://msdn.microsoft.com/en-us/library/9s0xa85y.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/9s0xa85y.aspx</a></p>\n" }, { "answer_id": 7155020, "author": "Smitha Poluri", "author_id": 906828, "author_profile": "https://Stackoverflow.com/users/906828", "pm_score": 3, "selected": false, "text": "<p>You can use system.globalization to format a number in any required format.</p>\n\n<p><strong>For example:</strong> </p>\n\n<pre><code>system.globalization.cultureinfo ci = new system.globalization.cultureinfo(\"en-ca\");\n</code></pre>\n\n<p>If you have a <code>decimal d = 1.2300000</code> and you need to trim it to 2 decimal places then it can be printed like this <code>d.Tostring(\"F2\",ci);</code> where F2 is string formating to 2 decimal places and ci is the locale or cultureinfo. </p>\n\n<p>for more info check this link<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx</a></p>\n" }, { "answer_id": 7899828, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 5, "selected": false, "text": "<p>There's a very important characteristic of <code>Decimal</code> that isn't obvious:</p>\n<blockquote>\n<p>A <code>Decimal</code> 'knows' how many decimal places it has based upon where it came from</p>\n</blockquote>\n<p>The following may be unexpected :</p>\n<pre><code>Decimal.Parse(&quot;25&quot;).ToString() =&gt; &quot;25&quot;\nDecimal.Parse(&quot;25.&quot;).ToString() =&gt; &quot;25&quot;\nDecimal.Parse(&quot;25.0&quot;).ToString() =&gt; &quot;25.0&quot;\nDecimal.Parse(&quot;25.0000&quot;).ToString() =&gt; &quot;25.0000&quot;\n\n25m.ToString() =&gt; &quot;25&quot;\n25.000m.ToString() =&gt; &quot;25.000&quot;\n</code></pre>\n<p>Doing the same operations with <code>Double</code> will result in zero decimal places (<code>&quot;25&quot;</code>) for all of the above examples.</p>\n<p>If you want a decimal to 2 decimal places there's a high likelyhood it's because it's currency in which case this is probably fine for 95% of the time:</p>\n<pre><code>Decimal.Parse(&quot;25.0&quot;).ToString(&quot;c&quot;) =&gt; &quot;$25.00&quot;\n</code></pre>\n<p>Or in XAML you would use <code>{Binding Price, StringFormat=c}</code></p>\n<p>One case I ran into where I needed a decimal AS a decimal was when sending XML to Amazon's webservice. The service was complaining because a Decimal value (originally from SQL Server) was being sent as <code>25.1200</code> and rejected, (<code>25.12</code> was the expected format).</p>\n<p>All I needed to do was <code>Decimal.Round(...)</code> with 2 decimal places to fix the problem regardless of the source of the value.</p>\n<pre><code> // generated code by XSD.exe\n StandardPrice = new OverrideCurrencyAmount()\n {\n TypedValue = Decimal.Round(product.StandardPrice, 2),\n currency = &quot;USD&quot;\n }\n</code></pre>\n<p><code>TypedValue</code> is of type <code>Decimal</code> so I couldn't just do <code>ToString(&quot;N2&quot;)</code> and needed to round it and keep it as a <code>decimal</code>.</p>\n" }, { "answer_id": 13070953, "author": "Kaido", "author_id": 513778, "author_profile": "https://Stackoverflow.com/users/513778", "pm_score": 3, "selected": false, "text": "<p>None of these did exactly what I needed, to force <strong>2 d.p.</strong> and round up as <code>0.005 -&gt; 0.01</code></p>\n\n<p>Forcing 2 d.p. requires increasing the precision by 2 d.p. to ensure we have at least 2 d.p. </p>\n\n<p>then rounding to ensure we do not have more than 2 d.p.</p>\n\n<pre><code>Math.Round(exactResult * 1.00m, 2, MidpointRounding.AwayFromZero)\n\n6.665m.ToString() -&gt; \"6.67\"\n\n6.6m.ToString() -&gt; \"6.60\"\n</code></pre>\n" }, { "answer_id": 20057499, "author": "What Would Be Cool", "author_id": 753279, "author_profile": "https://Stackoverflow.com/users/753279", "pm_score": 5, "selected": false, "text": "<p>Here is a little Linqpad program to show different formats:</p>\n\n<pre><code>void Main()\n{\n FormatDecimal(2345.94742M);\n FormatDecimal(43M);\n FormatDecimal(0M);\n FormatDecimal(0.007M);\n}\n\npublic void FormatDecimal(decimal val)\n{\n Console.WriteLine(\"ToString: {0}\", val);\n Console.WriteLine(\"c: {0:c}\", val);\n Console.WriteLine(\"0.00: {0:0.00}\", val);\n Console.WriteLine(\"0.##: {0:0.##}\", val);\n Console.WriteLine(\"===================\");\n}\n</code></pre>\n\n<p>Here are the results:</p>\n\n<pre><code>ToString: 2345.94742\nc: $2,345.95\n0.00: 2345.95\n0.##: 2345.95\n===================\nToString: 43\nc: $43.00\n0.00: 43.00\n0.##: 43\n===================\nToString: 0\nc: $0.00\n0.00: 0.00\n0.##: 0\n===================\nToString: 0.007\nc: $0.01\n0.00: 0.01\n0.##: 0.01\n===================\n</code></pre>\n" }, { "answer_id": 38032451, "author": "Jeff Jose", "author_id": 6147480, "author_profile": "https://Stackoverflow.com/users/6147480", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx\" rel=\"noreferrer\">https://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx</a></p>\n\n<p>This link explains in detail how you can handle your problem and what you can do if you want to learn more. For simplicity purposes, what you want to do is </p>\n\n<pre><code>double whateverYouWantToChange = whateverYouWantToChange.ToString(\"F2\");\n</code></pre>\n\n<p>if you want this for a currency, you can make it easier by typing \"C2\" instead of \"F2\"</p>\n" }, { "answer_id": 40051017, "author": "JsAndDotNet", "author_id": 852806, "author_profile": "https://Stackoverflow.com/users/852806", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/5724542\">Mike M.'s answer</a> was perfect for me on .NET, but .NET Core doesn't have a <code>decimal.Round</code> method at the time of writing.</p>\n\n<p>In .NET Core, I had to use:</p>\n\n<pre><code>decimal roundedValue = Math.Round(rawNumber, 2, MidpointRounding.AwayFromZero);\n</code></pre>\n\n<p>A hacky method, including conversion to string, is:</p>\n\n<pre><code>public string FormatTo2Dp(decimal myNumber)\n{\n // Use schoolboy rounding, not bankers.\n myNumber = Math.Round(myNumber, 2, MidpointRounding.AwayFromZero);\n\n return string.Format(\"{0:0.00}\", myNumber);\n}\n</code></pre>\n" }, { "answer_id": 45427758, "author": "goamn", "author_id": 712700, "author_profile": "https://Stackoverflow.com/users/712700", "pm_score": 4, "selected": false, "text": "<p>Very rarely would you want an empty string if the value is 0.</p>\n\n<pre><code>decimal test = 5.00;\ntest.ToString(\"0.00\"); //\"5.00\"\ndecimal? test2 = 5.05;\ntest2.ToString(\"0.00\"); //\"5.05\"\ndecimal? test3 = 0;\ntest3.ToString(\"0.00\"); //\"0.00\"\n</code></pre>\n\n<p>The top rated answer is incorrect and has wasted 10 minutes of (most) people's time.</p>\n" }, { "answer_id": 45865331, "author": "Alex", "author_id": 5221030, "author_profile": "https://Stackoverflow.com/users/5221030", "pm_score": 3, "selected": false, "text": "<p>The top-rated answer describes a method for formatting the <em>string representation</em> of the decimal value, and it works.</p>\n\n<p>However, if you actually want to change the precision saved to the actual value, you need to write something like the following:</p>\n\n<pre><code>public static class PrecisionHelper\n{\n public static decimal TwoDecimalPlaces(this decimal value)\n {\n // These first lines eliminate all digits past two places.\n var timesHundred = (int) (value * 100);\n var removeZeroes = timesHundred / 100m;\n\n // In this implementation, I don't want to alter the underlying\n // value. As such, if it needs greater precision to stay unaltered,\n // I return it.\n if (removeZeroes != value)\n return value;\n\n // Addition and subtraction can reliably change precision. \n // For two decimal values A and B, (A + B) will have at least as \n // many digits past the decimal point as A or B.\n return removeZeroes + 0.01m - 0.01m;\n }\n}\n</code></pre>\n\n<p>An example unit test:</p>\n\n<pre><code>[Test]\npublic void PrecisionExampleUnitTest()\n{\n decimal a = 500m;\n decimal b = 99.99m;\n decimal c = 123.4m;\n decimal d = 10101.1000000m;\n decimal e = 908.7650m\n\n Assert.That(a.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),\n Is.EqualTo(\"500.00\"));\n\n Assert.That(b.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),\n Is.EqualTo(\"99.99\"));\n\n Assert.That(c.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),\n Is.EqualTo(\"123.40\"));\n\n Assert.That(d.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),\n Is.EqualTo(\"10101.10\"));\n\n // In this particular implementation, values that can't be expressed in\n // two decimal places are unaltered, so this remains as-is.\n Assert.That(e.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),\n Is.EqualTo(\"908.7650\"));\n}\n</code></pre>\n" }, { "answer_id": 57568126, "author": "Code", "author_id": 9787173, "author_profile": "https://Stackoverflow.com/users/9787173", "pm_score": 2, "selected": false, "text": "<pre><code>Double Amount = 0;\nstring amount;\namount=string.Format(\"{0:F2}\", Decimal.Parse(Amount.ToString()));\n</code></pre>\n" }, { "answer_id": 60669801, "author": "Aleksei Mialkin", "author_id": 1833895, "author_profile": "https://Stackoverflow.com/users/1833895", "pm_score": 2, "selected": false, "text": "<p>If you need to keep only 2 decimal places (i.e. cut off all the rest of decimal digits):</p>\n\n<pre><code>decimal val = 3.14789m;\ndecimal result = Math.Floor(val * 100) / 100; // result = 3.14\n</code></pre>\n\n<p>If you need to keep only 3 decimal places:</p>\n\n<pre><code>decimal val = 3.14789m;\ndecimal result = Math.Floor(val * 1000) / 1000; // result = 3.147\n</code></pre>\n" }, { "answer_id": 71104865, "author": "ihsan güç", "author_id": 13056635, "author_profile": "https://Stackoverflow.com/users/13056635", "pm_score": 0, "selected": false, "text": "<pre><code> var arr = new List&lt;int&gt;() { -4, 3, -9, 0, 4, 1 };\n decimal result1 = arr.Where(p =&gt; p &gt; 0).Count();\n var responseResult1 = result1 / arr.Count();\n decimal result2 = arr.Where(p =&gt; p &lt; 0).Count();\n var responseResult2 = result2 / arr.Count();\n decimal result3 = arr.Where(p =&gt; p == 0).Count();\n var responseResult3 = result3 / arr.Count();\n Console.WriteLine(String.Format(&quot;{0:#,0.000}&quot;, responseResult1));\n Console.WriteLine(String.Format(&quot;{0:#,0.0000}&quot;, responseResult2));\n Console.WriteLine(String.Format(&quot;{0:#,0.00000}&quot;, responseResult3));\n</code></pre>\n<p>you can put as many 0 as you want.</p>\n" }, { "answer_id": 72628873, "author": "BanukaKA", "author_id": 19202848, "author_profile": "https://Stackoverflow.com/users/19202848", "pm_score": 2, "selected": false, "text": "<p>The most applicable solution is</p>\n<pre><code>decimalVar.ToString(&quot;#.##&quot;);\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1692/" ]
When displaying the value of a decimal currently with `.ToString()`, it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places. Do I use a variation of `.ToString()` for this?
``` decimalVar.ToString("#.##"); // returns ".5" when decimalVar == 0.5m ``` or ``` decimalVar.ToString("0.##"); // returns "0.5" when decimalVar == 0.5m ``` or ``` decimalVar.ToString("0.00"); // returns "0.50" when decimalVar == 0.5m ```
164,927
<p>What is the best way to find out if a primary key with a certain value already exists in a table?</p> <p>I can think of:</p> <pre><code>SELECT key FROM table WHERE key = 'value'; </code></pre> <p>and count the results, or:</p> <pre><code>SELECT SQL_CALC_FOUND_ROWS key FROM table WHERE key = 'value' LIMIT 1; SELECT FOUND_ROWS(); </code></pre>
[ { "answer_id": 164942, "author": "Jarod Elliott", "author_id": 1061, "author_profile": "https://Stackoverflow.com/users/1061", "pm_score": 3, "selected": true, "text": "<p>I think either of your suggestions in the question are suitable.</p>\n\n<p>Depending on how you are using this though, you can potentially save time by doing an INSERT IGNORE, which allows you to insert a new row if the primary key doesn't exist. If it does exist, the error is ignored so you can continue as normal.</p>\n\n<p>Other similar options depending on your usage include using the REPLACE or the INSERT ON DUPLICATE KEY UPDATE types of inserts. This allows you to update the existing entry if the primary key already exists, otherwise it just inserts your new entry.</p>\n" }, { "answer_id": 164946, "author": "Mike Ivanov", "author_id": 5126, "author_profile": "https://Stackoverflow.com/users/5126", "pm_score": 1, "selected": false, "text": "<p>Do the first and count the results (always 0 or 1). Easy and fast.</p>\n" }, { "answer_id": 164950, "author": "Brian", "author_id": 700, "author_profile": "https://Stackoverflow.com/users/700", "pm_score": 0, "selected": false, "text": "<p>Example</p>\n\n<pre><code>Select count(key) into :result from table where key = :theValue\n</code></pre>\n\n<p>If your trying to decide between an insert or update, use a MERGE statement in Oracle. I believe MS-SQL is something like an UPSERT statement.</p>\n" }, { "answer_id": 164952, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": -1, "selected": false, "text": "<p>I think it would be more intuitive and simplier to use IF EXISTS.</p>\n\n<pre><code>\nIF EXISTS (SELECT key FROM table WHERE key = 'value')\n PRINT 'Found it!'\nELSE\n PRINT 'Cannot find it!'\n</code></pre>\n" }, { "answer_id": 165024, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 1, "selected": false, "text": "<p>I'd do:</p>\n\n<pre><code>SELECT 1 FROM table WHERE id key = 'value'\n</code></pre>\n\n<p>Anything else is likely to interfere with query optimisation a little, so I'd stick with that.</p>\n\n<p>Edit: Although I just realised I don't think I've ever done that in MySQL, although I can't see why it wouldn't work.</p>\n" }, { "answer_id": 6495798, "author": "o17t H1H' S'k", "author_id": 664456, "author_profile": "https://Stackoverflow.com/users/664456", "pm_score": 0, "selected": false, "text": "<p>SELECT 1 FROM mytable WHERE mykey = 'value' LIMIT 1</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
What is the best way to find out if a primary key with a certain value already exists in a table? I can think of: ``` SELECT key FROM table WHERE key = 'value'; ``` and count the results, or: ``` SELECT SQL_CALC_FOUND_ROWS key FROM table WHERE key = 'value' LIMIT 1; SELECT FOUND_ROWS(); ```
I think either of your suggestions in the question are suitable. Depending on how you are using this though, you can potentially save time by doing an INSERT IGNORE, which allows you to insert a new row if the primary key doesn't exist. If it does exist, the error is ignored so you can continue as normal. Other similar options depending on your usage include using the REPLACE or the INSERT ON DUPLICATE KEY UPDATE types of inserts. This allows you to update the existing entry if the primary key already exists, otherwise it just inserts your new entry.
164,964
<p>I'm trying to determine the asymptotic run-time of one of my algorithms, which uses exponents, but I'm not sure of how exponents are calculated programmatically.</p> <p>I'm specifically looking for the pow() algorithm used for double-precision, floating point numbers.</p>
[ { "answer_id": 164972, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 1, "selected": false, "text": "<p>The usual approach, to raise a to the b, for an integer exponent, goes something like this:</p>\n\n<pre><code>result = 1\nwhile b &gt; 0\n if b is odd\n result *= a\n b -= 1\n b /= 2\n a = a * a\n</code></pre>\n\n<p>It is generally logarithmic in the size of the exponent. The algorithm is based on the invariant \"a^b*result = a0^b0\", where a0 and b0 are the initial values of a and b.</p>\n\n<p>For negative or non-integer exponents, logarithms and approximations and numerical analysis are needed. The running time will depend on the algorithm used and what precision the library is tuned for.</p>\n\n<p>Edit: Since there seems to be some interest, here's a version without the extra multiplication.</p>\n\n<pre><code>result = 1\nwhile b &gt; 0\n while b is even\n a = a * a\n b = b / 2\n result = result * a\n b = b - 1\n</code></pre>\n" }, { "answer_id": 165181, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "<p>I've had a chance to look at fdlibm's implementation. The comments describe the algorithm used:</p>\n\n<pre><code> * n\n * Method: Let x = 2 * (1+f)\n * 1. Compute and return log2(x) in two pieces:\n * log2(x) = w1 + w2,\n * where w1 has 53-24 = 29 bit trailing zeros.\n * 2. Perform y*log2(x) = n+y' by simulating muti-precision\n * arithmetic, where |y'|&lt;=0.5.\n * 3. Return x**y = 2**n*exp(y'*log2)\n</code></pre>\n\n<p>followed by a listing of all the special cases handled (0, 1, inf, nan).</p>\n\n<p>The most intense sections of the code, after all the special-case handling, involve the <code>log2</code> and <code>2**</code> calculations. And there are no loops in either of those. So, the complexity of floating-point primitives notwithstanding, it looks like a asymptotically constant-time algorithm.</p>\n\n<p>Floating-point experts (of which I'm not one) are welcome to comment. :-)</p>\n" }, { "answer_id": 165229, "author": "Windows programmer", "author_id": 23705, "author_profile": "https://Stackoverflow.com/users/23705", "pm_score": 0, "selected": false, "text": "<p>If I were writing a pow function targeting Intel, I would return exp2(log2(x) * y). Intel's microcode for log2 is surely faster than anything I'd be able to code, even if I could remember my first year calculus and grad school numerical analysis.</p>\n" }, { "answer_id": 165348, "author": "gsarnold", "author_id": 21961, "author_profile": "https://Stackoverflow.com/users/21961", "pm_score": 2, "selected": false, "text": "<p>Unless they've discovered a better way to do it, I believe that approximate values for trig, logarithmic and exponential functions (for exponential growth and decay, for example) are generally calculated using arithmetic rules and <strong>Taylor Series</strong> expansions to produce an approximate result accurate to within the requested precision. (See any Calculus book for details on power series, Taylor series, and Maclaurin series expansions of functions.) Please note that it's been a while since I did any of this so I couldn't tell you, for example, exactly how to calculate the number of terms in the series you need to include guarantee an error that small enough to be negligible in a double-precision calculation.</p>\n\n<p>For example, the Taylor/Maclaurin series expansion for e^x is this:</p>\n\n<pre><code> +inf [ x^k ] x^2 x^3 x^4 x^5\ne^x = SUM [ --- ] = 1 + x + --- + ----- + ------- + --------- + ....\n k=0 [ k! ] 2*1 3*2*1 4*3*2*1 5*4*3*2*1\n</code></pre>\n\n<p>If you take all of the terms (k from 0 to infinity), this expansion is exact and complete (no error).</p>\n\n<p>However, if you don't take all the terms going to infinity, but you stop after say 5 terms or 50 terms or whatever, you produce an <strong>approximate</strong> result that differs from the actual e^x function value by a remainder which is fairly easy to calculate.</p>\n\n<p>The good news for exponentials is that it converges nicely and the terms of its polynomial expansion are fairly easy to code iteratively, so you <strong>might</strong> (repeat, <strong>MIGHT</strong> - remember, it's been a while) not even need to pre-calculate how many terms you need to guarantee your error is less than precision because you can test the size of the contribution at each iteration and stop when it becomes close enough to zero. In practice, I do not know if this strategy is viable or not - I'd have to try it. There are important details I have long since forgotten about. Stuff like: machine precision, machine error and rounding error, etc.</p>\n\n<p>Also, please note that if you are not using e^x, but you are doing growth/decay with another base like 2^x or 10^x, the approximating polynomial function changes. </p>\n" }, { "answer_id": 178074, "author": "akalenuk", "author_id": 25459, "author_profile": "https://Stackoverflow.com/users/25459", "pm_score": 1, "selected": false, "text": "<p>You can use exp(n*ln(x)) for calculating x<sup>n</sup>. Both x and n can be double-precision, floating point numbers. Natural logarithm and exponential function can be calculated using Taylor series. Here you can find formulas: <a href=\"http://en.wikipedia.org/wiki/Taylor_series\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Taylor_series</a></p>\n" }, { "answer_id": 68959587, "author": "徐持恒 Xu Chiheng", "author_id": 16770359, "author_profile": "https://Stackoverflow.com/users/16770359", "pm_score": 0, "selected": false, "text": "<p>e^x = (1 + fraction) * (2^exponent), 1 &lt;= 1 + fraction &lt; 2</p>\n<p>x * log2(e) = log2(1 + fraction) + exponent, 0 &lt;= log2(1 + fraction) &lt; 1</p>\n<p>exponent = floor(x * log2(e))</p>\n<p>1 + fraction = 2^(x * log2(e) - exponent) = e^((x * log2(e) - exponent) * ln2) = e^(x - exponent * ln2), 0 &lt;= x - exponent * ln2 &lt; ln2</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55/" ]
I'm trying to determine the asymptotic run-time of one of my algorithms, which uses exponents, but I'm not sure of how exponents are calculated programmatically. I'm specifically looking for the pow() algorithm used for double-precision, floating point numbers.
I've had a chance to look at fdlibm's implementation. The comments describe the algorithm used: ``` * n * Method: Let x = 2 * (1+f) * 1. Compute and return log2(x) in two pieces: * log2(x) = w1 + w2, * where w1 has 53-24 = 29 bit trailing zeros. * 2. Perform y*log2(x) = n+y' by simulating muti-precision * arithmetic, where |y'|<=0.5. * 3. Return x**y = 2**n*exp(y'*log2) ``` followed by a listing of all the special cases handled (0, 1, inf, nan). The most intense sections of the code, after all the special-case handling, involve the `log2` and `2**` calculations. And there are no loops in either of those. So, the complexity of floating-point primitives notwithstanding, it looks like a asymptotically constant-time algorithm. Floating-point experts (of which I'm not one) are welcome to comment. :-)
164,967
<p>I have an Excel application in which I want to present the user with a list of the Data Source Names (ie: DSN's), whereby s/he can choose what data source to use.</p> <p>Hopefully once I've got the list, I can easily access the DSN properties to connect to the appropriate database.</p> <p>Please note, I do <em>not</em> want to use a DSN-less connection.</p>
[ { "answer_id": 165044, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 5, "selected": true, "text": "<p>The DSN entries are stored in the registry in the following keys.</p>\n\n<pre>HKEY_CURRENT_USER\\Software\\ODBC\\ODBC.INI\\ODBC Data Sources\nHKEY_LOCAL_MACHINE\\SOFTWARE\\ODBC\\ODBC.INI\\ODBC Data Sources</pre>\n\n<p>This contains the list of all defined DSN. This acts as an global index and the specific details for each DSN are stored in a key with the DSN name under:</p>\n\n<pre>HKEY_CURRENT_USER\\Software\\ODBC\\ODBC.INI\nHKEY_LOCAL_MACHINE\\SOFTWARE\\ODBC\\ODBC.INI</pre>\n\n<p>Create some entries in both User DSN and System DSN tabs from Data Sources (ODBC) control panel applet and check how these values are stored in the registry.</p>\n\n<p>The following example enumerate the DSN defined for the user trough Control Panel > Administrative Tools > Data Sources (ODBC) [User Dsn Tab].</p>\n\n<p><a href=\"http://support.microsoft.com/kb/178755\" rel=\"noreferrer\">http://support.microsoft.com/kb/178755</a></p>\n\n<pre><code> Option Explicit\n\n Private Declare Function RegOpenKeyEx Lib \"advapi32.dll\" _\n Alias \"RegOpenKeyExA\" _\n (ByVal hKey As Long, _\n ByVal lpSubKey As String, _\n ByVal ulOptions As Long, _\n ByVal samDesired As Long, phkResult As Long) As Long\n\n Private Declare Function RegEnumValue Lib \"advapi32.dll\" _\n Alias \"RegEnumValueA\" _\n (ByVal hKey As Long, _\n ByVal dwIndex As Long, _\n ByVal lpValueName As String, _\n lpcbValueName As Long, _\n ByVal lpReserved As Long, _\n lpType As Long, _\n lpData As Any, _\n lpcbData As Long) As Long\n\n Private Declare Function RegCloseKey Lib \"advapi32.dll\" _\n (ByVal hKey As Long) As Long\n\n Const HKEY_CLASSES_ROOT = &amp;H80000000\n Const HKEY_CURRENT_USER = &amp;H80000001\n Const HKEY_LOCAL_MACHINE = &amp;H80000002\n Const HKEY_USERS = &amp;H80000003\n\n Const ERROR_SUCCESS = 0&amp;\n\n Const SYNCHRONIZE = &amp;H100000\n Const STANDARD_RIGHTS_READ = &amp;H20000\n Const STANDARD_RIGHTS_WRITE = &amp;H20000\n Const STANDARD_RIGHTS_EXECUTE = &amp;H20000\n Const STANDARD_RIGHTS_REQUIRED = &amp;HF0000\n Const STANDARD_RIGHTS_ALL = &amp;H1F0000\n Const KEY_QUERY_VALUE = &amp;H1\n Const KEY_SET_VALUE = &amp;H2\n Const KEY_CREATE_SUB_KEY = &amp;H4\n Const KEY_ENUMERATE_SUB_KEYS = &amp;H8\n Const KEY_NOTIFY = &amp;H10\n Const KEY_CREATE_LINK = &amp;H20\n Const KEY_READ = ((STANDARD_RIGHTS_READ Or _\n KEY_QUERY_VALUE Or _\n KEY_ENUMERATE_SUB_KEYS Or _\n KEY_NOTIFY) And _\n (Not SYNCHRONIZE))\n\n Const REG_DWORD = 4\n Const REG_BINARY = 3\n Const REG_SZ = 1\n\n Private Sub Command1_Click()\n Dim lngKeyHandle As Long\n Dim lngResult As Long\n Dim lngCurIdx As Long\n Dim strValue As String\n Dim lngValueLen As Long\n Dim lngData As Long\n Dim lngDataLen As Long\n Dim strResult As String\n\n lngResult = RegOpenKeyEx(HKEY_CURRENT_USER, _\n \"SOFTWARE\\ODBC\\ODBC.INI\\ODBC Data Sources\", _\n 0&amp;, _\n KEY_READ, _\n lngKeyHandle)\n\n If lngResult &lt;&gt; ERROR_SUCCESS Then\n MsgBox \"Cannot open key\"\n Exit Sub\n End If\n\n lngCurIdx = 0\n Do\n lngValueLen = 2000\n strValue = String(lngValueLen, 0)\n lngDataLen = 2000\n\n lngResult = RegEnumValue(lngKeyHandle, _\n lngCurIdx, _\n ByVal strValue, _\n lngValueLen, _\n 0&amp;, _\n REG_DWORD, _\n ByVal lngData, _\n lngDataLen)\n lngCurIdx = lngCurIdx + 1\n\n If lngResult = ERROR_SUCCESS Then\n strResult = strResult &amp; lngCurIdx &amp; \": \" &amp; Left(strValue, lngValueLen) &amp; vbCrLf\n End If\n Loop While lngResult = ERROR_SUCCESS\n Call RegCloseKey(lngKeyHandle)\n\n Call MsgBox(strResult, vbInformation)\n End Sub\n</code></pre>\n" }, { "answer_id": 1026319, "author": "Dimitri C.", "author_id": 74612, "author_profile": "https://Stackoverflow.com/users/74612", "pm_score": 0, "selected": false, "text": "<p>You can use the <b>SQLDataSources</b> function of the ODBC API. See <a href=\"http://msdn.microsoft.com/en-us/library/ms711004.aspx\" rel=\"nofollow noreferrer\">MSDN documentation</a>.</p>\n" }, { "answer_id": 10216835, "author": "blah", "author_id": 1107749, "author_profile": "https://Stackoverflow.com/users/1107749", "pm_score": 0, "selected": false, "text": "<p>Extremely cool solution. I ran into an issue where CURRENT_USER wasn't showing all the DSN's, certainly not the one I needed. I changed it to LOCAL_MACHINE and saw all DSN's that showed up in the Connection Manager, including the subset that showed up under CURRENT_USER.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms712603(v=vs.85).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/windows/desktop/ms712603(v=vs.85).aspx</a></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1354/" ]
I have an Excel application in which I want to present the user with a list of the Data Source Names (ie: DSN's), whereby s/he can choose what data source to use. Hopefully once I've got the list, I can easily access the DSN properties to connect to the appropriate database. Please note, I do *not* want to use a DSN-less connection.
The DSN entries are stored in the registry in the following keys. ``` HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\ODBC Data Sources HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources ``` This contains the list of all defined DSN. This acts as an global index and the specific details for each DSN are stored in a key with the DSN name under: ``` HKEY_CURRENT_USER\Software\ODBC\ODBC.INI HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI ``` Create some entries in both User DSN and System DSN tabs from Data Sources (ODBC) control panel applet and check how these values are stored in the registry. The following example enumerate the DSN defined for the user trough Control Panel > Administrative Tools > Data Sources (ODBC) [User Dsn Tab]. <http://support.microsoft.com/kb/178755> ``` Option Explicit Private Declare Function RegOpenKeyEx Lib "advapi32.dll" _ Alias "RegOpenKeyExA" _ (ByVal hKey As Long, _ ByVal lpSubKey As String, _ ByVal ulOptions As Long, _ ByVal samDesired As Long, phkResult As Long) As Long Private Declare Function RegEnumValue Lib "advapi32.dll" _ Alias "RegEnumValueA" _ (ByVal hKey As Long, _ ByVal dwIndex As Long, _ ByVal lpValueName As String, _ lpcbValueName As Long, _ ByVal lpReserved As Long, _ lpType As Long, _ lpData As Any, _ lpcbData As Long) As Long Private Declare Function RegCloseKey Lib "advapi32.dll" _ (ByVal hKey As Long) As Long Const HKEY_CLASSES_ROOT = &H80000000 Const HKEY_CURRENT_USER = &H80000001 Const HKEY_LOCAL_MACHINE = &H80000002 Const HKEY_USERS = &H80000003 Const ERROR_SUCCESS = 0& Const SYNCHRONIZE = &H100000 Const STANDARD_RIGHTS_READ = &H20000 Const STANDARD_RIGHTS_WRITE = &H20000 Const STANDARD_RIGHTS_EXECUTE = &H20000 Const STANDARD_RIGHTS_REQUIRED = &HF0000 Const STANDARD_RIGHTS_ALL = &H1F0000 Const KEY_QUERY_VALUE = &H1 Const KEY_SET_VALUE = &H2 Const KEY_CREATE_SUB_KEY = &H4 Const KEY_ENUMERATE_SUB_KEYS = &H8 Const KEY_NOTIFY = &H10 Const KEY_CREATE_LINK = &H20 Const KEY_READ = ((STANDARD_RIGHTS_READ Or _ KEY_QUERY_VALUE Or _ KEY_ENUMERATE_SUB_KEYS Or _ KEY_NOTIFY) And _ (Not SYNCHRONIZE)) Const REG_DWORD = 4 Const REG_BINARY = 3 Const REG_SZ = 1 Private Sub Command1_Click() Dim lngKeyHandle As Long Dim lngResult As Long Dim lngCurIdx As Long Dim strValue As String Dim lngValueLen As Long Dim lngData As Long Dim lngDataLen As Long Dim strResult As String lngResult = RegOpenKeyEx(HKEY_CURRENT_USER, _ "SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources", _ 0&, _ KEY_READ, _ lngKeyHandle) If lngResult <> ERROR_SUCCESS Then MsgBox "Cannot open key" Exit Sub End If lngCurIdx = 0 Do lngValueLen = 2000 strValue = String(lngValueLen, 0) lngDataLen = 2000 lngResult = RegEnumValue(lngKeyHandle, _ lngCurIdx, _ ByVal strValue, _ lngValueLen, _ 0&, _ REG_DWORD, _ ByVal lngData, _ lngDataLen) lngCurIdx = lngCurIdx + 1 If lngResult = ERROR_SUCCESS Then strResult = strResult & lngCurIdx & ": " & Left(strValue, lngValueLen) & vbCrLf End If Loop While lngResult = ERROR_SUCCESS Call RegCloseKey(lngKeyHandle) Call MsgBox(strResult, vbInformation) End Sub ```
164,979
<p>I'm after a regex that will validate a full complex UK postcode only within an input string. All of the uncommon postcode forms must be covered as well as the usual. For instance:</p> <p><strong>Matches</strong></p> <ul> <li>CW3 9SS</li> <li>SE5 0EG</li> <li>SE50EG</li> <li>se5 0eg</li> <li>WC2H 7LT</li> </ul> <p><strong>No Match</strong></p> <ul> <li>aWC2H 7LT</li> <li>WC2H 7LTa</li> <li>WC2H</li> </ul> <p>How do I solve this problem?</p>
[ { "answer_id": 164992, "author": "Dan", "author_id": 230, "author_profile": "https://Stackoverflow.com/users/230", "pm_score": 5, "selected": false, "text": "<pre><code>^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$\n</code></pre>\n\n<blockquote>\n <p>Regular expression to match valid UK\n postcodes. In the UK postal system not\n all letters are used in all positions\n (the same with vehicle registration\n plates) and there are various rules to\n govern this. This regex takes into\n account those rules. Details of the\n rules: First half of postcode Valid\n formats [A-Z][A-Z][0-9][A-Z]\n [A-Z][A-Z][0-9][0-9] [A-Z][0-9][0-9]\n [A-Z][A-Z][0-9] [A-Z][A-Z][A-Z]\n [A-Z][0-9][A-Z] [A-Z][0-9] Exceptions\n Position - First. Contraint - QVX not\n used Position - Second. Contraint -\n IJZ not used except in GIR 0AA\n Position - Third. Constraint -\n AEHMNPRTVXY only used Position -\n Forth. Contraint - ABEHMNPRVWXY Second\n half of postcode Valid formats\n [0-9][A-Z][A-Z] Exceptions Position -\n Second and Third. Contraint - CIKMOV\n not used</p>\n</blockquote>\n\n<p><a href=\"http://regexlib.com/REDetails.aspx?regexp_id=260\" rel=\"noreferrer\">http://regexlib.com/REDetails.aspx?regexp_id=260</a></p>\n" }, { "answer_id": 164994, "author": "marcj", "author_id": 23940, "author_profile": "https://Stackoverflow.com/users/23940", "pm_score": 9, "selected": true, "text": "<p>I'd recommend taking a look at the UK Government Data Standard for postcodes [link now dead; <a href=\"http://webarchive.nationalarchives.gov.uk/+/http://www.cabinetoffice.gov.uk/media/291370/bs7666-v2-0-xsd-PostCodeType.htm\" rel=\"noreferrer\">archive of XML</a>, see <a href=\"http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation\" rel=\"noreferrer\">Wikipedia</a> for discussion]. There is a brief description about the data and the attached xml schema provides a regular expression. It may not be exactly what you want but would be a good starting point. The RegEx differs from the XML slightly, as a P character in third position in format A9A 9AA is allowed by the definition given.</p>\n\n<p>The RegEx supplied by the UK Government was:</p>\n\n<pre><code>([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\\s?[0-9][A-Za-z]{2})\n</code></pre>\n\n<p>As pointed out on the Wikipedia discussion, this will allow some non-real postcodes (e.g. those starting AA, ZY) and they do provide a more rigorous test that you could try.</p>\n" }, { "answer_id": 164995, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 2, "selected": false, "text": "<p>First half of postcode Valid formats </p>\n\n<ul>\n<li>[A-Z][A-Z][0-9][A-Z] </li>\n<li>[A-Z][A-Z][0-9][0-9] </li>\n<li>[A-Z][0-9][0-9] </li>\n<li>[A-Z][A-Z][0-9] </li>\n<li>[A-Z][A-Z][A-Z] </li>\n<li>[A-Z][0-9][A-Z] </li>\n<li>[A-Z][0-9] </li>\n</ul>\n\n<p>Exceptions<br>\nPosition 1 - QVX not used<br>\nPosition 2 - IJZ not used except in GIR 0AA<br>\nPosition 3 - AEHMNPRTVXY only used<br>\nPosition 4 - ABEHMNPRVWXY </p>\n\n<p>Second half of postcode </p>\n\n<ul>\n<li>[0-9][A-Z][A-Z] </li>\n</ul>\n\n<p>Exceptions<br>\nPosition 2+3 - CIKMOV not used</p>\n\n<p>Remember not all possible codes are used, so this list is a necessary but not sufficent condition for a valid code. It might be easier to just match against a list of all valid codes?</p>\n" }, { "answer_id": 1600314, "author": "Rudiger Wolf", "author_id": 41431, "author_profile": "https://Stackoverflow.com/users/41431", "pm_score": 1, "selected": false, "text": "<p>Have a look at the python code on this page:</p>\n<p><a href=\"http://www.brunningonline.net/simon/blog/archives/001292.html\" rel=\"nofollow noreferrer\">http://www.brunningonline.net/simon/blog/archives/001292.html</a></p>\n<blockquote>\n<p>I've got some postcode parsing to do. The requirement is pretty simple; I have to parse a postcode into an outcode and (optional) incode. The good new is that I don't have to perform any validation - I just have to chop up what I've been provided with in a vaguely intelligent manner. I can't assume much about my import in terms of formatting, i.e. case and embedded spaces. But this isn't the bad news; the bad news is that I have to do it all in RPG. :-(</p>\n<p>Nevertheless, I threw a little Python function together to clarify my thinking.</p>\n</blockquote>\n<p>I've used it to process postcodes for me.</p>\n" }, { "answer_id": 4793095, "author": "minglis", "author_id": 502087, "author_profile": "https://Stackoverflow.com/users/502087", "pm_score": 3, "selected": false, "text": "<p>Some of the regexs above are a little restrictive. Note the genuine postcode: \"W1K 7AA\" would fail given the rule \"Position 3 - AEHMNPRTVXY only used\" above as \"K\" would be disallowed.</p>\n\n<p>the regex:</p>\n\n<pre><code>^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKPS-UW])[0-9][ABD-HJLNP-UW-Z]{2})$\n</code></pre>\n\n<p>Seems a little more accurate, see the <a href=\"http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom\" rel=\"nofollow\">Wikipedia article entitled 'Postcodes in the United Kingdom'</a>.</p>\n\n<p>Note that this regex requires uppercase only characters.</p>\n\n<p>The bigger question is whether you are restricting user input to allow only postcodes that actually exist or whether you are simply trying to stop users entering complete rubbish into the form fields. Correctly matching every possible postcode, and future proofing it, is a harder puzzle, and probably not worth it unless you are HMRC.</p>\n" }, { "answer_id": 6276530, "author": "Will Tomlins", "author_id": 690904, "author_profile": "https://Stackoverflow.com/users/690904", "pm_score": 3, "selected": false, "text": "<p>Here's a regex based on the format specified in the documents which are linked to marcj's answer:</p>\n\n<pre><code>/^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-Z]{2}$/\n</code></pre>\n\n<p>The only difference between that and the specs is that the last 2 characters cannot be in [CIKMOV] according to the specs.</p>\n\n<p>Edit:\nHere's another version which does test for the trailing character limitations.</p>\n\n<pre><code>/^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-BD-HJLNP-UW-Z]{2}$/\n</code></pre>\n" }, { "answer_id": 7259020, "author": "Colin", "author_id": 521518, "author_profile": "https://Stackoverflow.com/users/521518", "pm_score": 6, "selected": false, "text": "<p>It looks like we're going to be using <code>^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$</code>, which is a slightly modified version of that sugested by Minglis above.</p>\n\n<p>However, we're going to have to investigate exactly what the rules are, as the various solutions listed above appear to apply different rules as to which letters are allowed.</p>\n\n<p>After some research, we've found some more information. Apparently a page on 'govtalk.gov.uk' points you to a postcode specification <a href=\"http://interim.cabinetoffice.gov.uk/govtalk/schemasstandards/e-gif/datastandards/address/postcode.aspx\" rel=\"noreferrer\">govtalk-postcodes</a>. This points to an XML schema at <a href=\"http://interim.cabinetoffice.gov.uk/media/291293/bs7666-v2-0.xml\" rel=\"noreferrer\">XML Schema</a> which provides a 'pseudo regex' statement of the postcode rules.</p>\n\n<p>We've taken that and worked on it a little to give us the following expression:</p>\n\n<pre><code>^((GIR &amp;0AA)|((([A-PR-UWYZ][A-HK-Y]?[0-9][0-9]?)|(([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]))) &amp;[0-9][ABD-HJLNP-UW-Z]{2}))$\n</code></pre>\n\n<p>This makes spaces optional, but does limit you to one space (replace the '&amp;' with '{0,} for unlimited spaces). It assumes all text must be upper-case.</p>\n\n<p>If you want to allow lower case, with any number of spaces, use:</p>\n\n<pre><code>^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$\n</code></pre>\n\n<p>This doesn't cover overseas territories and only enforces the format, NOT the existence of different areas. It is based on the following rules:</p>\n\n<p>Can accept the following formats:</p>\n\n<ul>\n<li>“GIR 0AA”</li>\n<li>A9 9ZZ</li>\n<li>A99 9ZZ</li>\n<li>AB9 9ZZ</li>\n<li>AB99 9ZZ</li>\n<li>A9C 9ZZ</li>\n<li>AD9E 9ZZ</li>\n</ul>\n\n<p>Where:</p>\n\n<ul>\n<li>9 can be any single digit number.</li>\n<li>A can be any letter except for Q, V or X.</li>\n<li>B can be any letter except for I, J or Z.</li>\n<li>C can be any letter except for I, L, M, N, O, P, Q, R, V, X, Y or Z.</li>\n<li>D can be any letter except for I, J or Z.</li>\n<li>E can be any of A, B, E, H, M, N, P, R, V, W, X or Y.</li>\n<li>Z can be any letter except for C, I, K, M, O or V.</li>\n</ul>\n\n<p>Best wishes</p>\n\n<p>Colin</p>\n" }, { "answer_id": 10600422, "author": "Vikas Pandey", "author_id": 1396126, "author_profile": "https://Stackoverflow.com/users/1396126", "pm_score": 1, "selected": false, "text": "<p>I have the regex for UK Postcode validation.</p>\n\n<p>This is working for all type of Postcode either inner or outer</p>\n\n<pre><code>^((([A-PR-UWYZ][0-9])|([A-PR-UWYZ][0-9][0-9])|([A-PR-UWYZ][A-HK-Y][0-9])|([A-PR-UWYZ][A-HK-Y][0-9][0-9])|([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))) || ^((GIR)[ ]?(0AA))$|^(([A-PR-UWYZ][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][0-9][A-HJKS-UW0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9][ABEHMNPRVWXY0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$\n</code></pre>\n\n<p>This is working for all type of format.</p>\n\n<p>Example:</p>\n\n<blockquote>\n <p>AB10-------------------->ONLY OUTER POSTCODE</p>\n \n <p>A1 1AA------------------>COMBINATION OF (OUTER AND INNER) POSTCODE</p>\n \n <p>WC2A-------------------->OUTER</p>\n</blockquote>\n" }, { "answer_id": 11865017, "author": "paulslater19", "author_id": 705752, "author_profile": "https://Stackoverflow.com/users/705752", "pm_score": 0, "selected": false, "text": "<p>We were given a spec:</p>\n\n<pre>UK postcodes must be in one of the following forms (with one exception, see below): \n § A9 9AA \n § A99 9AA\n § AA9 9AA\n § AA99 9AA\n § A9A 9AA\n § AA9A 9AA\nwhere A represents an alphabetic character and 9 represents a numeric character.\nAdditional rules apply to alphabetic characters, as follows:\n § The character in position 1 may not be Q, V or X\n § The character in position 2 may not be I, J or Z\n § The character in position 3 may not be I, L, M, N, O, P, Q, R, V, X, Y or Z\n § The character in position 4 may not be C, D, F, G, I, J, K, L, O, Q, S, T, U or Z\n § The characters in the rightmost two positions may not be C, I, K, M, O or V\nThe one exception that does not follow these general rules is the postcode \"GIR 0AA\", which is a special valid postcode.</pre>\n\n<p>We came up with this: </p>\n\n<pre><code>/^([A-PR-UWYZ][A-HK-Y0-9](?:[A-HJKS-UW0-9][ABEHMNPRV-Y0-9]?)?\\s*[0-9][ABD-HJLNP-UW-Z]{2}|GIR\\s*0AA)$/i\n</code></pre>\n\n<p>But note - this allows any number of spaces in between groups. </p>\n" }, { "answer_id": 14257846, "author": "Dan Solo", "author_id": 1139823, "author_profile": "https://Stackoverflow.com/users/1139823", "pm_score": 3, "selected": false, "text": "<p>I've been looking for a UK postcode regex for the last day or so and stumbled on this thread. I worked my way through most of the suggestions above and none of them worked for me so I came up with my own regex which, as far as I know, captures all valid UK postcodes as of Jan '13 (according to the latest literature from the Royal Mail).</p>\n\n<p>The regex and some simple postcode checking PHP code is posted below. NOTE:- It allows for lower or uppercase postcodes and the GIR 0AA anomaly but to deal with the, more than likely, presence of a space in the middle of an entered postcode it also makes use of a simple str_replace to remove the space before testing against the regex. Any discrepancies beyond that and the Royal Mail themselves don't even mention them in their literature (see <a href=\"http://www.royalmail.com/sites/default/files/docs/pdf/programmers_guide_edition_7_v5.pdf\">http://www.royalmail.com/sites/default/files/docs/pdf/programmers_guide_edition_7_v5.pdf</a> and start reading from page 17)!</p>\n\n<p><strong>Note:</strong> In the Royal Mail's own literature (link above) there is a slight ambiguity surrounding the 3rd and 4th positions and the exceptions in place if these characters are letters. I contacted Royal Mail directly to clear it up and in their own words \"A letter in the 4th position of the Outward Code with the format AANA NAA has no exceptions and the 3rd position exceptions apply only to the last letter of the Outward Code with the format ANA NAA.\" Straight from the horse's mouth!</p>\n\n<pre><code>&lt;?php\n\n $postcoderegex = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\\d[abd-hjlnp-uw-z]{2})?)$/i';\n\n $postcode2check = str_replace(' ','',$postcode2check);\n\n if (preg_match($postcoderegex, $postcode2check)) {\n\n echo \"$postcode2check is a valid postcode&lt;br&gt;\";\n\n } else {\n\n echo \"$postcode2check is not a valid postcode&lt;br&gt;\";\n\n }\n\n?&gt;\n</code></pre>\n\n<p>I hope it helps anyone else who comes across this thread looking for a solution.</p>\n" }, { "answer_id": 15953188, "author": "Alix Axel", "author_id": 89771, "author_profile": "https://Stackoverflow.com/users/89771", "pm_score": 4, "selected": false, "text": "<p>This is the regex Google serves on their <a href=\"http://i18napis.appspot.com/address/data/GB\">i18napis.appspot.com</a> domain:</p>\n\n<pre><code>GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|BX|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\\d[\\dA-Z]?[ ]?\\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\\d{1,4}\n</code></pre>\n" }, { "answer_id": 16485951, "author": "Jesús Carrera", "author_id": 2330244, "author_profile": "https://Stackoverflow.com/users/2330244", "pm_score": 4, "selected": false, "text": "<p>Most of the answers here didn't work for all the postcodes I have in my database. I finally found one that validates with all, using the new regex provided by the government:</p>\n\n<p><a href=\"https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/413338/Bulk_Data_Transfer_-_additional_validation_valid_from_March_2015.pdf\" rel=\"nofollow noreferrer\">https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/413338/Bulk_Data_Transfer_-_additional_validation_valid_from_March_2015.pdf</a></p>\n\n<p>It isn't in any of the previous answers so I post it here in case they take the link down:</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n</code></pre>\n\n<p>UPDATE: Updated regex as pointed by Jamie Bull. Not sure if it was my error copying or it was an error in the government's regex, the link is down now... </p>\n\n<p>UPDATE: As ctwheels found, this regex works with the javascript regex flavor. See his comment for one that works with the pcre (php) flavor.</p>\n" }, { "answer_id": 17024047, "author": "Ben", "author_id": 458741, "author_profile": "https://Stackoverflow.com/users/458741", "pm_score": 6, "selected": false, "text": "<p>There is no such thing as a comprehensive UK postcode regular expression that is capable of <em>validating</em> a postcode. You can check that a postcode is in the correct format using a regular expression; not that it actually exists.</p>\n\n<p>Postcodes are arbitrarily complex and constantly changing. For instance, the outcode <code>W1</code> does not, and may never, have every number between 1 and 99, for every postcode area.</p>\n\n<p>You can't expect what is there currently to be true forever. As an example, in 1990, the Post Office decided that Aberdeen was getting a bit crowded. They added a 0 to the end of AB1-5 making it AB10-50 and then created a number of postcodes in between these. </p>\n\n<p>Whenever a new street is build a new postcode is created. It's part of the process for obtaining permission to build; local authorities are obliged to keep this updated with the Post Office (not that they all do).</p>\n\n<p>Furthermore, as noted by a number of other users, there's the special postcodes such as Girobank, GIR 0AA, and the one for letters to Santa, SAN TA1 - you probably don't want to post anything there but it doesn't appear to be covered by any other answer.</p>\n\n<p>Then, there's the BFPO postcodes, which are now <a href=\"https://www.gov.uk/government/publications/british-forces-post-office-locations\" rel=\"noreferrer\">changing to a more standard format</a>. Both formats are going to be valid. Lastly, there's the overseas territories <sup><a href=\"http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom\" rel=\"noreferrer\">source Wikipedia</a></sup>.</p>\n\n<pre>\n+----------+----------------------------------------------+\n| Postcode | Location |\n+----------+----------------------------------------------+\n| AI-2640 | Anguilla |\n| ASCN 1ZZ | Ascension Island |\n| STHL 1ZZ | Saint Helena |\n| TDCU 1ZZ | Tristan da Cunha |\n| BBND 1ZZ | British Indian Ocean Territory |\n| BIQQ 1ZZ | British Antarctic Territory |\n| FIQQ 1ZZ | Falkland Islands |\n| GX11 1AA | Gibraltar |\n| PCRN 1ZZ | Pitcairn Islands |\n| SIQQ 1ZZ | South Georgia and the South Sandwich Islands |\n| TKCA 1ZZ | Turks and Caicos Islands |\n+----------+----------------------------------------------+</pre>\n\n<p>Next, you have to take into account that the UK \"exported\" its postcode system to many places in the world. Anything that validates a \"UK\" postcode will also validate the postcodes of a number of other countries.</p>\n\n<p>If you want to <em>validate</em> a UK postcode the safest way to do it is to use a look-up of current postcodes. There are a number of options:</p>\n\n<ul>\n<li><p>Ordnance Survey releases <a href=\"http://www.ordnancesurvey.co.uk/oswebsite/products/code-point-open/\" rel=\"noreferrer\">Code-Point Open</a> under an open data licence. It'll be very slightly behind the times but it's free. This will (probably - I can't remember) not include Northern Irish data as the Ordnance Survey has no remit there. Mapping in Northern Ireland is conducted by the Ordnance Survey of Northern Ireland and they have their, separate, paid-for, <a href=\"https://maps.osni.gov.uk/CMSPages/moreinfo_address_data.aspx\" rel=\"noreferrer\">Pointer</a> product. You could use this and append the few that aren't covered fairly easily.</p></li>\n<li><p>Royal Mail releases the <a href=\"http://www.poweredbypaf.com/\" rel=\"noreferrer\">Postcode Address File (PAF)</a>, this includes BFPO which I'm not sure Code-Point Open does. It's updated regularly but costs money (and they can be downright mean about it sometimes). PAF includes the full address rather than just postcodes and comes with its own <a href=\"http://www.poweredbypaf.com/wp-content/themes/amu/paf_downloads/programmers_guide.pdf\" rel=\"noreferrer\">Programmers Guide</a>. The Open Data User Group (ODUG) is currently lobbying to have PAF released for free, <a href=\"http://data.gov.uk/library/odug-response-to-ofcom-paf-review-consultation\" rel=\"noreferrer\">here's a description of their position</a>.</p></li>\n<li><p>Lastly, there's <a href=\"https://www.ordnancesurvey.co.uk/business-and-government/products/addressbase-products.html\" rel=\"noreferrer\">AddressBase</a>. This is a collaboration between Ordnance Survey, Local Authorities, Royal Mail and a matching company to create a definitive directory of all information about all UK addresses (they've been fairly successful as well). It's paid-for but if you're working with a Local Authority, government department, or government service it's free for them to use. There's a lot more information than just postcodes included.</p></li>\n</ul>\n" }, { "answer_id": 17507615, "author": "RichardTowers", "author_id": 1344760, "author_profile": "https://Stackoverflow.com/users/1344760", "pm_score": 4, "selected": false, "text": "<p>I had a look into some of the answers above and I'd recommend against using the pattern from @Dan's <a href=\"https://stackoverflow.com/questions/164979/uk-postcode-regex-comprehensive#answer-164992\">answer (c. Dec 15 '10)</a>, since it incorrectly flags almost 0.4% of valid postcodes as invalid, while the others do not. </p>\n\n<p>Ordnance Survey provide service called Code Point Open which:</p>\n\n<blockquote>\n <p>contains a list of all the current postcode units in Great Britain</p>\n</blockquote>\n\n<p>I ran each of the regexs above against the full list of postcodes (Jul 6 '13) from this data using <code>grep</code>:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>cat CSV/*.csv |\n # Strip leading quotes\n sed -e 's/^\"//g' |\n # Strip trailing quote and everything after it\n sed -e 's/\".*//g' |\n # Strip any spaces\n sed -E -e 's/ +//g' |\n # Find any lines that do not match the expression\n grep --invert-match --perl-regexp \"$pattern\"\n</code></pre>\n\n<p>There are 1,686,202 postcodes total.</p>\n\n<p>The following are the numbers of valid postcodes that do <em>not</em> match each <code>$pattern</code>:</p>\n\n<pre><code>'^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$'\n# =&gt; 6016 (0.36%)\n</code></pre>\n\n\n\n<pre><code>'^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$'\n# =&gt; 0\n</code></pre>\n\n\n\n<pre><code>'^GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|BX|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\\d[\\dA-Z]?[ ]?\\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\\d{1,4}$'\n# =&gt; 0\n</code></pre>\n\n<p>Of course, these results only deal with valid postcodes that are incorrectly flagged as invalid. So:</p>\n\n<pre><code>'^.*$'\n# =&gt; 0\n</code></pre>\n\n<p>I'm saying nothing about which pattern is the best regarding filtering out invalid postcodes.</p>\n" }, { "answer_id": 23375983, "author": "andre", "author_id": 3108126, "author_profile": "https://Stackoverflow.com/users/3108126", "pm_score": 3, "selected": false, "text": "<p>Postcodes are subject to change, and the only true way of validating a postcode is to have the complete list of postcodes and see if it's there.</p>\n\n<p>But regular expressions are useful because they:</p>\n\n<ul>\n<li>are easy to use and implement</li>\n<li>are short</li>\n<li>are quick to run</li>\n<li>are quite easy to maintain (compared to a full list of postcodes)</li>\n<li>still catch most input errors</li>\n</ul>\n\n<p>But regular expressions tend to be difficult to maintain, especially for someone who didn't come up with it in the first place. So it must be:</p>\n\n<ul>\n<li>as easy to understand as possible</li>\n<li>relatively future proof</li>\n</ul>\n\n<p>That means that most of the regular expressions in this answer aren't good enough. E.g. I can see that <code>[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]</code> is going to match a postcode area of the form AA1A — but it's going to be a pain in the neck if and when a new postcode area gets added, because it's difficult to understand which postcode areas it matches.</p>\n\n<p>I also want my regular expression to match the first and second half of the postcode as parenthesised matches.</p>\n\n<p>So I've come up with this:</p>\n\n<pre><code>(GIR(?=\\s*0AA)|(?:[BEGLMNSW]|[A-Z]{2})[0-9](?:[0-9]|(?&lt;=N1|E1|SE1|SW1|W1|NW1|EC[0-9]|WC[0-9])[A-HJ-NP-Z])?)\\s*([0-9][ABD-HJLNP-UW-Z]{2})\n</code></pre>\n\n<p>In PCRE format it can be written as follows:</p>\n\n<pre><code>/^\n ( GIR(?=\\s*0AA) # Match the special postcode \"GIR 0AA\"\n |\n (?:\n [BEGLMNSW] | # There are 8 single-letter postcode areas\n [A-Z]{2} # All other postcode areas have two letters\n )\n [0-9] # There is always at least one number after the postcode area\n (?:\n [0-9] # And an optional extra number\n |\n # Only certain postcode areas can have an extra letter after the number\n (?&lt;=N1|E1|SE1|SW1|W1|NW1|EC[0-9]|WC[0-9])\n [A-HJ-NP-Z] # Possible letters here may change, but [IO] will never be used\n )?\n )\n \\s*\n ([0-9][ABD-HJLNP-UW-Z]{2}) # The last two letters cannot be [CIKMOV]\n$/x\n</code></pre>\n\n<p>For me this is the right balance between validating as much as possible, while at the same time future-proofing and allowing for easy maintenance.</p>\n" }, { "answer_id": 25176865, "author": "Alex Stephens", "author_id": 1955203, "author_profile": "https://Stackoverflow.com/users/1955203", "pm_score": 2, "selected": false, "text": "<p>here's how we have been dealing with the UK postcode issue:</p>\n\n<pre><code>^([A-Za-z]{1,2}[0-9]{1,2}[A-Za-z]?[ ]?)([0-9]{1}[A-Za-z]{2})$\n</code></pre>\n\n<p><strong>Explanation:</strong></p>\n\n<ul>\n<li>expect 1 or 2 a-z chars, upper or lower fine</li>\n<li>expect 1 or 2 numbers</li>\n<li>expect 0 or 1 a-z char, upper or lower fine</li>\n<li>optional space allowed</li>\n<li>expect 1 number</li>\n<li>expect 2 a-z, upper or lower fine</li>\n</ul>\n\n<p>This gets most formats, we then use the db to validate whether the postcode is actually real, this data is driven by openpoint <a href=\"https://www.ordnancesurvey.co.uk/opendatadownload/products.html\" rel=\"nofollow\">https://www.ordnancesurvey.co.uk/opendatadownload/products.html</a></p>\n\n<p>hope this helps</p>\n" }, { "answer_id": 26887154, "author": "deadcrab", "author_id": 1071022, "author_profile": "https://Stackoverflow.com/users/1071022", "pm_score": 4, "selected": false, "text": "<p>An old post but still pretty high in google results so thought I'd update. This Oct 14 doc defines the UK postcode regular expression as:</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([**AZ**a-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n</code></pre>\n\n<p>from:</p>\n\n<p><a href=\"https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/359448/4__Bulk_Data_Transfer_-_additional_validation_valid.pdf\" rel=\"nofollow noreferrer\">https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/359448/4__Bulk_Data_Transfer_-_additional_validation_valid.pdf</a></p>\n\n<p>The document also explains the logic behind it. However, it has an error (bolded) and also allows lower case, which although legal is not usual, so amended version:</p>\n\n<pre><code>^(GIR 0AA)|((([A-Z][0-9]{1,2})|(([A-Z][A-HJ-Y][0-9]{1,2})|(([A-Z][0-9][A-Z])|([A-Z][A-HJ-Y][0-9]?[A-Z])))) [0-9][A-Z]{2})$\n</code></pre>\n\n<p>This works with new London postcodes (e.g. W1D 5LH) that previous versions did not.</p>\n" }, { "answer_id": 28108191, "author": "Raphos", "author_id": 4222767, "author_profile": "https://Stackoverflow.com/users/4222767", "pm_score": 2, "selected": false, "text": "<p><strong>Basic rules:</strong></p>\n\n<pre><code>^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$\n</code></pre>\n\n<p>Postal codes in the U.K. (or postcodes, as they’re called) are composed of five to seven alphanumeric characters separated by a space. The rules covering which characters can appear at particular positions are rather complicated and fraught with exceptions. The regular expression just shown therefore sticks to the basic rules.</p>\n\n<p><strong>Complete rules:</strong></p>\n\n<p>If you need a regex that ticks all the boxes for the postcode rules at the expense of readability, here you go:</p>\n\n<pre><code>^(?:(?:[A-PR-UWYZ][0-9]{1,2}|[A-PR-UWYZ][A-HK-Y][0-9]{1,2}|[A-PR-UWYZ][0-9][A-HJKSTUW]|[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]) [0-9][ABD-HJLNP-UW-Z]{2}|GIR 0AA)$\n</code></pre>\n\n<p><em>Source: <a href=\"https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s16.html\" rel=\"nofollow\">https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s16.html</a></em></p>\n\n<p>Tested against our customers database and seems perfectly accurate.</p>\n" }, { "answer_id": 29302162, "author": "Jackson Pauls", "author_id": 1777662, "author_profile": "https://Stackoverflow.com/users/1777662", "pm_score": 2, "selected": false, "text": "<p>To check a postcode is in a valid format as per the Royal Mail's <a href=\"http://www.royalmail.com/sites/default/files/docs/pdf/programmers_guide_edition_7_v5.pdf\" rel=\"nofollow\">programmer's guide</a>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> |----------------------------outward code------------------------------| |------inward code-----|\n#special↓ α1 α2 AAN AANA AANN AN ANN ANA (α3) N AA\n^(GIR 0AA|[A-PR-UWYZ]([A-HK-Y]([0-9][A-Z]?|[1-9][0-9])|[1-9]([0-9]|[A-HJKPSTUW])?) [0-9][ABD-HJLNP-UW-Z]{2})$\n</code></pre>\n\n<p>All postcodes on <a href=\"http://www.doogal.co.uk/UKPostcodes.php\" rel=\"nofollow\">doogal.co.uk</a> match, except for those no longer in use.</p>\n\n<p>Adding a <code>?</code> after the space and using case-insensitive match to answer this question:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>'se50eg'.match(/^(GIR 0AA|[A-PR-UWYZ]([A-HK-Y]([0-9][A-Z]?|[1-9][0-9])|[1-9]([0-9]|[A-HJKPSTUW])?) ?[0-9][ABD-HJLNP-UW-Z]{2})$/ig);\nArray [ \"se50eg\" ]\n</code></pre>\n" }, { "answer_id": 29363535, "author": "Stieb", "author_id": 3060634, "author_profile": "https://Stackoverflow.com/users/3060634", "pm_score": 0, "selected": false, "text": "<p>The accepted answer reflects the rules given by Royal Mail, although there is a typo in the regex. This typo seems to have been in there on the gov.uk site as well (as it is in the XML archive page).</p>\n\n<p>In the format A9A 9AA the rules allow a P character in the third position, whilst the regex disallows this. The correct regex would be:</p>\n\n<pre><code>(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKPSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2}) \n</code></pre>\n\n<p>Shortening this results in the following regex (which uses Perl/Ruby syntax):</p>\n\n<pre><code>(GIR 0AA)|([A-PR-UWYZ](([0-9]([0-9A-HJKPSTUW])?)|([A-HK-Y][0-9]([0-9ABEHMNPRVWXY])?))\\s?[0-9][ABD-HJLNP-UW-Z]{2})\n</code></pre>\n\n<p>It also includes an optional space between the first and second block. </p>\n" }, { "answer_id": 29820230, "author": "AntPachon", "author_id": 763085, "author_profile": "https://Stackoverflow.com/users/763085", "pm_score": 4, "selected": false, "text": "<p>According to this Wikipedia table</p>\n\n<p><img src=\"https://i.stack.imgur.com/XOv8u.png\" alt=\"enter image description here\"></p>\n\n<p>This pattern cover all the cases </p>\n\n<pre><code>(?:[A-Za-z]\\d ?\\d[A-Za-z]{2})|(?:[A-Za-z][A-Za-z\\d]\\d ?\\d[A-Za-z]{2})|(?:[A-Za-z]{2}\\d{2} ?\\d[A-Za-z]{2})|(?:[A-Za-z]\\d[A-Za-z] ?\\d[A-Za-z]{2})|(?:[A-Za-z]{2}\\d[A-Za-z] ?\\d[A-Za-z]{2})\n</code></pre>\n\n<p>When using it on Android\\Java use \\\\d</p>\n" }, { "answer_id": 32735959, "author": "User1", "author_id": 2987066, "author_profile": "https://Stackoverflow.com/users/2987066", "pm_score": 2, "selected": false, "text": "<p>To add to this list a more practical regex that I use that allows the user to enter an <code>empty string</code> is:</p>\n\n<pre><code>^$|^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,1}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$\n</code></pre>\n\n<p>This regex allows capital and lower case letters with an optional space in between</p>\n\n<p>From a software developers point of view this regex is useful for software where an address may be optional. For example if a user did not want to supply their address details</p>\n" }, { "answer_id": 33610889, "author": "Chisel", "author_id": 2991563, "author_profile": "https://Stackoverflow.com/users/2991563", "pm_score": 2, "selected": false, "text": "<p>I use the following regex that I have tested against all valid UK postcodes. It is based on the recommended rules, but condensed as much as reasonable and does not make use of any special language specific regex rules.</p>\n\n<pre><code>([A-PR-UWYZ]([A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y])?|[0-9]([0-9]|[A-HJKPSTUW])?) ?[0-9][ABD-HJLNP-UW-Z]{2})\n</code></pre>\n\n<p>It assumes that the postcode has been converted to uppercase and has not leading or trailing characters, but will accept an optional space between the outcode and incode.</p>\n\n<p>The special \"GIR0 0AA\" postcode is excluded and will not validate as it's not in the official Post Office list of postcodes and as far as I'm aware will not be used as registered address. Adding it should be trivial as a special case if required.</p>\n" }, { "answer_id": 34593598, "author": "Matas Vaitkevicius", "author_id": 1509764, "author_profile": "https://Stackoverflow.com/users/1509764", "pm_score": 2, "selected": false, "text": "<p>This one allows empty spaces and tabs from both sides in case you don't want to fail validation and then trim it sever side.</p>\n\n<pre><code>^\\s*(([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})\\s*$)\n</code></pre>\n" }, { "answer_id": 43793562, "author": "user667489", "author_id": 667489, "author_profile": "https://Stackoverflow.com/users/667489", "pm_score": -1, "selected": false, "text": "<p>I needed a version that would work in SAS with the <code>PRXMATCH</code> and related functions, so I came up with this:</p>\n\n<pre><code>^[A-PR-UWYZ](([A-HK-Y]?\\d\\d?)|(\\d[A-HJKPSTUW])|([A-HK-Y]\\d[ABEHMNPRV-Y]))\\s?\\d[ABD-HJLNP-UW-Z]{2}$\n</code></pre>\n\n<p>Test cases and notes:</p>\n\n<pre><code>/* \nNotes\nThe letters QVX are not used in the 1st position.\nThe letters IJZ are not used in the second position.\nThe only letters to appear in the third position are ABCDEFGHJKPSTUW when the structure starts with A9A.\nThe only letters to appear in the fourth position are ABEHMNPRVWXY when the structure starts with AA9A.\nThe final two letters do not use the letters CIKMOV, so as not to resemble digits or each other when hand-written.\n*/\n\n/*\n Bits and pieces\n 1st position (any): [A-PR-UWYZ] \n 2nd position (if letter): [A-HK-Y]\n 3rd position (A1A format): [A-HJKPSTUW]\n 4th position (AA1A format): [ABEHMNPRV-Y]\n Last 2 positions: [ABD-HJLNP-UW-Z] \n*/\n\n\ndata example;\ninfile cards truncover;\ninput valid 1. postcode &amp;$10. Notes &amp;$100.;\nflag = prxmatch('/^[A-PR-UWYZ](([A-HK-Y]?\\d\\d?)|(\\d[A-HJKPSTUW])|([A-HK-Y]\\d[ABEHMNPRV-Y]))\\s?\\d[ABD-HJLNP-UW-Z]{2}$/',strip(postcode));\ncards;\n1 EC1A 1BB Special case 1\n1 W1A 0AX Special case 2\n1 M1 1AE Standard format\n1 B33 8TH Standard format\n1 CR2 6XH Standard format\n1 DN55 1PT Standard format\n0 QN55 1PT Bad letter in 1st position\n0 DI55 1PT Bad letter in 2nd position\n0 W1Z 0AX Bad letter in 3rd position\n0 EC1Z 1BB Bad letter in 4th position\n0 DN55 1CT Bad letter in 2nd group\n0 A11A 1AA Invalid digits in 1st group\n0 AA11A 1AA 1st group too long\n0 AA11 1AAA 2nd group too long\n0 AA11 1AAA 2nd group too long\n0 AAA 1AA No digit in 1st group\n0 AA 1AA No digit in 1st group\n0 A 1AA No digit in 1st group\n0 1A 1AA Missing letter in 1st group\n0 1 1AA Missing letter in 1st group\n0 11 1AA Missing letter in 1st group\n0 AA1 1A Missing letter in 2nd group\n0 AA1 1 Missing letter in 2nd group\n;\nrun;\n</code></pre>\n" }, { "answer_id": 47313542, "author": "Andrew Schliewe", "author_id": 6211051, "author_profile": "https://Stackoverflow.com/users/6211051", "pm_score": 0, "selected": false, "text": "<p>What i have found in nearly all the variations and the regex from the bulk transfer pdf and what is on wikipedia site is this, specifically for the wikipedia regex is, there needs to be a ^ after the first |(vertical bar). I figured this out by testing for AA9A 9AA, because otherwise the format check for A9A 9AA will validate it. For Example checking for EC1D 1BB which should be invalid comes back valid because C1D 1BB is a valid format.</p>\n\n<p>Here is what I've come up with for a good regex:</p>\n\n<pre><code>^([G][I][R] 0[A]{2})|^((([A-Z-[QVX]][0-9]{1,2})|([A-Z-[QVX]][A-HK-Y][0-9]{1,2})|([A-Z-[QVX]][0-9][ABCDEFGHJKPSTUW])|([A-Z-[QVX]][A-HK-Y][0-9][ABEHMNPRVWXY])) [0-9][A-Z-[CIKMOV]]{2})$\n</code></pre>\n" }, { "answer_id": 47589824, "author": "Henrik N", "author_id": 6962, "author_profile": "https://Stackoverflow.com/users/6962", "pm_score": 3, "selected": false, "text": "<p>I wanted a simple regex, where it's fine to allow too much, but not to deny a valid postcode. I went with this (the input is a stripped/trimmed string):</p>\n\n<pre><code>/^([a-z0-9]\\s*){5,8}$/i\n</code></pre>\n\n<p>This allows the shortest possible postcodes like \"L1 8JQ\" as well as the longest ones like \"OL14 5ET\".</p>\n\n<p>Because it allows up to 8 characters, it will also allow incorrect 8 character postcodes if there is no space: \"OL145ETX\". But again, this is a simplistic regex, for when that's good enough.</p>\n" }, { "answer_id": 51885364, "author": "ctwheels", "author_id": 3600709, "author_profile": "https://Stackoverflow.com/users/3600709", "pm_score": 8, "selected": false, "text": "<p>I recently posted <a href=\"https://stackoverflow.com/a/51828886/3600709\">an answer</a> to <a href=\"https://stackoverflow.com/q/51828712/3600709\">this question on UK postcodes for the R language</a>. I discovered that <strong>the UK Government's regex pattern is incorrect</strong> and fails to <em>properly</em> validate some postcodes. Unfortunately, many of the answers here are based on this incorrect pattern.</p>\n\n<p>I'll outline some of these issues below and provide a revised regular expression that <em>actually</em> works.</p>\n\n<hr>\n\n<h1>Note</h1>\n\n<p><strong>My answer</strong> (and regular expressions in general):</p>\n\n<ul>\n<li><strong>Only validates postcode <em>formats</em></strong>.</li>\n<li><strong>Does not ensure that a postcode <em>legitimately exists</em></strong>.\n\n<ul>\n<li>For this, use an appropriate API! See <a href=\"https://stackoverflow.com/a/17024047/3600709\">Ben's answer</a> for more info.</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p><sub>If you don't care about the <em>bad regex</em> and just want to skip to the answer, scroll down to the <strong>Answer</strong> section.</sub></p>\n\n<h1>The Bad Regex</h1>\n\n<p><strong>The regular expressions in this section should not be used.</strong></p>\n\n<p>This is the failing regex that the UK government has provided developers (not sure how long this link will be up, but you can see it in their <a href=\"https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/488478/Bulk_Data_Transfer_-_additional_validation_valid_from_12_November_2015.pdf\" rel=\"noreferrer\">Bulk Data Transfer documentation</a>):</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$\n</code></pre>\n\n<h2>Problems</h2>\n\n<h3>Problem 1 - Copy/Paste</h3>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/1\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<p>As many developers likely do, they copy/paste code (especially regular expressions) and paste them expecting them to work. While this is great in theory, it fails in this particular case because copy/pasting from this document actually changes one of the characters (a space) into a newline character as shown below:</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\n[0-9][A-Za-z]{2})$\n</code></pre>\n\n<p>The first thing most developers will do is just erase the newline without thinking twice. Now the regex won't match postcodes with spaces in them (other than the <code>GIR 0AA</code> postcode).</p>\n\n<p>To fix this issue, the newline character should be replaced with the space character:</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n ^\n</code></pre>\n\n<h3>Problem 2 - Boundaries</h3>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/2\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n^^ ^ ^ ^^\n</code></pre>\n\n<p>The postcode regex improperly anchors the regex. Anyone using this regex to validate postcodes might be surprised if a value like <code>fooA11 1AA</code> gets through. That's because they've anchored the start of the first option and the end of the second option (independently of one another), as pointed out in the regex above.</p>\n\n<p>What this means is that <code>^</code> (asserts position at start of the line) only works on the first option <code>([Gg][Ii][Rr] 0[Aa]{2})</code>, so the second option will validate any strings that <strong>end</strong> in a postcode (regardless of what comes before).</p>\n\n<p>Similarly, the first option isn't anchored to the end of the line <code>$</code>, so <code>GIR 0AAfoo</code> is also accepted.</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$\n</code></pre>\n\n<p>To fix this issue, both options should be wrapped in another group (or non-capturing group) and the anchors placed around that: </p>\n\n<pre><code>^(([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2}))$\n^^ ^^\n</code></pre>\n\n<h3>Problem 3 - Improper Character Set</h3>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/3\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n ^^\n</code></pre>\n\n<p>The regex is missing a <code>-</code> here to indicate a range of characters. As it stands, if a postcode is in the format <code>ANA NAA</code> (where <code>A</code> represents a letter and <code>N</code> represents a number), and it begins with anything other than <code>A</code> or <code>Z</code>, it will fail.</p>\n\n<p>That means it will match <code>A1A 1AA</code> and <code>Z1A 1AA</code>, but not <code>B1A 1AA</code>.</p>\n\n<p>To fix this issue, the character <code>-</code> should be placed between the <code>A</code> and <code>Z</code> in the respective character set:</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n ^\n</code></pre>\n\n<h3>Problem 4 - Wrong Optional Character Set</h3>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/4\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n ^\n</code></pre>\n\n<p>I swear they didn't even test this thing before publicizing it on the web. They made the wrong character set optional. They made <code>[0-9]</code> option in the fourth sub-option of option 2 (group 9). This allows the regex to match incorrectly formatted postcodes like <code>AAA 1AA</code>.</p>\n\n<p>To fix this issue, make the next character class optional instead (and subsequently make the set <code>[0-9]</code> match exactly once):</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?)))) [0-9][A-Za-z]{2})$\n ^\n</code></pre>\n\n<h3>Problem 5 - Performance</h3>\n\n<p>Performance on this regex is extremely poor. First off, they placed the least likely pattern option to match <code>GIR 0AA</code> at the beginning. How many users will likely have this postcode versus any other postcode; probably never? This means every time the regex is used, it must exhaust this option first before proceeding to the next option. To see how performance is impacted check the number of steps the <a href=\"https://regex101.com/r/ajQHrd/5\" rel=\"noreferrer\">original regex</a> took (35) against the <a href=\"https://regex101.com/r/ajQHrd/6\" rel=\"noreferrer\">same regex after having flipped the options</a> (22).</p>\n\n<p>The second issue with performance is due to the way the entire regex is structured. There's no point backtracking over each option if one fails. The way the current regex is structured can greatly be simplified. I provide a fix for this in the <strong>Answer</strong> section.</p>\n\n<h3>Problem 6 - Spaces</h3>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/8\" rel=\"noreferrer\">See regex in use here</a></p>\n\n<p>This may not be considered a <em>problem</em>, per se, but it does raise concern for most developers. The spaces in the regex are not optional, which means the users inputting their postcodes must place a space in the postcode. This is an easy fix by simply adding <code>?</code> after the spaces to render them optional. See the <strong>Answer</strong> section for a fix.</p>\n\n<hr>\n\n<h1>Answer</h1>\n\n<h2>1. Fixing the UK Government's Regex</h2>\n\n<p>Fixing all the issues outlined in the <strong>Problems</strong> section and simplifying the pattern yields the following, shorter, more concise pattern. We can also remove most of the groups since we're validating the postcode as a whole (not individual parts):</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/12\" rel=\"noreferrer\">See regex in use here</a></p>\n\n<pre><code>^([A-Za-z][A-Ha-hJ-Yj-y]?[0-9][A-Za-z0-9]? ?[0-9][A-Za-z]{2}|[Gg][Ii][Rr] ?0[Aa]{2})$\n</code></pre>\n\n<p>This can further be shortened by removing all of the ranges from one of the cases (upper or lower case) and using a case-insensitive flag. <strong>Note</strong>: Some languages don't have one, so use the longer one above. Each language implements the case-insensitivity flag differently.</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/13\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([A-Z][A-HJ-Y]?[0-9][A-Z0-9]? ?[0-9][A-Z]{2}|GIR ?0A{2})$\n</code></pre>\n\n<p>Shorter again replacing <code>[0-9]</code> with <code>\\d</code> (if your regex engine supports it):</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/14\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([A-Z][A-HJ-Y]?\\d[A-Z\\d]? ?\\d[A-Z]{2}|GIR ?0A{2})$\n</code></pre>\n\n<h2>2. Simplified Patterns</h2>\n\n<p>Without ensuring specific alphabetic characters, the following can be used (keep in mind the simplifications from <strong>1. Fixing the UK Government's Regex</strong> have also been applied here):</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/15\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}|GIR ?0A{2})$\n</code></pre>\n\n<p>And even further if you don't care about the special case <code>GIR 0AA</code>:</p>\n\n<pre><code>^[A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}$\n</code></pre>\n\n<h2>3. Complicated Patterns</h2>\n\n<p>I would not suggest over-verification of a postcode as new Areas, Districts and Sub-districts may appear at any point in time. What I will suggest <em>potentially</em> doing, is added support for edge-cases. Some special cases exist and are outlined in <a href=\"https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Special_cases\" rel=\"noreferrer\">this Wikipedia article</a>.</p>\n\n<p>Here are complex regexes that include the subsections of <strong>3.</strong> (3.1, 3.2, 3.3).</p>\n\n<p>In relation to the patterns in <strong>1. Fixing the UK Government's Regex</strong>:</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/19\" rel=\"noreferrer\">See regex in use here</a></p>\n\n<pre><code>^(([A-Z][A-HJ-Y]?\\d[A-Z\\d]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?\\d[A-Z]{2}|BFPO ?\\d{1,4}|(KY\\d|MSR|VG|AI)[ -]?\\d{4}|[A-Z]{2} ?\\d{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$\n</code></pre>\n\n<p>And in relation to <strong>2. Simplified Patterns</strong>:</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/20\" rel=\"noreferrer\">See regex in use here</a></p>\n\n<pre><code>^(([A-Z]{1,2}\\d[A-Z\\d]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?\\d[A-Z]{2}|BFPO ?\\d{1,4}|(KY\\d|MSR|VG|AI)[ -]?\\d{4}|[A-Z]{2} ?\\d{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$\n</code></pre>\n\n<h3>3.1 British Overseas Territories</h3>\n\n<p>The Wikipedia article currently states (some formats slightly simplified):</p>\n\n<ul>\n<li><code>AI-1111</code>: Anguila</li>\n<li><code>ASCN 1ZZ</code>: Ascension Island</li>\n<li><code>STHL 1ZZ</code>: Saint Helena</li>\n<li><code>TDCU 1ZZ</code>: Tristan da Cunha</li>\n<li><code>BBND 1ZZ</code>: British Indian Ocean Territory</li>\n<li><code>BIQQ 1ZZ</code>: British Antarctic Territory</li>\n<li><code>FIQQ 1ZZ</code>: Falkland Islands</li>\n<li><code>GX11 1ZZ</code>: Gibraltar</li>\n<li><code>PCRN 1ZZ</code>: Pitcairn Islands</li>\n<li><code>SIQQ 1ZZ</code>: South Georgia and the South Sandwich Islands</li>\n<li><code>TKCA 1ZZ</code>: Turks and Caicos Islands</li>\n<li><code>BFPO 11</code>: Akrotiri and Dhekelia</li>\n<li><code>ZZ 11</code> &amp; <code>GE CX</code>: Bermuda (according to <a href=\"http://www.bpo.bm/Lists/Postal%20Codes/Attachments/1/Bermuda%20Postal%20Codes%20and%20Parishes%202013.pdf\" rel=\"noreferrer\">this document</a>)</li>\n<li><code>KY1-1111</code>: Cayman Islands (according to <a href=\"http://www.caymanpost.gov.ky/portal/page/portal/poshome/posnpimages/POSTCODE%20FINDER%20COLOUR.pdf\" rel=\"noreferrer\">this document</a>)</li>\n<li><code>VG1111</code>: British Virgin Islands (according to <a href=\"http://www.bvi.gov.vg/content/what-are-postcodes-addresses-british-virgin-islands\" rel=\"noreferrer\">this document</a>)</li>\n<li><code>MSR 1111</code>: Montserrat (according to <a href=\"http://www.gov.ms/wp-content/uploads/2014/02/Postal-Code-Guide-pamphlet.pdf\" rel=\"noreferrer\">this document</a>)</li>\n</ul>\n\n<p>An all-encompassing regex to match only the British Overseas Territories might look like this:</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/15\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^((ASCN|STHL|TDCU|BBND|[BFS]IQQ|GX\\d{2}|PCRN|TKCA) ?\\d[A-Z]{2}|(KY\\d|MSR|VG|AI)[ -]?\\d{4}|(BFPO|[A-Z]{2}) ?\\d{2}|GE ?CX)$\n</code></pre>\n\n<h3>3.2 British Forces Post Office</h3>\n\n<p>Although they've been recently changed it to better align with the British postcode system to <code>BF#</code> (where <code>#</code> represents a number), they're considered <em>optional alternative postcodes</em>. These postcodes follow(ed) the format of <code>BFPO</code>, followed by 1-4 digits:</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/17\" rel=\"noreferrer\">See regex in use here</a></p>\n\n<pre><code>^BFPO ?\\d{1,4}$\n</code></pre>\n\n<h3>3.3 Santa?</h3>\n\n<p>There's another special case with Santa (as mentioned in other answers): <code>SAN TA1</code> is a valid postcode. A regex for this is very simply:</p>\n\n<pre><code>^SAN ?TA1$\n</code></pre>\n" }, { "answer_id": 55083027, "author": "Aathi", "author_id": 3008370, "author_profile": "https://Stackoverflow.com/users/3008370", "pm_score": 0, "selected": false, "text": "<p>Below method will check the post code and provide complete info</p>\n<pre class=\"lang-js prettyprint-override\"><code>const isValidUKPostcode = postcode =&gt; {\n try {\n postcode = postcode.replace(/\\s/g, &quot;&quot;);\n const fromat = postcode\n .toUpperCase()\n .match(/^([A-Z]{1,2}\\d{1,2}[A-Z]?)\\s*(\\d[A-Z]{2})$/);\n const finalValue = `${fromat[1]} ${fromat[2]}`;\n const regex = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$/i;\n return {\n isValid: regex.test(postcode),\n formatedPostCode: finalValue,\n error: false,\n message: 'It is a valid postcode'\n };\n } catch (error) {\n return { error: true , message: 'Invalid postcode'};\n }\n};\n</code></pre>\n<pre class=\"lang-js prettyprint-override\"><code>console.log(isValidUKPostcode('GU348RR'))\n{isValid: true, formattedPostcode: &quot;GU34 8RR&quot;, error: false, message: &quot;It is a valid postcode&quot;}\n</code></pre>\n<pre class=\"lang-js prettyprint-override\"><code>console.log(isValidUKPostcode('sdasd4746asd'))\n{error: true, message: &quot;Invalid postcode!&quot;}\n</code></pre>\n<pre class=\"lang-js prettyprint-override\"><code>valid_postcode('787898523')\nresult =&gt; {error: true, message: &quot;Invalid postcode&quot;}\n</code></pre>\n" }, { "answer_id": 56134559, "author": "Ghoti", "author_id": 80662, "author_profile": "https://Stackoverflow.com/users/80662", "pm_score": -1, "selected": false, "text": "<p>I stole this from an XML document and it seems to cover all cases without the hard coded GIRO:</p>\n\n<pre><code>%r{[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}}i\n</code></pre>\n\n<p>(Ruby syntax with ignore case)</p>\n" }, { "answer_id": 61430132, "author": "jontsai", "author_id": 865091, "author_profile": "https://Stackoverflow.com/users/865091", "pm_score": 2, "selected": false, "text": "<p>Through empirical testing and observation, as well as confirming with <a href=\"https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation</a>, here is my version of a Python regex that correctly parses and validates a UK postcode:</p>\n\n<p><code>UK_POSTCODE_REGEX = r'(?P&lt;postcode_area&gt;[A-Z]{1,2})(?P&lt;district&gt;(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P&lt;sector&gt;[0-9])(?P&lt;postcode&gt;[A-Z]{2})'</code></p>\n\n<p>This regex is simple and has capture groups. It <strong>does not</strong> include all of the validations of <em>legal</em> UK postcodes, but only takes into account the letter vs number positions.</p>\n\n<p>Here is how I would use it in code:</p>\n\n<pre><code>@dataclass\nclass UKPostcode:\n postcode_area: str\n district: str\n sector: int\n postcode: str\n\n # https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation\n # Original author of this regex: @jontsai\n # NOTE TO FUTURE DEVELOPER:\n # Verified through empirical testing and observation, as well as confirming with the Wiki article\n # If this regex fails to capture all valid UK postcodes, then I apologize, for I am only human.\n UK_POSTCODE_REGEX = r'(?P&lt;postcode_area&gt;[A-Z]{1,2})(?P&lt;district&gt;(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P&lt;sector&gt;[0-9])(?P&lt;postcode&gt;[A-Z]{2})'\n\n @classmethod\n def from_postcode(cls, postcode):\n \"\"\"Parses a string into a UKPostcode\n\n Returns a UKPostcode or None\n \"\"\"\n m = re.match(cls.UK_POSTCODE_REGEX, postcode.replace(' ', ''))\n\n if m:\n uk_postcode = UKPostcode(\n postcode_area=m.group('postcode_area'),\n district=m.group('district'),\n sector=m.group('sector'),\n postcode=m.group('postcode')\n )\n else:\n uk_postcode = None\n\n return uk_postcode\n\n\ndef parse_uk_postcode(postcode):\n \"\"\"Wrapper for UKPostcode.from_postcode\n \"\"\"\n uk_postcode = UKPostcode.from_postcode(postcode)\n return uk_postcode\n</code></pre>\n\n<p>Here are unit tests:</p>\n\n<pre><code>@pytest.mark.parametrize(\n 'postcode, expected', [\n # https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation\n (\n 'EC1A1BB',\n UKPostcode(\n postcode_area='EC',\n district='1A',\n sector='1',\n postcode='BB'\n ),\n ),\n (\n 'W1A0AX',\n UKPostcode(\n postcode_area='W',\n district='1A',\n sector='0',\n postcode='AX'\n ),\n ),\n (\n 'M11AE',\n UKPostcode(\n postcode_area='M',\n district='1',\n sector='1',\n postcode='AE'\n ),\n ),\n (\n 'B338TH',\n UKPostcode(\n postcode_area='B',\n district='33',\n sector='8',\n postcode='TH'\n )\n ),\n (\n 'CR26XH',\n UKPostcode(\n postcode_area='CR',\n district='2',\n sector='6',\n postcode='XH'\n )\n ),\n (\n 'DN551PT',\n UKPostcode(\n postcode_area='DN',\n district='55',\n sector='1',\n postcode='PT'\n )\n )\n ]\n)\ndef test_parse_uk_postcode(postcode, expected):\n uk_postcode = parse_uk_postcode(postcode)\n assert(uk_postcode == expected)\n</code></pre>\n" }, { "answer_id": 69269028, "author": "Ella Bella", "author_id": 14713613, "author_profile": "https://Stackoverflow.com/users/14713613", "pm_score": -1, "selected": false, "text": "<p>I did the regex for UK postcode validation today, as far as I know, it works for all UK postcodes, it works if you put a space or if you don't.</p>\n<pre><code>^((([a-zA-Z][0-9])|([a-zA-Z][0-9]{2})|([a-zA-Z]{2}[0-9])|([a-zA-Z]{2}[0-9]{2})|([A-Za-z][0-9][a-zA-Z])|([a-zA-Z]{2}[0-9][a-zA-Z]))(\\s*[0-9][a-zA-Z]{2})$)\n</code></pre>\n<p>Let me know if there's a format it doesn't cover</p>\n" }, { "answer_id": 69806181, "author": "Mecanik", "author_id": 6583298, "author_profile": "https://Stackoverflow.com/users/6583298", "pm_score": 3, "selected": false, "text": "<p>Whilst there are many answers here, I'm not happy with either of them. Most of them are simply broken, are too complex or just broken.</p>\n<p>I looked at <a href=\"https://stackoverflow.com/questions/164979/regex-for-matching-uk-postcodes#51885364\">@ctwheels</a> answer and I found it very explanatory and correct; we must thank him for that. However once again too much &quot;data&quot; for me, for something so simple.</p>\n<p>Fortunately, I managed to get a database with over 1 million active postcodes for England only and made a small PowerShell script to test and benchmark the results.</p>\n<p>UK Postcode specifications: <a href=\"https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/611951/Appendix_C_ILR_2017_to_2018_v1_Published_28April17.pdf\" rel=\"noreferrer\">Valid Postcode Format</a>.</p>\n<p><strong>This is &quot;my&quot; Regex:</strong></p>\n<pre><code>^([a-zA-Z]{1,2}[a-zA-Z\\d]{1,2})\\s(\\d[a-zA-Z]{2})$\n</code></pre>\n<p>Short, simple and sweet. Even the most unexperienced can understand what is going on.</p>\n<p><strong>Explanation:</strong></p>\n<pre><code>^ asserts position at start of a line\n 1st Capturing Group ([a-zA-Z]{1,2}[a-zA-Z\\d]{1,2})\n Match a single character present in the list below [a-zA-Z]\n {1,2} matches the previous token between 1 and 2 times, as many times as possible, giving back as needed (greedy)\n a-z matches a single character in the range between a (index 97) and z (index 122) (case sensitive)\n A-Z matches a single character in the range between A (index 65) and Z (index 90) (case sensitive)\n Match a single character present in the list below [a-zA-Z\\d]\n {1,2} matches the previous token between 1 and 2 times, as many times as possible, giving back as needed (greedy)\n a-z matches a single character in the range between a (index 97) and z (index 122) (case sensitive)\n A-Z matches a single character in the range between A (index 65) and Z (index 90) (case sensitive)\n \\d matches a digit (equivalent to [0-9])\n \\s matches any whitespace character (equivalent to [\\r\\n\\t\\f\\v ])\n 2nd Capturing Group (\\d[a-zA-Z]{2})\n \\d matches a digit (equivalent to [0-9])\n Match a single character present in the list below [a-zA-Z]\n {2} matches the previous token exactly 2 times\n a-z matches a single character in the range between a (index 97) and z (index 122) (case sensitive)\n A-Z matches a single character in the range between A (index 65) and Z (index 90) (case sensitive)\n$ asserts position at the end of a line\n</code></pre>\n<p><strong>Result (postcodes checked):</strong></p>\n<pre><code>TOTAL OK: 1469193\nTOTAL FAILED: 0\n-------------------------------------------------------------------------\nDays : 0\nHours : 0\nMinutes : 5\nSeconds : 22\nMilliseconds : 718\nTicks : 3227185939\nTotalDays : 0.00373516891087963\nTotalHours : 0.0896440538611111\nTotalMinutes : 5.37864323166667\nTotalSeconds : 322.7185939\nTotalMilliseconds : 322718.5939\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5777/" ]
I'm after a regex that will validate a full complex UK postcode only within an input string. All of the uncommon postcode forms must be covered as well as the usual. For instance: **Matches** * CW3 9SS * SE5 0EG * SE50EG * se5 0eg * WC2H 7LT **No Match** * aWC2H 7LT * WC2H 7LTa * WC2H How do I solve this problem?
I'd recommend taking a look at the UK Government Data Standard for postcodes [link now dead; [archive of XML](http://webarchive.nationalarchives.gov.uk/+/http://www.cabinetoffice.gov.uk/media/291370/bs7666-v2-0-xsd-PostCodeType.htm), see [Wikipedia](http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation) for discussion]. There is a brief description about the data and the attached xml schema provides a regular expression. It may not be exactly what you want but would be a good starting point. The RegEx differs from the XML slightly, as a P character in third position in format A9A 9AA is allowed by the definition given. The RegEx supplied by the UK Government was: ``` ([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2}) ``` As pointed out on the Wikipedia discussion, this will allow some non-real postcodes (e.g. those starting AA, ZY) and they do provide a more rigorous test that you could try.
164,981
<p>I have a PHP script that uses the <code>system()</code> call to execute other (potentially long-running) programs (for interest: NCBI BLAST, phrap, primer3 and other programs for doing DNA sequence analysis and assembly).</p> <p>I'm running under Windows XP, using the CLI version of PHP from a command prompt, or as a service. (In either case I communicate with it via a queue of tasks in a database table).</p> <p>Under PHP4: when I hit <kbd>Ctrl</kbd>+<kbd>C</kbd> the script is stopped and any child process running at the time is also stopped. Under PHP5: when I hit <kbd>Ctrl</kbd>+<kbd>C</kbd> the script stops, but the child is left running.</p> <p>Similarly, when running the script as a service, stopping the service when running it with PHP4 stops the child, with PHP5 the child continues to run.</p> <p>I have tried writing a minimal test application, and found the same behaviour. The test PHP script just uses system() to execute a C program (that just sleeps for 30 seconds) and then waits for a key to be pressed.</p> <p>I had a look at the source for PHP 4.4.9 and 5.2.6 but could see no differences in the system() code that looked like they would cause this. I also had a quick look at the startup code for the CLI application and didn't see any differences in signal handling.</p> <p>Any hints on what might have caused this, or a workaround, would be appreciated.</p> <p>Thanks.</p>
[ { "answer_id": 164992, "author": "Dan", "author_id": 230, "author_profile": "https://Stackoverflow.com/users/230", "pm_score": 5, "selected": false, "text": "<pre><code>^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$\n</code></pre>\n\n<blockquote>\n <p>Regular expression to match valid UK\n postcodes. In the UK postal system not\n all letters are used in all positions\n (the same with vehicle registration\n plates) and there are various rules to\n govern this. This regex takes into\n account those rules. Details of the\n rules: First half of postcode Valid\n formats [A-Z][A-Z][0-9][A-Z]\n [A-Z][A-Z][0-9][0-9] [A-Z][0-9][0-9]\n [A-Z][A-Z][0-9] [A-Z][A-Z][A-Z]\n [A-Z][0-9][A-Z] [A-Z][0-9] Exceptions\n Position - First. Contraint - QVX not\n used Position - Second. Contraint -\n IJZ not used except in GIR 0AA\n Position - Third. Constraint -\n AEHMNPRTVXY only used Position -\n Forth. Contraint - ABEHMNPRVWXY Second\n half of postcode Valid formats\n [0-9][A-Z][A-Z] Exceptions Position -\n Second and Third. Contraint - CIKMOV\n not used</p>\n</blockquote>\n\n<p><a href=\"http://regexlib.com/REDetails.aspx?regexp_id=260\" rel=\"noreferrer\">http://regexlib.com/REDetails.aspx?regexp_id=260</a></p>\n" }, { "answer_id": 164994, "author": "marcj", "author_id": 23940, "author_profile": "https://Stackoverflow.com/users/23940", "pm_score": 9, "selected": true, "text": "<p>I'd recommend taking a look at the UK Government Data Standard for postcodes [link now dead; <a href=\"http://webarchive.nationalarchives.gov.uk/+/http://www.cabinetoffice.gov.uk/media/291370/bs7666-v2-0-xsd-PostCodeType.htm\" rel=\"noreferrer\">archive of XML</a>, see <a href=\"http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation\" rel=\"noreferrer\">Wikipedia</a> for discussion]. There is a brief description about the data and the attached xml schema provides a regular expression. It may not be exactly what you want but would be a good starting point. The RegEx differs from the XML slightly, as a P character in third position in format A9A 9AA is allowed by the definition given.</p>\n\n<p>The RegEx supplied by the UK Government was:</p>\n\n<pre><code>([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\\s?[0-9][A-Za-z]{2})\n</code></pre>\n\n<p>As pointed out on the Wikipedia discussion, this will allow some non-real postcodes (e.g. those starting AA, ZY) and they do provide a more rigorous test that you could try.</p>\n" }, { "answer_id": 164995, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 2, "selected": false, "text": "<p>First half of postcode Valid formats </p>\n\n<ul>\n<li>[A-Z][A-Z][0-9][A-Z] </li>\n<li>[A-Z][A-Z][0-9][0-9] </li>\n<li>[A-Z][0-9][0-9] </li>\n<li>[A-Z][A-Z][0-9] </li>\n<li>[A-Z][A-Z][A-Z] </li>\n<li>[A-Z][0-9][A-Z] </li>\n<li>[A-Z][0-9] </li>\n</ul>\n\n<p>Exceptions<br>\nPosition 1 - QVX not used<br>\nPosition 2 - IJZ not used except in GIR 0AA<br>\nPosition 3 - AEHMNPRTVXY only used<br>\nPosition 4 - ABEHMNPRVWXY </p>\n\n<p>Second half of postcode </p>\n\n<ul>\n<li>[0-9][A-Z][A-Z] </li>\n</ul>\n\n<p>Exceptions<br>\nPosition 2+3 - CIKMOV not used</p>\n\n<p>Remember not all possible codes are used, so this list is a necessary but not sufficent condition for a valid code. It might be easier to just match against a list of all valid codes?</p>\n" }, { "answer_id": 1600314, "author": "Rudiger Wolf", "author_id": 41431, "author_profile": "https://Stackoverflow.com/users/41431", "pm_score": 1, "selected": false, "text": "<p>Have a look at the python code on this page:</p>\n<p><a href=\"http://www.brunningonline.net/simon/blog/archives/001292.html\" rel=\"nofollow noreferrer\">http://www.brunningonline.net/simon/blog/archives/001292.html</a></p>\n<blockquote>\n<p>I've got some postcode parsing to do. The requirement is pretty simple; I have to parse a postcode into an outcode and (optional) incode. The good new is that I don't have to perform any validation - I just have to chop up what I've been provided with in a vaguely intelligent manner. I can't assume much about my import in terms of formatting, i.e. case and embedded spaces. But this isn't the bad news; the bad news is that I have to do it all in RPG. :-(</p>\n<p>Nevertheless, I threw a little Python function together to clarify my thinking.</p>\n</blockquote>\n<p>I've used it to process postcodes for me.</p>\n" }, { "answer_id": 4793095, "author": "minglis", "author_id": 502087, "author_profile": "https://Stackoverflow.com/users/502087", "pm_score": 3, "selected": false, "text": "<p>Some of the regexs above are a little restrictive. Note the genuine postcode: \"W1K 7AA\" would fail given the rule \"Position 3 - AEHMNPRTVXY only used\" above as \"K\" would be disallowed.</p>\n\n<p>the regex:</p>\n\n<pre><code>^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKPS-UW])[0-9][ABD-HJLNP-UW-Z]{2})$\n</code></pre>\n\n<p>Seems a little more accurate, see the <a href=\"http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom\" rel=\"nofollow\">Wikipedia article entitled 'Postcodes in the United Kingdom'</a>.</p>\n\n<p>Note that this regex requires uppercase only characters.</p>\n\n<p>The bigger question is whether you are restricting user input to allow only postcodes that actually exist or whether you are simply trying to stop users entering complete rubbish into the form fields. Correctly matching every possible postcode, and future proofing it, is a harder puzzle, and probably not worth it unless you are HMRC.</p>\n" }, { "answer_id": 6276530, "author": "Will Tomlins", "author_id": 690904, "author_profile": "https://Stackoverflow.com/users/690904", "pm_score": 3, "selected": false, "text": "<p>Here's a regex based on the format specified in the documents which are linked to marcj's answer:</p>\n\n<pre><code>/^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-Z]{2}$/\n</code></pre>\n\n<p>The only difference between that and the specs is that the last 2 characters cannot be in [CIKMOV] according to the specs.</p>\n\n<p>Edit:\nHere's another version which does test for the trailing character limitations.</p>\n\n<pre><code>/^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-BD-HJLNP-UW-Z]{2}$/\n</code></pre>\n" }, { "answer_id": 7259020, "author": "Colin", "author_id": 521518, "author_profile": "https://Stackoverflow.com/users/521518", "pm_score": 6, "selected": false, "text": "<p>It looks like we're going to be using <code>^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$</code>, which is a slightly modified version of that sugested by Minglis above.</p>\n\n<p>However, we're going to have to investigate exactly what the rules are, as the various solutions listed above appear to apply different rules as to which letters are allowed.</p>\n\n<p>After some research, we've found some more information. Apparently a page on 'govtalk.gov.uk' points you to a postcode specification <a href=\"http://interim.cabinetoffice.gov.uk/govtalk/schemasstandards/e-gif/datastandards/address/postcode.aspx\" rel=\"noreferrer\">govtalk-postcodes</a>. This points to an XML schema at <a href=\"http://interim.cabinetoffice.gov.uk/media/291293/bs7666-v2-0.xml\" rel=\"noreferrer\">XML Schema</a> which provides a 'pseudo regex' statement of the postcode rules.</p>\n\n<p>We've taken that and worked on it a little to give us the following expression:</p>\n\n<pre><code>^((GIR &amp;0AA)|((([A-PR-UWYZ][A-HK-Y]?[0-9][0-9]?)|(([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]))) &amp;[0-9][ABD-HJLNP-UW-Z]{2}))$\n</code></pre>\n\n<p>This makes spaces optional, but does limit you to one space (replace the '&amp;' with '{0,} for unlimited spaces). It assumes all text must be upper-case.</p>\n\n<p>If you want to allow lower case, with any number of spaces, use:</p>\n\n<pre><code>^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$\n</code></pre>\n\n<p>This doesn't cover overseas territories and only enforces the format, NOT the existence of different areas. It is based on the following rules:</p>\n\n<p>Can accept the following formats:</p>\n\n<ul>\n<li>“GIR 0AA”</li>\n<li>A9 9ZZ</li>\n<li>A99 9ZZ</li>\n<li>AB9 9ZZ</li>\n<li>AB99 9ZZ</li>\n<li>A9C 9ZZ</li>\n<li>AD9E 9ZZ</li>\n</ul>\n\n<p>Where:</p>\n\n<ul>\n<li>9 can be any single digit number.</li>\n<li>A can be any letter except for Q, V or X.</li>\n<li>B can be any letter except for I, J or Z.</li>\n<li>C can be any letter except for I, L, M, N, O, P, Q, R, V, X, Y or Z.</li>\n<li>D can be any letter except for I, J or Z.</li>\n<li>E can be any of A, B, E, H, M, N, P, R, V, W, X or Y.</li>\n<li>Z can be any letter except for C, I, K, M, O or V.</li>\n</ul>\n\n<p>Best wishes</p>\n\n<p>Colin</p>\n" }, { "answer_id": 10600422, "author": "Vikas Pandey", "author_id": 1396126, "author_profile": "https://Stackoverflow.com/users/1396126", "pm_score": 1, "selected": false, "text": "<p>I have the regex for UK Postcode validation.</p>\n\n<p>This is working for all type of Postcode either inner or outer</p>\n\n<pre><code>^((([A-PR-UWYZ][0-9])|([A-PR-UWYZ][0-9][0-9])|([A-PR-UWYZ][A-HK-Y][0-9])|([A-PR-UWYZ][A-HK-Y][0-9][0-9])|([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))) || ^((GIR)[ ]?(0AA))$|^(([A-PR-UWYZ][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][0-9][A-HJKS-UW0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9][ABEHMNPRVWXY0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$\n</code></pre>\n\n<p>This is working for all type of format.</p>\n\n<p>Example:</p>\n\n<blockquote>\n <p>AB10-------------------->ONLY OUTER POSTCODE</p>\n \n <p>A1 1AA------------------>COMBINATION OF (OUTER AND INNER) POSTCODE</p>\n \n <p>WC2A-------------------->OUTER</p>\n</blockquote>\n" }, { "answer_id": 11865017, "author": "paulslater19", "author_id": 705752, "author_profile": "https://Stackoverflow.com/users/705752", "pm_score": 0, "selected": false, "text": "<p>We were given a spec:</p>\n\n<pre>UK postcodes must be in one of the following forms (with one exception, see below): \n § A9 9AA \n § A99 9AA\n § AA9 9AA\n § AA99 9AA\n § A9A 9AA\n § AA9A 9AA\nwhere A represents an alphabetic character and 9 represents a numeric character.\nAdditional rules apply to alphabetic characters, as follows:\n § The character in position 1 may not be Q, V or X\n § The character in position 2 may not be I, J or Z\n § The character in position 3 may not be I, L, M, N, O, P, Q, R, V, X, Y or Z\n § The character in position 4 may not be C, D, F, G, I, J, K, L, O, Q, S, T, U or Z\n § The characters in the rightmost two positions may not be C, I, K, M, O or V\nThe one exception that does not follow these general rules is the postcode \"GIR 0AA\", which is a special valid postcode.</pre>\n\n<p>We came up with this: </p>\n\n<pre><code>/^([A-PR-UWYZ][A-HK-Y0-9](?:[A-HJKS-UW0-9][ABEHMNPRV-Y0-9]?)?\\s*[0-9][ABD-HJLNP-UW-Z]{2}|GIR\\s*0AA)$/i\n</code></pre>\n\n<p>But note - this allows any number of spaces in between groups. </p>\n" }, { "answer_id": 14257846, "author": "Dan Solo", "author_id": 1139823, "author_profile": "https://Stackoverflow.com/users/1139823", "pm_score": 3, "selected": false, "text": "<p>I've been looking for a UK postcode regex for the last day or so and stumbled on this thread. I worked my way through most of the suggestions above and none of them worked for me so I came up with my own regex which, as far as I know, captures all valid UK postcodes as of Jan '13 (according to the latest literature from the Royal Mail).</p>\n\n<p>The regex and some simple postcode checking PHP code is posted below. NOTE:- It allows for lower or uppercase postcodes and the GIR 0AA anomaly but to deal with the, more than likely, presence of a space in the middle of an entered postcode it also makes use of a simple str_replace to remove the space before testing against the regex. Any discrepancies beyond that and the Royal Mail themselves don't even mention them in their literature (see <a href=\"http://www.royalmail.com/sites/default/files/docs/pdf/programmers_guide_edition_7_v5.pdf\">http://www.royalmail.com/sites/default/files/docs/pdf/programmers_guide_edition_7_v5.pdf</a> and start reading from page 17)!</p>\n\n<p><strong>Note:</strong> In the Royal Mail's own literature (link above) there is a slight ambiguity surrounding the 3rd and 4th positions and the exceptions in place if these characters are letters. I contacted Royal Mail directly to clear it up and in their own words \"A letter in the 4th position of the Outward Code with the format AANA NAA has no exceptions and the 3rd position exceptions apply only to the last letter of the Outward Code with the format ANA NAA.\" Straight from the horse's mouth!</p>\n\n<pre><code>&lt;?php\n\n $postcoderegex = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\\d[abd-hjlnp-uw-z]{2})?)$/i';\n\n $postcode2check = str_replace(' ','',$postcode2check);\n\n if (preg_match($postcoderegex, $postcode2check)) {\n\n echo \"$postcode2check is a valid postcode&lt;br&gt;\";\n\n } else {\n\n echo \"$postcode2check is not a valid postcode&lt;br&gt;\";\n\n }\n\n?&gt;\n</code></pre>\n\n<p>I hope it helps anyone else who comes across this thread looking for a solution.</p>\n" }, { "answer_id": 15953188, "author": "Alix Axel", "author_id": 89771, "author_profile": "https://Stackoverflow.com/users/89771", "pm_score": 4, "selected": false, "text": "<p>This is the regex Google serves on their <a href=\"http://i18napis.appspot.com/address/data/GB\">i18napis.appspot.com</a> domain:</p>\n\n<pre><code>GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|BX|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\\d[\\dA-Z]?[ ]?\\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\\d{1,4}\n</code></pre>\n" }, { "answer_id": 16485951, "author": "Jesús Carrera", "author_id": 2330244, "author_profile": "https://Stackoverflow.com/users/2330244", "pm_score": 4, "selected": false, "text": "<p>Most of the answers here didn't work for all the postcodes I have in my database. I finally found one that validates with all, using the new regex provided by the government:</p>\n\n<p><a href=\"https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/413338/Bulk_Data_Transfer_-_additional_validation_valid_from_March_2015.pdf\" rel=\"nofollow noreferrer\">https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/413338/Bulk_Data_Transfer_-_additional_validation_valid_from_March_2015.pdf</a></p>\n\n<p>It isn't in any of the previous answers so I post it here in case they take the link down:</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n</code></pre>\n\n<p>UPDATE: Updated regex as pointed by Jamie Bull. Not sure if it was my error copying or it was an error in the government's regex, the link is down now... </p>\n\n<p>UPDATE: As ctwheels found, this regex works with the javascript regex flavor. See his comment for one that works with the pcre (php) flavor.</p>\n" }, { "answer_id": 17024047, "author": "Ben", "author_id": 458741, "author_profile": "https://Stackoverflow.com/users/458741", "pm_score": 6, "selected": false, "text": "<p>There is no such thing as a comprehensive UK postcode regular expression that is capable of <em>validating</em> a postcode. You can check that a postcode is in the correct format using a regular expression; not that it actually exists.</p>\n\n<p>Postcodes are arbitrarily complex and constantly changing. For instance, the outcode <code>W1</code> does not, and may never, have every number between 1 and 99, for every postcode area.</p>\n\n<p>You can't expect what is there currently to be true forever. As an example, in 1990, the Post Office decided that Aberdeen was getting a bit crowded. They added a 0 to the end of AB1-5 making it AB10-50 and then created a number of postcodes in between these. </p>\n\n<p>Whenever a new street is build a new postcode is created. It's part of the process for obtaining permission to build; local authorities are obliged to keep this updated with the Post Office (not that they all do).</p>\n\n<p>Furthermore, as noted by a number of other users, there's the special postcodes such as Girobank, GIR 0AA, and the one for letters to Santa, SAN TA1 - you probably don't want to post anything there but it doesn't appear to be covered by any other answer.</p>\n\n<p>Then, there's the BFPO postcodes, which are now <a href=\"https://www.gov.uk/government/publications/british-forces-post-office-locations\" rel=\"noreferrer\">changing to a more standard format</a>. Both formats are going to be valid. Lastly, there's the overseas territories <sup><a href=\"http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom\" rel=\"noreferrer\">source Wikipedia</a></sup>.</p>\n\n<pre>\n+----------+----------------------------------------------+\n| Postcode | Location |\n+----------+----------------------------------------------+\n| AI-2640 | Anguilla |\n| ASCN 1ZZ | Ascension Island |\n| STHL 1ZZ | Saint Helena |\n| TDCU 1ZZ | Tristan da Cunha |\n| BBND 1ZZ | British Indian Ocean Territory |\n| BIQQ 1ZZ | British Antarctic Territory |\n| FIQQ 1ZZ | Falkland Islands |\n| GX11 1AA | Gibraltar |\n| PCRN 1ZZ | Pitcairn Islands |\n| SIQQ 1ZZ | South Georgia and the South Sandwich Islands |\n| TKCA 1ZZ | Turks and Caicos Islands |\n+----------+----------------------------------------------+</pre>\n\n<p>Next, you have to take into account that the UK \"exported\" its postcode system to many places in the world. Anything that validates a \"UK\" postcode will also validate the postcodes of a number of other countries.</p>\n\n<p>If you want to <em>validate</em> a UK postcode the safest way to do it is to use a look-up of current postcodes. There are a number of options:</p>\n\n<ul>\n<li><p>Ordnance Survey releases <a href=\"http://www.ordnancesurvey.co.uk/oswebsite/products/code-point-open/\" rel=\"noreferrer\">Code-Point Open</a> under an open data licence. It'll be very slightly behind the times but it's free. This will (probably - I can't remember) not include Northern Irish data as the Ordnance Survey has no remit there. Mapping in Northern Ireland is conducted by the Ordnance Survey of Northern Ireland and they have their, separate, paid-for, <a href=\"https://maps.osni.gov.uk/CMSPages/moreinfo_address_data.aspx\" rel=\"noreferrer\">Pointer</a> product. You could use this and append the few that aren't covered fairly easily.</p></li>\n<li><p>Royal Mail releases the <a href=\"http://www.poweredbypaf.com/\" rel=\"noreferrer\">Postcode Address File (PAF)</a>, this includes BFPO which I'm not sure Code-Point Open does. It's updated regularly but costs money (and they can be downright mean about it sometimes). PAF includes the full address rather than just postcodes and comes with its own <a href=\"http://www.poweredbypaf.com/wp-content/themes/amu/paf_downloads/programmers_guide.pdf\" rel=\"noreferrer\">Programmers Guide</a>. The Open Data User Group (ODUG) is currently lobbying to have PAF released for free, <a href=\"http://data.gov.uk/library/odug-response-to-ofcom-paf-review-consultation\" rel=\"noreferrer\">here's a description of their position</a>.</p></li>\n<li><p>Lastly, there's <a href=\"https://www.ordnancesurvey.co.uk/business-and-government/products/addressbase-products.html\" rel=\"noreferrer\">AddressBase</a>. This is a collaboration between Ordnance Survey, Local Authorities, Royal Mail and a matching company to create a definitive directory of all information about all UK addresses (they've been fairly successful as well). It's paid-for but if you're working with a Local Authority, government department, or government service it's free for them to use. There's a lot more information than just postcodes included.</p></li>\n</ul>\n" }, { "answer_id": 17507615, "author": "RichardTowers", "author_id": 1344760, "author_profile": "https://Stackoverflow.com/users/1344760", "pm_score": 4, "selected": false, "text": "<p>I had a look into some of the answers above and I'd recommend against using the pattern from @Dan's <a href=\"https://stackoverflow.com/questions/164979/uk-postcode-regex-comprehensive#answer-164992\">answer (c. Dec 15 '10)</a>, since it incorrectly flags almost 0.4% of valid postcodes as invalid, while the others do not. </p>\n\n<p>Ordnance Survey provide service called Code Point Open which:</p>\n\n<blockquote>\n <p>contains a list of all the current postcode units in Great Britain</p>\n</blockquote>\n\n<p>I ran each of the regexs above against the full list of postcodes (Jul 6 '13) from this data using <code>grep</code>:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>cat CSV/*.csv |\n # Strip leading quotes\n sed -e 's/^\"//g' |\n # Strip trailing quote and everything after it\n sed -e 's/\".*//g' |\n # Strip any spaces\n sed -E -e 's/ +//g' |\n # Find any lines that do not match the expression\n grep --invert-match --perl-regexp \"$pattern\"\n</code></pre>\n\n<p>There are 1,686,202 postcodes total.</p>\n\n<p>The following are the numbers of valid postcodes that do <em>not</em> match each <code>$pattern</code>:</p>\n\n<pre><code>'^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$'\n# =&gt; 6016 (0.36%)\n</code></pre>\n\n\n\n<pre><code>'^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$'\n# =&gt; 0\n</code></pre>\n\n\n\n<pre><code>'^GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|BX|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\\d[\\dA-Z]?[ ]?\\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\\d{1,4}$'\n# =&gt; 0\n</code></pre>\n\n<p>Of course, these results only deal with valid postcodes that are incorrectly flagged as invalid. So:</p>\n\n<pre><code>'^.*$'\n# =&gt; 0\n</code></pre>\n\n<p>I'm saying nothing about which pattern is the best regarding filtering out invalid postcodes.</p>\n" }, { "answer_id": 23375983, "author": "andre", "author_id": 3108126, "author_profile": "https://Stackoverflow.com/users/3108126", "pm_score": 3, "selected": false, "text": "<p>Postcodes are subject to change, and the only true way of validating a postcode is to have the complete list of postcodes and see if it's there.</p>\n\n<p>But regular expressions are useful because they:</p>\n\n<ul>\n<li>are easy to use and implement</li>\n<li>are short</li>\n<li>are quick to run</li>\n<li>are quite easy to maintain (compared to a full list of postcodes)</li>\n<li>still catch most input errors</li>\n</ul>\n\n<p>But regular expressions tend to be difficult to maintain, especially for someone who didn't come up with it in the first place. So it must be:</p>\n\n<ul>\n<li>as easy to understand as possible</li>\n<li>relatively future proof</li>\n</ul>\n\n<p>That means that most of the regular expressions in this answer aren't good enough. E.g. I can see that <code>[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]</code> is going to match a postcode area of the form AA1A — but it's going to be a pain in the neck if and when a new postcode area gets added, because it's difficult to understand which postcode areas it matches.</p>\n\n<p>I also want my regular expression to match the first and second half of the postcode as parenthesised matches.</p>\n\n<p>So I've come up with this:</p>\n\n<pre><code>(GIR(?=\\s*0AA)|(?:[BEGLMNSW]|[A-Z]{2})[0-9](?:[0-9]|(?&lt;=N1|E1|SE1|SW1|W1|NW1|EC[0-9]|WC[0-9])[A-HJ-NP-Z])?)\\s*([0-9][ABD-HJLNP-UW-Z]{2})\n</code></pre>\n\n<p>In PCRE format it can be written as follows:</p>\n\n<pre><code>/^\n ( GIR(?=\\s*0AA) # Match the special postcode \"GIR 0AA\"\n |\n (?:\n [BEGLMNSW] | # There are 8 single-letter postcode areas\n [A-Z]{2} # All other postcode areas have two letters\n )\n [0-9] # There is always at least one number after the postcode area\n (?:\n [0-9] # And an optional extra number\n |\n # Only certain postcode areas can have an extra letter after the number\n (?&lt;=N1|E1|SE1|SW1|W1|NW1|EC[0-9]|WC[0-9])\n [A-HJ-NP-Z] # Possible letters here may change, but [IO] will never be used\n )?\n )\n \\s*\n ([0-9][ABD-HJLNP-UW-Z]{2}) # The last two letters cannot be [CIKMOV]\n$/x\n</code></pre>\n\n<p>For me this is the right balance between validating as much as possible, while at the same time future-proofing and allowing for easy maintenance.</p>\n" }, { "answer_id": 25176865, "author": "Alex Stephens", "author_id": 1955203, "author_profile": "https://Stackoverflow.com/users/1955203", "pm_score": 2, "selected": false, "text": "<p>here's how we have been dealing with the UK postcode issue:</p>\n\n<pre><code>^([A-Za-z]{1,2}[0-9]{1,2}[A-Za-z]?[ ]?)([0-9]{1}[A-Za-z]{2})$\n</code></pre>\n\n<p><strong>Explanation:</strong></p>\n\n<ul>\n<li>expect 1 or 2 a-z chars, upper or lower fine</li>\n<li>expect 1 or 2 numbers</li>\n<li>expect 0 or 1 a-z char, upper or lower fine</li>\n<li>optional space allowed</li>\n<li>expect 1 number</li>\n<li>expect 2 a-z, upper or lower fine</li>\n</ul>\n\n<p>This gets most formats, we then use the db to validate whether the postcode is actually real, this data is driven by openpoint <a href=\"https://www.ordnancesurvey.co.uk/opendatadownload/products.html\" rel=\"nofollow\">https://www.ordnancesurvey.co.uk/opendatadownload/products.html</a></p>\n\n<p>hope this helps</p>\n" }, { "answer_id": 26887154, "author": "deadcrab", "author_id": 1071022, "author_profile": "https://Stackoverflow.com/users/1071022", "pm_score": 4, "selected": false, "text": "<p>An old post but still pretty high in google results so thought I'd update. This Oct 14 doc defines the UK postcode regular expression as:</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([**AZ**a-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n</code></pre>\n\n<p>from:</p>\n\n<p><a href=\"https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/359448/4__Bulk_Data_Transfer_-_additional_validation_valid.pdf\" rel=\"nofollow noreferrer\">https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/359448/4__Bulk_Data_Transfer_-_additional_validation_valid.pdf</a></p>\n\n<p>The document also explains the logic behind it. However, it has an error (bolded) and also allows lower case, which although legal is not usual, so amended version:</p>\n\n<pre><code>^(GIR 0AA)|((([A-Z][0-9]{1,2})|(([A-Z][A-HJ-Y][0-9]{1,2})|(([A-Z][0-9][A-Z])|([A-Z][A-HJ-Y][0-9]?[A-Z])))) [0-9][A-Z]{2})$\n</code></pre>\n\n<p>This works with new London postcodes (e.g. W1D 5LH) that previous versions did not.</p>\n" }, { "answer_id": 28108191, "author": "Raphos", "author_id": 4222767, "author_profile": "https://Stackoverflow.com/users/4222767", "pm_score": 2, "selected": false, "text": "<p><strong>Basic rules:</strong></p>\n\n<pre><code>^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$\n</code></pre>\n\n<p>Postal codes in the U.K. (or postcodes, as they’re called) are composed of five to seven alphanumeric characters separated by a space. The rules covering which characters can appear at particular positions are rather complicated and fraught with exceptions. The regular expression just shown therefore sticks to the basic rules.</p>\n\n<p><strong>Complete rules:</strong></p>\n\n<p>If you need a regex that ticks all the boxes for the postcode rules at the expense of readability, here you go:</p>\n\n<pre><code>^(?:(?:[A-PR-UWYZ][0-9]{1,2}|[A-PR-UWYZ][A-HK-Y][0-9]{1,2}|[A-PR-UWYZ][0-9][A-HJKSTUW]|[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]) [0-9][ABD-HJLNP-UW-Z]{2}|GIR 0AA)$\n</code></pre>\n\n<p><em>Source: <a href=\"https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s16.html\" rel=\"nofollow\">https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s16.html</a></em></p>\n\n<p>Tested against our customers database and seems perfectly accurate.</p>\n" }, { "answer_id": 29302162, "author": "Jackson Pauls", "author_id": 1777662, "author_profile": "https://Stackoverflow.com/users/1777662", "pm_score": 2, "selected": false, "text": "<p>To check a postcode is in a valid format as per the Royal Mail's <a href=\"http://www.royalmail.com/sites/default/files/docs/pdf/programmers_guide_edition_7_v5.pdf\" rel=\"nofollow\">programmer's guide</a>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> |----------------------------outward code------------------------------| |------inward code-----|\n#special↓ α1 α2 AAN AANA AANN AN ANN ANA (α3) N AA\n^(GIR 0AA|[A-PR-UWYZ]([A-HK-Y]([0-9][A-Z]?|[1-9][0-9])|[1-9]([0-9]|[A-HJKPSTUW])?) [0-9][ABD-HJLNP-UW-Z]{2})$\n</code></pre>\n\n<p>All postcodes on <a href=\"http://www.doogal.co.uk/UKPostcodes.php\" rel=\"nofollow\">doogal.co.uk</a> match, except for those no longer in use.</p>\n\n<p>Adding a <code>?</code> after the space and using case-insensitive match to answer this question:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>'se50eg'.match(/^(GIR 0AA|[A-PR-UWYZ]([A-HK-Y]([0-9][A-Z]?|[1-9][0-9])|[1-9]([0-9]|[A-HJKPSTUW])?) ?[0-9][ABD-HJLNP-UW-Z]{2})$/ig);\nArray [ \"se50eg\" ]\n</code></pre>\n" }, { "answer_id": 29363535, "author": "Stieb", "author_id": 3060634, "author_profile": "https://Stackoverflow.com/users/3060634", "pm_score": 0, "selected": false, "text": "<p>The accepted answer reflects the rules given by Royal Mail, although there is a typo in the regex. This typo seems to have been in there on the gov.uk site as well (as it is in the XML archive page).</p>\n\n<p>In the format A9A 9AA the rules allow a P character in the third position, whilst the regex disallows this. The correct regex would be:</p>\n\n<pre><code>(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKPSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2}) \n</code></pre>\n\n<p>Shortening this results in the following regex (which uses Perl/Ruby syntax):</p>\n\n<pre><code>(GIR 0AA)|([A-PR-UWYZ](([0-9]([0-9A-HJKPSTUW])?)|([A-HK-Y][0-9]([0-9ABEHMNPRVWXY])?))\\s?[0-9][ABD-HJLNP-UW-Z]{2})\n</code></pre>\n\n<p>It also includes an optional space between the first and second block. </p>\n" }, { "answer_id": 29820230, "author": "AntPachon", "author_id": 763085, "author_profile": "https://Stackoverflow.com/users/763085", "pm_score": 4, "selected": false, "text": "<p>According to this Wikipedia table</p>\n\n<p><img src=\"https://i.stack.imgur.com/XOv8u.png\" alt=\"enter image description here\"></p>\n\n<p>This pattern cover all the cases </p>\n\n<pre><code>(?:[A-Za-z]\\d ?\\d[A-Za-z]{2})|(?:[A-Za-z][A-Za-z\\d]\\d ?\\d[A-Za-z]{2})|(?:[A-Za-z]{2}\\d{2} ?\\d[A-Za-z]{2})|(?:[A-Za-z]\\d[A-Za-z] ?\\d[A-Za-z]{2})|(?:[A-Za-z]{2}\\d[A-Za-z] ?\\d[A-Za-z]{2})\n</code></pre>\n\n<p>When using it on Android\\Java use \\\\d</p>\n" }, { "answer_id": 32735959, "author": "User1", "author_id": 2987066, "author_profile": "https://Stackoverflow.com/users/2987066", "pm_score": 2, "selected": false, "text": "<p>To add to this list a more practical regex that I use that allows the user to enter an <code>empty string</code> is:</p>\n\n<pre><code>^$|^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,1}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$\n</code></pre>\n\n<p>This regex allows capital and lower case letters with an optional space in between</p>\n\n<p>From a software developers point of view this regex is useful for software where an address may be optional. For example if a user did not want to supply their address details</p>\n" }, { "answer_id": 33610889, "author": "Chisel", "author_id": 2991563, "author_profile": "https://Stackoverflow.com/users/2991563", "pm_score": 2, "selected": false, "text": "<p>I use the following regex that I have tested against all valid UK postcodes. It is based on the recommended rules, but condensed as much as reasonable and does not make use of any special language specific regex rules.</p>\n\n<pre><code>([A-PR-UWYZ]([A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y])?|[0-9]([0-9]|[A-HJKPSTUW])?) ?[0-9][ABD-HJLNP-UW-Z]{2})\n</code></pre>\n\n<p>It assumes that the postcode has been converted to uppercase and has not leading or trailing characters, but will accept an optional space between the outcode and incode.</p>\n\n<p>The special \"GIR0 0AA\" postcode is excluded and will not validate as it's not in the official Post Office list of postcodes and as far as I'm aware will not be used as registered address. Adding it should be trivial as a special case if required.</p>\n" }, { "answer_id": 34593598, "author": "Matas Vaitkevicius", "author_id": 1509764, "author_profile": "https://Stackoverflow.com/users/1509764", "pm_score": 2, "selected": false, "text": "<p>This one allows empty spaces and tabs from both sides in case you don't want to fail validation and then trim it sever side.</p>\n\n<pre><code>^\\s*(([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})\\s*$)\n</code></pre>\n" }, { "answer_id": 43793562, "author": "user667489", "author_id": 667489, "author_profile": "https://Stackoverflow.com/users/667489", "pm_score": -1, "selected": false, "text": "<p>I needed a version that would work in SAS with the <code>PRXMATCH</code> and related functions, so I came up with this:</p>\n\n<pre><code>^[A-PR-UWYZ](([A-HK-Y]?\\d\\d?)|(\\d[A-HJKPSTUW])|([A-HK-Y]\\d[ABEHMNPRV-Y]))\\s?\\d[ABD-HJLNP-UW-Z]{2}$\n</code></pre>\n\n<p>Test cases and notes:</p>\n\n<pre><code>/* \nNotes\nThe letters QVX are not used in the 1st position.\nThe letters IJZ are not used in the second position.\nThe only letters to appear in the third position are ABCDEFGHJKPSTUW when the structure starts with A9A.\nThe only letters to appear in the fourth position are ABEHMNPRVWXY when the structure starts with AA9A.\nThe final two letters do not use the letters CIKMOV, so as not to resemble digits or each other when hand-written.\n*/\n\n/*\n Bits and pieces\n 1st position (any): [A-PR-UWYZ] \n 2nd position (if letter): [A-HK-Y]\n 3rd position (A1A format): [A-HJKPSTUW]\n 4th position (AA1A format): [ABEHMNPRV-Y]\n Last 2 positions: [ABD-HJLNP-UW-Z] \n*/\n\n\ndata example;\ninfile cards truncover;\ninput valid 1. postcode &amp;$10. Notes &amp;$100.;\nflag = prxmatch('/^[A-PR-UWYZ](([A-HK-Y]?\\d\\d?)|(\\d[A-HJKPSTUW])|([A-HK-Y]\\d[ABEHMNPRV-Y]))\\s?\\d[ABD-HJLNP-UW-Z]{2}$/',strip(postcode));\ncards;\n1 EC1A 1BB Special case 1\n1 W1A 0AX Special case 2\n1 M1 1AE Standard format\n1 B33 8TH Standard format\n1 CR2 6XH Standard format\n1 DN55 1PT Standard format\n0 QN55 1PT Bad letter in 1st position\n0 DI55 1PT Bad letter in 2nd position\n0 W1Z 0AX Bad letter in 3rd position\n0 EC1Z 1BB Bad letter in 4th position\n0 DN55 1CT Bad letter in 2nd group\n0 A11A 1AA Invalid digits in 1st group\n0 AA11A 1AA 1st group too long\n0 AA11 1AAA 2nd group too long\n0 AA11 1AAA 2nd group too long\n0 AAA 1AA No digit in 1st group\n0 AA 1AA No digit in 1st group\n0 A 1AA No digit in 1st group\n0 1A 1AA Missing letter in 1st group\n0 1 1AA Missing letter in 1st group\n0 11 1AA Missing letter in 1st group\n0 AA1 1A Missing letter in 2nd group\n0 AA1 1 Missing letter in 2nd group\n;\nrun;\n</code></pre>\n" }, { "answer_id": 47313542, "author": "Andrew Schliewe", "author_id": 6211051, "author_profile": "https://Stackoverflow.com/users/6211051", "pm_score": 0, "selected": false, "text": "<p>What i have found in nearly all the variations and the regex from the bulk transfer pdf and what is on wikipedia site is this, specifically for the wikipedia regex is, there needs to be a ^ after the first |(vertical bar). I figured this out by testing for AA9A 9AA, because otherwise the format check for A9A 9AA will validate it. For Example checking for EC1D 1BB which should be invalid comes back valid because C1D 1BB is a valid format.</p>\n\n<p>Here is what I've come up with for a good regex:</p>\n\n<pre><code>^([G][I][R] 0[A]{2})|^((([A-Z-[QVX]][0-9]{1,2})|([A-Z-[QVX]][A-HK-Y][0-9]{1,2})|([A-Z-[QVX]][0-9][ABCDEFGHJKPSTUW])|([A-Z-[QVX]][A-HK-Y][0-9][ABEHMNPRVWXY])) [0-9][A-Z-[CIKMOV]]{2})$\n</code></pre>\n" }, { "answer_id": 47589824, "author": "Henrik N", "author_id": 6962, "author_profile": "https://Stackoverflow.com/users/6962", "pm_score": 3, "selected": false, "text": "<p>I wanted a simple regex, where it's fine to allow too much, but not to deny a valid postcode. I went with this (the input is a stripped/trimmed string):</p>\n\n<pre><code>/^([a-z0-9]\\s*){5,8}$/i\n</code></pre>\n\n<p>This allows the shortest possible postcodes like \"L1 8JQ\" as well as the longest ones like \"OL14 5ET\".</p>\n\n<p>Because it allows up to 8 characters, it will also allow incorrect 8 character postcodes if there is no space: \"OL145ETX\". But again, this is a simplistic regex, for when that's good enough.</p>\n" }, { "answer_id": 51885364, "author": "ctwheels", "author_id": 3600709, "author_profile": "https://Stackoverflow.com/users/3600709", "pm_score": 8, "selected": false, "text": "<p>I recently posted <a href=\"https://stackoverflow.com/a/51828886/3600709\">an answer</a> to <a href=\"https://stackoverflow.com/q/51828712/3600709\">this question on UK postcodes for the R language</a>. I discovered that <strong>the UK Government's regex pattern is incorrect</strong> and fails to <em>properly</em> validate some postcodes. Unfortunately, many of the answers here are based on this incorrect pattern.</p>\n\n<p>I'll outline some of these issues below and provide a revised regular expression that <em>actually</em> works.</p>\n\n<hr>\n\n<h1>Note</h1>\n\n<p><strong>My answer</strong> (and regular expressions in general):</p>\n\n<ul>\n<li><strong>Only validates postcode <em>formats</em></strong>.</li>\n<li><strong>Does not ensure that a postcode <em>legitimately exists</em></strong>.\n\n<ul>\n<li>For this, use an appropriate API! See <a href=\"https://stackoverflow.com/a/17024047/3600709\">Ben's answer</a> for more info.</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p><sub>If you don't care about the <em>bad regex</em> and just want to skip to the answer, scroll down to the <strong>Answer</strong> section.</sub></p>\n\n<h1>The Bad Regex</h1>\n\n<p><strong>The regular expressions in this section should not be used.</strong></p>\n\n<p>This is the failing regex that the UK government has provided developers (not sure how long this link will be up, but you can see it in their <a href=\"https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/488478/Bulk_Data_Transfer_-_additional_validation_valid_from_12_November_2015.pdf\" rel=\"noreferrer\">Bulk Data Transfer documentation</a>):</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$\n</code></pre>\n\n<h2>Problems</h2>\n\n<h3>Problem 1 - Copy/Paste</h3>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/1\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<p>As many developers likely do, they copy/paste code (especially regular expressions) and paste them expecting them to work. While this is great in theory, it fails in this particular case because copy/pasting from this document actually changes one of the characters (a space) into a newline character as shown below:</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\n[0-9][A-Za-z]{2})$\n</code></pre>\n\n<p>The first thing most developers will do is just erase the newline without thinking twice. Now the regex won't match postcodes with spaces in them (other than the <code>GIR 0AA</code> postcode).</p>\n\n<p>To fix this issue, the newline character should be replaced with the space character:</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n ^\n</code></pre>\n\n<h3>Problem 2 - Boundaries</h3>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/2\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n^^ ^ ^ ^^\n</code></pre>\n\n<p>The postcode regex improperly anchors the regex. Anyone using this regex to validate postcodes might be surprised if a value like <code>fooA11 1AA</code> gets through. That's because they've anchored the start of the first option and the end of the second option (independently of one another), as pointed out in the regex above.</p>\n\n<p>What this means is that <code>^</code> (asserts position at start of the line) only works on the first option <code>([Gg][Ii][Rr] 0[Aa]{2})</code>, so the second option will validate any strings that <strong>end</strong> in a postcode (regardless of what comes before).</p>\n\n<p>Similarly, the first option isn't anchored to the end of the line <code>$</code>, so <code>GIR 0AAfoo</code> is also accepted.</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$\n</code></pre>\n\n<p>To fix this issue, both options should be wrapped in another group (or non-capturing group) and the anchors placed around that: </p>\n\n<pre><code>^(([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2}))$\n^^ ^^\n</code></pre>\n\n<h3>Problem 3 - Improper Character Set</h3>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/3\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n ^^\n</code></pre>\n\n<p>The regex is missing a <code>-</code> here to indicate a range of characters. As it stands, if a postcode is in the format <code>ANA NAA</code> (where <code>A</code> represents a letter and <code>N</code> represents a number), and it begins with anything other than <code>A</code> or <code>Z</code>, it will fail.</p>\n\n<p>That means it will match <code>A1A 1AA</code> and <code>Z1A 1AA</code>, but not <code>B1A 1AA</code>.</p>\n\n<p>To fix this issue, the character <code>-</code> should be placed between the <code>A</code> and <code>Z</code> in the respective character set:</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n ^\n</code></pre>\n\n<h3>Problem 4 - Wrong Optional Character Set</h3>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/4\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n ^\n</code></pre>\n\n<p>I swear they didn't even test this thing before publicizing it on the web. They made the wrong character set optional. They made <code>[0-9]</code> option in the fourth sub-option of option 2 (group 9). This allows the regex to match incorrectly formatted postcodes like <code>AAA 1AA</code>.</p>\n\n<p>To fix this issue, make the next character class optional instead (and subsequently make the set <code>[0-9]</code> match exactly once):</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?)))) [0-9][A-Za-z]{2})$\n ^\n</code></pre>\n\n<h3>Problem 5 - Performance</h3>\n\n<p>Performance on this regex is extremely poor. First off, they placed the least likely pattern option to match <code>GIR 0AA</code> at the beginning. How many users will likely have this postcode versus any other postcode; probably never? This means every time the regex is used, it must exhaust this option first before proceeding to the next option. To see how performance is impacted check the number of steps the <a href=\"https://regex101.com/r/ajQHrd/5\" rel=\"noreferrer\">original regex</a> took (35) against the <a href=\"https://regex101.com/r/ajQHrd/6\" rel=\"noreferrer\">same regex after having flipped the options</a> (22).</p>\n\n<p>The second issue with performance is due to the way the entire regex is structured. There's no point backtracking over each option if one fails. The way the current regex is structured can greatly be simplified. I provide a fix for this in the <strong>Answer</strong> section.</p>\n\n<h3>Problem 6 - Spaces</h3>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/8\" rel=\"noreferrer\">See regex in use here</a></p>\n\n<p>This may not be considered a <em>problem</em>, per se, but it does raise concern for most developers. The spaces in the regex are not optional, which means the users inputting their postcodes must place a space in the postcode. This is an easy fix by simply adding <code>?</code> after the spaces to render them optional. See the <strong>Answer</strong> section for a fix.</p>\n\n<hr>\n\n<h1>Answer</h1>\n\n<h2>1. Fixing the UK Government's Regex</h2>\n\n<p>Fixing all the issues outlined in the <strong>Problems</strong> section and simplifying the pattern yields the following, shorter, more concise pattern. We can also remove most of the groups since we're validating the postcode as a whole (not individual parts):</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/12\" rel=\"noreferrer\">See regex in use here</a></p>\n\n<pre><code>^([A-Za-z][A-Ha-hJ-Yj-y]?[0-9][A-Za-z0-9]? ?[0-9][A-Za-z]{2}|[Gg][Ii][Rr] ?0[Aa]{2})$\n</code></pre>\n\n<p>This can further be shortened by removing all of the ranges from one of the cases (upper or lower case) and using a case-insensitive flag. <strong>Note</strong>: Some languages don't have one, so use the longer one above. Each language implements the case-insensitivity flag differently.</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/13\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([A-Z][A-HJ-Y]?[0-9][A-Z0-9]? ?[0-9][A-Z]{2}|GIR ?0A{2})$\n</code></pre>\n\n<p>Shorter again replacing <code>[0-9]</code> with <code>\\d</code> (if your regex engine supports it):</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/14\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([A-Z][A-HJ-Y]?\\d[A-Z\\d]? ?\\d[A-Z]{2}|GIR ?0A{2})$\n</code></pre>\n\n<h2>2. Simplified Patterns</h2>\n\n<p>Without ensuring specific alphabetic characters, the following can be used (keep in mind the simplifications from <strong>1. Fixing the UK Government's Regex</strong> have also been applied here):</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/15\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}|GIR ?0A{2})$\n</code></pre>\n\n<p>And even further if you don't care about the special case <code>GIR 0AA</code>:</p>\n\n<pre><code>^[A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}$\n</code></pre>\n\n<h2>3. Complicated Patterns</h2>\n\n<p>I would not suggest over-verification of a postcode as new Areas, Districts and Sub-districts may appear at any point in time. What I will suggest <em>potentially</em> doing, is added support for edge-cases. Some special cases exist and are outlined in <a href=\"https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Special_cases\" rel=\"noreferrer\">this Wikipedia article</a>.</p>\n\n<p>Here are complex regexes that include the subsections of <strong>3.</strong> (3.1, 3.2, 3.3).</p>\n\n<p>In relation to the patterns in <strong>1. Fixing the UK Government's Regex</strong>:</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/19\" rel=\"noreferrer\">See regex in use here</a></p>\n\n<pre><code>^(([A-Z][A-HJ-Y]?\\d[A-Z\\d]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?\\d[A-Z]{2}|BFPO ?\\d{1,4}|(KY\\d|MSR|VG|AI)[ -]?\\d{4}|[A-Z]{2} ?\\d{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$\n</code></pre>\n\n<p>And in relation to <strong>2. Simplified Patterns</strong>:</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/20\" rel=\"noreferrer\">See regex in use here</a></p>\n\n<pre><code>^(([A-Z]{1,2}\\d[A-Z\\d]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?\\d[A-Z]{2}|BFPO ?\\d{1,4}|(KY\\d|MSR|VG|AI)[ -]?\\d{4}|[A-Z]{2} ?\\d{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$\n</code></pre>\n\n<h3>3.1 British Overseas Territories</h3>\n\n<p>The Wikipedia article currently states (some formats slightly simplified):</p>\n\n<ul>\n<li><code>AI-1111</code>: Anguila</li>\n<li><code>ASCN 1ZZ</code>: Ascension Island</li>\n<li><code>STHL 1ZZ</code>: Saint Helena</li>\n<li><code>TDCU 1ZZ</code>: Tristan da Cunha</li>\n<li><code>BBND 1ZZ</code>: British Indian Ocean Territory</li>\n<li><code>BIQQ 1ZZ</code>: British Antarctic Territory</li>\n<li><code>FIQQ 1ZZ</code>: Falkland Islands</li>\n<li><code>GX11 1ZZ</code>: Gibraltar</li>\n<li><code>PCRN 1ZZ</code>: Pitcairn Islands</li>\n<li><code>SIQQ 1ZZ</code>: South Georgia and the South Sandwich Islands</li>\n<li><code>TKCA 1ZZ</code>: Turks and Caicos Islands</li>\n<li><code>BFPO 11</code>: Akrotiri and Dhekelia</li>\n<li><code>ZZ 11</code> &amp; <code>GE CX</code>: Bermuda (according to <a href=\"http://www.bpo.bm/Lists/Postal%20Codes/Attachments/1/Bermuda%20Postal%20Codes%20and%20Parishes%202013.pdf\" rel=\"noreferrer\">this document</a>)</li>\n<li><code>KY1-1111</code>: Cayman Islands (according to <a href=\"http://www.caymanpost.gov.ky/portal/page/portal/poshome/posnpimages/POSTCODE%20FINDER%20COLOUR.pdf\" rel=\"noreferrer\">this document</a>)</li>\n<li><code>VG1111</code>: British Virgin Islands (according to <a href=\"http://www.bvi.gov.vg/content/what-are-postcodes-addresses-british-virgin-islands\" rel=\"noreferrer\">this document</a>)</li>\n<li><code>MSR 1111</code>: Montserrat (according to <a href=\"http://www.gov.ms/wp-content/uploads/2014/02/Postal-Code-Guide-pamphlet.pdf\" rel=\"noreferrer\">this document</a>)</li>\n</ul>\n\n<p>An all-encompassing regex to match only the British Overseas Territories might look like this:</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/15\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^((ASCN|STHL|TDCU|BBND|[BFS]IQQ|GX\\d{2}|PCRN|TKCA) ?\\d[A-Z]{2}|(KY\\d|MSR|VG|AI)[ -]?\\d{4}|(BFPO|[A-Z]{2}) ?\\d{2}|GE ?CX)$\n</code></pre>\n\n<h3>3.2 British Forces Post Office</h3>\n\n<p>Although they've been recently changed it to better align with the British postcode system to <code>BF#</code> (where <code>#</code> represents a number), they're considered <em>optional alternative postcodes</em>. These postcodes follow(ed) the format of <code>BFPO</code>, followed by 1-4 digits:</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/17\" rel=\"noreferrer\">See regex in use here</a></p>\n\n<pre><code>^BFPO ?\\d{1,4}$\n</code></pre>\n\n<h3>3.3 Santa?</h3>\n\n<p>There's another special case with Santa (as mentioned in other answers): <code>SAN TA1</code> is a valid postcode. A regex for this is very simply:</p>\n\n<pre><code>^SAN ?TA1$\n</code></pre>\n" }, { "answer_id": 55083027, "author": "Aathi", "author_id": 3008370, "author_profile": "https://Stackoverflow.com/users/3008370", "pm_score": 0, "selected": false, "text": "<p>Below method will check the post code and provide complete info</p>\n<pre class=\"lang-js prettyprint-override\"><code>const isValidUKPostcode = postcode =&gt; {\n try {\n postcode = postcode.replace(/\\s/g, &quot;&quot;);\n const fromat = postcode\n .toUpperCase()\n .match(/^([A-Z]{1,2}\\d{1,2}[A-Z]?)\\s*(\\d[A-Z]{2})$/);\n const finalValue = `${fromat[1]} ${fromat[2]}`;\n const regex = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$/i;\n return {\n isValid: regex.test(postcode),\n formatedPostCode: finalValue,\n error: false,\n message: 'It is a valid postcode'\n };\n } catch (error) {\n return { error: true , message: 'Invalid postcode'};\n }\n};\n</code></pre>\n<pre class=\"lang-js prettyprint-override\"><code>console.log(isValidUKPostcode('GU348RR'))\n{isValid: true, formattedPostcode: &quot;GU34 8RR&quot;, error: false, message: &quot;It is a valid postcode&quot;}\n</code></pre>\n<pre class=\"lang-js prettyprint-override\"><code>console.log(isValidUKPostcode('sdasd4746asd'))\n{error: true, message: &quot;Invalid postcode!&quot;}\n</code></pre>\n<pre class=\"lang-js prettyprint-override\"><code>valid_postcode('787898523')\nresult =&gt; {error: true, message: &quot;Invalid postcode&quot;}\n</code></pre>\n" }, { "answer_id": 56134559, "author": "Ghoti", "author_id": 80662, "author_profile": "https://Stackoverflow.com/users/80662", "pm_score": -1, "selected": false, "text": "<p>I stole this from an XML document and it seems to cover all cases without the hard coded GIRO:</p>\n\n<pre><code>%r{[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}}i\n</code></pre>\n\n<p>(Ruby syntax with ignore case)</p>\n" }, { "answer_id": 61430132, "author": "jontsai", "author_id": 865091, "author_profile": "https://Stackoverflow.com/users/865091", "pm_score": 2, "selected": false, "text": "<p>Through empirical testing and observation, as well as confirming with <a href=\"https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation</a>, here is my version of a Python regex that correctly parses and validates a UK postcode:</p>\n\n<p><code>UK_POSTCODE_REGEX = r'(?P&lt;postcode_area&gt;[A-Z]{1,2})(?P&lt;district&gt;(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P&lt;sector&gt;[0-9])(?P&lt;postcode&gt;[A-Z]{2})'</code></p>\n\n<p>This regex is simple and has capture groups. It <strong>does not</strong> include all of the validations of <em>legal</em> UK postcodes, but only takes into account the letter vs number positions.</p>\n\n<p>Here is how I would use it in code:</p>\n\n<pre><code>@dataclass\nclass UKPostcode:\n postcode_area: str\n district: str\n sector: int\n postcode: str\n\n # https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation\n # Original author of this regex: @jontsai\n # NOTE TO FUTURE DEVELOPER:\n # Verified through empirical testing and observation, as well as confirming with the Wiki article\n # If this regex fails to capture all valid UK postcodes, then I apologize, for I am only human.\n UK_POSTCODE_REGEX = r'(?P&lt;postcode_area&gt;[A-Z]{1,2})(?P&lt;district&gt;(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P&lt;sector&gt;[0-9])(?P&lt;postcode&gt;[A-Z]{2})'\n\n @classmethod\n def from_postcode(cls, postcode):\n \"\"\"Parses a string into a UKPostcode\n\n Returns a UKPostcode or None\n \"\"\"\n m = re.match(cls.UK_POSTCODE_REGEX, postcode.replace(' ', ''))\n\n if m:\n uk_postcode = UKPostcode(\n postcode_area=m.group('postcode_area'),\n district=m.group('district'),\n sector=m.group('sector'),\n postcode=m.group('postcode')\n )\n else:\n uk_postcode = None\n\n return uk_postcode\n\n\ndef parse_uk_postcode(postcode):\n \"\"\"Wrapper for UKPostcode.from_postcode\n \"\"\"\n uk_postcode = UKPostcode.from_postcode(postcode)\n return uk_postcode\n</code></pre>\n\n<p>Here are unit tests:</p>\n\n<pre><code>@pytest.mark.parametrize(\n 'postcode, expected', [\n # https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation\n (\n 'EC1A1BB',\n UKPostcode(\n postcode_area='EC',\n district='1A',\n sector='1',\n postcode='BB'\n ),\n ),\n (\n 'W1A0AX',\n UKPostcode(\n postcode_area='W',\n district='1A',\n sector='0',\n postcode='AX'\n ),\n ),\n (\n 'M11AE',\n UKPostcode(\n postcode_area='M',\n district='1',\n sector='1',\n postcode='AE'\n ),\n ),\n (\n 'B338TH',\n UKPostcode(\n postcode_area='B',\n district='33',\n sector='8',\n postcode='TH'\n )\n ),\n (\n 'CR26XH',\n UKPostcode(\n postcode_area='CR',\n district='2',\n sector='6',\n postcode='XH'\n )\n ),\n (\n 'DN551PT',\n UKPostcode(\n postcode_area='DN',\n district='55',\n sector='1',\n postcode='PT'\n )\n )\n ]\n)\ndef test_parse_uk_postcode(postcode, expected):\n uk_postcode = parse_uk_postcode(postcode)\n assert(uk_postcode == expected)\n</code></pre>\n" }, { "answer_id": 69269028, "author": "Ella Bella", "author_id": 14713613, "author_profile": "https://Stackoverflow.com/users/14713613", "pm_score": -1, "selected": false, "text": "<p>I did the regex for UK postcode validation today, as far as I know, it works for all UK postcodes, it works if you put a space or if you don't.</p>\n<pre><code>^((([a-zA-Z][0-9])|([a-zA-Z][0-9]{2})|([a-zA-Z]{2}[0-9])|([a-zA-Z]{2}[0-9]{2})|([A-Za-z][0-9][a-zA-Z])|([a-zA-Z]{2}[0-9][a-zA-Z]))(\\s*[0-9][a-zA-Z]{2})$)\n</code></pre>\n<p>Let me know if there's a format it doesn't cover</p>\n" }, { "answer_id": 69806181, "author": "Mecanik", "author_id": 6583298, "author_profile": "https://Stackoverflow.com/users/6583298", "pm_score": 3, "selected": false, "text": "<p>Whilst there are many answers here, I'm not happy with either of them. Most of them are simply broken, are too complex or just broken.</p>\n<p>I looked at <a href=\"https://stackoverflow.com/questions/164979/regex-for-matching-uk-postcodes#51885364\">@ctwheels</a> answer and I found it very explanatory and correct; we must thank him for that. However once again too much &quot;data&quot; for me, for something so simple.</p>\n<p>Fortunately, I managed to get a database with over 1 million active postcodes for England only and made a small PowerShell script to test and benchmark the results.</p>\n<p>UK Postcode specifications: <a href=\"https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/611951/Appendix_C_ILR_2017_to_2018_v1_Published_28April17.pdf\" rel=\"noreferrer\">Valid Postcode Format</a>.</p>\n<p><strong>This is &quot;my&quot; Regex:</strong></p>\n<pre><code>^([a-zA-Z]{1,2}[a-zA-Z\\d]{1,2})\\s(\\d[a-zA-Z]{2})$\n</code></pre>\n<p>Short, simple and sweet. Even the most unexperienced can understand what is going on.</p>\n<p><strong>Explanation:</strong></p>\n<pre><code>^ asserts position at start of a line\n 1st Capturing Group ([a-zA-Z]{1,2}[a-zA-Z\\d]{1,2})\n Match a single character present in the list below [a-zA-Z]\n {1,2} matches the previous token between 1 and 2 times, as many times as possible, giving back as needed (greedy)\n a-z matches a single character in the range between a (index 97) and z (index 122) (case sensitive)\n A-Z matches a single character in the range between A (index 65) and Z (index 90) (case sensitive)\n Match a single character present in the list below [a-zA-Z\\d]\n {1,2} matches the previous token between 1 and 2 times, as many times as possible, giving back as needed (greedy)\n a-z matches a single character in the range between a (index 97) and z (index 122) (case sensitive)\n A-Z matches a single character in the range between A (index 65) and Z (index 90) (case sensitive)\n \\d matches a digit (equivalent to [0-9])\n \\s matches any whitespace character (equivalent to [\\r\\n\\t\\f\\v ])\n 2nd Capturing Group (\\d[a-zA-Z]{2})\n \\d matches a digit (equivalent to [0-9])\n Match a single character present in the list below [a-zA-Z]\n {2} matches the previous token exactly 2 times\n a-z matches a single character in the range between a (index 97) and z (index 122) (case sensitive)\n A-Z matches a single character in the range between A (index 65) and Z (index 90) (case sensitive)\n$ asserts position at the end of a line\n</code></pre>\n<p><strong>Result (postcodes checked):</strong></p>\n<pre><code>TOTAL OK: 1469193\nTOTAL FAILED: 0\n-------------------------------------------------------------------------\nDays : 0\nHours : 0\nMinutes : 5\nSeconds : 22\nMilliseconds : 718\nTicks : 3227185939\nTotalDays : 0.00373516891087963\nTotalHours : 0.0896440538611111\nTotalMinutes : 5.37864323166667\nTotalSeconds : 322.7185939\nTotalMilliseconds : 322718.5939\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a PHP script that uses the `system()` call to execute other (potentially long-running) programs (for interest: NCBI BLAST, phrap, primer3 and other programs for doing DNA sequence analysis and assembly). I'm running under Windows XP, using the CLI version of PHP from a command prompt, or as a service. (In either case I communicate with it via a queue of tasks in a database table). Under PHP4: when I hit `Ctrl`+`C` the script is stopped and any child process running at the time is also stopped. Under PHP5: when I hit `Ctrl`+`C` the script stops, but the child is left running. Similarly, when running the script as a service, stopping the service when running it with PHP4 stops the child, with PHP5 the child continues to run. I have tried writing a minimal test application, and found the same behaviour. The test PHP script just uses system() to execute a C program (that just sleeps for 30 seconds) and then waits for a key to be pressed. I had a look at the source for PHP 4.4.9 and 5.2.6 but could see no differences in the system() code that looked like they would cause this. I also had a quick look at the startup code for the CLI application and didn't see any differences in signal handling. Any hints on what might have caused this, or a workaround, would be appreciated. Thanks.
I'd recommend taking a look at the UK Government Data Standard for postcodes [link now dead; [archive of XML](http://webarchive.nationalarchives.gov.uk/+/http://www.cabinetoffice.gov.uk/media/291370/bs7666-v2-0-xsd-PostCodeType.htm), see [Wikipedia](http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation) for discussion]. There is a brief description about the data and the attached xml schema provides a regular expression. It may not be exactly what you want but would be a good starting point. The RegEx differs from the XML slightly, as a P character in third position in format A9A 9AA is allowed by the definition given. The RegEx supplied by the UK Government was: ``` ([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2}) ``` As pointed out on the Wikipedia discussion, this will allow some non-real postcodes (e.g. those starting AA, ZY) and they do provide a more rigorous test that you could try.
164,990
<p>This is a continuation question from a previous question <a href="https://stackoverflow.com/questions/142237/integrating-external-sources-in-a-build.">I have asked</a></p> <p>I now have a /externals directory in the root of my project tree. Inside this I have a reference to another project. I'm able to script the build of all my externals in the main project NAnt script. The result of these builds are as follows:</p> <p>/externals/external-project1/build/buildartifacts/{dlls|html|js}</p> <p>/externals/external-project2/build/buildartifacts/{dlls|html|js}</p> <p>This is all well and good, but now I'm curious as to how my main project should reference these build artifacts. For example, let's say that external project builds a DLL that some of my codebase depends on. Should I simply reference the DLL in the build artifacts directory or should I implement another NAnt task that copies these to a /thirdparty/libs/ folder?</p> <p>This means that my build is now dependent on the ability to build this external project (which could either be internal, or thirdparty). Is it a good idea to check in the latest set of build artifacts to ensure that the main build won't break because of dependent builds breaking?</p> <p>Hope that's clear enough. Just writing this down has a least clarified the problem for me :-).</p> <p>--Edit--</p> <p>Thanks guys. I think I'm going to implement the "checkout a revision", but since the builds are so quick I'm not going to check in any build artifiacts. Also going to have to figure out how to deal with the dependencies of the external project (eg: prototype, swfobject, etc).</p>
[ { "answer_id": 164992, "author": "Dan", "author_id": 230, "author_profile": "https://Stackoverflow.com/users/230", "pm_score": 5, "selected": false, "text": "<pre><code>^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$\n</code></pre>\n\n<blockquote>\n <p>Regular expression to match valid UK\n postcodes. In the UK postal system not\n all letters are used in all positions\n (the same with vehicle registration\n plates) and there are various rules to\n govern this. This regex takes into\n account those rules. Details of the\n rules: First half of postcode Valid\n formats [A-Z][A-Z][0-9][A-Z]\n [A-Z][A-Z][0-9][0-9] [A-Z][0-9][0-9]\n [A-Z][A-Z][0-9] [A-Z][A-Z][A-Z]\n [A-Z][0-9][A-Z] [A-Z][0-9] Exceptions\n Position - First. Contraint - QVX not\n used Position - Second. Contraint -\n IJZ not used except in GIR 0AA\n Position - Third. Constraint -\n AEHMNPRTVXY only used Position -\n Forth. Contraint - ABEHMNPRVWXY Second\n half of postcode Valid formats\n [0-9][A-Z][A-Z] Exceptions Position -\n Second and Third. Contraint - CIKMOV\n not used</p>\n</blockquote>\n\n<p><a href=\"http://regexlib.com/REDetails.aspx?regexp_id=260\" rel=\"noreferrer\">http://regexlib.com/REDetails.aspx?regexp_id=260</a></p>\n" }, { "answer_id": 164994, "author": "marcj", "author_id": 23940, "author_profile": "https://Stackoverflow.com/users/23940", "pm_score": 9, "selected": true, "text": "<p>I'd recommend taking a look at the UK Government Data Standard for postcodes [link now dead; <a href=\"http://webarchive.nationalarchives.gov.uk/+/http://www.cabinetoffice.gov.uk/media/291370/bs7666-v2-0-xsd-PostCodeType.htm\" rel=\"noreferrer\">archive of XML</a>, see <a href=\"http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation\" rel=\"noreferrer\">Wikipedia</a> for discussion]. There is a brief description about the data and the attached xml schema provides a regular expression. It may not be exactly what you want but would be a good starting point. The RegEx differs from the XML slightly, as a P character in third position in format A9A 9AA is allowed by the definition given.</p>\n\n<p>The RegEx supplied by the UK Government was:</p>\n\n<pre><code>([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\\s?[0-9][A-Za-z]{2})\n</code></pre>\n\n<p>As pointed out on the Wikipedia discussion, this will allow some non-real postcodes (e.g. those starting AA, ZY) and they do provide a more rigorous test that you could try.</p>\n" }, { "answer_id": 164995, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 2, "selected": false, "text": "<p>First half of postcode Valid formats </p>\n\n<ul>\n<li>[A-Z][A-Z][0-9][A-Z] </li>\n<li>[A-Z][A-Z][0-9][0-9] </li>\n<li>[A-Z][0-9][0-9] </li>\n<li>[A-Z][A-Z][0-9] </li>\n<li>[A-Z][A-Z][A-Z] </li>\n<li>[A-Z][0-9][A-Z] </li>\n<li>[A-Z][0-9] </li>\n</ul>\n\n<p>Exceptions<br>\nPosition 1 - QVX not used<br>\nPosition 2 - IJZ not used except in GIR 0AA<br>\nPosition 3 - AEHMNPRTVXY only used<br>\nPosition 4 - ABEHMNPRVWXY </p>\n\n<p>Second half of postcode </p>\n\n<ul>\n<li>[0-9][A-Z][A-Z] </li>\n</ul>\n\n<p>Exceptions<br>\nPosition 2+3 - CIKMOV not used</p>\n\n<p>Remember not all possible codes are used, so this list is a necessary but not sufficent condition for a valid code. It might be easier to just match against a list of all valid codes?</p>\n" }, { "answer_id": 1600314, "author": "Rudiger Wolf", "author_id": 41431, "author_profile": "https://Stackoverflow.com/users/41431", "pm_score": 1, "selected": false, "text": "<p>Have a look at the python code on this page:</p>\n<p><a href=\"http://www.brunningonline.net/simon/blog/archives/001292.html\" rel=\"nofollow noreferrer\">http://www.brunningonline.net/simon/blog/archives/001292.html</a></p>\n<blockquote>\n<p>I've got some postcode parsing to do. The requirement is pretty simple; I have to parse a postcode into an outcode and (optional) incode. The good new is that I don't have to perform any validation - I just have to chop up what I've been provided with in a vaguely intelligent manner. I can't assume much about my import in terms of formatting, i.e. case and embedded spaces. But this isn't the bad news; the bad news is that I have to do it all in RPG. :-(</p>\n<p>Nevertheless, I threw a little Python function together to clarify my thinking.</p>\n</blockquote>\n<p>I've used it to process postcodes for me.</p>\n" }, { "answer_id": 4793095, "author": "minglis", "author_id": 502087, "author_profile": "https://Stackoverflow.com/users/502087", "pm_score": 3, "selected": false, "text": "<p>Some of the regexs above are a little restrictive. Note the genuine postcode: \"W1K 7AA\" would fail given the rule \"Position 3 - AEHMNPRTVXY only used\" above as \"K\" would be disallowed.</p>\n\n<p>the regex:</p>\n\n<pre><code>^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKPS-UW])[0-9][ABD-HJLNP-UW-Z]{2})$\n</code></pre>\n\n<p>Seems a little more accurate, see the <a href=\"http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom\" rel=\"nofollow\">Wikipedia article entitled 'Postcodes in the United Kingdom'</a>.</p>\n\n<p>Note that this regex requires uppercase only characters.</p>\n\n<p>The bigger question is whether you are restricting user input to allow only postcodes that actually exist or whether you are simply trying to stop users entering complete rubbish into the form fields. Correctly matching every possible postcode, and future proofing it, is a harder puzzle, and probably not worth it unless you are HMRC.</p>\n" }, { "answer_id": 6276530, "author": "Will Tomlins", "author_id": 690904, "author_profile": "https://Stackoverflow.com/users/690904", "pm_score": 3, "selected": false, "text": "<p>Here's a regex based on the format specified in the documents which are linked to marcj's answer:</p>\n\n<pre><code>/^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-Z]{2}$/\n</code></pre>\n\n<p>The only difference between that and the specs is that the last 2 characters cannot be in [CIKMOV] according to the specs.</p>\n\n<p>Edit:\nHere's another version which does test for the trailing character limitations.</p>\n\n<pre><code>/^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-BD-HJLNP-UW-Z]{2}$/\n</code></pre>\n" }, { "answer_id": 7259020, "author": "Colin", "author_id": 521518, "author_profile": "https://Stackoverflow.com/users/521518", "pm_score": 6, "selected": false, "text": "<p>It looks like we're going to be using <code>^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$</code>, which is a slightly modified version of that sugested by Minglis above.</p>\n\n<p>However, we're going to have to investigate exactly what the rules are, as the various solutions listed above appear to apply different rules as to which letters are allowed.</p>\n\n<p>After some research, we've found some more information. Apparently a page on 'govtalk.gov.uk' points you to a postcode specification <a href=\"http://interim.cabinetoffice.gov.uk/govtalk/schemasstandards/e-gif/datastandards/address/postcode.aspx\" rel=\"noreferrer\">govtalk-postcodes</a>. This points to an XML schema at <a href=\"http://interim.cabinetoffice.gov.uk/media/291293/bs7666-v2-0.xml\" rel=\"noreferrer\">XML Schema</a> which provides a 'pseudo regex' statement of the postcode rules.</p>\n\n<p>We've taken that and worked on it a little to give us the following expression:</p>\n\n<pre><code>^((GIR &amp;0AA)|((([A-PR-UWYZ][A-HK-Y]?[0-9][0-9]?)|(([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]))) &amp;[0-9][ABD-HJLNP-UW-Z]{2}))$\n</code></pre>\n\n<p>This makes spaces optional, but does limit you to one space (replace the '&amp;' with '{0,} for unlimited spaces). It assumes all text must be upper-case.</p>\n\n<p>If you want to allow lower case, with any number of spaces, use:</p>\n\n<pre><code>^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$\n</code></pre>\n\n<p>This doesn't cover overseas territories and only enforces the format, NOT the existence of different areas. It is based on the following rules:</p>\n\n<p>Can accept the following formats:</p>\n\n<ul>\n<li>“GIR 0AA”</li>\n<li>A9 9ZZ</li>\n<li>A99 9ZZ</li>\n<li>AB9 9ZZ</li>\n<li>AB99 9ZZ</li>\n<li>A9C 9ZZ</li>\n<li>AD9E 9ZZ</li>\n</ul>\n\n<p>Where:</p>\n\n<ul>\n<li>9 can be any single digit number.</li>\n<li>A can be any letter except for Q, V or X.</li>\n<li>B can be any letter except for I, J or Z.</li>\n<li>C can be any letter except for I, L, M, N, O, P, Q, R, V, X, Y or Z.</li>\n<li>D can be any letter except for I, J or Z.</li>\n<li>E can be any of A, B, E, H, M, N, P, R, V, W, X or Y.</li>\n<li>Z can be any letter except for C, I, K, M, O or V.</li>\n</ul>\n\n<p>Best wishes</p>\n\n<p>Colin</p>\n" }, { "answer_id": 10600422, "author": "Vikas Pandey", "author_id": 1396126, "author_profile": "https://Stackoverflow.com/users/1396126", "pm_score": 1, "selected": false, "text": "<p>I have the regex for UK Postcode validation.</p>\n\n<p>This is working for all type of Postcode either inner or outer</p>\n\n<pre><code>^((([A-PR-UWYZ][0-9])|([A-PR-UWYZ][0-9][0-9])|([A-PR-UWYZ][A-HK-Y][0-9])|([A-PR-UWYZ][A-HK-Y][0-9][0-9])|([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))) || ^((GIR)[ ]?(0AA))$|^(([A-PR-UWYZ][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][0-9][A-HJKS-UW0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9][ABEHMNPRVWXY0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$\n</code></pre>\n\n<p>This is working for all type of format.</p>\n\n<p>Example:</p>\n\n<blockquote>\n <p>AB10-------------------->ONLY OUTER POSTCODE</p>\n \n <p>A1 1AA------------------>COMBINATION OF (OUTER AND INNER) POSTCODE</p>\n \n <p>WC2A-------------------->OUTER</p>\n</blockquote>\n" }, { "answer_id": 11865017, "author": "paulslater19", "author_id": 705752, "author_profile": "https://Stackoverflow.com/users/705752", "pm_score": 0, "selected": false, "text": "<p>We were given a spec:</p>\n\n<pre>UK postcodes must be in one of the following forms (with one exception, see below): \n § A9 9AA \n § A99 9AA\n § AA9 9AA\n § AA99 9AA\n § A9A 9AA\n § AA9A 9AA\nwhere A represents an alphabetic character and 9 represents a numeric character.\nAdditional rules apply to alphabetic characters, as follows:\n § The character in position 1 may not be Q, V or X\n § The character in position 2 may not be I, J or Z\n § The character in position 3 may not be I, L, M, N, O, P, Q, R, V, X, Y or Z\n § The character in position 4 may not be C, D, F, G, I, J, K, L, O, Q, S, T, U or Z\n § The characters in the rightmost two positions may not be C, I, K, M, O or V\nThe one exception that does not follow these general rules is the postcode \"GIR 0AA\", which is a special valid postcode.</pre>\n\n<p>We came up with this: </p>\n\n<pre><code>/^([A-PR-UWYZ][A-HK-Y0-9](?:[A-HJKS-UW0-9][ABEHMNPRV-Y0-9]?)?\\s*[0-9][ABD-HJLNP-UW-Z]{2}|GIR\\s*0AA)$/i\n</code></pre>\n\n<p>But note - this allows any number of spaces in between groups. </p>\n" }, { "answer_id": 14257846, "author": "Dan Solo", "author_id": 1139823, "author_profile": "https://Stackoverflow.com/users/1139823", "pm_score": 3, "selected": false, "text": "<p>I've been looking for a UK postcode regex for the last day or so and stumbled on this thread. I worked my way through most of the suggestions above and none of them worked for me so I came up with my own regex which, as far as I know, captures all valid UK postcodes as of Jan '13 (according to the latest literature from the Royal Mail).</p>\n\n<p>The regex and some simple postcode checking PHP code is posted below. NOTE:- It allows for lower or uppercase postcodes and the GIR 0AA anomaly but to deal with the, more than likely, presence of a space in the middle of an entered postcode it also makes use of a simple str_replace to remove the space before testing against the regex. Any discrepancies beyond that and the Royal Mail themselves don't even mention them in their literature (see <a href=\"http://www.royalmail.com/sites/default/files/docs/pdf/programmers_guide_edition_7_v5.pdf\">http://www.royalmail.com/sites/default/files/docs/pdf/programmers_guide_edition_7_v5.pdf</a> and start reading from page 17)!</p>\n\n<p><strong>Note:</strong> In the Royal Mail's own literature (link above) there is a slight ambiguity surrounding the 3rd and 4th positions and the exceptions in place if these characters are letters. I contacted Royal Mail directly to clear it up and in their own words \"A letter in the 4th position of the Outward Code with the format AANA NAA has no exceptions and the 3rd position exceptions apply only to the last letter of the Outward Code with the format ANA NAA.\" Straight from the horse's mouth!</p>\n\n<pre><code>&lt;?php\n\n $postcoderegex = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\\d[abd-hjlnp-uw-z]{2})?)$/i';\n\n $postcode2check = str_replace(' ','',$postcode2check);\n\n if (preg_match($postcoderegex, $postcode2check)) {\n\n echo \"$postcode2check is a valid postcode&lt;br&gt;\";\n\n } else {\n\n echo \"$postcode2check is not a valid postcode&lt;br&gt;\";\n\n }\n\n?&gt;\n</code></pre>\n\n<p>I hope it helps anyone else who comes across this thread looking for a solution.</p>\n" }, { "answer_id": 15953188, "author": "Alix Axel", "author_id": 89771, "author_profile": "https://Stackoverflow.com/users/89771", "pm_score": 4, "selected": false, "text": "<p>This is the regex Google serves on their <a href=\"http://i18napis.appspot.com/address/data/GB\">i18napis.appspot.com</a> domain:</p>\n\n<pre><code>GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|BX|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\\d[\\dA-Z]?[ ]?\\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\\d{1,4}\n</code></pre>\n" }, { "answer_id": 16485951, "author": "Jesús Carrera", "author_id": 2330244, "author_profile": "https://Stackoverflow.com/users/2330244", "pm_score": 4, "selected": false, "text": "<p>Most of the answers here didn't work for all the postcodes I have in my database. I finally found one that validates with all, using the new regex provided by the government:</p>\n\n<p><a href=\"https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/413338/Bulk_Data_Transfer_-_additional_validation_valid_from_March_2015.pdf\" rel=\"nofollow noreferrer\">https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/413338/Bulk_Data_Transfer_-_additional_validation_valid_from_March_2015.pdf</a></p>\n\n<p>It isn't in any of the previous answers so I post it here in case they take the link down:</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n</code></pre>\n\n<p>UPDATE: Updated regex as pointed by Jamie Bull. Not sure if it was my error copying or it was an error in the government's regex, the link is down now... </p>\n\n<p>UPDATE: As ctwheels found, this regex works with the javascript regex flavor. See his comment for one that works with the pcre (php) flavor.</p>\n" }, { "answer_id": 17024047, "author": "Ben", "author_id": 458741, "author_profile": "https://Stackoverflow.com/users/458741", "pm_score": 6, "selected": false, "text": "<p>There is no such thing as a comprehensive UK postcode regular expression that is capable of <em>validating</em> a postcode. You can check that a postcode is in the correct format using a regular expression; not that it actually exists.</p>\n\n<p>Postcodes are arbitrarily complex and constantly changing. For instance, the outcode <code>W1</code> does not, and may never, have every number between 1 and 99, for every postcode area.</p>\n\n<p>You can't expect what is there currently to be true forever. As an example, in 1990, the Post Office decided that Aberdeen was getting a bit crowded. They added a 0 to the end of AB1-5 making it AB10-50 and then created a number of postcodes in between these. </p>\n\n<p>Whenever a new street is build a new postcode is created. It's part of the process for obtaining permission to build; local authorities are obliged to keep this updated with the Post Office (not that they all do).</p>\n\n<p>Furthermore, as noted by a number of other users, there's the special postcodes such as Girobank, GIR 0AA, and the one for letters to Santa, SAN TA1 - you probably don't want to post anything there but it doesn't appear to be covered by any other answer.</p>\n\n<p>Then, there's the BFPO postcodes, which are now <a href=\"https://www.gov.uk/government/publications/british-forces-post-office-locations\" rel=\"noreferrer\">changing to a more standard format</a>. Both formats are going to be valid. Lastly, there's the overseas territories <sup><a href=\"http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom\" rel=\"noreferrer\">source Wikipedia</a></sup>.</p>\n\n<pre>\n+----------+----------------------------------------------+\n| Postcode | Location |\n+----------+----------------------------------------------+\n| AI-2640 | Anguilla |\n| ASCN 1ZZ | Ascension Island |\n| STHL 1ZZ | Saint Helena |\n| TDCU 1ZZ | Tristan da Cunha |\n| BBND 1ZZ | British Indian Ocean Territory |\n| BIQQ 1ZZ | British Antarctic Territory |\n| FIQQ 1ZZ | Falkland Islands |\n| GX11 1AA | Gibraltar |\n| PCRN 1ZZ | Pitcairn Islands |\n| SIQQ 1ZZ | South Georgia and the South Sandwich Islands |\n| TKCA 1ZZ | Turks and Caicos Islands |\n+----------+----------------------------------------------+</pre>\n\n<p>Next, you have to take into account that the UK \"exported\" its postcode system to many places in the world. Anything that validates a \"UK\" postcode will also validate the postcodes of a number of other countries.</p>\n\n<p>If you want to <em>validate</em> a UK postcode the safest way to do it is to use a look-up of current postcodes. There are a number of options:</p>\n\n<ul>\n<li><p>Ordnance Survey releases <a href=\"http://www.ordnancesurvey.co.uk/oswebsite/products/code-point-open/\" rel=\"noreferrer\">Code-Point Open</a> under an open data licence. It'll be very slightly behind the times but it's free. This will (probably - I can't remember) not include Northern Irish data as the Ordnance Survey has no remit there. Mapping in Northern Ireland is conducted by the Ordnance Survey of Northern Ireland and they have their, separate, paid-for, <a href=\"https://maps.osni.gov.uk/CMSPages/moreinfo_address_data.aspx\" rel=\"noreferrer\">Pointer</a> product. You could use this and append the few that aren't covered fairly easily.</p></li>\n<li><p>Royal Mail releases the <a href=\"http://www.poweredbypaf.com/\" rel=\"noreferrer\">Postcode Address File (PAF)</a>, this includes BFPO which I'm not sure Code-Point Open does. It's updated regularly but costs money (and they can be downright mean about it sometimes). PAF includes the full address rather than just postcodes and comes with its own <a href=\"http://www.poweredbypaf.com/wp-content/themes/amu/paf_downloads/programmers_guide.pdf\" rel=\"noreferrer\">Programmers Guide</a>. The Open Data User Group (ODUG) is currently lobbying to have PAF released for free, <a href=\"http://data.gov.uk/library/odug-response-to-ofcom-paf-review-consultation\" rel=\"noreferrer\">here's a description of their position</a>.</p></li>\n<li><p>Lastly, there's <a href=\"https://www.ordnancesurvey.co.uk/business-and-government/products/addressbase-products.html\" rel=\"noreferrer\">AddressBase</a>. This is a collaboration between Ordnance Survey, Local Authorities, Royal Mail and a matching company to create a definitive directory of all information about all UK addresses (they've been fairly successful as well). It's paid-for but if you're working with a Local Authority, government department, or government service it's free for them to use. There's a lot more information than just postcodes included.</p></li>\n</ul>\n" }, { "answer_id": 17507615, "author": "RichardTowers", "author_id": 1344760, "author_profile": "https://Stackoverflow.com/users/1344760", "pm_score": 4, "selected": false, "text": "<p>I had a look into some of the answers above and I'd recommend against using the pattern from @Dan's <a href=\"https://stackoverflow.com/questions/164979/uk-postcode-regex-comprehensive#answer-164992\">answer (c. Dec 15 '10)</a>, since it incorrectly flags almost 0.4% of valid postcodes as invalid, while the others do not. </p>\n\n<p>Ordnance Survey provide service called Code Point Open which:</p>\n\n<blockquote>\n <p>contains a list of all the current postcode units in Great Britain</p>\n</blockquote>\n\n<p>I ran each of the regexs above against the full list of postcodes (Jul 6 '13) from this data using <code>grep</code>:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>cat CSV/*.csv |\n # Strip leading quotes\n sed -e 's/^\"//g' |\n # Strip trailing quote and everything after it\n sed -e 's/\".*//g' |\n # Strip any spaces\n sed -E -e 's/ +//g' |\n # Find any lines that do not match the expression\n grep --invert-match --perl-regexp \"$pattern\"\n</code></pre>\n\n<p>There are 1,686,202 postcodes total.</p>\n\n<p>The following are the numbers of valid postcodes that do <em>not</em> match each <code>$pattern</code>:</p>\n\n<pre><code>'^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$'\n# =&gt; 6016 (0.36%)\n</code></pre>\n\n\n\n<pre><code>'^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$'\n# =&gt; 0\n</code></pre>\n\n\n\n<pre><code>'^GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|BX|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\\d[\\dA-Z]?[ ]?\\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\\d{1,4}$'\n# =&gt; 0\n</code></pre>\n\n<p>Of course, these results only deal with valid postcodes that are incorrectly flagged as invalid. So:</p>\n\n<pre><code>'^.*$'\n# =&gt; 0\n</code></pre>\n\n<p>I'm saying nothing about which pattern is the best regarding filtering out invalid postcodes.</p>\n" }, { "answer_id": 23375983, "author": "andre", "author_id": 3108126, "author_profile": "https://Stackoverflow.com/users/3108126", "pm_score": 3, "selected": false, "text": "<p>Postcodes are subject to change, and the only true way of validating a postcode is to have the complete list of postcodes and see if it's there.</p>\n\n<p>But regular expressions are useful because they:</p>\n\n<ul>\n<li>are easy to use and implement</li>\n<li>are short</li>\n<li>are quick to run</li>\n<li>are quite easy to maintain (compared to a full list of postcodes)</li>\n<li>still catch most input errors</li>\n</ul>\n\n<p>But regular expressions tend to be difficult to maintain, especially for someone who didn't come up with it in the first place. So it must be:</p>\n\n<ul>\n<li>as easy to understand as possible</li>\n<li>relatively future proof</li>\n</ul>\n\n<p>That means that most of the regular expressions in this answer aren't good enough. E.g. I can see that <code>[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]</code> is going to match a postcode area of the form AA1A — but it's going to be a pain in the neck if and when a new postcode area gets added, because it's difficult to understand which postcode areas it matches.</p>\n\n<p>I also want my regular expression to match the first and second half of the postcode as parenthesised matches.</p>\n\n<p>So I've come up with this:</p>\n\n<pre><code>(GIR(?=\\s*0AA)|(?:[BEGLMNSW]|[A-Z]{2})[0-9](?:[0-9]|(?&lt;=N1|E1|SE1|SW1|W1|NW1|EC[0-9]|WC[0-9])[A-HJ-NP-Z])?)\\s*([0-9][ABD-HJLNP-UW-Z]{2})\n</code></pre>\n\n<p>In PCRE format it can be written as follows:</p>\n\n<pre><code>/^\n ( GIR(?=\\s*0AA) # Match the special postcode \"GIR 0AA\"\n |\n (?:\n [BEGLMNSW] | # There are 8 single-letter postcode areas\n [A-Z]{2} # All other postcode areas have two letters\n )\n [0-9] # There is always at least one number after the postcode area\n (?:\n [0-9] # And an optional extra number\n |\n # Only certain postcode areas can have an extra letter after the number\n (?&lt;=N1|E1|SE1|SW1|W1|NW1|EC[0-9]|WC[0-9])\n [A-HJ-NP-Z] # Possible letters here may change, but [IO] will never be used\n )?\n )\n \\s*\n ([0-9][ABD-HJLNP-UW-Z]{2}) # The last two letters cannot be [CIKMOV]\n$/x\n</code></pre>\n\n<p>For me this is the right balance between validating as much as possible, while at the same time future-proofing and allowing for easy maintenance.</p>\n" }, { "answer_id": 25176865, "author": "Alex Stephens", "author_id": 1955203, "author_profile": "https://Stackoverflow.com/users/1955203", "pm_score": 2, "selected": false, "text": "<p>here's how we have been dealing with the UK postcode issue:</p>\n\n<pre><code>^([A-Za-z]{1,2}[0-9]{1,2}[A-Za-z]?[ ]?)([0-9]{1}[A-Za-z]{2})$\n</code></pre>\n\n<p><strong>Explanation:</strong></p>\n\n<ul>\n<li>expect 1 or 2 a-z chars, upper or lower fine</li>\n<li>expect 1 or 2 numbers</li>\n<li>expect 0 or 1 a-z char, upper or lower fine</li>\n<li>optional space allowed</li>\n<li>expect 1 number</li>\n<li>expect 2 a-z, upper or lower fine</li>\n</ul>\n\n<p>This gets most formats, we then use the db to validate whether the postcode is actually real, this data is driven by openpoint <a href=\"https://www.ordnancesurvey.co.uk/opendatadownload/products.html\" rel=\"nofollow\">https://www.ordnancesurvey.co.uk/opendatadownload/products.html</a></p>\n\n<p>hope this helps</p>\n" }, { "answer_id": 26887154, "author": "deadcrab", "author_id": 1071022, "author_profile": "https://Stackoverflow.com/users/1071022", "pm_score": 4, "selected": false, "text": "<p>An old post but still pretty high in google results so thought I'd update. This Oct 14 doc defines the UK postcode regular expression as:</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([**AZ**a-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n</code></pre>\n\n<p>from:</p>\n\n<p><a href=\"https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/359448/4__Bulk_Data_Transfer_-_additional_validation_valid.pdf\" rel=\"nofollow noreferrer\">https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/359448/4__Bulk_Data_Transfer_-_additional_validation_valid.pdf</a></p>\n\n<p>The document also explains the logic behind it. However, it has an error (bolded) and also allows lower case, which although legal is not usual, so amended version:</p>\n\n<pre><code>^(GIR 0AA)|((([A-Z][0-9]{1,2})|(([A-Z][A-HJ-Y][0-9]{1,2})|(([A-Z][0-9][A-Z])|([A-Z][A-HJ-Y][0-9]?[A-Z])))) [0-9][A-Z]{2})$\n</code></pre>\n\n<p>This works with new London postcodes (e.g. W1D 5LH) that previous versions did not.</p>\n" }, { "answer_id": 28108191, "author": "Raphos", "author_id": 4222767, "author_profile": "https://Stackoverflow.com/users/4222767", "pm_score": 2, "selected": false, "text": "<p><strong>Basic rules:</strong></p>\n\n<pre><code>^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$\n</code></pre>\n\n<p>Postal codes in the U.K. (or postcodes, as they’re called) are composed of five to seven alphanumeric characters separated by a space. The rules covering which characters can appear at particular positions are rather complicated and fraught with exceptions. The regular expression just shown therefore sticks to the basic rules.</p>\n\n<p><strong>Complete rules:</strong></p>\n\n<p>If you need a regex that ticks all the boxes for the postcode rules at the expense of readability, here you go:</p>\n\n<pre><code>^(?:(?:[A-PR-UWYZ][0-9]{1,2}|[A-PR-UWYZ][A-HK-Y][0-9]{1,2}|[A-PR-UWYZ][0-9][A-HJKSTUW]|[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]) [0-9][ABD-HJLNP-UW-Z]{2}|GIR 0AA)$\n</code></pre>\n\n<p><em>Source: <a href=\"https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s16.html\" rel=\"nofollow\">https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s16.html</a></em></p>\n\n<p>Tested against our customers database and seems perfectly accurate.</p>\n" }, { "answer_id": 29302162, "author": "Jackson Pauls", "author_id": 1777662, "author_profile": "https://Stackoverflow.com/users/1777662", "pm_score": 2, "selected": false, "text": "<p>To check a postcode is in a valid format as per the Royal Mail's <a href=\"http://www.royalmail.com/sites/default/files/docs/pdf/programmers_guide_edition_7_v5.pdf\" rel=\"nofollow\">programmer's guide</a>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> |----------------------------outward code------------------------------| |------inward code-----|\n#special↓ α1 α2 AAN AANA AANN AN ANN ANA (α3) N AA\n^(GIR 0AA|[A-PR-UWYZ]([A-HK-Y]([0-9][A-Z]?|[1-9][0-9])|[1-9]([0-9]|[A-HJKPSTUW])?) [0-9][ABD-HJLNP-UW-Z]{2})$\n</code></pre>\n\n<p>All postcodes on <a href=\"http://www.doogal.co.uk/UKPostcodes.php\" rel=\"nofollow\">doogal.co.uk</a> match, except for those no longer in use.</p>\n\n<p>Adding a <code>?</code> after the space and using case-insensitive match to answer this question:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>'se50eg'.match(/^(GIR 0AA|[A-PR-UWYZ]([A-HK-Y]([0-9][A-Z]?|[1-9][0-9])|[1-9]([0-9]|[A-HJKPSTUW])?) ?[0-9][ABD-HJLNP-UW-Z]{2})$/ig);\nArray [ \"se50eg\" ]\n</code></pre>\n" }, { "answer_id": 29363535, "author": "Stieb", "author_id": 3060634, "author_profile": "https://Stackoverflow.com/users/3060634", "pm_score": 0, "selected": false, "text": "<p>The accepted answer reflects the rules given by Royal Mail, although there is a typo in the regex. This typo seems to have been in there on the gov.uk site as well (as it is in the XML archive page).</p>\n\n<p>In the format A9A 9AA the rules allow a P character in the third position, whilst the regex disallows this. The correct regex would be:</p>\n\n<pre><code>(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKPSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2}) \n</code></pre>\n\n<p>Shortening this results in the following regex (which uses Perl/Ruby syntax):</p>\n\n<pre><code>(GIR 0AA)|([A-PR-UWYZ](([0-9]([0-9A-HJKPSTUW])?)|([A-HK-Y][0-9]([0-9ABEHMNPRVWXY])?))\\s?[0-9][ABD-HJLNP-UW-Z]{2})\n</code></pre>\n\n<p>It also includes an optional space between the first and second block. </p>\n" }, { "answer_id": 29820230, "author": "AntPachon", "author_id": 763085, "author_profile": "https://Stackoverflow.com/users/763085", "pm_score": 4, "selected": false, "text": "<p>According to this Wikipedia table</p>\n\n<p><img src=\"https://i.stack.imgur.com/XOv8u.png\" alt=\"enter image description here\"></p>\n\n<p>This pattern cover all the cases </p>\n\n<pre><code>(?:[A-Za-z]\\d ?\\d[A-Za-z]{2})|(?:[A-Za-z][A-Za-z\\d]\\d ?\\d[A-Za-z]{2})|(?:[A-Za-z]{2}\\d{2} ?\\d[A-Za-z]{2})|(?:[A-Za-z]\\d[A-Za-z] ?\\d[A-Za-z]{2})|(?:[A-Za-z]{2}\\d[A-Za-z] ?\\d[A-Za-z]{2})\n</code></pre>\n\n<p>When using it on Android\\Java use \\\\d</p>\n" }, { "answer_id": 32735959, "author": "User1", "author_id": 2987066, "author_profile": "https://Stackoverflow.com/users/2987066", "pm_score": 2, "selected": false, "text": "<p>To add to this list a more practical regex that I use that allows the user to enter an <code>empty string</code> is:</p>\n\n<pre><code>^$|^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,1}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$\n</code></pre>\n\n<p>This regex allows capital and lower case letters with an optional space in between</p>\n\n<p>From a software developers point of view this regex is useful for software where an address may be optional. For example if a user did not want to supply their address details</p>\n" }, { "answer_id": 33610889, "author": "Chisel", "author_id": 2991563, "author_profile": "https://Stackoverflow.com/users/2991563", "pm_score": 2, "selected": false, "text": "<p>I use the following regex that I have tested against all valid UK postcodes. It is based on the recommended rules, but condensed as much as reasonable and does not make use of any special language specific regex rules.</p>\n\n<pre><code>([A-PR-UWYZ]([A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y])?|[0-9]([0-9]|[A-HJKPSTUW])?) ?[0-9][ABD-HJLNP-UW-Z]{2})\n</code></pre>\n\n<p>It assumes that the postcode has been converted to uppercase and has not leading or trailing characters, but will accept an optional space between the outcode and incode.</p>\n\n<p>The special \"GIR0 0AA\" postcode is excluded and will not validate as it's not in the official Post Office list of postcodes and as far as I'm aware will not be used as registered address. Adding it should be trivial as a special case if required.</p>\n" }, { "answer_id": 34593598, "author": "Matas Vaitkevicius", "author_id": 1509764, "author_profile": "https://Stackoverflow.com/users/1509764", "pm_score": 2, "selected": false, "text": "<p>This one allows empty spaces and tabs from both sides in case you don't want to fail validation and then trim it sever side.</p>\n\n<pre><code>^\\s*(([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})\\s*$)\n</code></pre>\n" }, { "answer_id": 43793562, "author": "user667489", "author_id": 667489, "author_profile": "https://Stackoverflow.com/users/667489", "pm_score": -1, "selected": false, "text": "<p>I needed a version that would work in SAS with the <code>PRXMATCH</code> and related functions, so I came up with this:</p>\n\n<pre><code>^[A-PR-UWYZ](([A-HK-Y]?\\d\\d?)|(\\d[A-HJKPSTUW])|([A-HK-Y]\\d[ABEHMNPRV-Y]))\\s?\\d[ABD-HJLNP-UW-Z]{2}$\n</code></pre>\n\n<p>Test cases and notes:</p>\n\n<pre><code>/* \nNotes\nThe letters QVX are not used in the 1st position.\nThe letters IJZ are not used in the second position.\nThe only letters to appear in the third position are ABCDEFGHJKPSTUW when the structure starts with A9A.\nThe only letters to appear in the fourth position are ABEHMNPRVWXY when the structure starts with AA9A.\nThe final two letters do not use the letters CIKMOV, so as not to resemble digits or each other when hand-written.\n*/\n\n/*\n Bits and pieces\n 1st position (any): [A-PR-UWYZ] \n 2nd position (if letter): [A-HK-Y]\n 3rd position (A1A format): [A-HJKPSTUW]\n 4th position (AA1A format): [ABEHMNPRV-Y]\n Last 2 positions: [ABD-HJLNP-UW-Z] \n*/\n\n\ndata example;\ninfile cards truncover;\ninput valid 1. postcode &amp;$10. Notes &amp;$100.;\nflag = prxmatch('/^[A-PR-UWYZ](([A-HK-Y]?\\d\\d?)|(\\d[A-HJKPSTUW])|([A-HK-Y]\\d[ABEHMNPRV-Y]))\\s?\\d[ABD-HJLNP-UW-Z]{2}$/',strip(postcode));\ncards;\n1 EC1A 1BB Special case 1\n1 W1A 0AX Special case 2\n1 M1 1AE Standard format\n1 B33 8TH Standard format\n1 CR2 6XH Standard format\n1 DN55 1PT Standard format\n0 QN55 1PT Bad letter in 1st position\n0 DI55 1PT Bad letter in 2nd position\n0 W1Z 0AX Bad letter in 3rd position\n0 EC1Z 1BB Bad letter in 4th position\n0 DN55 1CT Bad letter in 2nd group\n0 A11A 1AA Invalid digits in 1st group\n0 AA11A 1AA 1st group too long\n0 AA11 1AAA 2nd group too long\n0 AA11 1AAA 2nd group too long\n0 AAA 1AA No digit in 1st group\n0 AA 1AA No digit in 1st group\n0 A 1AA No digit in 1st group\n0 1A 1AA Missing letter in 1st group\n0 1 1AA Missing letter in 1st group\n0 11 1AA Missing letter in 1st group\n0 AA1 1A Missing letter in 2nd group\n0 AA1 1 Missing letter in 2nd group\n;\nrun;\n</code></pre>\n" }, { "answer_id": 47313542, "author": "Andrew Schliewe", "author_id": 6211051, "author_profile": "https://Stackoverflow.com/users/6211051", "pm_score": 0, "selected": false, "text": "<p>What i have found in nearly all the variations and the regex from the bulk transfer pdf and what is on wikipedia site is this, specifically for the wikipedia regex is, there needs to be a ^ after the first |(vertical bar). I figured this out by testing for AA9A 9AA, because otherwise the format check for A9A 9AA will validate it. For Example checking for EC1D 1BB which should be invalid comes back valid because C1D 1BB is a valid format.</p>\n\n<p>Here is what I've come up with for a good regex:</p>\n\n<pre><code>^([G][I][R] 0[A]{2})|^((([A-Z-[QVX]][0-9]{1,2})|([A-Z-[QVX]][A-HK-Y][0-9]{1,2})|([A-Z-[QVX]][0-9][ABCDEFGHJKPSTUW])|([A-Z-[QVX]][A-HK-Y][0-9][ABEHMNPRVWXY])) [0-9][A-Z-[CIKMOV]]{2})$\n</code></pre>\n" }, { "answer_id": 47589824, "author": "Henrik N", "author_id": 6962, "author_profile": "https://Stackoverflow.com/users/6962", "pm_score": 3, "selected": false, "text": "<p>I wanted a simple regex, where it's fine to allow too much, but not to deny a valid postcode. I went with this (the input is a stripped/trimmed string):</p>\n\n<pre><code>/^([a-z0-9]\\s*){5,8}$/i\n</code></pre>\n\n<p>This allows the shortest possible postcodes like \"L1 8JQ\" as well as the longest ones like \"OL14 5ET\".</p>\n\n<p>Because it allows up to 8 characters, it will also allow incorrect 8 character postcodes if there is no space: \"OL145ETX\". But again, this is a simplistic regex, for when that's good enough.</p>\n" }, { "answer_id": 51885364, "author": "ctwheels", "author_id": 3600709, "author_profile": "https://Stackoverflow.com/users/3600709", "pm_score": 8, "selected": false, "text": "<p>I recently posted <a href=\"https://stackoverflow.com/a/51828886/3600709\">an answer</a> to <a href=\"https://stackoverflow.com/q/51828712/3600709\">this question on UK postcodes for the R language</a>. I discovered that <strong>the UK Government's regex pattern is incorrect</strong> and fails to <em>properly</em> validate some postcodes. Unfortunately, many of the answers here are based on this incorrect pattern.</p>\n\n<p>I'll outline some of these issues below and provide a revised regular expression that <em>actually</em> works.</p>\n\n<hr>\n\n<h1>Note</h1>\n\n<p><strong>My answer</strong> (and regular expressions in general):</p>\n\n<ul>\n<li><strong>Only validates postcode <em>formats</em></strong>.</li>\n<li><strong>Does not ensure that a postcode <em>legitimately exists</em></strong>.\n\n<ul>\n<li>For this, use an appropriate API! See <a href=\"https://stackoverflow.com/a/17024047/3600709\">Ben's answer</a> for more info.</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p><sub>If you don't care about the <em>bad regex</em> and just want to skip to the answer, scroll down to the <strong>Answer</strong> section.</sub></p>\n\n<h1>The Bad Regex</h1>\n\n<p><strong>The regular expressions in this section should not be used.</strong></p>\n\n<p>This is the failing regex that the UK government has provided developers (not sure how long this link will be up, but you can see it in their <a href=\"https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/488478/Bulk_Data_Transfer_-_additional_validation_valid_from_12_November_2015.pdf\" rel=\"noreferrer\">Bulk Data Transfer documentation</a>):</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$\n</code></pre>\n\n<h2>Problems</h2>\n\n<h3>Problem 1 - Copy/Paste</h3>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/1\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<p>As many developers likely do, they copy/paste code (especially regular expressions) and paste them expecting them to work. While this is great in theory, it fails in this particular case because copy/pasting from this document actually changes one of the characters (a space) into a newline character as shown below:</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\n[0-9][A-Za-z]{2})$\n</code></pre>\n\n<p>The first thing most developers will do is just erase the newline without thinking twice. Now the regex won't match postcodes with spaces in them (other than the <code>GIR 0AA</code> postcode).</p>\n\n<p>To fix this issue, the newline character should be replaced with the space character:</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n ^\n</code></pre>\n\n<h3>Problem 2 - Boundaries</h3>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/2\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n^^ ^ ^ ^^\n</code></pre>\n\n<p>The postcode regex improperly anchors the regex. Anyone using this regex to validate postcodes might be surprised if a value like <code>fooA11 1AA</code> gets through. That's because they've anchored the start of the first option and the end of the second option (independently of one another), as pointed out in the regex above.</p>\n\n<p>What this means is that <code>^</code> (asserts position at start of the line) only works on the first option <code>([Gg][Ii][Rr] 0[Aa]{2})</code>, so the second option will validate any strings that <strong>end</strong> in a postcode (regardless of what comes before).</p>\n\n<p>Similarly, the first option isn't anchored to the end of the line <code>$</code>, so <code>GIR 0AAfoo</code> is also accepted.</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$\n</code></pre>\n\n<p>To fix this issue, both options should be wrapped in another group (or non-capturing group) and the anchors placed around that: </p>\n\n<pre><code>^(([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2}))$\n^^ ^^\n</code></pre>\n\n<h3>Problem 3 - Improper Character Set</h3>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/3\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n ^^\n</code></pre>\n\n<p>The regex is missing a <code>-</code> here to indicate a range of characters. As it stands, if a postcode is in the format <code>ANA NAA</code> (where <code>A</code> represents a letter and <code>N</code> represents a number), and it begins with anything other than <code>A</code> or <code>Z</code>, it will fail.</p>\n\n<p>That means it will match <code>A1A 1AA</code> and <code>Z1A 1AA</code>, but not <code>B1A 1AA</code>.</p>\n\n<p>To fix this issue, the character <code>-</code> should be placed between the <code>A</code> and <code>Z</code> in the respective character set:</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n ^\n</code></pre>\n\n<h3>Problem 4 - Wrong Optional Character Set</h3>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/4\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$\n ^\n</code></pre>\n\n<p>I swear they didn't even test this thing before publicizing it on the web. They made the wrong character set optional. They made <code>[0-9]</code> option in the fourth sub-option of option 2 (group 9). This allows the regex to match incorrectly formatted postcodes like <code>AAA 1AA</code>.</p>\n\n<p>To fix this issue, make the next character class optional instead (and subsequently make the set <code>[0-9]</code> match exactly once):</p>\n\n<pre><code>^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?)))) [0-9][A-Za-z]{2})$\n ^\n</code></pre>\n\n<h3>Problem 5 - Performance</h3>\n\n<p>Performance on this regex is extremely poor. First off, they placed the least likely pattern option to match <code>GIR 0AA</code> at the beginning. How many users will likely have this postcode versus any other postcode; probably never? This means every time the regex is used, it must exhaust this option first before proceeding to the next option. To see how performance is impacted check the number of steps the <a href=\"https://regex101.com/r/ajQHrd/5\" rel=\"noreferrer\">original regex</a> took (35) against the <a href=\"https://regex101.com/r/ajQHrd/6\" rel=\"noreferrer\">same regex after having flipped the options</a> (22).</p>\n\n<p>The second issue with performance is due to the way the entire regex is structured. There's no point backtracking over each option if one fails. The way the current regex is structured can greatly be simplified. I provide a fix for this in the <strong>Answer</strong> section.</p>\n\n<h3>Problem 6 - Spaces</h3>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/8\" rel=\"noreferrer\">See regex in use here</a></p>\n\n<p>This may not be considered a <em>problem</em>, per se, but it does raise concern for most developers. The spaces in the regex are not optional, which means the users inputting their postcodes must place a space in the postcode. This is an easy fix by simply adding <code>?</code> after the spaces to render them optional. See the <strong>Answer</strong> section for a fix.</p>\n\n<hr>\n\n<h1>Answer</h1>\n\n<h2>1. Fixing the UK Government's Regex</h2>\n\n<p>Fixing all the issues outlined in the <strong>Problems</strong> section and simplifying the pattern yields the following, shorter, more concise pattern. We can also remove most of the groups since we're validating the postcode as a whole (not individual parts):</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/12\" rel=\"noreferrer\">See regex in use here</a></p>\n\n<pre><code>^([A-Za-z][A-Ha-hJ-Yj-y]?[0-9][A-Za-z0-9]? ?[0-9][A-Za-z]{2}|[Gg][Ii][Rr] ?0[Aa]{2})$\n</code></pre>\n\n<p>This can further be shortened by removing all of the ranges from one of the cases (upper or lower case) and using a case-insensitive flag. <strong>Note</strong>: Some languages don't have one, so use the longer one above. Each language implements the case-insensitivity flag differently.</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/13\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([A-Z][A-HJ-Y]?[0-9][A-Z0-9]? ?[0-9][A-Z]{2}|GIR ?0A{2})$\n</code></pre>\n\n<p>Shorter again replacing <code>[0-9]</code> with <code>\\d</code> (if your regex engine supports it):</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/14\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([A-Z][A-HJ-Y]?\\d[A-Z\\d]? ?\\d[A-Z]{2}|GIR ?0A{2})$\n</code></pre>\n\n<h2>2. Simplified Patterns</h2>\n\n<p>Without ensuring specific alphabetic characters, the following can be used (keep in mind the simplifications from <strong>1. Fixing the UK Government's Regex</strong> have also been applied here):</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/15\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^([A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}|GIR ?0A{2})$\n</code></pre>\n\n<p>And even further if you don't care about the special case <code>GIR 0AA</code>:</p>\n\n<pre><code>^[A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}$\n</code></pre>\n\n<h2>3. Complicated Patterns</h2>\n\n<p>I would not suggest over-verification of a postcode as new Areas, Districts and Sub-districts may appear at any point in time. What I will suggest <em>potentially</em> doing, is added support for edge-cases. Some special cases exist and are outlined in <a href=\"https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Special_cases\" rel=\"noreferrer\">this Wikipedia article</a>.</p>\n\n<p>Here are complex regexes that include the subsections of <strong>3.</strong> (3.1, 3.2, 3.3).</p>\n\n<p>In relation to the patterns in <strong>1. Fixing the UK Government's Regex</strong>:</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/19\" rel=\"noreferrer\">See regex in use here</a></p>\n\n<pre><code>^(([A-Z][A-HJ-Y]?\\d[A-Z\\d]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?\\d[A-Z]{2}|BFPO ?\\d{1,4}|(KY\\d|MSR|VG|AI)[ -]?\\d{4}|[A-Z]{2} ?\\d{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$\n</code></pre>\n\n<p>And in relation to <strong>2. Simplified Patterns</strong>:</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/20\" rel=\"noreferrer\">See regex in use here</a></p>\n\n<pre><code>^(([A-Z]{1,2}\\d[A-Z\\d]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?\\d[A-Z]{2}|BFPO ?\\d{1,4}|(KY\\d|MSR|VG|AI)[ -]?\\d{4}|[A-Z]{2} ?\\d{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$\n</code></pre>\n\n<h3>3.1 British Overseas Territories</h3>\n\n<p>The Wikipedia article currently states (some formats slightly simplified):</p>\n\n<ul>\n<li><code>AI-1111</code>: Anguila</li>\n<li><code>ASCN 1ZZ</code>: Ascension Island</li>\n<li><code>STHL 1ZZ</code>: Saint Helena</li>\n<li><code>TDCU 1ZZ</code>: Tristan da Cunha</li>\n<li><code>BBND 1ZZ</code>: British Indian Ocean Territory</li>\n<li><code>BIQQ 1ZZ</code>: British Antarctic Territory</li>\n<li><code>FIQQ 1ZZ</code>: Falkland Islands</li>\n<li><code>GX11 1ZZ</code>: Gibraltar</li>\n<li><code>PCRN 1ZZ</code>: Pitcairn Islands</li>\n<li><code>SIQQ 1ZZ</code>: South Georgia and the South Sandwich Islands</li>\n<li><code>TKCA 1ZZ</code>: Turks and Caicos Islands</li>\n<li><code>BFPO 11</code>: Akrotiri and Dhekelia</li>\n<li><code>ZZ 11</code> &amp; <code>GE CX</code>: Bermuda (according to <a href=\"http://www.bpo.bm/Lists/Postal%20Codes/Attachments/1/Bermuda%20Postal%20Codes%20and%20Parishes%202013.pdf\" rel=\"noreferrer\">this document</a>)</li>\n<li><code>KY1-1111</code>: Cayman Islands (according to <a href=\"http://www.caymanpost.gov.ky/portal/page/portal/poshome/posnpimages/POSTCODE%20FINDER%20COLOUR.pdf\" rel=\"noreferrer\">this document</a>)</li>\n<li><code>VG1111</code>: British Virgin Islands (according to <a href=\"http://www.bvi.gov.vg/content/what-are-postcodes-addresses-british-virgin-islands\" rel=\"noreferrer\">this document</a>)</li>\n<li><code>MSR 1111</code>: Montserrat (according to <a href=\"http://www.gov.ms/wp-content/uploads/2014/02/Postal-Code-Guide-pamphlet.pdf\" rel=\"noreferrer\">this document</a>)</li>\n</ul>\n\n<p>An all-encompassing regex to match only the British Overseas Territories might look like this:</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/15\" rel=\"noreferrer\">See regex in use here</a>.</p>\n\n<pre><code>^((ASCN|STHL|TDCU|BBND|[BFS]IQQ|GX\\d{2}|PCRN|TKCA) ?\\d[A-Z]{2}|(KY\\d|MSR|VG|AI)[ -]?\\d{4}|(BFPO|[A-Z]{2}) ?\\d{2}|GE ?CX)$\n</code></pre>\n\n<h3>3.2 British Forces Post Office</h3>\n\n<p>Although they've been recently changed it to better align with the British postcode system to <code>BF#</code> (where <code>#</code> represents a number), they're considered <em>optional alternative postcodes</em>. These postcodes follow(ed) the format of <code>BFPO</code>, followed by 1-4 digits:</p>\n\n<p><a href=\"https://regex101.com/r/ajQHrd/17\" rel=\"noreferrer\">See regex in use here</a></p>\n\n<pre><code>^BFPO ?\\d{1,4}$\n</code></pre>\n\n<h3>3.3 Santa?</h3>\n\n<p>There's another special case with Santa (as mentioned in other answers): <code>SAN TA1</code> is a valid postcode. A regex for this is very simply:</p>\n\n<pre><code>^SAN ?TA1$\n</code></pre>\n" }, { "answer_id": 55083027, "author": "Aathi", "author_id": 3008370, "author_profile": "https://Stackoverflow.com/users/3008370", "pm_score": 0, "selected": false, "text": "<p>Below method will check the post code and provide complete info</p>\n<pre class=\"lang-js prettyprint-override\"><code>const isValidUKPostcode = postcode =&gt; {\n try {\n postcode = postcode.replace(/\\s/g, &quot;&quot;);\n const fromat = postcode\n .toUpperCase()\n .match(/^([A-Z]{1,2}\\d{1,2}[A-Z]?)\\s*(\\d[A-Z]{2})$/);\n const finalValue = `${fromat[1]} ${fromat[2]}`;\n const regex = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$/i;\n return {\n isValid: regex.test(postcode),\n formatedPostCode: finalValue,\n error: false,\n message: 'It is a valid postcode'\n };\n } catch (error) {\n return { error: true , message: 'Invalid postcode'};\n }\n};\n</code></pre>\n<pre class=\"lang-js prettyprint-override\"><code>console.log(isValidUKPostcode('GU348RR'))\n{isValid: true, formattedPostcode: &quot;GU34 8RR&quot;, error: false, message: &quot;It is a valid postcode&quot;}\n</code></pre>\n<pre class=\"lang-js prettyprint-override\"><code>console.log(isValidUKPostcode('sdasd4746asd'))\n{error: true, message: &quot;Invalid postcode!&quot;}\n</code></pre>\n<pre class=\"lang-js prettyprint-override\"><code>valid_postcode('787898523')\nresult =&gt; {error: true, message: &quot;Invalid postcode&quot;}\n</code></pre>\n" }, { "answer_id": 56134559, "author": "Ghoti", "author_id": 80662, "author_profile": "https://Stackoverflow.com/users/80662", "pm_score": -1, "selected": false, "text": "<p>I stole this from an XML document and it seems to cover all cases without the hard coded GIRO:</p>\n\n<pre><code>%r{[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}}i\n</code></pre>\n\n<p>(Ruby syntax with ignore case)</p>\n" }, { "answer_id": 61430132, "author": "jontsai", "author_id": 865091, "author_profile": "https://Stackoverflow.com/users/865091", "pm_score": 2, "selected": false, "text": "<p>Through empirical testing and observation, as well as confirming with <a href=\"https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation</a>, here is my version of a Python regex that correctly parses and validates a UK postcode:</p>\n\n<p><code>UK_POSTCODE_REGEX = r'(?P&lt;postcode_area&gt;[A-Z]{1,2})(?P&lt;district&gt;(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P&lt;sector&gt;[0-9])(?P&lt;postcode&gt;[A-Z]{2})'</code></p>\n\n<p>This regex is simple and has capture groups. It <strong>does not</strong> include all of the validations of <em>legal</em> UK postcodes, but only takes into account the letter vs number positions.</p>\n\n<p>Here is how I would use it in code:</p>\n\n<pre><code>@dataclass\nclass UKPostcode:\n postcode_area: str\n district: str\n sector: int\n postcode: str\n\n # https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation\n # Original author of this regex: @jontsai\n # NOTE TO FUTURE DEVELOPER:\n # Verified through empirical testing and observation, as well as confirming with the Wiki article\n # If this regex fails to capture all valid UK postcodes, then I apologize, for I am only human.\n UK_POSTCODE_REGEX = r'(?P&lt;postcode_area&gt;[A-Z]{1,2})(?P&lt;district&gt;(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P&lt;sector&gt;[0-9])(?P&lt;postcode&gt;[A-Z]{2})'\n\n @classmethod\n def from_postcode(cls, postcode):\n \"\"\"Parses a string into a UKPostcode\n\n Returns a UKPostcode or None\n \"\"\"\n m = re.match(cls.UK_POSTCODE_REGEX, postcode.replace(' ', ''))\n\n if m:\n uk_postcode = UKPostcode(\n postcode_area=m.group('postcode_area'),\n district=m.group('district'),\n sector=m.group('sector'),\n postcode=m.group('postcode')\n )\n else:\n uk_postcode = None\n\n return uk_postcode\n\n\ndef parse_uk_postcode(postcode):\n \"\"\"Wrapper for UKPostcode.from_postcode\n \"\"\"\n uk_postcode = UKPostcode.from_postcode(postcode)\n return uk_postcode\n</code></pre>\n\n<p>Here are unit tests:</p>\n\n<pre><code>@pytest.mark.parametrize(\n 'postcode, expected', [\n # https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation\n (\n 'EC1A1BB',\n UKPostcode(\n postcode_area='EC',\n district='1A',\n sector='1',\n postcode='BB'\n ),\n ),\n (\n 'W1A0AX',\n UKPostcode(\n postcode_area='W',\n district='1A',\n sector='0',\n postcode='AX'\n ),\n ),\n (\n 'M11AE',\n UKPostcode(\n postcode_area='M',\n district='1',\n sector='1',\n postcode='AE'\n ),\n ),\n (\n 'B338TH',\n UKPostcode(\n postcode_area='B',\n district='33',\n sector='8',\n postcode='TH'\n )\n ),\n (\n 'CR26XH',\n UKPostcode(\n postcode_area='CR',\n district='2',\n sector='6',\n postcode='XH'\n )\n ),\n (\n 'DN551PT',\n UKPostcode(\n postcode_area='DN',\n district='55',\n sector='1',\n postcode='PT'\n )\n )\n ]\n)\ndef test_parse_uk_postcode(postcode, expected):\n uk_postcode = parse_uk_postcode(postcode)\n assert(uk_postcode == expected)\n</code></pre>\n" }, { "answer_id": 69269028, "author": "Ella Bella", "author_id": 14713613, "author_profile": "https://Stackoverflow.com/users/14713613", "pm_score": -1, "selected": false, "text": "<p>I did the regex for UK postcode validation today, as far as I know, it works for all UK postcodes, it works if you put a space or if you don't.</p>\n<pre><code>^((([a-zA-Z][0-9])|([a-zA-Z][0-9]{2})|([a-zA-Z]{2}[0-9])|([a-zA-Z]{2}[0-9]{2})|([A-Za-z][0-9][a-zA-Z])|([a-zA-Z]{2}[0-9][a-zA-Z]))(\\s*[0-9][a-zA-Z]{2})$)\n</code></pre>\n<p>Let me know if there's a format it doesn't cover</p>\n" }, { "answer_id": 69806181, "author": "Mecanik", "author_id": 6583298, "author_profile": "https://Stackoverflow.com/users/6583298", "pm_score": 3, "selected": false, "text": "<p>Whilst there are many answers here, I'm not happy with either of them. Most of them are simply broken, are too complex or just broken.</p>\n<p>I looked at <a href=\"https://stackoverflow.com/questions/164979/regex-for-matching-uk-postcodes#51885364\">@ctwheels</a> answer and I found it very explanatory and correct; we must thank him for that. However once again too much &quot;data&quot; for me, for something so simple.</p>\n<p>Fortunately, I managed to get a database with over 1 million active postcodes for England only and made a small PowerShell script to test and benchmark the results.</p>\n<p>UK Postcode specifications: <a href=\"https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/611951/Appendix_C_ILR_2017_to_2018_v1_Published_28April17.pdf\" rel=\"noreferrer\">Valid Postcode Format</a>.</p>\n<p><strong>This is &quot;my&quot; Regex:</strong></p>\n<pre><code>^([a-zA-Z]{1,2}[a-zA-Z\\d]{1,2})\\s(\\d[a-zA-Z]{2})$\n</code></pre>\n<p>Short, simple and sweet. Even the most unexperienced can understand what is going on.</p>\n<p><strong>Explanation:</strong></p>\n<pre><code>^ asserts position at start of a line\n 1st Capturing Group ([a-zA-Z]{1,2}[a-zA-Z\\d]{1,2})\n Match a single character present in the list below [a-zA-Z]\n {1,2} matches the previous token between 1 and 2 times, as many times as possible, giving back as needed (greedy)\n a-z matches a single character in the range between a (index 97) and z (index 122) (case sensitive)\n A-Z matches a single character in the range between A (index 65) and Z (index 90) (case sensitive)\n Match a single character present in the list below [a-zA-Z\\d]\n {1,2} matches the previous token between 1 and 2 times, as many times as possible, giving back as needed (greedy)\n a-z matches a single character in the range between a (index 97) and z (index 122) (case sensitive)\n A-Z matches a single character in the range between A (index 65) and Z (index 90) (case sensitive)\n \\d matches a digit (equivalent to [0-9])\n \\s matches any whitespace character (equivalent to [\\r\\n\\t\\f\\v ])\n 2nd Capturing Group (\\d[a-zA-Z]{2})\n \\d matches a digit (equivalent to [0-9])\n Match a single character present in the list below [a-zA-Z]\n {2} matches the previous token exactly 2 times\n a-z matches a single character in the range between a (index 97) and z (index 122) (case sensitive)\n A-Z matches a single character in the range between A (index 65) and Z (index 90) (case sensitive)\n$ asserts position at the end of a line\n</code></pre>\n<p><strong>Result (postcodes checked):</strong></p>\n<pre><code>TOTAL OK: 1469193\nTOTAL FAILED: 0\n-------------------------------------------------------------------------\nDays : 0\nHours : 0\nMinutes : 5\nSeconds : 22\nMilliseconds : 718\nTicks : 3227185939\nTotalDays : 0.00373516891087963\nTotalHours : 0.0896440538611111\nTotalMinutes : 5.37864323166667\nTotalSeconds : 322.7185939\nTotalMilliseconds : 322718.5939\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1894/" ]
This is a continuation question from a previous question [I have asked](https://stackoverflow.com/questions/142237/integrating-external-sources-in-a-build.) I now have a /externals directory in the root of my project tree. Inside this I have a reference to another project. I'm able to script the build of all my externals in the main project NAnt script. The result of these builds are as follows: /externals/external-project1/build/buildartifacts/{dlls|html|js} /externals/external-project2/build/buildartifacts/{dlls|html|js} This is all well and good, but now I'm curious as to how my main project should reference these build artifacts. For example, let's say that external project builds a DLL that some of my codebase depends on. Should I simply reference the DLL in the build artifacts directory or should I implement another NAnt task that copies these to a /thirdparty/libs/ folder? This means that my build is now dependent on the ability to build this external project (which could either be internal, or thirdparty). Is it a good idea to check in the latest set of build artifacts to ensure that the main build won't break because of dependent builds breaking? Hope that's clear enough. Just writing this down has a least clarified the problem for me :-). --Edit-- Thanks guys. I think I'm going to implement the "checkout a revision", but since the builds are so quick I'm not going to check in any build artifiacts. Also going to have to figure out how to deal with the dependencies of the external project (eg: prototype, swfobject, etc).
I'd recommend taking a look at the UK Government Data Standard for postcodes [link now dead; [archive of XML](http://webarchive.nationalarchives.gov.uk/+/http://www.cabinetoffice.gov.uk/media/291370/bs7666-v2-0-xsd-PostCodeType.htm), see [Wikipedia](http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation) for discussion]. There is a brief description about the data and the attached xml schema provides a regular expression. It may not be exactly what you want but would be a good starting point. The RegEx differs from the XML slightly, as a P character in third position in format A9A 9AA is allowed by the definition given. The RegEx supplied by the UK Government was: ``` ([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2}) ``` As pointed out on the Wikipedia discussion, this will allow some non-real postcodes (e.g. those starting AA, ZY) and they do provide a more rigorous test that you could try.
164,996
<p>Using C# in Visual Studio 2008 and stepping through a function in the debugger I get to the end of a function and am on the final curly brace } and about to return. Is there a way to find out what value the function is about to return?</p> <p>This is necessary if the return value is calculated such as:</p> <pre><code>return (x.Func() &gt; y.Func()); </code></pre>
[ { "answer_id": 165004, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 2, "selected": false, "text": "<p>You can put </p>\n\n<pre><code>(x.Func() &gt; y.Func())\n</code></pre>\n\n<p>in a watch window to evaluate it, and see the result. Unless the statement is</p>\n\n<pre><code>return ValueChangesAfterEveryCall();\n</code></pre>\n\n<p>you should be fine. </p>\n" }, { "answer_id": 165006, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 3, "selected": true, "text": "<p>It's a little low level, but if you switch to disassembly then you can single step through the instructions and see what the return value is being set to. It is typically set in the @eax register.</p>\n\n<p>You can place a breakpoint on the ret instructions and inspect the register at that point if you don't want to single step through it.</p>\n" }, { "answer_id": 165027, "author": "Jim Buck", "author_id": 2666, "author_profile": "https://Stackoverflow.com/users/2666", "pm_score": 2, "selected": false, "text": "<p>I am still using VS 2003 with C++, so this may or may not apply. If you use the \"auto\" tab (near the \"locals\" and \"watch\" tabs), it will tell you the return value of a function once you return.</p>\n" }, { "answer_id": 165226, "author": "Gabriel Isenberg", "author_id": 1473493, "author_profile": "https://Stackoverflow.com/users/1473493", "pm_score": 1, "selected": false, "text": "<p>I'd actually recommend refactoring the code to put the individual function returns in local variables. That way, yourself and others don't have to jump through hoops when debugging the code to figure out a particular evaluation. Generally, this produces code that is easier to debug and, consequently, easier for others to understand and maintain.</p>\n\n<pre><code>int sumOfSomething = x.Func();\nint pendingSomethings = y.Func();\nreturn (sumOfSomething &gt; pendingSomethings);\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
Using C# in Visual Studio 2008 and stepping through a function in the debugger I get to the end of a function and am on the final curly brace } and about to return. Is there a way to find out what value the function is about to return? This is necessary if the return value is calculated such as: ``` return (x.Func() > y.Func()); ```
It's a little low level, but if you switch to disassembly then you can single step through the instructions and see what the return value is being set to. It is typically set in the @eax register. You can place a breakpoint on the ret instructions and inspect the register at that point if you don't want to single step through it.
165,025
<p>In ASP.NET, I am exporting some data to Excel by simply binding a DataSet to a GridView and then setting the ContentType to Excel.</p> <p>My ASPX page is very simple and looks like this:</p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExamExportReport.aspx.cs" Inherits="Cabi.CamCentral.Web.Pages.Utility.ExamExportReport" %&gt; &lt;html&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;asp:GridView ID="gridExam" AutoGenerateColumns="true" runat="server"&gt; &lt;/asp:GridView&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>In the Page_Load method of the code behind, I am doing this:</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { BindGrid(); Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("content-disposition", "attachment; filename=ExamExport.xls"); } </code></pre> <p>Generally, everything works fine, and the Excel file pops up with the right data. The problem is that the Excel file always ends up with a blank first row right above the column headers. I just can't figure out what is causing this. Maybe it's something about the form tag? Maybe I need to add some styling or something to strip out padding or margins? I've tried a bunch of things but I just can't get rid of that dang first blank row. Has anyone else run into this? Any solutions?</p>
[ { "answer_id": 165084, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 2, "selected": false, "text": "<p>Here is my code that works fine: </p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n {\n if (!Page.IsPostBack)\n {\n BindData();\n }\n }\n\n private void BindData()\n {\n string connectionString = \"Server=localhost;Database=Northwind;Trusted_Connection=true\";\n SqlConnection myConnection = new SqlConnection(connectionString);\n SqlDataAdapter ad = new SqlDataAdapter(\"select * from products\", myConnection);\n DataSet ds = new DataSet();\n ad.Fill(ds);\n\n gvProducts.DataSource = ds;\n gvProducts.DataBind(); \n }\n\n protected void ExportGridView(object sender, EventArgs e)\n {\n Response.ClearContent();\n\n Response.AddHeader(\"content-disposition\", \"attachment; filename=MyExcelFile.xls\");\n\n Response.ContentType = \"application/excel\";\n\n StringWriter sw = new StringWriter();\n\n HtmlTextWriter htw = new HtmlTextWriter(sw);\n\n gvProducts.RenderControl(htw);\n\n Response.Write(sw.ToString());\n\n Response.End();\n }\n\n public override void VerifyRenderingInServerForm(Control control)\n {\n\n }\n</code></pre>\n" }, { "answer_id": 165118, "author": "jeremcc", "author_id": 1436, "author_profile": "https://Stackoverflow.com/users/1436", "pm_score": 3, "selected": true, "text": "<p>@azamsharp - I found the solution elsewhere while you were replying. :-) It turns out that removing the form tag entirely from the ASPX page is the trick, and the only way to do this is to override the VerifyRenderingInServerForm method as you are doing.</p>\n\n<p>If you update your solution to include the fact that you need to remove the form tag from the page, I will accept your answer. Thanks.</p>\n" }, { "answer_id": 841599, "author": "Erik K.", "author_id": 103800, "author_profile": "https://Stackoverflow.com/users/103800", "pm_score": 1, "selected": false, "text": "<p>An easier solution is to override the Render (HtmlTextWriter writer) method and make it empty:</p>\n\n<p>protected override void Render(HtmlTextWriter writer){}</p>\n\n<p><a href=\"http://c-sharpe.blogspot.com/2009/05/get-rid-of-blank-row-when-exporting-to.html\" rel=\"nofollow noreferrer\">http://c-sharpe.blogspot.com/2009/05/get-rid-of-blank-row-when-exporting-to.html</a></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/165025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1436/" ]
In ASP.NET, I am exporting some data to Excel by simply binding a DataSet to a GridView and then setting the ContentType to Excel. My ASPX page is very simple and looks like this: ``` <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExamExportReport.aspx.cs" Inherits="Cabi.CamCentral.Web.Pages.Utility.ExamExportReport" %> <html> <body> <form id="form1" runat="server"> <asp:GridView ID="gridExam" AutoGenerateColumns="true" runat="server"> </asp:GridView> </form> </body> </html> ``` In the Page\_Load method of the code behind, I am doing this: ``` protected void Page_Load(object sender, EventArgs e) { BindGrid(); Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("content-disposition", "attachment; filename=ExamExport.xls"); } ``` Generally, everything works fine, and the Excel file pops up with the right data. The problem is that the Excel file always ends up with a blank first row right above the column headers. I just can't figure out what is causing this. Maybe it's something about the form tag? Maybe I need to add some styling or something to strip out padding or margins? I've tried a bunch of things but I just can't get rid of that dang first blank row. Has anyone else run into this? Any solutions?
@azamsharp - I found the solution elsewhere while you were replying. :-) It turns out that removing the form tag entirely from the ASPX page is the trick, and the only way to do this is to override the VerifyRenderingInServerForm method as you are doing. If you update your solution to include the fact that you need to remove the form tag from the page, I will accept your answer. Thanks.
165,043
<p>This is an excerpt of code from a class I am working with in Java (below). Obviously the code is defining a static variable named EPSILON with the data type double. What I don't understand is the "1E-14" part. What kind of number is that? What does it mean?</p> <p>final double EPSILON = 1E-14;</p>
[ { "answer_id": 165051, "author": "Owen", "author_id": 11442, "author_profile": "https://Stackoverflow.com/users/11442", "pm_score": 3, "selected": false, "text": "<p>1E3 => 1000</p>\n\n<p>1E-1 => 0.1</p>\n\n<p>1E-2 => 0.01</p>\n\n<p>It's a way for writing 1 * 10<sup>-14</sup></p>\n" }, { "answer_id": 165054, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 3, "selected": false, "text": "<p>The \"E\" notation is scientific notation. You'll see it on calculators too. It means \"one times (ten to the power of -14)\".</p>\n\n<p>For another example, 2E+6 == 2,000,000.</p>\n" }, { "answer_id": 165056, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 2, "selected": false, "text": "<p>1E-14 is 1 times 10 to the power of -14</p>\n" }, { "answer_id": 165057, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "<p>In your case, this is equivalent to writing:</p>\n\n<pre><code>final double EPSILON = 0.00000000000001;\n</code></pre>\n\n<p>except you don't have to count the zeros. This is called <a href=\"http://en.wikipedia.org/wiki/Scientific_notation\" rel=\"noreferrer\">scientific notation</a> and is helpful when writing very large or very small numbers.</p>\n" }, { "answer_id": 165060, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 2, "selected": false, "text": "<p>That's <a href=\"http://en.wikipedia.org/wiki/Exponential_notation#E_notation\" rel=\"nofollow noreferrer\">Exponential notation</a></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/165043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This is an excerpt of code from a class I am working with in Java (below). Obviously the code is defining a static variable named EPSILON with the data type double. What I don't understand is the "1E-14" part. What kind of number is that? What does it mean? final double EPSILON = 1E-14;
In your case, this is equivalent to writing: ``` final double EPSILON = 0.00000000000001; ``` except you don't have to count the zeros. This is called [scientific notation](http://en.wikipedia.org/wiki/Scientific_notation) and is helpful when writing very large or very small numbers.
165,075
<p>I'd like to map a reference to an object instead of the object value with an HashTable</p> <pre><code>configMapping.Add("HEADERS_PATH", Me.headers_path) </code></pre> <p>that way when I'm going to retrieve the value of "HEADERS_PATH" I'll be able to assign a value to Me.headers_path</p> <p>something like the " &amp; " operator in C</p>
[ { "answer_id": 165088, "author": "Enrico Murru", "author_id": 68336, "author_profile": "https://Stackoverflow.com/users/68336", "pm_score": 1, "selected": false, "text": "<p>make headers_path be a propriety (with set)</p>\n" }, { "answer_id": 165091, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": true, "text": "<p>I am assuming that <em>Me.headers_path</em> is a System.String. Because <strong>System.String</strong> are immutable what you want cannot be achieved. But you can add an extra level of indirection to achieve a similar behavior.</p>\n\n<blockquote>\n <p>All problems in computer science can\n be solved by another level of\n indirection.\n <em>Butler Lampson</em></p>\n</blockquote>\n\n<p>Sample in C# (Please be kind to edit to VB and remove this comment later):</p>\n\n<pre><code>public class Holder&lt;T&gt; {\n public T Value { get; set; }\n}\n\n...\n\nHolder&lt;String&gt; headerPath = new Holder&lt;String&gt;() { Value = \"this is a test\" };\nconfigMapping.Add(\"HEADERS_PATH\", headerPath);\n\n...\n\n((Holder&lt;String&gt;)configMapping[\"HEADERS_PATH\"]).Value = \"this is a new test\";\n\n// headerPath.Value == \"this is a new test\"\n</code></pre>\n" }, { "answer_id": 165104, "author": "marcj", "author_id": 23940, "author_profile": "https://Stackoverflow.com/users/23940", "pm_score": 1, "selected": false, "text": "<p>This would appear to be a dictionary, which in .Net 2.0 you could define as Dictionary if the references you want to update are always strings, or Dictionary (not recommended) if you want to get an arbitrary reference. </p>\n\n<p>If you need to replace the values in the dictionary you could define your own class and provide some helper methods to make this easier.</p>\n" }, { "answer_id": 287996, "author": "pipTheGeek", "author_id": 28552, "author_profile": "https://Stackoverflow.com/users/28552", "pm_score": 1, "selected": false, "text": "<p>I am not entirely sure what you want to do. Assuming that smink is correct then here is the VB translation of his code. Sorry I can't edit it, I don't think I have enough rep yet.</p>\n\n<pre><code>public class Holder(Of T)\n public Value as T \nend class\n...\nDim headerPath as new Holder(Of String)\nheaderPath.Value = \"this is a test\"\nconfigMapping.Add(\"HEADERS_PATH\", headerPath)\n...\nDirectcast(configMapping[\"HEADERS_PATH\"]),Holder(Of String)).Value = \"this is a new test\"\n\n'headerPath.Value now equals \"this is a new test\"\n</code></pre>\n\n<p>@marcj - you need to escape the angled brackets in your answer, so use &amp;lt; for a &lt; and &amp;gt; for a &gt;. Again sorry I couldn't just edit your post for you.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/165075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6367/" ]
I'd like to map a reference to an object instead of the object value with an HashTable ``` configMapping.Add("HEADERS_PATH", Me.headers_path) ``` that way when I'm going to retrieve the value of "HEADERS\_PATH" I'll be able to assign a value to Me.headers\_path something like the " & " operator in C
I am assuming that *Me.headers\_path* is a System.String. Because **System.String** are immutable what you want cannot be achieved. But you can add an extra level of indirection to achieve a similar behavior. > > All problems in computer science can > be solved by another level of > indirection. > *Butler Lampson* > > > Sample in C# (Please be kind to edit to VB and remove this comment later): ``` public class Holder<T> { public T Value { get; set; } } ... Holder<String> headerPath = new Holder<String>() { Value = "this is a test" }; configMapping.Add("HEADERS_PATH", headerPath); ... ((Holder<String>)configMapping["HEADERS_PATH"]).Value = "this is a new test"; // headerPath.Value == "this is a new test" ```
165,082
<p>I'm hand-maintaining an HTML document, and I'm looking for a way to automatically insert a link around text in a table. Let me illustrate:</p> <pre><code>&lt;table&gt;&lt;tr&gt;&lt;td class="case"&gt;123456&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; </code></pre> <p>I would like to automatically make every text in a TD with class "case" a link to that case in our bug tracking system (which, incidentally, is FogBugz).</p> <p>So I'd like that "123456" to be changed to a link of this form:</p> <pre><code>&lt;a href="http://bugs.example.com/fogbugz/default.php?123456"&gt;123456&lt;/a&gt; </code></pre> <p>Is that possible? I've played with the :before and :after pseudo-elements, but there doesn't seem to be a way to repeat the case number.</p>
[ { "answer_id": 165100, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 5, "selected": true, "text": "<p>Not in a manner that will work across browsers. You could, however, do that with some relatively trivial Javascript..</p>\n\n<pre><code>function makeCasesClickable(){\n var cells = document.getElementsByTagName('td')\n for (var i = 0, cell; cell = cells[i]; i++){\n if (cell.className != 'case') continue\n var caseId = cell.innerHTML\n cell.innerHTML = ''\n var link = document.createElement('a')\n link.href = 'http://bugs.example.com/fogbugz/default.php?' + caseId\n link.appendChild(document.createTextNode(caseId))\n cell.appendChild(link)\n }\n}\n</code></pre>\n\n<p>You can apply it with something like <code>onload = makeCasesClickable</code>, or simply include it right at the end of the page.</p>\n" }, { "answer_id": 165110, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 2, "selected": false, "text": "<p>Not possible with CSS, plus that's not what CSS is for any way. Client-side Javascript or Server-side (insert language of choice) is the way to go.</p>\n" }, { "answer_id": 165112, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 1, "selected": false, "text": "<p>I don't think it's possible with CSS. CSS is only supposed to affect the looks and layout of your content.</p>\n\n<p>This seems like a job for a PHP script (or some other language). You didn't give enough information for me to know the best way to do it, but maybe something like this:</p>\n\n<pre><code>function case_link($id) {\n return '&lt;a href=\"http://bugs.example.com/fogbuz/default.php?' . $id . '\"&gt;' . $id . '&lt;/a&gt;';\n}\n</code></pre>\n\n<p>Then later in your document:</p>\n\n<pre><code>&lt;table&gt;&lt;tr&gt;&lt;td class=\"case\"&gt;&lt;?php echo case_link('123456'); ?&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;\n</code></pre>\n\n<p>And if you want an .html file, just run the script from the command line and redirect the output to an .html file.</p>\n" }, { "answer_id": 165146, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": false, "text": "<p>here is a <a href=\"http://jquery.com\" rel=\"noreferrer\">jQuery</a> solution specific to your HTML posted:</p>\n\n<pre><code>$('.case').each(function() {\n var link = $(this).html();\n $(this).contents().wrap('&lt;a href=\"example.com/script.php?id='+link+'\"&gt;&lt;/a&gt;');\n});\n</code></pre>\n\n<p>in essence, over each .case element, will grab the contents of the element, and throw them into a link wrapped around it.</p>\n" }, { "answer_id": 165155, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 0, "selected": false, "text": "<p>You could have something like this (using Javascript). Inside <code>&lt;head&gt;</code>, have</p>\n\n<pre><code>&lt;script type=\"text/javascript\" language=\"javascript\"&gt;\n function getElementsByClass (className) {\n var all = document.all ? document.all :\n document.getElementsByTagName('*');\n var elements = new Array();\n for (var i = 0; i &lt; all.length; i++)\n if (all[i].className == className)\n elements[elements.length] = all[i];\n return elements;\n }\n\n function makeLinks(className, url) {\n nodes = getElementsByClass(className);\n for(var i = 0; i &lt; nodes.length; i++) {\n node = nodes[i];\n text = node.innerHTML\n node.innerHTML = '&lt;a href=\"' + url + text + '\"&gt;' + text + '&lt;/a&gt;';\n }\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>And then at the end of <code>&lt;body&gt;</code></p>\n\n<pre><code>&lt;script type=\"text/javascript\" language=\"javascript\"&gt;\n makeLinks(\"case\", \"http://bugs.example.com/fogbugz/default.php?\");\n&lt;/script&gt;\n</code></pre>\n\n<p>I've tested it, and it works fine.</p>\n" }, { "answer_id": 17301005, "author": "piethh", "author_id": 2520659, "author_profile": "https://Stackoverflow.com/users/2520659", "pm_score": -1, "selected": false, "text": "<p>I know this is an old question, but I stumbled upon this post looking for a solution for creating hyperlinks using CSS and ended up making my own, could be of interest for someone stumbling across this question like I did:</p>\n\n<p>Here's a php function called 'linker();'that enables a fake CSS attribute </p>\n\n<blockquote>\n <p>connect: 'url.com';</p>\n</blockquote>\n\n<p>for an #id defined item.\njust let the php call this on every item of HTML you deem link worthy.\nthe inputs are the .css file <strong>as a string</strong>, using: </p>\n\n<blockquote>\n <p>$style_cont = file_get_contents($style_path);</p>\n</blockquote>\n\n<p>and the #id of the corresponding item. Heres the whole thing:</p>\n\n<pre><code> function linker($style_cont, $id_html){\n\n if (strpos($style_cont,'connect:') !== false) {\n\n $url;\n $id_final;\n $id_outer = '#'.$id_html;\n $id_loc = strpos($style_cont,$id_outer); \n\n $connect_loc = strpos($style_cont,'connect:', $id_loc);\n\n $next_single_quote = stripos($style_cont,\"'\", $connect_loc);\n $next_double_quote = stripos($style_cont,'\"', $connect_loc);\n\n if($connect_loc &lt; $next_single_quote)\n { \n $link_start = $next_single_quote +1;\n $last_single_quote = stripos($style_cont, \"'\", $link_start);\n $link_end = $last_single_quote;\n $link_size = $link_end - $link_start;\n $url = substr($style_cont, $link_start, $link_size);\n }\n else\n {\n $link_start = $next_double_quote +1;\n $last_double_quote = stripos($style_cont, '\"', $link_start);\n $link_end = $last_double_quote;\n $link_size = $link_end - $link_start;\n $url = substr($style_cont, $link_start, $link_size); //link!\n }\n\n $connect_loc_rev = (strlen($style_cont) - $connect_loc) * -1;\n $id_start = strrpos($style_cont, '#', $connect_loc_rev);\n $id_end = strpos($style_cont,'{', $id_start);\n $id_size = $id_end - $id_start;\n $id_raw = substr($style_cont, $id_start, $id_size);\n $id_clean = rtrim($id_raw); //id!\n\n if (strpos($url,'http://') !== false) \n {\n $url_clean = $url;\n }\n else\n {\n $url_clean = 'http://'.$url;\n };\n\n if($id_clean[0] == '#')\n {\n $id_final = $id_clean;\n\n if($id_outer == $id_final)\n {\n echo '&lt;a href=\"';\n echo $url_clean;\n echo '\" target=\"_blank\"&gt;';\n };\n };\n };\n};\n</code></pre>\n\n<p>this could probably be improved/shortened using commands like .wrap() or getelementbyID()\nbecause it only generates the <code>&lt;a href='blah'&gt;</code> portion, but seeing as <code>&lt;/a&gt;</code> disappears anyway without a opening clause it still works if you just add them everywhere :D</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/165082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19207/" ]
I'm hand-maintaining an HTML document, and I'm looking for a way to automatically insert a link around text in a table. Let me illustrate: ``` <table><tr><td class="case">123456</td></tr></table> ``` I would like to automatically make every text in a TD with class "case" a link to that case in our bug tracking system (which, incidentally, is FogBugz). So I'd like that "123456" to be changed to a link of this form: ``` <a href="http://bugs.example.com/fogbugz/default.php?123456">123456</a> ``` Is that possible? I've played with the :before and :after pseudo-elements, but there doesn't seem to be a way to repeat the case number.
Not in a manner that will work across browsers. You could, however, do that with some relatively trivial Javascript.. ``` function makeCasesClickable(){ var cells = document.getElementsByTagName('td') for (var i = 0, cell; cell = cells[i]; i++){ if (cell.className != 'case') continue var caseId = cell.innerHTML cell.innerHTML = '' var link = document.createElement('a') link.href = 'http://bugs.example.com/fogbugz/default.php?' + caseId link.appendChild(document.createTextNode(caseId)) cell.appendChild(link) } } ``` You can apply it with something like `onload = makeCasesClickable`, or simply include it right at the end of the page.
165,092
<p>Basically I wanted to do something like <code>git push mybranch to repo1, repo2, repo3</code></p> <p>right now I'm just typing push many times, and if I'm in a hurry to the the pushing done, I just send them all to the background <code>git push repo1 &amp; git push repo2 &amp;</code></p> <p>I'm just wondering if <code>git</code> natively supports what I want to do, or if maybe there's a clever script out there, or maybe a way to edit the local repo config file to say a branch should be pushed to multiple remotes.</p>
[ { "answer_id": 165131, "author": "Adam Franco", "author_id": 15872, "author_profile": "https://Stackoverflow.com/users/15872", "pm_score": 3, "selected": false, "text": "<p>What I do is have a single bare repository that lives in my home directory that I push to. The post-update hook in that repository then pushes or rsyncs to several other publicly visible locations.</p>\n\n<p>Here is my hooks/post-update:</p>\n\n<pre><code>#!/bin/sh\n#\n# An example hook script to prepare a packed repository for use over\n# dumb transports.\n#\n# To enable this hook, make this file executable by \"chmod +x post-update\".\n\n# Update static info that will be used by git clients accessing\n# the git directory over HTTP rather than the git protocol.\ngit-update-server-info\n\n# Copy git repository files to my web server for HTTP serving.\nrsync -av --delete -e ssh /home/afranco/repositories/public/ [email protected]:/srv/www/htdocs/git/\n\n# Upload to github\ngit-push --mirror github \n</code></pre>\n" }, { "answer_id": 166043, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 7, "selected": true, "text": "<p>You can have several URLs per remote in git, even though the <code>git remote</code> command did not appear to expose this last I checked. In <code>.git/config</code>, put something like this:</p>\n\n<pre><code>[remote \"public\"]\n url = [email protected]:kch/inheritable_templates.git\n url = kch@homeserver:projects/inheritable_templates.git\n</code></pre>\n\n<p>Now you can say “<code>git push public</code>” to push to both repos at once.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/165092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13989/" ]
Basically I wanted to do something like `git push mybranch to repo1, repo2, repo3` right now I'm just typing push many times, and if I'm in a hurry to the the pushing done, I just send them all to the background `git push repo1 & git push repo2 &` I'm just wondering if `git` natively supports what I want to do, or if maybe there's a clever script out there, or maybe a way to edit the local repo config file to say a branch should be pushed to multiple remotes.
You can have several URLs per remote in git, even though the `git remote` command did not appear to expose this last I checked. In `.git/config`, put something like this: ``` [remote "public"] url = [email protected]:kch/inheritable_templates.git url = kch@homeserver:projects/inheritable_templates.git ``` Now you can say “`git push public`” to push to both repos at once.
165,101
<p>The following code:</p> <pre><code>template &lt;typename S, typename T&gt; struct foo { void bar(); }; template &lt;typename T&gt; void foo &lt;int, T&gt;::bar() { } </code></pre> <p>gives me the error</p> <pre><code>invalid use of incomplete type 'struct foo&lt;int, T&gt;' declaration of 'struct foo&lt;int, T&gt;' </code></pre> <p>(I'm using gcc.) Is my syntax for partial specialization wrong? Note that if I remove the second argument:</p> <pre><code>template &lt;typename S&gt; struct foo { void bar(); }; template &lt;&gt; void foo &lt;int&gt;::bar() { } </code></pre> <p>then it compiles correctly.</p>
[ { "answer_id": 165153, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 7, "selected": true, "text": "<p>You can't partially specialize a function. If you wish to do so on a member function, you must partially specialize the entire template (yes, it's irritating). On a large templated class, to partially specialize a function, you would need a workaround. Perhaps a templated member struct (e.g. <code>template &lt;typename U = T&gt; struct Nested</code>) would work. Or else you can try deriving from another template that partially specializes (works if you use the <code>this-&gt;member</code> notation, otherwise you will encounter compiler errors).</p>\n" }, { "answer_id": 6238814, "author": "Anonymous Coward", "author_id": 784194, "author_profile": "https://Stackoverflow.com/users/784194", "pm_score": 3, "selected": false, "text": "<p>If you need to partially specialise a constructor, you might try something like:</p>\n\n<pre><code>template &lt;class T, int N&gt;\nstruct thingBase\n{\n //Data members and other stuff.\n};\n\ntemplate &lt;class T, int N&gt; struct thing : thingBase&lt;T, N&gt; {};\n\ntemplate &lt;class T&gt; struct thing&lt;T, 42&gt; : thingBase&lt;T, 42&gt;\n{\n thing(T * param1, wchar_t * param2)\n {\n //Special construction if N equals 42.\n }\n};\n</code></pre>\n\n<p>Note: this was anonymised from something I'm working on. You can also use this when you have a template class with lots and lots of members and you just want to add a function.</p>\n" }, { "answer_id": 23738555, "author": "Echsecutor", "author_id": 3586021, "author_profile": "https://Stackoverflow.com/users/3586021", "pm_score": 3, "selected": false, "text": "<p>Although coppro mentioned two solutions already and Anonymous explained the second one, it took me quite some time to understand the first one. Maybe the following code is helpful for someone stumbling across this site, which still ranks high in google, like me. The example (passing a vector/array/single element of numericalT as dataT and then accessing it via [] or directly) is of course somewhat contrived, but should illustrate how you actually can come very close to partially specializing a member function by wrapping it in a partially specialized class. </p>\n\n<pre><code>/* The following circumvents the impossible partial specialization of \na member function \nactualClass&lt;dataT,numericalT,1&gt;::access\nas well as the non-nonsensical full specialisation of the possibly\nvery big actualClass. */\n\n//helper:\ntemplate &lt;typename dataT, typename numericalT, unsigned int dataDim&gt;\nclass specialised{\npublic:\n numericalT&amp; access(dataT&amp; x, const unsigned int index){return x[index];}\n};\n\n//partial specialisation:\ntemplate &lt;typename dataT, typename numericalT&gt;\nclass specialised&lt;dataT,numericalT,1&gt;{\npublic:\n numericalT&amp; access(dataT&amp; x, const unsigned int index){return x;}\n};\n\n//your actual class:\ntemplate &lt;typename dataT, typename numericalT, unsigned int dataDim&gt;\nclass actualClass{\nprivate:\n dataT x;\n specialised&lt;dataT,numericalT,dataDim&gt; accessor;\npublic:\n //... for(int i=0;i&lt;dataDim;++i) ...accessor.access(x,i) ...\n};\n</code></pre>\n" }, { "answer_id": 62695743, "author": "Nathan Phillips", "author_id": 740378, "author_profile": "https://Stackoverflow.com/users/740378", "pm_score": 2, "selected": false, "text": "<p>If you're reading this question then you might like to be reminded that although you can't partially specialise methods you can add a non-templated overload, which will be called in preference to the templated function. i.e.</p>\n<pre><code>struct A\n{\n template&lt;typename T&gt;\n bool foo(T arg) { return true; }\n\n bool foo(int arg) { return false; }\n\n void bar()\n {\n bool test = foo(7); // Returns false\n }\n};\n</code></pre>\n" }, { "answer_id": 63540063, "author": "Jonathan SIX", "author_id": 12703286, "author_profile": "https://Stackoverflow.com/users/12703286", "pm_score": 1, "selected": false, "text": "<p>In C++ 17, I use &quot;if constexpr&quot; to avoid specialize (and rewrite) my method. For example :</p>\n<pre><code>template &lt;size_t TSize&gt;\nstruct A\n{\n void recursiveMethod();\n};\n\ntemplate &lt;size_t TSize&gt;\nvoid A&lt;TSize&gt;::recursiveMethod()\n{\n if constexpr (TSize == 1)\n {\n //[...] imple without subA\n }\n else\n {\n A&lt;TSize - 1&gt; subA;\n\n //[...] imple\n }\n}\n</code></pre>\n<p>That avoid to specialize A&lt;1&gt;::recursiveMethod().\nYou can also use this method for type like this example :</p>\n<pre><code>template &lt;typename T&gt;\nstruct A\n{\n void foo();\n};\n\ntemplate &lt;typename T&gt;\nvoid A&lt;T&gt;::foo()\n{\n if constexpr (std::is_arithmetic_v&lt;T&gt;)\n {\n std::cout &lt;&lt; &quot;arithmetic&quot; &lt;&lt; std::endl;\n }\n else\n {\n std::cout &lt;&lt; &quot;other&quot; &lt;&lt; std::endl;\n }\n}\n\n\nint main()\n{\n A&lt;char*&gt; a;\n a.foo();\n\n A&lt;int&gt; b;\n\n b.foo();\n}\n</code></pre>\n<p>output :</p>\n<pre><code>other\narithmetic\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/165101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112/" ]
The following code: ``` template <typename S, typename T> struct foo { void bar(); }; template <typename T> void foo <int, T>::bar() { } ``` gives me the error ``` invalid use of incomplete type 'struct foo<int, T>' declaration of 'struct foo<int, T>' ``` (I'm using gcc.) Is my syntax for partial specialization wrong? Note that if I remove the second argument: ``` template <typename S> struct foo { void bar(); }; template <> void foo <int>::bar() { } ``` then it compiles correctly.
You can't partially specialize a function. If you wish to do so on a member function, you must partially specialize the entire template (yes, it's irritating). On a large templated class, to partially specialize a function, you would need a workaround. Perhaps a templated member struct (e.g. `template <typename U = T> struct Nested`) would work. Or else you can try deriving from another template that partially specializes (works if you use the `this->member` notation, otherwise you will encounter compiler errors).
165,106
<p>I work with a lot of offsite developers and contractors. I ask them daily to send me a quick 5 minute status of their work for the day. I have to sometimes consolidate the status of individuals into teams and sometimes consolidate the status of a week, for end-of-period reporting to my clients.</p> I want to learn: <ul> <li>Items accomplished and how much time was spent on each</li> <li>Problems encountered and how much time was spent on each</li> <li>Items that will be worked on next, their estimates (in man hours) and their target dates</li> <li>Questions they have on the work</li> </ul> I'm looking for a format that will provide this information while: <ul> <li>Being quick for the developers to complete (5-10 minutes, without thinking too much)</li> <li>Easy for me to read and browse quickly</li> <li>Is uniform for each developer</li> </ul> <p>What would you suggest?</p>
[ { "answer_id": 165134, "author": "jasonbar", "author_id": 15099, "author_profile": "https://Stackoverflow.com/users/15099", "pm_score": 0, "selected": false, "text": "<p>Just give them a template laid out in a format that you expect to see the data returned in. You may also consider increasing the time they are going to devote to this and removing the \"not thinking too much\" clause if you are requiring estimates for future work. I wouldn't trust an estimate that someone came up with in 5 mins. without thinking.</p>\n\n<p>If you are currently using any project management software, it should be trivial for the developers to record and review (or even just remember) what they have done compile it for you. Ideally they would be recording issues or questions throughout the day and not trying to come up with them just to fill in the report.</p>\n\n<p>It seems like your \"I want to learn\" list is an excellent starting point to generate a template from. Only you will know what the perfect format for you is.</p>\n" }, { "answer_id": 165136, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 3, "selected": true, "text": "<p>Use <a href=\"http://en.wikipedia.org/wiki/Scrum_(development)\" rel=\"nofollow noreferrer\">Scrum</a>. Create the sprint backlog, have a spreadsheet with the tasks and a column for each day of the sprint. Ask people to fill out the hours worked on each task every day. Send daily report starting with the burndown chart for the sprint and then short two one liners for each member - last worked on and next working on. Send weekly report with the burndown chart, red/yellow/green status for each major feature (and blocking issues and notes if it's not green) and the remaining items on the sprint backlog.</p>\n\n<p>I don't have a link to samples, but here are some drafts:</p>\n\n<pre>\n10/02/2008 - Product A daily status\n\n&lt;Burndown chart&gt;\n\nTeam member A\nLast 24: feature A\nNext 24: feature A unit tests\n\nTeam member B\nLast 24: bug jail\nNext 24: feature B\n\nTeam member C\nLast 24: feature C\nNext 24: feature C\nBlocked on: Dependency D - still waiting on the redist from team D\n</pre>\n\n<pre>\n10/02/2008 - Product A weekly status\n\n&lt;Burndown chart&gt;\n\n**Feature A** - Green\n[note: red/yellow/green represents status; use background color as well for better visualisation]\nOn track\n\n**Feature B** - Yellow\n[note: red/yellow/green represents status; use background color as well for better visualisation]\nSlipping a day due to bug jail\nMitigation: will load balance unit tests on team member A\n\n**Feature C** - Red\n[note: red/yellow/green represents status; use background color as well for better visualisation]\nFeature is blocked on external dependency from team D. No ETA on unblock.\nMitigation: consider cutting the feature for this sprint\n\n**Milestone schedule:**\nPlanning complete - 9/15 (two weeks of planning)\nCode complete - 10/15 (four weeks of coding)\nRC - 10/30 (two weeks stabilization and testing)\n</pre>\n" }, { "answer_id": 165147, "author": "Bartosz Blimke", "author_id": 18715, "author_profile": "https://Stackoverflow.com/users/18715", "pm_score": 0, "selected": false, "text": "<p>Looks like you want to do Extreme Programming stand up meetings.</p>\n\n<p><a href=\"http://www.extremeprogramming.org/rules/standupmeeting.html\" rel=\"nofollow noreferrer\">http://www.extremeprogramming.org/rules/standupmeeting.html</a></p>\n\n<p>You can talk to off site team members using the phone with laudspeaker, or some VOIP.</p>\n" }, { "answer_id": 165173, "author": "marcj", "author_id": 23940, "author_profile": "https://Stackoverflow.com/users/23940", "pm_score": 0, "selected": false, "text": "<p>Generally I have just relied on e-mail as a means of providing status reports, it provides the simplicity and speed of completion but does not enforce any sort of uniformity.</p>\n\n<p>There are a number of options to achieve this but they all risk making the process more complex and time consuming. Some of these could be:</p>\n\n<p>An online form with sections for each or a multi sheet spreadsheet, with each sheet being a section.</p>\n\n<p>All of these require some effort by yourself to create them, do you need the uniformity for some purpose? e.g. to automate the summary reports.</p>\n\n<p>An alternative to this would be to use some project management tool which the contractors filled in whilst they were working and that you could report on at any time. I would recommend Thoughtworks Studio Mingle, but it does rely on an agile-like process.</p>\n" }, { "answer_id": 165425, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p>you probably do not want to hear this, but here is it anyway -</p>\n\n<p>i have been in this situation on both sides of the desk, and come to the conclusion that these kinds of rolled-up status reports are a complete waste of time for you and the developers. Here's why:</p>\n\n<ul>\n<li>the developers should be working on features/deliverables with specified deadlines</li>\n<li>the developers should be asking questions when they occur</li>\n<li>communication should flow in both directions as needed</li>\n</ul>\n\n<p>if these things are not happening, no amount of passive status reporting is going to fix the problems that will inevitably arise</p>\n\n<p>on the developer side of the fence - a \"quick five minute status\" [i hate that phrase, five minutes is not quick!] interrupts the developer's flow, causing a loss of fifteen minutes (or more) of productivity (joel even blogged about this i think). But even if it really is only five minutes, if you have a dozen developers then you're wasting five man-hours <em>per week</em> on administrivia (and it's probably more like 20)</p>\n\n<p>on the manager side of the fence - rolling up the status reports of individuals into teams by project etc. is non-productive busywork that wastes your time also. Chances are that no one even reads the reports.</p>\n\n<p>but here's the real problem: this kind of reporting and roll-up may indicate reactive management instead of pro-active management. In other words, it doesn't matter what methodology is being used - scrum, xp, agile, rational, waterfall, home-grown, or whatever - if the project is properly planned and executed then <em>you should already know what everyone is doing</em> because it was planned in advance. And it doesn't matter if it was planned that morning or six months ago.</p>\n\n<p>ignoring client requirements for a moment, if you really need this information on a daily basis to manage the projects then there are probably some serious problems with the projects - asking the developer <strong><em>every day</em></strong> what they're going to work on next and how long it will take, for example, hints that no real planning was done in advance...</p>\n\n<p>as for the client requirements, if they absolutely insist on this kind of minutia [and i know that, for example, some government agencies do] then the best option is to provide a web interface or other application to automate the tedium that will do the roll-up for you. You'll still be wasting the developers' time, but at least you won't be wasting your time ;-)</p>\n\n<p>oh, and to answer your question literally: the perfect status report says \"on target with the project plan\", and nothing more ;-)</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/165106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16794/" ]
I work with a lot of offsite developers and contractors. I ask them daily to send me a quick 5 minute status of their work for the day. I have to sometimes consolidate the status of individuals into teams and sometimes consolidate the status of a week, for end-of-period reporting to my clients. I want to learn: * Items accomplished and how much time was spent on each * Problems encountered and how much time was spent on each * Items that will be worked on next, their estimates (in man hours) and their target dates * Questions they have on the work I'm looking for a format that will provide this information while: * Being quick for the developers to complete (5-10 minutes, without thinking too much) * Easy for me to read and browse quickly * Is uniform for each developer What would you suggest?
Use [Scrum](http://en.wikipedia.org/wiki/Scrum_(development)). Create the sprint backlog, have a spreadsheet with the tasks and a column for each day of the sprint. Ask people to fill out the hours worked on each task every day. Send daily report starting with the burndown chart for the sprint and then short two one liners for each member - last worked on and next working on. Send weekly report with the burndown chart, red/yellow/green status for each major feature (and blocking issues and notes if it's not green) and the remaining items on the sprint backlog. I don't have a link to samples, but here are some drafts: ``` 10/02/2008 - Product A daily status <Burndown chart> Team member A Last 24: feature A Next 24: feature A unit tests Team member B Last 24: bug jail Next 24: feature B Team member C Last 24: feature C Next 24: feature C Blocked on: Dependency D - still waiting on the redist from team D ``` ``` 10/02/2008 - Product A weekly status <Burndown chart> **Feature A** - Green [note: red/yellow/green represents status; use background color as well for better visualisation] On track **Feature B** - Yellow [note: red/yellow/green represents status; use background color as well for better visualisation] Slipping a day due to bug jail Mitigation: will load balance unit tests on team member A **Feature C** - Red [note: red/yellow/green represents status; use background color as well for better visualisation] Feature is blocked on external dependency from team D. No ETA on unblock. Mitigation: consider cutting the feature for this sprint **Milestone schedule:** Planning complete - 9/15 (two weeks of planning) Code complete - 10/15 (four weeks of coding) RC - 10/30 (two weeks stabilization and testing) ```
165,140
<p>Does SubSonic.SqlQuery have a between/and for date ranges? If not, what would be the best way to get a range.</p>
[ { "answer_id": 165234, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 3, "selected": true, "text": "<p>Try something like this:</p>\n\n<pre><code>SqlQuery query = new SqlQuery().From(\"Table\")\n .WhereExpression(\"Column\")\n .IsBetweenAnd(\"1/1/2008\", \"12/31/2008\");\nDataSet dataSet = query.ExecuteDataSet(); // Or whatever output you need\n</code></pre>\n" }, { "answer_id": 185880, "author": "aherrick", "author_id": 20446, "author_profile": "https://Stackoverflow.com/users/20446", "pm_score": 2, "selected": false, "text": "<p>Another way to query with SubSonic.</p>\n\n<p><code>\n TableCollection data = new TableCollection();</p>\n\n<pre><code>Query q = Table.CreateQuery()\n .BETWEEN_AND(\"Column\", \"1/1/2008\", \"12/31/2008\");\n\n data.LoadAndCloseReader(q.ExecuteReader());\n\n// loop through collection\n</code></pre>\n\n<p></code></p>\n" }, { "answer_id": 941125, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 0, "selected": false, "text": "<p>Combined Northwind answer: </p>\n\n<pre><code> SqlQuery query = new SqlQuery().From(\"Orders\")\n .WhereExpression(\"OrderDate\")\n .IsBetweenAnd(\"1996-07-02\", \"1996-07-08\");\n DataSet dataSet = query.ExecuteDataSet(); // Or whatever output you need\n\n #region PresentResultsReplaceResponseWriteWithConsole.WriteLineForConsoleApp\n\n DataTable dt = dataSet.Tables[0];\n Response.Write(\"&lt;table&gt;\");\n foreach ( DataRow dr in dt.Rows ) \n {\n Response.Write(\"&lt;tr&gt;\");\n for (int i = 0; i &lt; dt.Columns.Count; i++)\n {\n Response.Write(\"&lt;td&gt;\");\n Response.Write(dr[i].ToString() + \" \");\n Response.Write(\"&lt;td&gt;\");\n } //eof for \n Response.Write(\"&lt;/br&gt;\");\n Response.Write(\"&lt;/tr&gt;\");\n\n\n }\n Response.Write(\"&lt;table&gt;\");\n #endregion PresentResultsReplaceResponseWriteWithConsole.WriteLineForConsoleApp\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13954/" ]
Does SubSonic.SqlQuery have a between/and for date ranges? If not, what would be the best way to get a range.
Try something like this: ``` SqlQuery query = new SqlQuery().From("Table") .WhereExpression("Column") .IsBetweenAnd("1/1/2008", "12/31/2008"); DataSet dataSet = query.ExecuteDataSet(); // Or whatever output you need ```
165,170
<p>I want to display dates in the format: short day of week, short month, day of month without leading zero but including "th", "st", "nd", or "rd" suffix.</p> <p>For example, the day this question was asked would display "Thu Oct 2nd".</p> <p>I'm using Ruby 1.8.7, and <a href="http://ruby-doc.org/core/Time.html#method-i-strftime" rel="noreferrer">Time.strftime</a> just doesn't seem to do this. I'd prefer a standard library if one exists.</p>
[ { "answer_id": 165202, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 7, "selected": false, "text": "<p>You can use active_support's ordinalize helper method on numbers. </p>\n\n<pre><code>&gt;&gt; 3.ordinalize\n=&gt; \"3rd\"\n&gt;&gt; 2.ordinalize\n=&gt; \"2nd\"\n&gt;&gt; 1.ordinalize\n=&gt; \"1st\"\n</code></pre>\n" }, { "answer_id": 165213, "author": "Bartosz Blimke", "author_id": 18715, "author_profile": "https://Stackoverflow.com/users/18715", "pm_score": 9, "selected": true, "text": "<p>Use the ordinalize method from 'active_support'.</p>\n\n<pre><code>&gt;&gt; time = Time.new\n=&gt; Fri Oct 03 01:24:48 +0100 2008\n&gt;&gt; time.strftime(\"%a %b #{time.day.ordinalize}\")\n=&gt; \"Fri Oct 3rd\"\n</code></pre>\n\n<p>Note, if you are using IRB with Ruby 2.0, you must first run:</p>\n\n<pre><code>require 'active_support/core_ext/integer/inflections'\n</code></pre>\n" }, { "answer_id": 165225, "author": "Jimmy Schementi", "author_id": 5721, "author_profile": "https://Stackoverflow.com/users/5721", "pm_score": 4, "selected": false, "text": "<pre><code>&gt;&gt; require 'activesupport'\n=&gt; []\n&gt;&gt; t = Time.now\n=&gt; Thu Oct 02 17:28:37 -0700 2008\n&gt;&gt; formatted = \"#{t.strftime(\"%a %b\")} #{t.day.ordinalize}\"\n=&gt; \"Thu Oct 2nd\"\n</code></pre>\n" }, { "answer_id": 165350, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 3, "selected": false, "text": "<p>I like Bartosz's answer, but hey, since this is Rails we're talking about, let's take it one step up in devious. (Edit: Although I was going to just monkeypatch the following method, turns out there is a cleaner way.)</p>\n\n<p><code>DateTime</code> instances have a <code>to_formatted_s</code> method supplied by ActiveSupport, which takes a single symbol as a parameter and, if that symbol is recognized as a valid predefined format, returns a String with the appropriate formatting. </p>\n\n<p>Those symbols are defined by <code>Time::DATE_FORMATS</code>, which is a hash of symbols to either strings for the standard formatting function... or procs. Bwahaha.</p>\n\n<pre><code>d = DateTime.now #Examples were executed on October 3rd 2008\nTime::DATE_FORMATS[:weekday_month_ordinal] = \n lambda { |time| time.strftime(\"%a %b #{time.day.ordinalize}\") }\nd.to_formatted_s :weekday_month_ordinal #Fri Oct 3rd\n</code></pre>\n\n<p>But hey, if you can't resist the opportunity to monkeypatch, you could always give that a cleaner interface:</p>\n\n<pre><code>class DateTime\n\n Time::DATE_FORMATS[:weekday_month_ordinal] = \n lambda { |time| time.strftime(\"%a %b #{time.day.ordinalize}\") }\n\n def to_my_special_s\n to_formatted_s :weekday_month_ordinal\n end\nend\n\nDateTime.now.to_my_special_s #Fri Oct 3rd\n</code></pre>\n" }, { "answer_id": 433127, "author": "Richard Hurt", "author_id": 21512, "author_profile": "https://Stackoverflow.com/users/21512", "pm_score": 5, "selected": false, "text": "<p>Taking Patrick McKenzie's answer just a bit further, you could create a new file in your <code>config/initializers</code> directory called <code>date_format.rb</code> (or whatever you want) and put this in it:</p>\n\n<pre><code>Time::DATE_FORMATS.merge!(\n my_date: lambda { |time| time.strftime(\"%a, %b #{time.day.ordinalize}\") }\n)\n</code></pre>\n\n<p>Then in your view code you can format any date simply by assigning it your new date format:</p>\n\n<pre><code>My Date: &lt;%= h some_date.to_s(:my_date) %&gt;\n</code></pre>\n\n<p>It's simple, it works, and is easy to build on. Just add more format lines in the date_format.rb file for each of your different date formats. Here is a more fleshed out example.</p>\n\n<pre><code>Time::DATE_FORMATS.merge!(\n datetime_military: '%Y-%m-%d %H:%M',\n datetime: '%Y-%m-%d %I:%M%P',\n time: '%I:%M%P',\n time_military: '%H:%M%P',\n datetime_short: '%m/%d %I:%M',\n due_date: lambda { |time| time.strftime(\"%a, %b #{time.day.ordinalize}\") }\n)\n</code></pre>\n" }, { "answer_id": 52906913, "author": "Joshua Pinter", "author_id": 293280, "author_profile": "https://Stackoverflow.com/users/293280", "pm_score": 3, "selected": false, "text": "<h2>Create your own <code>%o</code> format.</h2>\n\n<h3>Initializer</h3>\n\n<p><strong><code>config/initializers/srtftime.rb</code></strong></p>\n\n<pre><code>module StrftimeOrdinal\n def self.included( base )\n base.class_eval do\n alias_method :old_strftime, :strftime\n def strftime( format )\n old_strftime format.gsub( \"%o\", day.ordinalize )\n end\n end\n end\nend\n\n[ Time, Date, DateTime ].each{ |c| c.send :include, StrftimeOrdinal }\n</code></pre>\n\n<h3>Usage</h3>\n\n<pre><code>Time.new( 2018, 10, 2 ).strftime( \"%a %b %o\" )\n=&gt; \"Tue Oct 2nd\"\n</code></pre>\n\n<p>You can use this with <code>Date</code> and <code>DateTime</code> as well:</p>\n\n<pre><code>DateTime.new( 2018, 10, 2 ).strftime( \"%a %b %o\" )\n=&gt; \"Tue Oct 2nd\"\n\nDate.new( 2018, 10, 2 ).strftime( \"%a %b %o\" )\n=&gt; \"Tue Oct 2nd\"\n</code></pre>\n" }, { "answer_id": 54375658, "author": "Olivier Lacan", "author_id": 385622, "author_profile": "https://Stackoverflow.com/users/385622", "pm_score": 3, "selected": false, "text": "<p>Although Jonathan Tran did say he was looking for the abbreviated day of the week first followed by the abbreviated month, I think it might be useful for people who end up here to know that Rails has out-of-the-box support for the more commonly usable long month, ordinalized day integer, followed by the year, as in <code>June 1st, 2018</code>.</p>\n\n<p>It can be easily achieved with:</p>\n\n<pre><code>Time.current.to_date.to_s(:long_ordinal)\n=&gt; \"January 26th, 2019\"\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>Date.current.to_s(:long_ordinal)\n=&gt; \"January 26th, 2019\"\n</code></pre>\n\n<p>You can stick to a time instance if you wish as well:</p>\n\n<pre><code>Time.current.to_s(:long_ordinal)\n=&gt; \"January 26th, 2019 04:21\"\n</code></pre>\n\n<p>You can find more formats and context on how to create a custom one in the <a href=\"https://api.rubyonrails.org/classes/Date.html#DATE_FORMATS\" rel=\"noreferrer\">Rails API docs</a>.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12887/" ]
I want to display dates in the format: short day of week, short month, day of month without leading zero but including "th", "st", "nd", or "rd" suffix. For example, the day this question was asked would display "Thu Oct 2nd". I'm using Ruby 1.8.7, and [Time.strftime](http://ruby-doc.org/core/Time.html#method-i-strftime) just doesn't seem to do this. I'd prefer a standard library if one exists.
Use the ordinalize method from 'active\_support'. ``` >> time = Time.new => Fri Oct 03 01:24:48 +0100 2008 >> time.strftime("%a %b #{time.day.ordinalize}") => "Fri Oct 3rd" ``` Note, if you are using IRB with Ruby 2.0, you must first run: ``` require 'active_support/core_ext/integer/inflections' ```
165,175
<p>I'm failing to understand exactly what the IF statement is doing, from what I can see it is checking if the variable <code>x</code> is equal to the int <code>0</code>. If this is <code>true</code> the ABSOLUTE value of the variable <code>y</code> is returned... this is when I lose the plot, why would the return statement then go on to include <code>&lt;= ESPILON</code>? Surely this means less than or equal to the value of epsilon? if so how is that working? If it doesn't mean that then what does it mean?</p> <p>(JAVA CODE)</p> <pre><code>final double EPSILON = 1E-14; if (x == 0) return Math.abs(y) &lt;= EPSILON; </code></pre>
[ { "answer_id": 165180, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 3, "selected": false, "text": "<p>It returns true if the absolute value of y is &lt;= EPSILON, and false otherwise. The &lt;= is evaluated before the return statement. This code is equivalent:</p>\n\n<pre><code>if(x == 0)\n{\n boolean ret = Math.abs(y) &lt;= EPSILON;\n return ret;\n}\n</code></pre>\n\n<p>The code isn't simply read from left to right. A simpler example is</p>\n\n<pre><code>int x = 3 + 4 * 5;\n</code></pre>\n\n<p>After evaluating this, x is 23, not 35. The evaluation is 3 + (4*5), not (3+4)*5, because the * has a higher precedence than the +. The return statement in the original example has a very low precedence. All operators like +, -, &lt;, >= are evaluated before it.</p>\n" }, { "answer_id": 165182, "author": "Windows programmer", "author_id": 23705, "author_profile": "https://Stackoverflow.com/users/23705", "pm_score": 1, "selected": false, "text": "<p>You're right that it is checking if the variable x is equal to (well, maybe int) 0. However, if this is true then it doesn't return the absolute value of y, it returns a boolean, the result of the &lt;= operator.</p>\n" }, { "answer_id": 165185, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 1, "selected": false, "text": "<p>It's returning a boolean value.</p>\n\n<p>Epsilon is a double, holding the value 1E-14.</p>\n\n<p>This is the actual IF statement</p>\n\n<pre><code>if (x==0) {\n return MATH.abs(y) &lt;= EPSILON;\n}\n</code></pre>\n\n<p>So, what's getting returned is if the absolute value of y is less than or equals to Epsilon.</p>\n" }, { "answer_id": 165186, "author": "Jedidja", "author_id": 9913, "author_profile": "https://Stackoverflow.com/users/9913", "pm_score": 3, "selected": false, "text": "<p>The entire expression </p>\n\n<pre><code>Math.abs(y) &lt;= EPSILON\n</code></pre>\n\n<p>should be evaluated first, which means the function is going to return a boolean value (true/false). Having said that, if </p>\n\n<pre><code>x != 0\n</code></pre>\n\n<p>then I'm not sure what will get returned.</p>\n" }, { "answer_id": 165190, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 5, "selected": true, "text": "<p>Floating-point math is by its nature inaccurate, so rather than testing for equivalence (which is always a bad idea), instead the developer has chosen a small number (1x10^-14 in this case) as the acceptable tolerance for proximity to zero. The return statement returns a comparison, so what this will do is take the absolute value of y, and return true if and only if it is sufficiently close to zero, where sufficiently close is defined by EPSILON.</p>\n" }, { "answer_id": 165193, "author": "marcj", "author_id": 23940, "author_profile": "https://Stackoverflow.com/users/23940", "pm_score": 0, "selected": false, "text": "<p>I haven't done Java in a long time but it would appear that this is actually returning a boolean (which might be implicitly cast).</p>\n\n<p>I would say that if x equals 0, it returns true when the absolute value of y &lt;= Epsilon, otherwise it returns false.</p>\n\n<p>However if x doesn't equal 0 then it would return null, as no statement covers the else.</p>\n" }, { "answer_id": 166066, "author": "Myrrdyn", "author_id": 21550, "author_profile": "https://Stackoverflow.com/users/21550", "pm_score": 0, "selected": false, "text": "<p>The \"issue\" is that this fragment relies heavyly on operator precedence (not bad per se, but sometimes it can be confusing).</p>\n\n<p><a href=\"http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html\" rel=\"nofollow noreferrer\">Here</a> you can find a list of all java operators with their precedence, and <a href=\"http://www.cppreference.com/wiki/operator_precedence\" rel=\"nofollow noreferrer\">here</a> for comparison the same table for C/C++</p>\n" }, { "answer_id": 166816, "author": "Robin", "author_id": 21925, "author_profile": "https://Stackoverflow.com/users/21925", "pm_score": 0, "selected": false, "text": "<p>It is equivalent to this</p>\n\n<pre><code>return (Math.abs(y) &lt;= EPSILON);\n</code></pre>\n\n<p>which should have been added to the code for clarity. As has been mentioned, it returns a boolean.</p>\n\n<p>An alternatives would be </p>\n\n<pre><code>if (Math.abs(y) &lt;= EPSILON)\n return true;\nelse\n return false;\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm failing to understand exactly what the IF statement is doing, from what I can see it is checking if the variable `x` is equal to the int `0`. If this is `true` the ABSOLUTE value of the variable `y` is returned... this is when I lose the plot, why would the return statement then go on to include `<= ESPILON`? Surely this means less than or equal to the value of epsilon? if so how is that working? If it doesn't mean that then what does it mean? (JAVA CODE) ``` final double EPSILON = 1E-14; if (x == 0) return Math.abs(y) <= EPSILON; ```
Floating-point math is by its nature inaccurate, so rather than testing for equivalence (which is always a bad idea), instead the developer has chosen a small number (1x10^-14 in this case) as the acceptable tolerance for proximity to zero. The return statement returns a comparison, so what this will do is take the absolute value of y, and return true if and only if it is sufficiently close to zero, where sufficiently close is defined by EPSILON.
165,188
<p>I have some c(++) code that uses sprintf to convert a uint_64 to a string. This needs to be portable to both linux and Solaris.</p> <p>On linux we use %ju, but there does not appear to be any equivalent on Solaris. The closest I can find is %lu, but this produces incorrect output. Some sample code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;sys/types.h&gt; #ifdef SunOS typedef uint64_t u_int64_t; #endif int main(int argc, char **argv) { u_int64_t val = 123456789123L; #ifdef SunOS printf("%lu\n", val); #else printf("%ju\n", val); #endif } </code></pre> <p>On linux, the output is as expected; on Solaris 9 (don't ask), it's "28"</p> <p>What can I use?</p>
[ { "answer_id": 165199, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "<p>You can use <code>%llu</code> for long long. However, this is not very portable either, because <code>long long</code> isn't guaranteed to be 64 bits. :-)</p>\n" }, { "answer_id": 165203, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": true, "text": "<p>If you have have inttypes.h available you can use the macros it provides:</p>\n\n<pre><code>printf( \"%\" PRIu64 \"\\n\", val);\n</code></pre>\n\n<p>Not pretty (I seem to be saying that a lot recently), but it works.</p>\n" }, { "answer_id": 165204, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 0, "selected": false, "text": "<p>You can get <code>uint64_t</code> from <code>stdint.h</code> if you want to avoid the SunOS conditional typedef.</p>\n" }, { "answer_id": 165207, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 2, "selected": false, "text": "<p>The answer depends on whether your code is actually C or C++. In C, you should be using an <code>unsigned long long</code> rather than another type (this is conformant to the current standard, and <code>long long</code> is pretty common as far as C99 support goes), appending <code>ULL</code> instead of <code>L</code> to your constant, and using (as has been mentioned) <code>%llu</code> as your specifier. If support for C99 doesn't exist, you may want to check the compiler documentation, as there is no other standard way to do it. <code>long long</code> is guarateed to be 64 bits at least.</p>\n" }, { "answer_id": 165238, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 3, "selected": false, "text": "<p>On a C99 compliant system: </p>\n\n<pre><code>#include &lt;inttypes.h&gt;\n\nuint64_t big = ...;\nprintf(\"%\" PRIu64 \"\\n\", big);\n</code></pre>\n\n<p>See section 7.8 of the C99 standard.</p>\n\n<p>The specifiers are {PRI,SCN}[diouxX]{N,LEASTN,MAX,FASTN,PTR}</p>\n\n<p>Where PRI is for the printf() family, SCN is for the scanf() family, d and i for signed integral types; o,u,x,X are for unsigned integral types as octal, decimal, hex, and Hex; N is one of the supported widths; LEAST and FAST correspond to those modifiers; PTR is for intptr_t; and MAX is for intmax_t.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16977/" ]
I have some c(++) code that uses sprintf to convert a uint\_64 to a string. This needs to be portable to both linux and Solaris. On linux we use %ju, but there does not appear to be any equivalent on Solaris. The closest I can find is %lu, but this produces incorrect output. Some sample code: ``` #include <stdio.h> #include <sys/types.h> #ifdef SunOS typedef uint64_t u_int64_t; #endif int main(int argc, char **argv) { u_int64_t val = 123456789123L; #ifdef SunOS printf("%lu\n", val); #else printf("%ju\n", val); #endif } ``` On linux, the output is as expected; on Solaris 9 (don't ask), it's "28" What can I use?
If you have have inttypes.h available you can use the macros it provides: ``` printf( "%" PRIu64 "\n", val); ``` Not pretty (I seem to be saying that a lot recently), but it works.
165,212
<p>How can I check the umask of a program which is currently running?</p> <p>[update: another process, not the current process.]</p>
[ { "answer_id": 165305, "author": "Josh", "author_id": 257, "author_profile": "https://Stackoverflow.com/users/257", "pm_score": 2, "selected": false, "text": "<p>If you're the current process, you can write a file to /tmp and check its setting. A better solution is to call umask(3) passing zero - the function returns the setting prior to the call - and then reset it back by passing that value back into umask.</p>\n\n<p>The umask for another process doesn't seem to be exposed.</p>\n" }, { "answer_id": 165327, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "<p>From the GNU C Library manual:</p>\n\n<blockquote>\n <p>Here is an example showing how to read the mask with <code>umask</code>\n without changing it permanently:</p>\n\n<pre><code>mode_t\nread_umask (void)\n{\n mode_t mask = umask (0);\n umask (mask);\n return mask;\n}\n</code></pre>\n \n <p>However, it is better to use <code>getumask</code> if you just want to read\n the mask value, because it is reentrant (at least if you use the\n GNU operating system).</p>\n</blockquote>\n\n<p><code>getumask</code> is glibc-specific, though. So if you value portability, then the non-reentrant solution is the only one there is.</p>\n\n<p>Edit: I've just grepped for <code>-&gt;umask</code> all through the Linux source code. There is nowhere that will get you the umask of a different process. Also, there is no <code>getumask</code>; apparently that's a Hurd-only thing.</p>\n" }, { "answer_id": 165718, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<p>You can attach gdb to a running process and then call umask in the debugger:</p>\n<pre><code>(gdb) attach &lt;your pid&gt;\n...\n(gdb) call umask(0)\n[Switching to Thread -1217489200 (LWP 11037)]\n$1 = 18 # this is the umask\n(gdb) call umask(18) # reset umask\n$2 = 0\n(gdb) \n</code></pre>\n<p>(note: 18 corresponds to a umask of <code>O22</code> in this example)</p>\n<p>This suggests that there may be a really ugly way to get the umask using ptrace.</p>\n" }, { "answer_id": 38861278, "author": "tbc0", "author_id": 650264, "author_profile": "https://Stackoverflow.com/users/650264", "pm_score": 1, "selected": false, "text": "<p>A colleague just showed me this command line pattern for this. I always have emacs running, so that's in the example below. The <code>perl</code> is my contribution:</p>\n<pre><code>sudo gdb --pid=$(pgrep emacs) --batch -ex 'call/o umask(0)' -ex 'call umask($1)' 2&gt; /dev/null | perl -ne 'print(&quot;$1\\n&quot;)if(/^\\$1 = (\\d+)$/)'\n</code></pre>\n" }, { "answer_id": 43066791, "author": "egmont", "author_id": 4457671, "author_profile": "https://Stackoverflow.com/users/4457671", "pm_score": 4, "selected": false, "text": "<p>Beginning with Linux kernel 4.7, the umask is available in <code>/proc/&lt;pid&gt;/status</code>.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
How can I check the umask of a program which is currently running? [update: another process, not the current process.]
You can attach gdb to a running process and then call umask in the debugger: ``` (gdb) attach <your pid> ... (gdb) call umask(0) [Switching to Thread -1217489200 (LWP 11037)] $1 = 18 # this is the umask (gdb) call umask(18) # reset umask $2 = 0 (gdb) ``` (note: 18 corresponds to a umask of `O22` in this example) This suggests that there may be a really ugly way to get the umask using ptrace.
165,231
<p>Although I played with it before, I'm finally starting to use <a href="http://en.wikipedia.org/wiki/Dvorak_Simplified_Keyboard" rel="noreferrer">Dvorak (Simplified)</a> regularly. I've been in a steady relationship with Vim for several years now, and I'm trying to figure out the best way to remap the key bindings to suit my newfound Dvorak skills.</p> <p>How do <em>you</em> remap Vim's key bindings to best work with Dvorak?</p> <p>Explanations encouraged!</p>
[ { "answer_id": 165252, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 6, "selected": true, "text": "<p>I use one of the more <a href=\"http://vim.wikia.com/wiki/Change_cursor_movement_keys_for_Dvorak_layout\" rel=\"noreferrer\">common recommended keybindings</a>:</p>\n\n<pre><code>Dvorak it!\nno d h\nno h j\nno t k\nno n l\nno s :\nno S :\nno j d\nno l n\nno L N\nAdded benefits\nno - $\nno _ ^\nno N &lt;C-w&gt;&lt;C-w&gt;\nno T &lt;C-w&gt;&lt;C-r&gt;\nno H 8&lt;Down&gt;\nno T 8&lt;Up&gt;\nno D &lt;C-w&gt;&lt;C-r&gt;\n</code></pre>\n\n<p>Movement keys stay in the same location. Other changes:</p>\n\n<ul>\n<li>Delete 'd' -> Junk 'j'</li>\n<li>Next 'n' -> Look 'l'</li>\n<li>Previous 'N' -> Look Back 'L' </li>\n</ul>\n\n<p>There were also some changes for familiarity, 's'/'S' can be used to access command mode (the old location of the :, which still works).</p>\n\n<p>Added Benefits</p>\n\n<ul>\n<li>End of line '$' -also- '-'</li>\n<li>Beginning of line '^' -also- '_'</li>\n<li>Move up 8 'T'</li>\n<li>Move down 8 'H'</li>\n<li>Next window <code>&lt;C-w&gt;&lt;C-w&gt;</code> -also- 'N'</li>\n<li>Swap windows <code>&lt;C-w&gt;&lt;C-r&gt;</code> -also- 'D' </li>\n</ul>\n\n<p>-Adam</p>\n" }, { "answer_id": 166064, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 2, "selected": false, "text": "<p>Vim ships with an extensive Dvorak script, but unfortunately it’s not directly <code>source</code>-able, since the file includes a few lines of instructions and another script that undoes its effects. To read it, issue the following command:</p>\n\n<pre><code>:e $VIMRUNTIME/macros/dvorak\n</code></pre>\n" }, { "answer_id": 166254, "author": "Andrew Aylett", "author_id": 24762, "author_profile": "https://Stackoverflow.com/users/24762", "pm_score": 4, "selected": false, "text": "<p>I don't find that I need to remap the keys for Dvorak -- I very quickly got used to using the default keybindings when I switched layouts.</p>\n\n<p>As a bonus, it means that I don't have to remember two different key combinations when I switch between Dvorak and Qwerty. The difference in keyboard layout is enough that I'm not expecting keys to be in the same location.</p>\n" }, { "answer_id": 192174, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I simply use standard qwerty for commands and dvorak for insert mode</p>\n\n<p>Here is <a href=\"http://vim.wikia.com/wiki/Using_Vim_with_the_Dvorak_keyboard_layout\" rel=\"noreferrer\">how to set it up</a></p>\n" }, { "answer_id": 483885, "author": "zcrar70", "author_id": 59384, "author_profile": "https://Stackoverflow.com/users/59384", "pm_score": 3, "selected": false, "text": "<p>A little late, but I use the following:</p>\n\n<pre><code>\" dvorak remap\nnoremap h h\nnoremap t j\nnoremap n k\nnoremap s l\nnoremap l n\nnoremap L N\n\n\" easy access to beginning and end of line\nnoremap - $\nnoremap _ ^\n</code></pre>\n\n<p>This basically does the following:</p>\n\n<ul>\n<li>left-down-up-right are all under the default finger positions on the home row (i.e. not moved over by one as in the default QWERTY Vim mappings)</li>\n<li>l/L is used for next/previous search result</li>\n<li>use -/_ to reach the end/beginning of a line</li>\n</ul>\n\n<p>This seems to work for me...</p>\n" }, { "answer_id": 3234552, "author": "weakish", "author_id": 222893, "author_profile": "https://Stackoverflow.com/users/222893", "pm_score": 2, "selected": false, "text": "<p>My rebindings:</p>\n\n<pre><code>noremap h h\nnoremap t j\nnoremap n k\nnoremap s l\nnoremap j t\nnoremap l n\nnoremap k s\nnoremap J T\nnoremap L N\nnoremap K S\nnoremap T J\nnoremap N L\nnoremap S K\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>In qwert, vi has to use 'h', because vi doesn't want to use ';' a non-letter. But\nin dvroak, we have 's', so why not take this advantage?</li>\n<li>vi uses Caps for relative actions. This is a good design philosophy. So I try to\nconform this.</li>\n</ul>\n\n<p>Meanings:</p>\n\n<pre><code>n (Next) -&gt; l (Left) -- \"What's left?\" resembles \"What's next?\"\ns (Substitute) -&gt; k (Kill then insert)\nt (jump Till) -&gt; j (Jump till)\nN, S, T are similar.\n\nJ (Join lines) -&gt; T (make lines Together)\nK (Keyword) -&gt; S (Subject)\nL[count] (Line count) -&gt; N (line Number)\n</code></pre>\n\n<p>B.T.W. L itself goes to the last line, and N is the last letter of fin.\n(Thanks for tenzu to point out this.)</p>\n\n<p>P.S. I have used these rebindings for a while. Now I does not use it in vim. I just use the default ones.</p>\n" }, { "answer_id": 14790810, "author": "Gordon Gustafson", "author_id": 89989, "author_profile": "https://Stackoverflow.com/users/89989", "pm_score": 1, "selected": false, "text": "<p>You can use this to <a href=\"https://stackoverflow.com/questions/14025247/make-vim-use-dvorak-keybindings-only-in-insert-mode\">have Vim use Dvorak only in insert mode:</a></p>\n\n<pre><code>:set keymap=dvorak\n</code></pre>\n\n<p>This way all of the commands are still in QWERTY, but everything you type will be in Dvorak. </p>\n\n<p><strong>Caveats:</strong> Well, almost everything. Insert mode, search mode, and replace mode will all be dvorak, but ex commands will not. This means that you don't have to relearn <code>:wq</code>, but you will need type <code>:%s/foo/bar/gc</code> in QWERTY. </p>\n\n<p>This won't help if you only want to move certain commands, but I found that in my head, \"move forward one word\" was bound to \"move left ring finger up,\" rather than \"ask the typing department where the letter 'w' is and then press it,\" which made this method much easier for me.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
Although I played with it before, I'm finally starting to use [Dvorak (Simplified)](http://en.wikipedia.org/wiki/Dvorak_Simplified_Keyboard) regularly. I've been in a steady relationship with Vim for several years now, and I'm trying to figure out the best way to remap the key bindings to suit my newfound Dvorak skills. How do *you* remap Vim's key bindings to best work with Dvorak? Explanations encouraged!
I use one of the more [common recommended keybindings](http://vim.wikia.com/wiki/Change_cursor_movement_keys_for_Dvorak_layout): ``` Dvorak it! no d h no h j no t k no n l no s : no S : no j d no l n no L N Added benefits no - $ no _ ^ no N <C-w><C-w> no T <C-w><C-r> no H 8<Down> no T 8<Up> no D <C-w><C-r> ``` Movement keys stay in the same location. Other changes: * Delete 'd' -> Junk 'j' * Next 'n' -> Look 'l' * Previous 'N' -> Look Back 'L' There were also some changes for familiarity, 's'/'S' can be used to access command mode (the old location of the :, which still works). Added Benefits * End of line '$' -also- '-' * Beginning of line '^' -also- '\_' * Move up 8 'T' * Move down 8 'H' * Next window `<C-w><C-w>` -also- 'N' * Swap windows `<C-w><C-r>` -also- 'D' -Adam
165,253
<p>If I load the nextimg URL manually in the browser, it gives a new picture every time I reload. But this bit of code shows the same image every iteration of <code>draw()</code>.</p> <p>How can I force myimg not to be cached?</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; function draw(){ var canvas = document.getElementById('canv'); var ctx = canvas.getContext('2d'); var rx; var ry; var i; myimg = new Image(); myimg.src = 'http://ohm:8080/cgi-bin/nextimg' rx=Math.floor(Math.random()*100)*10 ry=Math.floor(Math.random()*100)*10 ctx.drawImage(myimg,rx,ry); window.setTimeout('draw()',0); } &lt;/script&gt; &lt;/head&gt; &lt;body onload="draw();"&gt; &lt;canvas id="canv" width="1024" height="1024"&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 165256, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 5, "selected": false, "text": "<p>The easiest way is to sling an ever-changing querystring onto the end:</p>\n\n<pre><code>var url = 'http://.../?' + escape(new Date())\n</code></pre>\n\n<p>Some people prefer using <code>Math.random()</code> for that instead of <code>escape(new Date())</code>. But the correct way is probably to alter the headers the web server sends to disallow caching.</p>\n" }, { "answer_id": 165258, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 3, "selected": false, "text": "<p>You can't stop it from caching the image altogether within Javascript. But, you can toy with the src/address of the image to force it to cache anew:</p>\n\n<pre><code>[Image].src = 'image.png?' + (new Date()).getTime();\n</code></pre>\n\n<p>You can probably take any of the Ajax cache solutions and apply it here.</p>\n" }, { "answer_id": 165310, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 4, "selected": true, "text": "<p>That actually sounds like a bug in the browser -- you could file at <a href=\"http://bugs.webkit.org\" rel=\"nofollow noreferrer\">http://bugs.webkit.org</a> if it's in Safari or <a href=\"https://bugzilla.mozilla.org/\" rel=\"nofollow noreferrer\">https://bugzilla.mozilla.org/</a> for Firefox. Why do i say potential browser bug? Because the browser realises it should not be caching on reload, yet it does give you a cached copy of the image when you request it programmatically.</p>\n\n<p>That said are you sure you're actually drawing anything? the Canvas.drawImage API will not wait for an image to load, and is spec'd to not draw if the image has not completely loaded when you try to use it.</p>\n\n<p>A better practice is something like:</p>\n\n<pre><code> var myimg = new Image();\n myimg.onload = function() {\n var rx=Math.floor(Math.random()*100)*10\n var ry=Math.floor(Math.random()*100)*10\n ctx.drawImage(myimg,rx,ry);\n window.setTimeout(draw,0);\n }\n myimg.src = 'http://ohm:8080/cgi-bin/nextimg'\n</code></pre>\n\n<p>(You can also just pass <code>draw</code> as an argument to setTimeout rather than using a string, which will save reparsing and compiling the same string over and over again.)</p>\n" }, { "answer_id": 22430139, "author": "Doin", "author_id": 999120, "author_profile": "https://Stackoverflow.com/users/999120", "pm_score": 0, "selected": false, "text": "<p>There are actually <strong>two</strong> caches you need to bypass here: One is the regular HTTP cache, that you can avoid by using the correct HTTP headers on the image. But you've also got to stop the browser from re-using an in-memory copy of the image; if it decides it can do that it will never even get to the point of querying its cache, so HTTP headers won't help.</p>\n\n<p>To prevent this, you can use either a changing querystring or a changing fragment identifier.</p>\n\n<p>See my post <a href=\"https://stackoverflow.com/a/22429796/999120\" title=\"My answer to: Refresh image with a new one at the same url\">here</a> for more details.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
If I load the nextimg URL manually in the browser, it gives a new picture every time I reload. But this bit of code shows the same image every iteration of `draw()`. How can I force myimg not to be cached? ``` <html> <head> <script type="text/javascript"> function draw(){ var canvas = document.getElementById('canv'); var ctx = canvas.getContext('2d'); var rx; var ry; var i; myimg = new Image(); myimg.src = 'http://ohm:8080/cgi-bin/nextimg' rx=Math.floor(Math.random()*100)*10 ry=Math.floor(Math.random()*100)*10 ctx.drawImage(myimg,rx,ry); window.setTimeout('draw()',0); } </script> </head> <body onload="draw();"> <canvas id="canv" width="1024" height="1024"></canvas> </body> </html> ```
That actually sounds like a bug in the browser -- you could file at <http://bugs.webkit.org> if it's in Safari or <https://bugzilla.mozilla.org/> for Firefox. Why do i say potential browser bug? Because the browser realises it should not be caching on reload, yet it does give you a cached copy of the image when you request it programmatically. That said are you sure you're actually drawing anything? the Canvas.drawImage API will not wait for an image to load, and is spec'd to not draw if the image has not completely loaded when you try to use it. A better practice is something like: ``` var myimg = new Image(); myimg.onload = function() { var rx=Math.floor(Math.random()*100)*10 var ry=Math.floor(Math.random()*100)*10 ctx.drawImage(myimg,rx,ry); window.setTimeout(draw,0); } myimg.src = 'http://ohm:8080/cgi-bin/nextimg' ``` (You can also just pass `draw` as an argument to setTimeout rather than using a string, which will save reparsing and compiling the same string over and over again.)
165,346
<p>I've been working on porting some of my Processing code over to regular Java in NetBeans. So far so well, most everything works great, except for when I go to use non-grayscale colors. </p> <p>I have a script that draws a spiral pattern, and should vary the colors in the spiral based on a modulus check. The script seems to hang, however, and I can't really explain why.</p> <p>If anyone has some experience with Processing and Java, and you could tell me where my mistake is, I'd really love to know.</p> <p>For the sake of peer-review, here's my little program:</p> <pre><code>package spirals; import processing.core.*; public class Main extends PApplet { float x, y; int i = 1, dia = 1; float angle = 0.0f, orbit = 0f; float speed = 0.05f; //color palette int gray = 0x0444444; int blue = 0x07cb5f7; int pink = 0x0f77cb5; int green = 0x0b5f77c; public Main(){} public static void main( String[] args ) { PApplet.main( new String[] { "spirals.Main" } ); } public void setup() { background( gray ); size( 400, 400 ); noStroke(); smooth(); } public void draw() { if( i % 11 == 0 ) fill( green ); else if( i % 13 == 0 ) fill( blue ); else if( i % 17 == 0 ) fill( pink ); else fill( gray ); orbit += 0.1f; //ever so slightly increase the orbit angle += speed % ( width * height ); float sinval = sin( angle ); float cosval = cos( angle ); //calculate the (x, y) to produce an orbit x = ( width / 2 ) + ( cosval * orbit ); y = ( height / 2 ) + ( sinval * orbit ); dia %= 11; //keep the diameter within bounds. ellipse( x, y, dia, dia ); dia++; i++; } } </code></pre>
[ { "answer_id": 170069, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 3, "selected": true, "text": "<p>Have you considered adding debugging statements (System.out.println) and looking at the Java Console?</p>\n\n<p>There may be a massive amount of output and definitive slowdown, but you can at least see what happens when nothing seems to happen.</p>\n\n<p>What I do think is a logic error is the filling if statement; every iteratation you decide the color of that iteration and fill with that color. Only iterations with i == 11, 13, or 17 get filled with a color. And the next iteration that color is overwritten by gray. I would think it tends to flicker, possibly to fast to see.</p>\n\n<p>Didn't you want something like</p>\n\n<pre><code>public class Main extends PApplet\n{\n ...\n\n int currentColor = gray;\n\n public Main(){}\n\n ...\n\n public void draw()\n {\n if( i % 11 == 0 )\n currentColor = green;\n else if( i % 13 == 0 )\n currentColor = blue;\n else if( i % 17 == 0 )\n currentColor = pink;\n else {\n // Use current color\n } \n\n fill(currentColor);\n\n ...\n}\n</code></pre>\n\n<p>In that way you start with gray, go to green, blue, pink, green, blue, pink etc. If you\nalso want to see gray at some point you'd have to add something like</p>\n\n<pre><code> else if ( i % 19 ) {\n currentColor = gray;\n }\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 221188, "author": "razong", "author_id": 29885, "author_profile": "https://Stackoverflow.com/users/29885", "pm_score": 0, "selected": false, "text": "<p>To see whats happening here add</p>\n\n<pre><code>stroke(255);\n</code></pre>\n\n<p>at the beginning of the draw. You'll see all the wanted circles draw, but without color. As the previous poster mentioned: you're using a non gray color only every 11th, 13th and 17th iteration.</p>\n\n<p>I think that your color values are the main issue here. As from the reference page</p>\n\n<p><em>From a technical standpoint, colors are 32 bits of information ordered as AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB where the A's contain the alpha value, the R's are the red/hue value, G's are green/saturation, and B's are blue/brightness.</em></p>\n\n<p>If you look at your values you'll see a very low alpha value, which is maybe impossible to distinguish from the background.</p>\n" }, { "answer_id": 249795, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>Not sure if you have still an issue. You mention hanging. It is a shot in the dark, but I remember fry repeating that size() call must be the first instruction in setup(). So perhaps moving down the background() call might help. Couldn't hurt anyway.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13293/" ]
I've been working on porting some of my Processing code over to regular Java in NetBeans. So far so well, most everything works great, except for when I go to use non-grayscale colors. I have a script that draws a spiral pattern, and should vary the colors in the spiral based on a modulus check. The script seems to hang, however, and I can't really explain why. If anyone has some experience with Processing and Java, and you could tell me where my mistake is, I'd really love to know. For the sake of peer-review, here's my little program: ``` package spirals; import processing.core.*; public class Main extends PApplet { float x, y; int i = 1, dia = 1; float angle = 0.0f, orbit = 0f; float speed = 0.05f; //color palette int gray = 0x0444444; int blue = 0x07cb5f7; int pink = 0x0f77cb5; int green = 0x0b5f77c; public Main(){} public static void main( String[] args ) { PApplet.main( new String[] { "spirals.Main" } ); } public void setup() { background( gray ); size( 400, 400 ); noStroke(); smooth(); } public void draw() { if( i % 11 == 0 ) fill( green ); else if( i % 13 == 0 ) fill( blue ); else if( i % 17 == 0 ) fill( pink ); else fill( gray ); orbit += 0.1f; //ever so slightly increase the orbit angle += speed % ( width * height ); float sinval = sin( angle ); float cosval = cos( angle ); //calculate the (x, y) to produce an orbit x = ( width / 2 ) + ( cosval * orbit ); y = ( height / 2 ) + ( sinval * orbit ); dia %= 11; //keep the diameter within bounds. ellipse( x, y, dia, dia ); dia++; i++; } } ```
Have you considered adding debugging statements (System.out.println) and looking at the Java Console? There may be a massive amount of output and definitive slowdown, but you can at least see what happens when nothing seems to happen. What I do think is a logic error is the filling if statement; every iteratation you decide the color of that iteration and fill with that color. Only iterations with i == 11, 13, or 17 get filled with a color. And the next iteration that color is overwritten by gray. I would think it tends to flicker, possibly to fast to see. Didn't you want something like ``` public class Main extends PApplet { ... int currentColor = gray; public Main(){} ... public void draw() { if( i % 11 == 0 ) currentColor = green; else if( i % 13 == 0 ) currentColor = blue; else if( i % 17 == 0 ) currentColor = pink; else { // Use current color } fill(currentColor); ... } ``` In that way you start with gray, go to green, blue, pink, green, blue, pink etc. If you also want to see gray at some point you'd have to add something like ``` else if ( i % 19 ) { currentColor = gray; } ``` Hope this helps.
165,355
<p>I'm trying to produce just the day number in a WPF text block, without leading zeroes and without extra space padding (which throws off the layout). The first produces the day number with a space, the second produces the entire date. According to the <a href="http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx" rel="nofollow noreferrer">docs</a>, 'd' should produce the day (1-31).</p> <pre><code>string.Format("{0:d }", DateTime.Today); string.Format("{0:d}", DateTime.Today); </code></pre> <p>UPDATE:Adding % is indeed the trick. Appropriate docs <a href="http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#UsingSingleSpecifiers" rel="nofollow noreferrer">here</a>.</p>
[ { "answer_id": 165374, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 4, "selected": true, "text": "<p>See <a href=\"http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n\n<blockquote>\n <p>d, %d</p>\n \n <p>The day of the month. Single-digit days do not have a leading zero. The application specifies \"%d\" if the format pattern is not combined with other format patterns.</p>\n</blockquote>\n\n<p>Otherwise d is interpreted as:</p>\n\n<blockquote>\n <p>d - 'ShortDatePattern'</p>\n</blockquote>\n\n<p>PS. For messing around with format strings, using <a href=\"http://www.linqpad.net/\" rel=\"nofollow noreferrer\">LinqPad</a> is invaluable.</p>\n" }, { "answer_id": 165375, "author": "Michael Petrotta", "author_id": 23897, "author_profile": "https://Stackoverflow.com/users/23897", "pm_score": 1, "selected": false, "text": "<p>From the MSDN documentation for \"Custom Date and Time Format Strings\":</p>\n\n<blockquote>\n <p>Any string that is not a standard date\n and time format string is interpreted\n as a custom date and time format\n string.</p>\n</blockquote>\n\n<p>{0:d} is interpreted as a standard data and time format string. From \"Standard Date and Time Format Strings\", the \"d\" format specifier:</p>\n\n<blockquote>\n <p>Represents a custom date and time\n format string defined by the current\n ShortDatePattern property.</p>\n</blockquote>\n\n<p>With the space, {0:d } doesn't match any standard date and time format string, and is interpreted as a custom data and time format string. From \"Custom Date and Time Format Strings\", the \"d\" format specifier:</p>\n\n<blockquote>\n <p>Represents the day of the month as a\n number from 1 through 31.</p>\n</blockquote>\n" }, { "answer_id": 165382, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 0, "selected": false, "text": "<p>The <code>{0:d}</code> format uses the patterns defined in the <a href=\"http://msdn.microsoft.com/en-us/library/az4se3k1.aspx\" rel=\"nofollow noreferrer\">Standard Date and Time Format Strings document of MSDN</a>. 'd' translates to the short date pattern, 'D' to the long date pattern, and so on and so forth.</p>\n\n<p>The format that you want appears to be the <a href=\"http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx\" rel=\"nofollow noreferrer\">Custom Date and Time Format Modifiers</a>, which work when there is no matching specified format (e.g., 'd ' including the space) or when you use ToString().</p>\n\n<p>You could use the following code instead:</p>\n\n<pre><code>string.Format(\"{0}\", DateTime.Today.ToString(\"d \", CultureInfo.InvariantCulture));\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18482/" ]
I'm trying to produce just the day number in a WPF text block, without leading zeroes and without extra space padding (which throws off the layout). The first produces the day number with a space, the second produces the entire date. According to the [docs](http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx), 'd' should produce the day (1-31). ``` string.Format("{0:d }", DateTime.Today); string.Format("{0:d}", DateTime.Today); ``` UPDATE:Adding % is indeed the trick. Appropriate docs [here](http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#UsingSingleSpecifiers).
See [here](http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx) > > d, %d > > > The day of the month. Single-digit days do not have a leading zero. The application specifies "%d" if the format pattern is not combined with other format patterns. > > > Otherwise d is interpreted as: > > d - 'ShortDatePattern' > > > PS. For messing around with format strings, using [LinqPad](http://www.linqpad.net/) is invaluable.
165,365
<p>I am having fickle of problem in Oracle 9i</p> <p>select 1"FirstColumn" from dual;</p> <p>Oracle throwing error while executing above query. ORA-03001: unimplemented feature in my Production server.</p> <p>The Same query is working fine in my Validation server. Both servers are with Oracle 9i</p> <p>Any one have Idea what's wrong...? Is this something configurable item in Oracle server.</p>
[ { "answer_id": 165414, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 1, "selected": false, "text": "<p>What is the full Oracle version on both servers? 9i is a marketing label-- are you comparing a 9.0.1.x database to a 9.2.0.x database?</p>\n" }, { "answer_id": 165616, "author": "Doug Porter", "author_id": 4311, "author_profile": "https://Stackoverflow.com/users/4311", "pm_score": 1, "selected": false, "text": "<p>Does it give the same output if you do?</p>\n\n<pre><code>select 1 as \"FirstColumn\" from dual;\n</code></pre>\n\n<p>To find out the specific versions on yoru Validation and Production servers, do this SQL on each and compare the results:</p>\n\n<pre><code>select * from v$version;\n</code></pre>\n" }, { "answer_id": 166288, "author": "borjab", "author_id": 16206, "author_profile": "https://Stackoverflow.com/users/16206", "pm_score": 2, "selected": false, "text": "<p>Try: </p>\n\n<pre><code> SELECT 1 AS \"'FirstColumn'\" FROM dual;\n</code></pre>\n\n<p>There is a similar question:\n<a href=\"https://stackoverflow.com/questions/56591/double-quotes-in-oracle-column-aliases\">Double Quotes in Oracle Column Aliases</a></p>\n" }, { "answer_id": 167319, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The below are the versions of my server:</p>\n\n<p>Oracle9i Enterprise Edition Release 9.2.0.8.0 - Validation\nOracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production</p>\n\n<p>64 bit does make a difference. SELECT 1 AS \"'FirstColumn'\" FROM dual; is working but will leads me to update nearly hundreds of packages. Configuration change could be handy rather changing the code.</p>\n\n<p>Regards,\nHanumath</p>\n" }, { "answer_id": 167704, "author": "Nick Pierpoint", "author_id": 4003, "author_profile": "https://Stackoverflow.com/users/4003", "pm_score": 0, "selected": false, "text": "<p>For what it's worth, I have it working fine with me on 9.2.0.7:</p>\n\n<pre><code>select 1\"FirstColumn\" from dual\n</code></pre>\n\n<p>Feels like a bug to me; have you tried Metalink?</p>\n" }, { "answer_id": 175897, "author": "Osama Al-Maadeed", "author_id": 25544, "author_profile": "https://Stackoverflow.com/users/25544", "pm_score": 0, "selected": false, "text": "<p>Hanumath: MetaLink is Oracle's support service. If you're Oracle is licensed, and with a support contract, you would have a MetaLink ID.</p>\n" }, { "answer_id": 175919, "author": "Dylan", "author_id": 4580, "author_profile": "https://Stackoverflow.com/users/4580", "pm_score": 0, "selected": false, "text": "<p>Pretty sure you should have a space between the 1 and the \"FirstColumn\"</p>\n\n<pre><code>SELECT 1 \"FirstColumn\" from dual;\n</code></pre>\n\n<p>That said, it's more correct to use the AS keyword the previous answerers indicated.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am having fickle of problem in Oracle 9i select 1"FirstColumn" from dual; Oracle throwing error while executing above query. ORA-03001: unimplemented feature in my Production server. The Same query is working fine in my Validation server. Both servers are with Oracle 9i Any one have Idea what's wrong...? Is this something configurable item in Oracle server.
Try: ``` SELECT 1 AS "'FirstColumn'" FROM dual; ``` There is a similar question: [Double Quotes in Oracle Column Aliases](https://stackoverflow.com/questions/56591/double-quotes-in-oracle-column-aliases)
165,386
<p>I have just started using Boost 1.36. These libraries would be very useful in reducing the amount of code needed in the unmanaged C++ software project that I am working on.</p> <p>However when I tried to used these libraries my compile times increased ten fold. This would pretty much offset the productivity gains I would receive by using the library.</p> <p>I am using a 3GHz Intel Dual Core with 2GB of RAM and VS 2003.</p> <p>There is a snippet of the code that I added.</p> <pre> #include "boost/numeric/ublas/matrix.hpp" #include "boost/numeric/ublas/vector.hpp" #include "boost/numeric/ublas/matrix_proxy.hpp" typedef ublas::bounded_matrix &lt;long double,NUM_OF_COLUMNS,NUM_OF_CATEGORIES,ublas::row_major&gt; Matrix; typedef ublas::bounded_vector &lt;long double,NUM_OF_COLUMNS&gt; Vector; </pre> <p><code> void Print(const Matrix&amp; amount)<br> {</p> <pre><code>Vector total; total.clear(); for (int category = 0; category &lt; NUM_OF_CATEGORIES; category++) { PrintLine(ublas::row(amount, category)); total += ublas::row(amount, category); } PrintLine(total); </code></pre> <p>} </code></p> <p>Is the problem with VS 2003?<br> I know that VS 2008 is faster but upgrading is going to be a hard sell.<br> Is it just that Boost is optimized for fast run times not fast compile times?<br> Am I just using the Boost Library in a sub-optimal manner?<br> Or am I just using the wrong tool for the job? </p>
[ { "answer_id": 165391, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 4, "selected": true, "text": "<p>Have you tried using precompiled headers? That is including the boost headers in StdAfx.h or whatever header file you use for precompiled headers?</p>\n" }, { "answer_id": 165397, "author": "David Segonds", "author_id": 13673, "author_profile": "https://Stackoverflow.com/users/13673", "pm_score": 1, "selected": false, "text": "<p>Did you try <a href=\"http://www.xoreax.com/\" rel=\"nofollow noreferrer\">Incredibuild</a>? It will allow you to distribute your build on multiple computers. I have seen it used successfully.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5398/" ]
I have just started using Boost 1.36. These libraries would be very useful in reducing the amount of code needed in the unmanaged C++ software project that I am working on. However when I tried to used these libraries my compile times increased ten fold. This would pretty much offset the productivity gains I would receive by using the library. I am using a 3GHz Intel Dual Core with 2GB of RAM and VS 2003. There is a snippet of the code that I added. ``` #include "boost/numeric/ublas/matrix.hpp" #include "boost/numeric/ublas/vector.hpp" #include "boost/numeric/ublas/matrix_proxy.hpp" typedef ublas::bounded_matrix <long double,NUM_OF_COLUMNS,NUM_OF_CATEGORIES,ublas::row_major> Matrix; typedef ublas::bounded_vector <long double,NUM_OF_COLUMNS> Vector; ``` `void Print(const Matrix& amount) {` ``` Vector total; total.clear(); for (int category = 0; category < NUM_OF_CATEGORIES; category++) { PrintLine(ublas::row(amount, category)); total += ublas::row(amount, category); } PrintLine(total); ``` } Is the problem with VS 2003? I know that VS 2008 is faster but upgrading is going to be a hard sell. Is it just that Boost is optimized for fast run times not fast compile times? Am I just using the Boost Library in a sub-optimal manner? Or am I just using the wrong tool for the job?
Have you tried using precompiled headers? That is including the boost headers in StdAfx.h or whatever header file you use for precompiled headers?
165,401
<p>I'm looking for a way to validate the SQL schema on a production DB after updating an application version. If the application does not match the DB schema version, there should be a way to warn the user and list the changes needed.</p> <p>Is there a tool or a framework (to use programatically) with built-in features to do that? Or is there some simple algorithm to run this comparison?</p> <blockquote> <p><strong>Update:</strong> Red gate lists "from $395". Anything free? Or more foolproof than just keeping the version number?</p> </blockquote>
[ { "answer_id": 165411, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 0, "selected": false, "text": "<p>Make a table and store your version number in there. Just make sure you update it as necessary. </p>\n\n<pre><code>CREATE TABLE version (\n version VARCHAR(255) NOT NULL\n)\nINSERT INTO version VALUES ('v1.0');\n</code></pre>\n\n<p>You can then check the version number stored in the database matches the application code during your app's setup or wherever is convenient.</p>\n" }, { "answer_id": 165439, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.red-gate.com/products/SQL_Compare/index.htm\" rel=\"nofollow noreferrer\">SQL Compare by Red Gate</a>.</p>\n" }, { "answer_id": 165440, "author": "Ed Haber", "author_id": 2926, "author_profile": "https://Stackoverflow.com/users/2926", "pm_score": 1, "selected": false, "text": "<p>If you are looking for a tool that can compare two databases and show you the difference Red Gate makes <a href=\"http://www.red-gate.com/products/SQL_Compare/index.htm\" rel=\"nofollow noreferrer\">SQL Compare</a></p>\n" }, { "answer_id": 165904, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 3, "selected": false, "text": "<p>You can do it programatically by looking in the data dictionary (sys.objects, sys.columns etc.) of both databases and comparing them. However, there are also tools like <a href=\"http://www.red-gate.com/products/SQL_Compare/index.htm\" rel=\"noreferrer\">Redgate SQL Compare Pro</a> that do this for you. I have specified this as a part of the tooling for QA on data warehouse systems on a few occasions now, including the one I am currently working on. On my current gig this was no problem at all, as the DBA's here were already using it.</p>\n\n<p>The basic methodology for using these tools is to maintain a reference script that builds the database and keep this in version control. Run the script into a scratch database and compare it with your target to see the differences. It will also generate patch scripts if you feel so inclined.</p>\n\n<p>As far as I know there's nothing free that does this unless you feel like writing your own. Redgate is cheap enough that it might as well be free. Even as a QA tool to prove that the production DB is not in the configuration it was meant to be it will save you its purchase price after one incident.</p>\n" }, { "answer_id": 166561, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 0, "selected": false, "text": "<p>Which RDBMS is this, and how complex are the potential changes?</p>\n\n<p>Maybe this is just a matter of comparing row counts and index counts for each table -- if you have trigger and stored procedure versions to worry about also then you need something more industrial</p>\n" }, { "answer_id": 167208, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 6, "selected": true, "text": "<p>Try this SQL.<br>\n- Run it against each database.<br>\n- Save the output to text files.<br>\n- Diff the text files. </p>\n\n<pre><code>/* get list of objects in the database */\nSELECT name, \n type \nFROM sysobjects\nORDER BY type, name\n\n/* get list of columns in each table / parameters for each stored procedure */\nSELECT so.name, \n so.type, \n sc.name, \n sc.number, \n sc.colid, \n sc.status, \n sc.type, \n sc.length, \n sc.usertype , \n sc.scale \nFROM sysobjects so , \n syscolumns sc \nWHERE so.id = sc.id \nORDER BY so.type, so.name, sc.name\n\n/* get definition of each stored procedure */\nSELECT so.name, \n so.type, \n sc.number, \n sc.text \nFROM sysobjects so , \n syscomments sc \nWHERE so.id = sc.id \nORDER BY so.type, so.name, sc.number \n</code></pre>\n" }, { "answer_id": 168284, "author": "Eric R. Rath", "author_id": 23883, "author_profile": "https://Stackoverflow.com/users/23883", "pm_score": 1, "selected": false, "text": "<p>You didn't mention which RDMBS you're using: if the INFORMATION SCHEMA views are available in your RDBMS, and if you can reference both schemas from the same host, you can query the INFORMATION SCHEMA views to identify differences in:\n-tables\n-columns\n-column types\n-constraints (e.g. primary keys, unique constraints, foreign keys, etc)</p>\n\n<p>I've written a set of queries for exactly this purpose on SQL Server for a past job - it worked well to identify differences. Many of the queries were using LEFT JOINs with IS NULL to check for the absence of expected items, others were comparing things like column types or constraint names.</p>\n\n<p>It's a little tedious, but its possible.</p>\n" }, { "answer_id": 2606936, "author": "Devart", "author_id": 135566, "author_profile": "https://Stackoverflow.com/users/135566", "pm_score": 0, "selected": false, "text": "<p>Try <a href=\"http://www.devart.com/dbforge/sql/datacompare/\" rel=\"nofollow noreferrer\">dbForge Data Compare for SQL Server</a>. It can compare and sync any databases, even very large ones. Quick, easy, always delivers a correct result.\nTry it on your database and comment upon the product. </p>\n\n<p>We can recommend you a reliable SQL comparison tool that offer 3 time’s faster comparison and synchronization of table data in your SQL Server databases. It's dbForge Data Compare for SQL Server.</p>\n\n<p>Main advantages:</p>\n\n<ul>\n<li>Speedier comparison and synchronization of large databases</li>\n<li>Support of native SQL Server backups</li>\n<li>Custom mapping of tables, columns, and schemas</li>\n<li>Multiple options to tune your comparison and synchronization</li>\n<li>Generating comparison and synchronization reports</li>\n</ul>\n\n<p>Plus free 30-day trial and risk-free purchase with 30-day money back guarantee.</p>\n" }, { "answer_id": 6651300, "author": "Sean Cleaver", "author_id": 839031, "author_profile": "https://Stackoverflow.com/users/839031", "pm_score": 2, "selected": false, "text": "<p>You can now use my <strong>SQL Admin Studio</strong> for free to run a <strong>Schema Compare</strong>, <strong>Data Compare</strong> and Sync the Changes. No longer requires a license key download from here <a href=\"http://www.simego.com/Products/SQL-Admin-Studio\" rel=\"nofollow\">http://www.simego.com/Products/SQL-Admin-Studio</a></p>\n\n<p>Also works against SQL Azure.</p>\n\n<p>[UPDATE: Yes I am the Author of the above program, as it's now Free I just wanted to Share it with the community]</p>\n" }, { "answer_id": 8338726, "author": "merger", "author_id": 619791, "author_profile": "https://Stackoverflow.com/users/619791", "pm_score": 1, "selected": false, "text": "<p>I found this small and free tool that fits most of my needs.\n<a href=\"http://www.wintestgear.com/products/MSSQLSchemaDiff/MSSQLSchemaDiff.html\" rel=\"nofollow\">http://www.wintestgear.com/products/MSSQLSchemaDiff/MSSQLSchemaDiff.html</a></p>\n\n<p>It's very basic but it shows you the schema differences of two databases.\nIt doesn't have any fancy stuff like auto generated scripts to make the differences to go away and it doesn't compare any data.</p>\n\n<p>It's just a small, free utility that shows you schema differences :)</p>\n" }, { "answer_id": 21548068, "author": "Dario Cage", "author_id": 2362365, "author_profile": "https://Stackoverflow.com/users/2362365", "pm_score": 3, "selected": false, "text": "<p>I hope I can help - this is the article I suggest reading:</p>\n\n<p><a href=\"http://solutioncenter.apexsql.com/compare-sql-server-database-schemas-automatically/\" rel=\"noreferrer\">Compare SQL Server database schemas automatically</a></p>\n\n<p>It describes how you can automate the SQL Server schema comparison and synchronization process using T-SQL, SSMS or a third party tool.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1363/" ]
I'm looking for a way to validate the SQL schema on a production DB after updating an application version. If the application does not match the DB schema version, there should be a way to warn the user and list the changes needed. Is there a tool or a framework (to use programatically) with built-in features to do that? Or is there some simple algorithm to run this comparison? > > **Update:** Red gate lists "from $395". Anything free? Or more foolproof than just keeping the version number? > > >
Try this SQL. - Run it against each database. - Save the output to text files. - Diff the text files. ``` /* get list of objects in the database */ SELECT name, type FROM sysobjects ORDER BY type, name /* get list of columns in each table / parameters for each stored procedure */ SELECT so.name, so.type, sc.name, sc.number, sc.colid, sc.status, sc.type, sc.length, sc.usertype , sc.scale FROM sysobjects so , syscolumns sc WHERE so.id = sc.id ORDER BY so.type, so.name, sc.name /* get definition of each stored procedure */ SELECT so.name, so.type, sc.number, sc.text FROM sysobjects so , syscomments sc WHERE so.id = sc.id ORDER BY so.type, so.name, sc.number ```
165,402
<p>I need help on this following aspx code</p> <p>aspx Code:</p> <pre><code>&lt;asp:Label ID ="lblName" runat ="server" Text ="Name"&gt;&lt;/asp:Label&gt; &lt;asp:TextBox ID ="txtName" runat ="server"&gt;&lt;/asp:TextBox&gt; </code></pre> <p>Consider this is my aspx page content. I am going to populate the values for the TextBox only after the postback from server. But the label is also posting to the server (<code>runat="server"</code>) even though it's not necessary. Should I write my code like this to save time from server with less load.</p> <p>Corrected Code:</p> <pre><code>&lt;label id ="lblNames"&gt;Name&lt;/label&gt; &lt;asp:TextBox ID ="txtName" runat ="server"&gt;&lt;/asp:TextBox&gt; </code></pre> <p>Only my server control will send to the server for postback and not my HTML control which has a static value.</p> <p>Please suggest whether this is the correct way of coding.</p>
[ { "answer_id": 165409, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": true, "text": "<p>If you take the <strong><code>runat='server'</code></strong> out of the <code>&lt;label&gt;</code> element then it won't be parsed as a server control. If you're not going to do anything with <em><code>lblNames</code></em> from the server then it is perfectly okay to leave it out.</p>\n" }, { "answer_id": 165469, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>If you're not doing <em>anything</em> with the label server-side, then just use a <code>&lt;span></code>. It'll end up as the same html at the browser.</p>\n" }, { "answer_id": 165541, "author": "DancesWithBamboo", "author_id": 1334, "author_profile": "https://Stackoverflow.com/users/1334", "pm_score": 0, "selected": false, "text": "<p>.net label controls are rendered as html label elements and do not get posted back to the server. Labels just don't post back. The server control allows you to manipulate the properties of the control in code however which is very useful.</p>\n\n<p>There is nothing wrong with using html tags as well in your aspx/ascx page though if you don't need any programmatic control of the element.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
I need help on this following aspx code aspx Code: ``` <asp:Label ID ="lblName" runat ="server" Text ="Name"></asp:Label> <asp:TextBox ID ="txtName" runat ="server"></asp:TextBox> ``` Consider this is my aspx page content. I am going to populate the values for the TextBox only after the postback from server. But the label is also posting to the server (`runat="server"`) even though it's not necessary. Should I write my code like this to save time from server with less load. Corrected Code: ``` <label id ="lblNames">Name</label> <asp:TextBox ID ="txtName" runat ="server"></asp:TextBox> ``` Only my server control will send to the server for postback and not my HTML control which has a static value. Please suggest whether this is the correct way of coding.
If you take the **`runat='server'`** out of the `<label>` element then it won't be parsed as a server control. If you're not going to do anything with *`lblNames`* from the server then it is perfectly okay to leave it out.
165,424
<p>I have a ListBox which until recently was displaying a flat list of items. I was able to use myList.ItemContainerGenerator.ConainerFromItem(thing) to retrieve the ListBoxItem hosting "thing" in the list.</p> <p>This week I've modified the ListBox slightly in that the CollectionViewSource that it binds to for its items has grouping enabled. Now the items within the ListBox are grouped underneath nice headers.</p> <p>However, since doing this, ItemContainerGenerator.ContainerFromItem has stopped working - it returns null even for items I know are in the ListBox. Heck - ContainerFromIndex(0) is returning null even when the ListBox is populated with many items!</p> <p>How do I retrieve a ListBoxItem from a ListBox that's displaying grouped items?</p> <p>Edit: Here's the XAML and code-behind for a trimmed-down example. This raises a NullReferenceException because ContainerFromIndex(1) is returning null even though there are four items in the list.</p> <p>XAML:</p> <pre><code>&lt;Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase" Title="Window1"&gt; &lt;Window.Resources&gt; &lt;XmlDataProvider x:Key="myTasks" XPath="Tasks/Task"&gt; &lt;x:XData&gt; &lt;Tasks xmlns=""&gt; &lt;Task Name="Groceries" Type="Home"/&gt; &lt;Task Name="Cleaning" Type="Home"/&gt; &lt;Task Name="Coding" Type="Work"/&gt; &lt;Task Name="Meetings" Type="Work"/&gt; &lt;/Tasks&gt; &lt;/x:XData&gt; &lt;/XmlDataProvider&gt; &lt;CollectionViewSource x:Key="mySortedTasks" Source="{StaticResource myTasks}"&gt; &lt;CollectionViewSource.SortDescriptions&gt; &lt;scm:SortDescription PropertyName="@Type" /&gt; &lt;scm:SortDescription PropertyName="@Name" /&gt; &lt;/CollectionViewSource.SortDescriptions&gt; &lt;CollectionViewSource.GroupDescriptions&gt; &lt;PropertyGroupDescription PropertyName="@Type" /&gt; &lt;/CollectionViewSource.GroupDescriptions&gt; &lt;/CollectionViewSource&gt; &lt;/Window.Resources&gt; &lt;ListBox x:Name="listBox1" ItemsSource="{Binding Source={StaticResource mySortedTasks}}" DisplayMemberPath="@Name" &gt; &lt;ListBox.GroupStyle&gt; &lt;GroupStyle&gt; &lt;GroupStyle.HeaderTemplate&gt; &lt;DataTemplate&gt; &lt;TextBlock Text="{Binding Name}"/&gt; &lt;/DataTemplate&gt; &lt;/GroupStyle.HeaderTemplate&gt; &lt;/GroupStyle&gt; &lt;/ListBox.GroupStyle&gt; &lt;/ListBox&gt; &lt;/Window&gt; </code></pre> <p>CS:</p> <pre><code>public Window1() { InitializeComponent(); listBox1.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged; } void ItemContainerGenerator_StatusChanged(object sender, EventArgs e) { if (listBox1.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated) { listBox1.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged; var i = listBox1.ItemContainerGenerator.ContainerFromIndex(1) as ListBoxItem; // select and keyboard-focus the second item i.IsSelected = true; i.Focus(); } } </code></pre>
[ { "answer_id": 165431, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 0, "selected": false, "text": "<p>Try parsing the VisualTree up from the 'thing' until you reach a ListBoxItem type</p>\n" }, { "answer_id": 169123, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 6, "selected": true, "text": "<p>You <strong>have</strong> to listen and react to the <code>ItemsGenerator.StatusChanged</code> Event and wait until the ItemContainers are generated before you can access them with ContainerFromElement.</p>\n\n<hr>\n\n<p>Searching further, I've found <a href=\"http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/8be8307b-83dd-4658-971d-22d47a34dfb6/\" rel=\"noreferrer\">a thread in the MSDN forum</a> from someone who has the same problem. This seems to be a bug in WPF, when one has a GroupStyle set. The solution is to punt the access of the ItemGenerator after the rendering process. Below is the code for your question. I tried this, and it works:</p>\n\n<pre><code> void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)\n {\n if (listBox1.ItemContainerGenerator.Status\n == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)\n {\n listBox1.ItemContainerGenerator.StatusChanged\n -= ItemContainerGenerator_StatusChanged;\n Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input,\n new Action(DelayedAction));\n }\n }\n\n void DelayedAction()\n {\n var i = listBox1.ItemContainerGenerator.ContainerFromIndex(1) as ListBoxItem;\n\n // select and keyboard-focus the second item\n i.IsSelected = true;\n i.Focus();\n }\n</code></pre>\n" }, { "answer_id": 23608785, "author": "D.Kempkes", "author_id": 2459350, "author_profile": "https://Stackoverflow.com/users/2459350", "pm_score": 2, "selected": false, "text": "<p>If the above code doesn't work for you, give this a try</p>\n\n<pre><code>public class ListBoxExtenders : DependencyObject\n{\n public static readonly DependencyProperty AutoScrollToCurrentItemProperty = DependencyProperty.RegisterAttached(\"AutoScrollToCurrentItem\", typeof(bool), typeof(ListBoxExtenders), new UIPropertyMetadata(default(bool), OnAutoScrollToCurrentItemChanged));\n\n public static bool GetAutoScrollToCurrentItem(DependencyObject obj)\n {\n return (bool)obj.GetValue(AutoScrollToSelectedItemProperty);\n }\n\n public static void SetAutoScrollToCurrentItem(DependencyObject obj, bool value)\n {\n obj.SetValue(AutoScrollToSelectedItemProperty, value);\n }\n\n public static void OnAutoScrollToCurrentItemChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)\n {\n var listBox = s as ListBox;\n if (listBox != null)\n {\n var listBoxItems = listBox.Items;\n if (listBoxItems != null)\n {\n var newValue = (bool)e.NewValue;\n\n var autoScrollToCurrentItemWorker = new EventHandler((s1, e2) =&gt; OnAutoScrollToCurrentItem(listBox, listBox.Items.CurrentPosition));\n\n if (newValue)\n listBoxItems.CurrentChanged += autoScrollToCurrentItemWorker;\n else\n listBoxItems.CurrentChanged -= autoScrollToCurrentItemWorker;\n }\n }\n }\n\n public static void OnAutoScrollToCurrentItem(ListBox listBox, int index)\n {\n if (listBox != null &amp;&amp; listBox.Items != null &amp;&amp; listBox.Items.Count &gt; index &amp;&amp; index &gt;= 0)\n listBox.ScrollIntoView(listBox.Items[index]);\n }\n\n}\n</code></pre>\n\n<p>Usage in XAML</p>\n\n<pre><code>&lt;ListBox IsSynchronizedWithCurrentItem=\"True\" extenders:ListBoxExtenders.AutoScrollToCurrentItem=\"True\" ..../&gt;\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615/" ]
I have a ListBox which until recently was displaying a flat list of items. I was able to use myList.ItemContainerGenerator.ConainerFromItem(thing) to retrieve the ListBoxItem hosting "thing" in the list. This week I've modified the ListBox slightly in that the CollectionViewSource that it binds to for its items has grouping enabled. Now the items within the ListBox are grouped underneath nice headers. However, since doing this, ItemContainerGenerator.ContainerFromItem has stopped working - it returns null even for items I know are in the ListBox. Heck - ContainerFromIndex(0) is returning null even when the ListBox is populated with many items! How do I retrieve a ListBoxItem from a ListBox that's displaying grouped items? Edit: Here's the XAML and code-behind for a trimmed-down example. This raises a NullReferenceException because ContainerFromIndex(1) is returning null even though there are four items in the list. XAML: ``` <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase" Title="Window1"> <Window.Resources> <XmlDataProvider x:Key="myTasks" XPath="Tasks/Task"> <x:XData> <Tasks xmlns=""> <Task Name="Groceries" Type="Home"/> <Task Name="Cleaning" Type="Home"/> <Task Name="Coding" Type="Work"/> <Task Name="Meetings" Type="Work"/> </Tasks> </x:XData> </XmlDataProvider> <CollectionViewSource x:Key="mySortedTasks" Source="{StaticResource myTasks}"> <CollectionViewSource.SortDescriptions> <scm:SortDescription PropertyName="@Type" /> <scm:SortDescription PropertyName="@Name" /> </CollectionViewSource.SortDescriptions> <CollectionViewSource.GroupDescriptions> <PropertyGroupDescription PropertyName="@Type" /> </CollectionViewSource.GroupDescriptions> </CollectionViewSource> </Window.Resources> <ListBox x:Name="listBox1" ItemsSource="{Binding Source={StaticResource mySortedTasks}}" DisplayMemberPath="@Name" > <ListBox.GroupStyle> <GroupStyle> <GroupStyle.HeaderTemplate> <DataTemplate> <TextBlock Text="{Binding Name}"/> </DataTemplate> </GroupStyle.HeaderTemplate> </GroupStyle> </ListBox.GroupStyle> </ListBox> </Window> ``` CS: ``` public Window1() { InitializeComponent(); listBox1.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged; } void ItemContainerGenerator_StatusChanged(object sender, EventArgs e) { if (listBox1.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated) { listBox1.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged; var i = listBox1.ItemContainerGenerator.ContainerFromIndex(1) as ListBoxItem; // select and keyboard-focus the second item i.IsSelected = true; i.Focus(); } } ```
You **have** to listen and react to the `ItemsGenerator.StatusChanged` Event and wait until the ItemContainers are generated before you can access them with ContainerFromElement. --- Searching further, I've found [a thread in the MSDN forum](http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/8be8307b-83dd-4658-971d-22d47a34dfb6/) from someone who has the same problem. This seems to be a bug in WPF, when one has a GroupStyle set. The solution is to punt the access of the ItemGenerator after the rendering process. Below is the code for your question. I tried this, and it works: ``` void ItemContainerGenerator_StatusChanged(object sender, EventArgs e) { if (listBox1.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated) { listBox1.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged; Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input, new Action(DelayedAction)); } } void DelayedAction() { var i = listBox1.ItemContainerGenerator.ContainerFromIndex(1) as ListBoxItem; // select and keyboard-focus the second item i.IsSelected = true; i.Focus(); } ```
165,443
<p>I have a "span" element inside a "table" "td" element. The span tag has a Title.</p> <p>I want to get the title of that span tag and pull it out to make it the "mouseover" tip for the "td" element.</p> <p>For example:</p> <p>I want to turn this:</p> <pre><code>&lt;td&gt; &lt;a href="#"&gt;&lt;span id="test" title="Acres for each province"&gt;Acres&lt;/span&gt;&lt;/a&gt; &lt;/td&gt; </code></pre> <p>Into this:</p> <pre><code>&lt;td onmouseover="tip(Acres for each province)"&gt; &lt;a href="#"&gt;&lt;span id="test"&gt;Acres&lt;/span&gt;&lt;/a&gt; &lt;/td&gt; </code></pre> <p><strong>EDIT:</strong> I don't think you guys understand. I am trying to put the onmouseover function into the "td" tag. I am NOT trying to put it into the "span" tag.</p>
[ { "answer_id": 165449, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 1, "selected": false, "text": "<p>something like:</p>\n\n<pre><code>$(\"span#test\").mouseover( function () {\n tip($(this).attr(\"title\"));\n}\n</code></pre>\n" }, { "answer_id": 165450, "author": "Nick Sergeant", "author_id": 22468, "author_profile": "https://Stackoverflow.com/users/22468", "pm_score": -1, "selected": false, "text": "<p>With jQuery:</p>\n\n<pre><code>$('#test').attr('title')\n</code></pre>\n" }, { "answer_id": 165532, "author": "Bob Somers", "author_id": 1384, "author_profile": "https://Stackoverflow.com/users/1384", "pm_score": 4, "selected": true, "text": "<p>Based on your edit, you might check out jQuery's DOM traversal methods: <a href=\"http://docs.jquery.com/Traversing\" rel=\"noreferrer\">http://docs.jquery.com/Traversing</a></p>\n\n<p>Something along these lines (not tested, I don't claim it's syntactically correct, just general ideas here)...</p>\n\n<pre><code>$(\"td\").each(function()\n{\n $(this).mouseover(function()\n {\n tip($(this).children(\"span\").attr(\"title\"));\n });\n});\n</code></pre>\n" }, { "answer_id": 165536, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 0, "selected": false, "text": "<p>If you cant put a class on the td or select it in some way then start by selecting the span, then go to the span's grandparent and attach to the mouseover:</p>\n\n<pre><code>// get each span with id = test\n$(\"span#test\").each(function(){\n var $this = $(this);\n // attach to mouseover event of the grandparent (td)\n $this.parent().parent().mouseover( function () {\n tip($this.attr(\"title\"));\n }\n);\n</code></pre>\n" }, { "answer_id": 172374, "author": "matdumsa", "author_id": 1775, "author_profile": "https://Stackoverflow.com/users/1775", "pm_score": 0, "selected": false, "text": "<p>Ok, I'll try it too :P</p>\n\n<pre><code>$(\"#yourTable\").find(\"td\").over(function()\n { generateTip($(this).find(\"span:first\").attr(\"title\") }\n , function() { removeTip() }\n)\n</code></pre>\n\n<p>What this does:</p>\n\n<ul>\n<li>Get the table with id yourTable</li>\n<li>Select all its td</li>\n<li>insert a mouseover and mouseout event</li>\n<li>mouseover event : call the generateTip function with the title value of the first span in that td</li>\n<li>mouseout event : call the removeTip() (optionnal) function.</li>\n</ul>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7644/" ]
I have a "span" element inside a "table" "td" element. The span tag has a Title. I want to get the title of that span tag and pull it out to make it the "mouseover" tip for the "td" element. For example: I want to turn this: ``` <td> <a href="#"><span id="test" title="Acres for each province">Acres</span></a> </td> ``` Into this: ``` <td onmouseover="tip(Acres for each province)"> <a href="#"><span id="test">Acres</span></a> </td> ``` **EDIT:** I don't think you guys understand. I am trying to put the onmouseover function into the "td" tag. I am NOT trying to put it into the "span" tag.
Based on your edit, you might check out jQuery's DOM traversal methods: <http://docs.jquery.com/Traversing> Something along these lines (not tested, I don't claim it's syntactically correct, just general ideas here)... ``` $("td").each(function() { $(this).mouseover(function() { tip($(this).children("span").attr("title")); }); }); ```
165,445
<p>I have a function that includes a file based on the string that gets passed to it i.e. the action variable from the query string. I use this for filtering purposes etc so people can't include files they shouldn't be able to and if the file doesn't exist a default file is loaded instead. The problem is that when the function runs and includes the file scope, is lost because the include ran inside a function. This becomes a problem because I use a global configuration file, then I use specific configuration files for each module on the site. The way I'm doing it at the moment is defining the variables I want to be able to use as global and then adding them into the top of the filtering function.</p> <p>Is there any easier way to do this, i.e. by preserving scope when a function call is made or is there such a thing as PHP macros?</p> <p><strong>Edit:</strong> Would it be better to use extract($_GLOBALS); inside my function call instead?</p> <p><strong>Edit 2:</strong> For anyone that cared. I realised I was over thinking the problem altogether and that instead of using a function I should just use an include, duh! That way I can keep my scope and have my cake too.</p>
[ { "answer_id": 165448, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 3, "selected": false, "text": "<p><strong>Edit:</strong> Okay, I've re-read your question and I think I get what you're talking about now:<br>\nyou want something like this to work:</p>\n\n<pre><code>// myInclude.php\n$x = \"abc\";\n\n// -----------------------\n// myRegularFile.php\n\nfunction doInclude() {\n include 'myInclude.php';\n}\n$x = \"A default value\";\ndoInclude();\necho $x; // should be \"abc\", but actually prints \"A default value\"\n</code></pre>\n\n<p>If you are only changing a couple of variables, and you know ahead of time which variables are going to be defined in the include, declare them as <code>global</code> in the <code>doInclude()</code> function.</p>\n\n<p>Alternatively, if each of your includes could define any number of variables, you could put them all into one array:</p>\n\n<pre><code>// myInclude.php\n$includedVars['x'] = \"abc\";\n$includedVars['y'] = \"def\";\n\n// ------------------\n// myRegularFile.php\nfunction doInclude() {\n global $includedVars;\n include 'myInclude.php';\n // perhaps filter out any \"unexpected\" variables here if you want\n}\n\ndoInclude();\nextract($includedVars);\necho $x; // \"abc\"\necho $y; // \"def\"\n</code></pre>\n\n<hr>\n\n<p><em>original answer:</em></p>\n\n<p>this sort of thing is known as \"closures\" and are being introduced in PHP 5.3</p>\n\n<p><a href=\"http://steike.com/code/php-closures/\" rel=\"nofollow noreferrer\">http://steike.com/code/php-closures/</a></p>\n\n<blockquote>\n <p>Would it be better to use extract($_GLOBALS); inside my function call instead?</p>\n</blockquote>\n\n<p>dear lord, no. if you want to access a global variable from inside a function, just use the <code>global</code> keyword. eg:</p>\n\n<pre><code>$x = \"foo\";\nfunction wrong() {\n echo $x;\n}\nfunction right() {\n global $x;\n echo $x;\n}\n\nwrong(); // undefined variable $x\nright(); // \"foo\"\n</code></pre>\n" }, { "answer_id": 165555, "author": "Bob Somers", "author_id": 1384, "author_profile": "https://Stackoverflow.com/users/1384", "pm_score": 0, "selected": false, "text": "<p>When it comes to configuration options (especially file paths and such) I generally just define them with absolute paths using a define(). Something like:</p>\n\n<pre><code>define('MY_CONFIG_PATH', '/home/jschmoe/myfiles/config.inc.php');\n</code></pre>\n\n<p>That way they're always globally accessible regardless of scope changes and unless I migrate to a different file structure it's always able to find everything.</p>\n" }, { "answer_id": 165805, "author": "Grey Panther", "author_id": 1265, "author_profile": "https://Stackoverflow.com/users/1265", "pm_score": 0, "selected": false, "text": "<p>If I understand correctly, you have a code along the lines of:</p>\n\n<pre><code>function do_include($foo) {\n if (is_valid($foo))\n include $foo;\n}\n\ndo_include(@$_GET['foo']);\n</code></pre>\n\n<p>One solution (which may or may not be simple, depending on the codebase) is to move the include out in the global scope:</p>\n\n<pre><code>if (is_valid(@$_GET['foo']))\n include $_GET['foo'];\n</code></pre>\n\n<p>Other workarounds exists (like you mentioned: declaring globals, working with the $_GLOBALS array directly, etc), but the advantage of this solution is that you don't have to remember such conventions in all the included files.</p>\n" }, { "answer_id": 165976, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 0, "selected": false, "text": "<p>Why not return a value from your include and then set the value of the include call to a variable:</p>\n\n<p>config.php</p>\n\n<pre><code>return array(\n 'foo'=&gt;'bar',\n 'x'=&gt;23,\n 'y'=&gt;12\n);\n</code></pre>\n\n<p>script.php</p>\n\n<pre><code>$config = require('config.php');\nvar_dump($config);\n</code></pre>\n\n<p>No need to mess up the place with global variables</p>\n" }, { "answer_id": 178018, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Is there any easier way to do this, i.e. by preserving scope when a function call is made</p>\n</blockquote>\n\n<p>You could use:</p>\n\n<pre><code>function doInclude($file, $args = array()) {\n extract($args);\n include($file);\n}\n</code></pre>\n\n<p>If you don't want to explicitly pass the variables, you could call <code>doInclude</code> with <a href=\"http://docs.php.net/get_defined_vars\" rel=\"nofollow noreferrer\"><code>get_defined_vars</code></a> as argument, eg.:</p>\n\n<pre><code>doInclude('test.template.php', get_defined_vars());\n</code></pre>\n\n<p>Personally I would prefer to pass an explicit array, rather than use this, but it would work.</p>\n" }, { "answer_id": 2657542, "author": "outis", "author_id": 90527, "author_profile": "https://Stackoverflow.com/users/90527", "pm_score": 0, "selected": false, "text": "<p>You can declare variables within the included file as global, ensuring they have global scope:</p>\n\n<pre><code>//inc.php\nglobal $cfg;\n$cfg['foo'] = bar;\n\n//index.php\nfunction get_cfg($cfgFile) {\n if (valid_cfg_file($cfgFile)) {\n include_once($cfgFile);\n }\n}\n...\nget_cfg('inc.php');\necho \"cfg[foo]: $cfg[foo]\\n\";\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11753/" ]
I have a function that includes a file based on the string that gets passed to it i.e. the action variable from the query string. I use this for filtering purposes etc so people can't include files they shouldn't be able to and if the file doesn't exist a default file is loaded instead. The problem is that when the function runs and includes the file scope, is lost because the include ran inside a function. This becomes a problem because I use a global configuration file, then I use specific configuration files for each module on the site. The way I'm doing it at the moment is defining the variables I want to be able to use as global and then adding them into the top of the filtering function. Is there any easier way to do this, i.e. by preserving scope when a function call is made or is there such a thing as PHP macros? **Edit:** Would it be better to use extract($\_GLOBALS); inside my function call instead? **Edit 2:** For anyone that cared. I realised I was over thinking the problem altogether and that instead of using a function I should just use an include, duh! That way I can keep my scope and have my cake too.
**Edit:** Okay, I've re-read your question and I think I get what you're talking about now: you want something like this to work: ``` // myInclude.php $x = "abc"; // ----------------------- // myRegularFile.php function doInclude() { include 'myInclude.php'; } $x = "A default value"; doInclude(); echo $x; // should be "abc", but actually prints "A default value" ``` If you are only changing a couple of variables, and you know ahead of time which variables are going to be defined in the include, declare them as `global` in the `doInclude()` function. Alternatively, if each of your includes could define any number of variables, you could put them all into one array: ``` // myInclude.php $includedVars['x'] = "abc"; $includedVars['y'] = "def"; // ------------------ // myRegularFile.php function doInclude() { global $includedVars; include 'myInclude.php'; // perhaps filter out any "unexpected" variables here if you want } doInclude(); extract($includedVars); echo $x; // "abc" echo $y; // "def" ``` --- *original answer:* this sort of thing is known as "closures" and are being introduced in PHP 5.3 <http://steike.com/code/php-closures/> > > Would it be better to use extract($\_GLOBALS); inside my function call instead? > > > dear lord, no. if you want to access a global variable from inside a function, just use the `global` keyword. eg: ``` $x = "foo"; function wrong() { echo $x; } function right() { global $x; echo $x; } wrong(); // undefined variable $x right(); // "foo" ```
165,455
<p>Just wondering why people like case sensitivity in a programming language? I'm not trying to start a flame war just curious thats all.<br> Personally I have never really liked it because I find my productivity goes down when ever I have tried a language that has case sensitivity, mind you I am slowly warming up/getting used to it now that I'm using C# and F# alot more then I used to.</p> <p>So why do you like it?</p> <p>Cheers </p>
[ { "answer_id": 165459, "author": "Keng", "author_id": 730, "author_profile": "https://Stackoverflow.com/users/730", "pm_score": 1, "selected": false, "text": "<p>It gives you more options.</p>\n\n<p>Bell\nbell\nBEll</p>\n\n<p>are all different.</p>\n\n<p>Besides, it drives the newbies that were just hired nuts trying to find out why the totals aren't coming out right ;o)))</p>\n" }, { "answer_id": 165461, "author": "BlueVoid", "author_id": 193278, "author_profile": "https://Stackoverflow.com/users/193278", "pm_score": 0, "selected": false, "text": "<p>It's useful for distinguishing between types in code.</p>\n\n<p>For example in Java:\nIf it begins with a capital letter, then its probably a class.\nif its ALL_CAPS its probably a constant.</p>\n\n<p>It gives more versatility. </p>\n" }, { "answer_id": 165470, "author": "RedWolves", "author_id": 648, "author_profile": "https://Stackoverflow.com/users/648", "pm_score": 0, "selected": false, "text": "<p>Feels like a more professional way of coding. Shouldn't need the compiler to figure out what you meant.</p>\n" }, { "answer_id": 165472, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 6, "selected": true, "text": "<p>Consistency. Code is more difficult to read if \"foo\", \"Foo\", \"fOO\", and \"fOo\" are considered to be identical.</p>\n\n<p>SOME PEOPLE WOULD WRITE EVERYTHING IN ALL CAPS, MAKING EVERYTHING LESS READABLE.</p>\n\n<p>Case sensitivity makes it easy to use the \"same name\" in different ways, according to a capitalization convention, e.g.,</p>\n\n<pre><code>Foo foo = ... // \"Foo\" is a type, \"foo\" is a variable with that type\n</code></pre>\n" }, { "answer_id": 165475, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 1, "selected": false, "text": "<p>Because now you actually have to type everything in a consistent way. And then things suddenly begin to make sense.</p>\n\n<p>If you have a decent editor - one that features IntelliSense or the same thing by another name - you shouldn't have any problems figuring out case-sensitive namees.</p>\n" }, { "answer_id": 165478, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "<p>I felt the same way as you a long time ago when i used VB3/4 a lot more. Now I work in mainly C#. But now I find the IDE's do a great job of finding the symbols, and giving good intellisense on the different cases. It also gives me more flexibility in my own code as I can have differnt meaning to items with different cases, which I do a lot now.</p>\n" }, { "answer_id": 165480, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>IMHO it's entirely a question of habit. Whichever one you're used to will seem natural and right.</p>\n\n<p>You can come up with plenty of justifications as to why it's good or bad, but none of them hold much water. Eg:</p>\n\n<ul>\n<li>You get more possible identifiers, eg. <code>foo</code> vs <code>Foo</code> vs <code>FOO</code>.</li>\n<li>But having identifiers that differ only in case is not a good idea</li>\n<li>You can encode type-info into a name (eg. <code>FooBar</code>=typename, <code>fooBar</code>=function, <code>foo_bar</code>=variable, <code>FOO_BAR</code>=macro)</li>\n<li>But you can do that anyway with Hungarian notation</li>\n</ul>\n" }, { "answer_id": 165497, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 0, "selected": false, "text": "<p>Also a good habit if your working in Linux where referencing file names is case sensitive. I had to port a Windows ColdFusion application to work in Linux and it was an utter nightmare. Also some databases have case sensitivity turned on, imagine the joy there.</p>\n\n<p>It is good habit though regardless of platform and certainly leads to a more consistent development style.</p>\n" }, { "answer_id": 165512, "author": "Bryan M.", "author_id": 4636, "author_profile": "https://Stackoverflow.com/users/4636", "pm_score": 2, "selected": false, "text": "<p>I believe it enforces consistency, which improves the readability of code, and lets your eye parse out the pieces better.</p>\n\n<pre><code>class Doohickey {\n\n public void doSomethingWith(string things) {\n print(things);\n }\n}\n</code></pre>\n\n<p>Using casing conventions makes that code appear very standarized to any programmer. You can pick out classes, types, methods easily. It would be much harder to do if anyone could capitalize it in any way:</p>\n\n<pre><code>Class DOOHICKEY {\n Public Void dosomethingwith(string Things) {\n Print(things);\n }\n} \n</code></pre>\n\n<p>Not to say that people would write ugly code, but much in the way capitalization and punctuation rules make writing easier to read, case sensitivity or casing standards make code easier to read.</p>\n" }, { "answer_id": 165548, "author": "Joe Brinkman", "author_id": 4820, "author_profile": "https://Stackoverflow.com/users/4820", "pm_score": 3, "selected": false, "text": "<p>Case sensitivity doesn't enforce coding styles or consistency. If you pascal case a constant, the compiler won't complain. It'll just force you to type it in using pascal case every time you use it. I personally find it irritating to have to try and distinguish between two items which only differ in case. It is easy to do in a short block of code, but very difficult to keep straight in a very large block of code. Also notice that the only way people can actually use case sensitivity without going nuts is if they all rigidly follow the same naming conventions. It is the naming convention which added the value, not the case sensitivity.</p>\n" }, { "answer_id": 165559, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": false, "text": "<p>An advantage of VB.NET is that although it is not case-sensitive, the IDE automatically re-formats everything to the \"official\" case for an identifier you are using - so it's easy to be consistent, easy to read.</p>\n\n<p>Disadvantage is that I hate VB-style syntax, and much prefer C-style operators, punctuation and syntax.</p>\n\n<p>In C# I find I'm always hitting Ctrl-Space to save having to use the proper type.</p>\n\n<p>Just because you can name things which only differ by case doesn't mean it's a good idea, because it can lead to misunderstandings if a lot of that leaks out to larger scopes, so I recommend steering clear of it at the application or subsystem-level, but allowing it only internally to a function or method or class.</p>\n" }, { "answer_id": 165577, "author": "raven", "author_id": 4228, "author_profile": "https://Stackoverflow.com/users/4228", "pm_score": 2, "selected": false, "text": "<p>Case sensitivity is madness! What sort of insane coder would use variables named foo, foO, fOo, and fOO all in the same scope? You'll never convince me that there is a reason for case sensitivity!</p>\n" }, { "answer_id": 165617, "author": "Jacob Krall", "author_id": 3140, "author_profile": "https://Stackoverflow.com/users/3140", "pm_score": 2, "selected": false, "text": "<p>I maintain an internal compiler for my company, and am tempted to make it a hybrid - you can use whatever case you want for an identifier, and you have to refer to it with the same casing, but naming something else with the same name and different case will cause an error.</p>\n\n<pre>Dim abc = 1\nDim y = Abc - 1 ' error, case doesn't match \"abc\"\nDim ABC = False ' error, can't redeclare variable \"abc\"\n</pre>\n\n<p>It's currently case-insensitive, so I could probably fix the few existing errors and nobody would complain too much...</p>\n" }, { "answer_id": 165633, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I believe it is important that you understand the difference between what case sensitivity is and what readability is to properly answer this. While having different casing strategies is useful, you can have them within a language that isn't case sensitive. </p>\n\n<p>For example foo can be used for a variable and FOO as a constant in both java and VB. There is the minor difference that VB will allow you to type fOo later on, but this is mostly a matter of readability and hopefully is fixed by some form of code completion.</p>\n\n<p>What can be extremely useful is when you want to have instances of your objects. If you use a consistent naming convention it can become very easy to see where your objects come from. </p>\n\n<p>For example:\nFooBar fooBar = new FooBar();</p>\n\n<p>When only one object of a type is needed, readability is significantly increased as it is immediately apparent what the object is. When multiple instances are needed, you will obviously have to choose new (hopefully meaningful names), but in small code sections it makes a lot of sense to use the Class name with a lowercase first character rather than a system like myFooBar, x, or some other arbitrary value that you'll forget what it does.</p>\n\n<p>Of course all of this is a matter of context, however in this context I'd say 9 times out of 10 it pays off.</p>\n" }, { "answer_id": 165671, "author": "Sundar R", "author_id": 8127, "author_profile": "https://Stackoverflow.com/users/8127", "pm_score": 1, "selected": false, "text": "<p>I think there is also an issue of psychology involved here. We are programmers, we distinguish minutely between things. <code>a</code> is not the same ASCII value as <code>A</code>, and I would feel odd when my compiler considers them the same. This is why, when I type </p>\n\n<pre><code>(list 'a 'b 'c) \n</code></pre>\n\n<p>in LISP (in the REPL), and it responds with</p>\n\n<pre><code>(A B C)\n</code></pre>\n\n<p>My mind immediately exclaims '<em>That's not what I said!</em>'. \nWhen things are not the same, they <em>are</em> different and must be considered so.</p>\n" }, { "answer_id": 165691, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 2, "selected": false, "text": "<p>Many people who like case-<em>sensitivity</em> misunderstand what case-<em>in</em>sensitivity means.</p>\n\n<p>VB .NET is case-insensitive. That doesn't mean that you can declare a variable as abc, then later refer to it as ABC, Abc, and aBc. It means that if you type it as any of those others, the IDE will automatically change it to the correct form.</p>\n\n<p>Case-insensitivity means you can type</p>\n\n<pre><code>dim a as string\n</code></pre>\n\n<p>and VS will automatically change it to the correctly-cased</p>\n\n<pre><code>Dim a As String\n</code></pre>\n\n<p>In practice, this means you almost never have to hit the Shift key, because you can type in all lowercase and let the IDE correct for you.</p>\n\n<p>But C# is not so bad about this as it used to be. Intellisense in C# is much more aggressive than it was in VS 2002 and 2003, so that the keystroke count falls quite a bit.</p>\n" }, { "answer_id": 165695, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 0, "selected": false, "text": "<p>Because it's how natural language works, too.</p>\n" }, { "answer_id": 166218, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 0, "selected": false, "text": "<p>In progamming there's something to be said for case sensitivity, for instance having a public property Foo and a corresponding private/protected field foo. With IntelliSense it's not very hard not to make mistakes.</p>\n\n<p>However in an OS, case sensitivity is just crazy. I really don't want to have a file Foo <em>and</em> foo <em>and</em> fOO in the same directory. This drives me cray everytime i'm doing *nix stuff. </p>\n" }, { "answer_id": 166300, "author": "rshimoda", "author_id": 23297, "author_profile": "https://Stackoverflow.com/users/23297", "pm_score": 0, "selected": false, "text": "<p>For me case sensitivity is just a play on scopes like thisValue for an argument and ThisValue for a public property or function. </p>\n\n<p>More than often you need to use the same variable name (as it represents the same thing) in different scopes and case sensitivity helps you doing this without resorting to prefixes.</p>\n\n<p>Whew, at least we are no longer using Hungarian notation.</p>\n" }, { "answer_id": 183892, "author": "akalenuk", "author_id": 25459, "author_profile": "https://Stackoverflow.com/users/25459", "pm_score": 1, "selected": false, "text": "<p>I usually spend some time with Delphi programming on vacation, and most of the other time I use only C++ and MASM. And one thing's odd: when I'm on Delphi, I don't like case sensitivity, but when I'm on C++ - I do. I like case sensitivity, becouse it makes similar words (functions, variables) look similar, and I like non-case sensitivity because it doesn't put excessive restrictions on syntaxis.</p>\n" }, { "answer_id": 549517, "author": "Tom A", "author_id": 10226, "author_profile": "https://Stackoverflow.com/users/10226", "pm_score": 1, "selected": false, "text": "<p>From\n.NET Framework Developer's Guide\n<a href=\"http://msdn.microsoft.com/en-us/library/ms229043.aspx\" rel=\"nofollow noreferrer\">Capitalization Conventions</a>, Case-Sensitivity: </p>\n\n<blockquote>\n <p>The capitalization guidelines exist\n solely to make identifiers easier to\n read and recognize. Casing cannot be\n used as a means of avoiding name\n collisions between library elements. </p>\n \n <p>Do not assume that all programming\n languages are case-sensitive. They are\n not. Names cannot differ by case\n alone.</p>\n</blockquote>\n" }, { "answer_id": 1747632, "author": "Marc Climent", "author_id": 58791, "author_profile": "https://Stackoverflow.com/users/58791", "pm_score": 0, "selected": false, "text": "<p>After working many years with legacy VBScript ASP code, when we moved to .NET we chose C#, and one of the main reasons was case sensitivity. The old code was unreadable because people didn't follow any convention: code was an unreadable mess (well, poor VBScript IDEs helped on that).</p>\n\n<p>In C# we can define naming conventions and everybody must follow them. If something is not correctly cased, you can rename it (with refactoring, but that's an IDE feature) and there won't be any problem because the class or variable will be named the same way all across the code.</p>\n\n<p>Finally, I think it's much more readable if everything is correctly cased. Maybe it's faster to write without case sensitivity, but from a code reviewing and maintaining point, it's not the best thing because skipping through the code looking for something is easier. For example it's easier to find all the <code>foo</code> strings at a glance than looking for <code>foo</code>, <code>Foo</code>, <code>FOO</code>, <code>FOo</code>...</p>\n" }, { "answer_id": 4684017, "author": "idbrii", "author_id": 79125, "author_profile": "https://Stackoverflow.com/users/79125", "pm_score": 2, "selected": false, "text": "<p>There's a lot of answers here, but I'm surprised no one pointed out the obvious example that also makes fun of a stackoverflow competitor:</p>\n\n<pre><code>expertSexChange != expertsExchange\n</code></pre>\n\n<p>Case is very important when you use camel case variable names.</p>\n" }, { "answer_id": 4684659, "author": "Seva Alekseyev", "author_id": 219159, "author_profile": "https://Stackoverflow.com/users/219159", "pm_score": 0, "selected": false, "text": "<p>Case-insensitive languages don't easily generalize to non-ASCII character sets. Proper case conversion for a language other than English is not a straightforward task, and depends on system locale, among other things.</p>\n" }, { "answer_id": 8906802, "author": "Arafangion", "author_id": 52273, "author_profile": "https://Stackoverflow.com/users/52273", "pm_score": 0, "selected": false, "text": "<p>Case insensitivity is very difficult, unless you restrict the syntax to ascii (or only apply the case insensitivity to the ascii characters), and also you need to restrict the locale.</p>\n\n<p>The rules for determining upper and lower case of characters is neither well defined, nor is it lossless.</p>\n\n<p>Some characters can have more than one 'lowercase' form. Some people will disagree as to what the correct uppercase form should be.</p>\n\n<p>(Some languages and environments allow for almost character to be used in names)</p>\n\n<p>Consider <a href=\"https://stackoverflow.com/questions/3550213/in-c-sharp-what-is-the-difference-between-toupper-and-toupperinvariant\">In C# what is the difference between ToUpper() and ToUpperInvariant()?</a></p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
Just wondering why people like case sensitivity in a programming language? I'm not trying to start a flame war just curious thats all. Personally I have never really liked it because I find my productivity goes down when ever I have tried a language that has case sensitivity, mind you I am slowly warming up/getting used to it now that I'm using C# and F# alot more then I used to. So why do you like it? Cheers
Consistency. Code is more difficult to read if "foo", "Foo", "fOO", and "fOo" are considered to be identical. SOME PEOPLE WOULD WRITE EVERYTHING IN ALL CAPS, MAKING EVERYTHING LESS READABLE. Case sensitivity makes it easy to use the "same name" in different ways, according to a capitalization convention, e.g., ``` Foo foo = ... // "Foo" is a type, "foo" is a variable with that type ```
165,458
<p>Which is the most correct code?</p> <pre><code>if (HttpContext.Current.Response.Cookies[authCookieName] != null) { HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value"; } </code></pre> <p>or </p> <pre><code>if (HttpContext.Current != null) if (HttpContext.Current.Response != null) if (HttpContext.Current.Response.Cookies != null) if (HttpContext.Current.Response.Cookies[authCookieName] != null) HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value"; </code></pre>
[ { "answer_id": 165462, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 5, "selected": true, "text": "<p>If any one of HttpContext, HttpContext.Current, HttpContext.Current.Response, or Http.Current.Response.Cookies is null, you're already in trouble. Let the exception happen and fix your web server.</p>\n" }, { "answer_id": 165467, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 0, "selected": false, "text": "<p>Neither is really more correct, though I would avoid the second, as deeply nested conditionals tend to be hard to understand and maintain.</p>\n\n<p>If you would prefer you get a null pointer exception, use the first. If you want to deal with nulls in another way or silently, use the second (or a refactored version of the second).</p>\n" }, { "answer_id": 165468, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 0, "selected": false, "text": "<p>If you think there's a chance that <code>Current</code>, <code>Response</code>, <code>Cookies</code>, or <code>Cookies[authCookieName]</code> could be <code>null</code>, and you have a reasonable thing to do if any of them are, then the latter's the way to go. If the chances are low, and/or there's nothing you can do if the intermediates are null, go for the former, as it's more concise - the best you could do is to get better logging if you use the expanded example.</p>\n" }, { "answer_id": 165476, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 2, "selected": false, "text": "<p>could try:</p>\n\n<pre><code>if(HttpContext.Current != null &amp;&amp; \n HttpContext.Current.Response != null &amp;&amp; \n HttpContext.Current.Response.Cookies != null &amp;&amp; \n HttpContext.Current.Response.Cookies[authCookieName] != null) \n{\n // do your thing\n}\n</code></pre>\n" }, { "answer_id": 165485, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 1, "selected": false, "text": "<p>HttpContext.Current.Response.Cookies will never be null. The only thing that can cause a null is if the cookie you are expecting doesn't exist, so the first is correct. HttpContext.Current would be null if you weren't accepting a web request though :)</p>\n" }, { "answer_id": 165565, "author": "KristoferA", "author_id": 11241, "author_profile": "https://Stackoverflow.com/users/11241", "pm_score": 3, "selected": false, "text": "<p>Both are good. Assuming that you have already checked everything else that need to be checked first. E.g.:</p>\n\n<pre><code>private bool CheckSuspendersAndBelt()\n{\n try\n {\n //ensure that true is true...\n if (true == true)\n {\n //...and that false is false...\n if (false == false)\n {\n //...and that true and false are not equal...\n if (false != true)\n {\n //don't proceed if we don't have at least one processor\n if (System.Environment.ProcessorCount &gt; 0)\n {\n //and if there is no system directory then something is wrong\n if (System.Environment.SystemDirectory != null)\n {\n //hopefully the code is running under some version of the CLR...\n if (System.Environment.Version != null)\n {\n //we don't want to proceed if we're not in a process...\n if (System.Diagnostics.Process.GetCurrentProcess() != null)\n {\n //and code running without a thread would not be good...\n if (System.Threading.Thread.CurrentThread != null)\n {\n //finally, make sure instantiating an object really results in an object...\n if (typeof(System.Object) == (new System.Object()).GetType())\n {\n //good to go\n return true;\n }\n }\n }\n }\n }\n }\n }\n }\n }\n return false;\n }\n catch\n {\n return false;\n }\n}\n</code></pre>\n\n<p>(sorry, couldn't resist... :) )</p>\n" }, { "answer_id": 165702, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 1, "selected": false, "text": "<p>The first example you gave is more than enough. Like mentioned, if any of the other objects are null there is a problem with ASP.NET.</p>\n\n<pre><code>if (HttpContext.Current.Response.Cookies[authCookieName] != null) {\n HttpContext.Current.Response.Cookies[authCookieName].Value = \"New Value\";\n}\n</code></pre>\n\n<p>But rather than littering your code with these often many checks, you should create some generic functions like <strong>SetCookie</strong>, <strong>GetCookie</strong>, <strong>GetQueryString</strong>, and <strong>GetForm</strong>, etc. which accept the name and value (for Set functions) as parameters, handle the null check, and returns the value or an empty string (for Get Functions). This will make your code much easier to maintain and possibly improve, and if you decide to use something other than Cookies to store/retrieve options in the future, you'll only have to change the functions.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24395/" ]
Which is the most correct code? ``` if (HttpContext.Current.Response.Cookies[authCookieName] != null) { HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value"; } ``` or ``` if (HttpContext.Current != null) if (HttpContext.Current.Response != null) if (HttpContext.Current.Response.Cookies != null) if (HttpContext.Current.Response.Cookies[authCookieName] != null) HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value"; ```
If any one of HttpContext, HttpContext.Current, HttpContext.Current.Response, or Http.Current.Response.Cookies is null, you're already in trouble. Let the exception happen and fix your web server.
165,466
<p>I think this is best asked in the form of a simple example. The following chunk of SQL causes a <em>"DB-Library Error:20049 Severity:4 Message:Data-conversion resulted in overflow"</em> message, but how come? </p> <pre><code>declare @a numeric(18,6), @b numeric(18,6), @c numeric(18,6) select @a = 1.000000, @b = 1.000000, @c = 1.000000 select @a/(@b/@c) go </code></pre> <p>How is this any different to:</p> <pre><code>select 1.000000/(1.000000/1.000000) go </code></pre> <p>which works fine?</p>
[ { "answer_id": 168490, "author": "Patrick Szalapski", "author_id": 7453, "author_profile": "https://Stackoverflow.com/users/7453", "pm_score": 1, "selected": false, "text": "<p>This is just speculation, but could it be that the DBMS doesn't look at the dynamic value of your variables but only the potential values? Thus, a six-decimal numeric divided by a six-decimal numeric could result in a twelve-decimal numeric; in the literal division, the DBMS knows there is no overflow. Still not sure why the DBMS would care, though--shouldn't it return the result of two six-decimal divisions as up to a 18-decimal numeric?</p>\n" }, { "answer_id": 171165, "author": "Brody", "author_id": 17131, "author_profile": "https://Stackoverflow.com/users/17131", "pm_score": 1, "selected": false, "text": "<p>Because you have declared the variables in the first example the result is expected to be of the same declaration (i.e. numeric (18,6)) but it is not.</p>\n\n<p>I have to say that the first one worked in SQL2005 though (returned 1.000000 [The same declared type]) while the second one returned (1.00000000000000000000000 [A total different declaration]).</p>\n" }, { "answer_id": 171863, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 3, "selected": true, "text": "<p>I ran into the same problem the last time I tried to use Sybase (many years ago). Coming from a SQL Server mindset, I didn't realize that Sybase would attempt to coerce the decimals out -- which, mathematically, is what it <strong>should</strong> do. :)</p>\n\n<p>From the <a href=\"http://manuals.sybase.com/onlinebooks/group-as/asg1250e/sqlug/@Generic__BookTextView/34781;pt=35709\" rel=\"nofollow noreferrer\">Sybase manual</a>:</p>\n\n<blockquote>\n <p>Arithmetic overflow errors occur when\n the new type has too few decimal\n places to accommodate the results.</p>\n</blockquote>\n\n<p>And further down:</p>\n\n<blockquote>\n <p>During implicit conversions to numeric\n or decimal types, loss of scale\n generates a scale error. Use the\n arithabort numeric_truncation option\n to determine how serious such an error\n is considered. The default setting,\n arithabort numeric_truncation on,\n aborts the statement that causes the\n error but continues to process other\n statements in the transaction or\n batch. If you set arithabort\n numeric_truncation off, Adaptive\n Server truncates the query results and\n continues processing.</p>\n</blockquote>\n\n<p>So <em>assuming that the loss of precision is acceptable in your scenario</em>, you probably want the following at the beginning of your transaction:</p>\n\n<pre><code>SET ARITHABORT NUMERIC_TRUNCATION OFF\n</code></pre>\n\n<p>And then at the end of your transaction:</p>\n\n<pre><code>SET ARITHABORT NUMERIC_TRUNCATION ON\n</code></pre>\n\n<p>This is what solved it for me those many years ago ... </p>\n" }, { "answer_id": 32738583, "author": "dumle", "author_id": 2116173, "author_profile": "https://Stackoverflow.com/users/2116173", "pm_score": 0, "selected": false, "text": "<p>Not directly related, but could possibly save someone some time with the Arithmetic overflow errors using Sybase ASE (12.5.0.3).</p>\n\n<p>I was setting a few default values in a temporary table which I intended to update later on, and stumbled on to an Arithmetic overflow error.</p>\n\n<pre><code>declare @a numeric(6,3)\n\nselect 0.000 as thenumber into #test --indirect declare\n\nselect @a = ( select thenumber + 100 from #test )\n\nupdate #test set thenumber = @a\n\nselect * from #test\n</code></pre>\n\n<p>Shows the error: </p>\n\n<pre><code>Arithmetic overflow during implicit conversion of NUMERIC value '100.000' to a NUMERIC field .\n</code></pre>\n\n<p>Which in my head should work, but doesn't as the 'thenumber' column wasn't declared ( or indirectly declared as decimal(4,3) ). So you would have to indirectly declare the temp table column with scale and precision to the format you want, as in my case was 000.000.</p>\n\n<pre><code>select 000.000 as thenumber into #test --this solved it\n</code></pre>\n\n<p>Hopefully that saves someone some time :)</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1030/" ]
I think this is best asked in the form of a simple example. The following chunk of SQL causes a *"DB-Library Error:20049 Severity:4 Message:Data-conversion resulted in overflow"* message, but how come? ``` declare @a numeric(18,6), @b numeric(18,6), @c numeric(18,6) select @a = 1.000000, @b = 1.000000, @c = 1.000000 select @a/(@b/@c) go ``` How is this any different to: ``` select 1.000000/(1.000000/1.000000) go ``` which works fine?
I ran into the same problem the last time I tried to use Sybase (many years ago). Coming from a SQL Server mindset, I didn't realize that Sybase would attempt to coerce the decimals out -- which, mathematically, is what it **should** do. :) From the [Sybase manual](http://manuals.sybase.com/onlinebooks/group-as/asg1250e/sqlug/@Generic__BookTextView/34781;pt=35709): > > Arithmetic overflow errors occur when > the new type has too few decimal > places to accommodate the results. > > > And further down: > > During implicit conversions to numeric > or decimal types, loss of scale > generates a scale error. Use the > arithabort numeric\_truncation option > to determine how serious such an error > is considered. The default setting, > arithabort numeric\_truncation on, > aborts the statement that causes the > error but continues to process other > statements in the transaction or > batch. If you set arithabort > numeric\_truncation off, Adaptive > Server truncates the query results and > continues processing. > > > So *assuming that the loss of precision is acceptable in your scenario*, you probably want the following at the beginning of your transaction: ``` SET ARITHABORT NUMERIC_TRUNCATION OFF ``` And then at the end of your transaction: ``` SET ARITHABORT NUMERIC_TRUNCATION ON ``` This is what solved it for me those many years ago ...
165,488
<p>I am trying to install the starling gem on my Windows machine. But, whenever I try to install it I get this error:</p> <pre><code>Building native extensions. This could take a while... ERROR: Error installing starling: ERROR: Failed to build gem native extension. c:/ruby/bin/ruby.exe extconf.rb install starling -- --srcdir= c:\ruby-1.8.7-p72 checking for windows.h... no *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --srcdir=. --curdir --ruby=c:/ruby/bin/ruby Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/eventmachine-0 .12.2 for inspection. Results logged to c:/ruby/lib/ruby/gems/1.8/gems/eventmachine-0.12.2/ext/gem_mak e.out </code></pre> <p>What do I need to install to provide the <code>windows.h</code> header?</p>
[ { "answer_id": 165721, "author": "user6325", "author_id": 6325, "author_profile": "https://Stackoverflow.com/users/6325", "pm_score": 0, "selected": false, "text": "<p>The install seems to be stuck on installing the eventmachine gem.\nThe easiest approach here may be to download and install the eventmachine binary gem for windows <a href=\"http://rubyforge.org/frs/?group_id=1555&amp;release_id=22647\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>Otherwise you will need a compiler. (which I assume you don't have)</p>\n" }, { "answer_id": 166537, "author": "Jeff Waltzer", "author_id": 23513, "author_profile": "https://Stackoverflow.com/users/23513", "pm_score": 0, "selected": false, "text": "<p>I don't know if this will work but someone is working on a one click installer of Ruby under Windows that comes with a C compiler.</p>\n\n<p>See <a href=\"http://github.com/luislavena/rubyinstaller/tree/master\" rel=\"nofollow noreferrer\">http://github.com/luislavena/rubyinstaller/tree/master</a></p>\n" }, { "answer_id": 167250, "author": "Charles Roper", "author_id": 1944, "author_profile": "https://Stackoverflow.com/users/1944", "pm_score": 3, "selected": false, "text": "<p>Gems <strike>is <a href=\"https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken\">somewhat broken</a> on Windows at present</strike> was at the time broken on Windows, but it's fixed now. The following workaround applies to the old One-Click Installer version of Ruby; you should really update to the new MinGW-based <a href=\"http://rubyinstaller.org/\" rel=\"nofollow noreferrer\">RubyInstaller</a> and the <a href=\"http://rubyinstaller.org/add-ons/devkit/\" rel=\"nofollow noreferrer\">DevKit</a> to which the workaround still works, but is more future proof.</p>\n\n<ul>\n<li>Locate a version of the problem gem (in this case it's <strong>eventmachine</strong>) that has a win32 binary. If you look on <a href=\"http://rubyforge.org/frs/?group_id=1555\" rel=\"nofollow noreferrer\">RubyForge</a>, you'll see that the last eventmachine gem to possess a win32 binary is version 0.12.0</li>\n<li><p>Force that version of event machine to install:</p>\n\n<p><code>$ gem install eventmachine --version=0.12.0<br>\nSuccessfully installed eventmachine-0.12.0-x86-mswin32<br>\n1 gem installed<br>\nInstalling ri documentation for eventmachine-0.12.0-x86-mswin32...<br>\nInstalling RDoc documentation for eventmachine-0.12.0-x86-mswin32...</code></p></li>\n<li><p>Now install try installing your original gem again:</p>\n\n<p><code>$ gem install starling<br>\nSuccessfully installed ZenTest-3.10.0<br>\nSuccessfully installed memcache-client-1.5.0<br>\nSuccessfully installed SyslogLogger-1.4.0<br>\nSuccessfully installed starling-0.9.8<br>\n4 gems installed<br>\nInstalling ri documentation for ZenTest-3.10.0...<br>\nInstalling ri documentation for memcache-client-1.5.0...<br>\nInstalling ri documentation for SyslogLogger-1.4.0...<br>\nInstalling ri documentation for starling-0.9.8...<br>\nInstalling RDoc documentation for ZenTest-3.10.0...<br>\nInstalling RDoc documentation for memcache-client-1.5.0...<br>\nInstalling RDoc documentation for SyslogLogger-1.4.0...<br>\nInstalling RDoc documentation for starling-0.9.8...</code></p></li>\n</ul>\n\n<p>Be warned though, if you now run <strong><code>gem update</code></strong> gems will stupidly try and install the latest version of eventmachine which, as we already know, won't build on Windows. This causes gem update to stop completely. See <a href=\"https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken\">this question</a> to find out how to work around <em>this</em> particular annoyance.</p>\n" }, { "answer_id": 364933, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Now that everything is installed, is it possible to get it working under windows? I'm getting a fork() function unimplemented on this machine, because, Windows doesn't have a fork() process. </p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5004/" ]
I am trying to install the starling gem on my Windows machine. But, whenever I try to install it I get this error: ``` Building native extensions. This could take a while... ERROR: Error installing starling: ERROR: Failed to build gem native extension. c:/ruby/bin/ruby.exe extconf.rb install starling -- --srcdir= c:\ruby-1.8.7-p72 checking for windows.h... no *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --srcdir=. --curdir --ruby=c:/ruby/bin/ruby Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/eventmachine-0 .12.2 for inspection. Results logged to c:/ruby/lib/ruby/gems/1.8/gems/eventmachine-0.12.2/ext/gem_mak e.out ``` What do I need to install to provide the `windows.h` header?
Gems is [somewhat broken](https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken) on Windows at present was at the time broken on Windows, but it's fixed now. The following workaround applies to the old One-Click Installer version of Ruby; you should really update to the new MinGW-based [RubyInstaller](http://rubyinstaller.org/) and the [DevKit](http://rubyinstaller.org/add-ons/devkit/) to which the workaround still works, but is more future proof. * Locate a version of the problem gem (in this case it's **eventmachine**) that has a win32 binary. If you look on [RubyForge](http://rubyforge.org/frs/?group_id=1555), you'll see that the last eventmachine gem to possess a win32 binary is version 0.12.0 * Force that version of event machine to install: `$ gem install eventmachine --version=0.12.0 Successfully installed eventmachine-0.12.0-x86-mswin32 1 gem installed Installing ri documentation for eventmachine-0.12.0-x86-mswin32... Installing RDoc documentation for eventmachine-0.12.0-x86-mswin32...` * Now install try installing your original gem again: `$ gem install starling Successfully installed ZenTest-3.10.0 Successfully installed memcache-client-1.5.0 Successfully installed SyslogLogger-1.4.0 Successfully installed starling-0.9.8 4 gems installed Installing ri documentation for ZenTest-3.10.0... Installing ri documentation for memcache-client-1.5.0... Installing ri documentation for SyslogLogger-1.4.0... Installing ri documentation for starling-0.9.8... Installing RDoc documentation for ZenTest-3.10.0... Installing RDoc documentation for memcache-client-1.5.0... Installing RDoc documentation for SyslogLogger-1.4.0... Installing RDoc documentation for starling-0.9.8...` Be warned though, if you now run **`gem update`** gems will stupidly try and install the latest version of eventmachine which, as we already know, won't build on Windows. This causes gem update to stop completely. See [this question](https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken) to find out how to work around *this* particular annoyance.
165,495
<p>How can I detect mouse clicks regardless of the window the mouse is in?</p> <p>Perferabliy in python, but if someone can explain it in any langauge I might be able to figure it out.</p> <p>I found this on microsoft's site: <a href="http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx</a></p> <p>But I don't see how I can detect or pick up the notifications listed.</p> <p>Tried using pygame's pygame.mouse.get_pos() function as follows:</p> <pre><code>import pygame pygame.init() while True: print pygame.mouse.get_pos() </code></pre> <p>This just returns 0,0. I'm not familiar with pygame, is something missing?</p> <p>In anycase I'd prefer a method without the need to install a 3rd party module. (other than pywin32 <a href="http://sourceforge.net/projects/pywin32/" rel="noreferrer">http://sourceforge.net/projects/pywin32/</a> )</p>
[ { "answer_id": 166054, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 2, "selected": false, "text": "<p>The windows way of doing it is to handle the <code>WM_LBUTTONDBLCLK</code> message. </p>\n\n<p>For this to be sent, your window class needs to be created with the <code>CS_DBLCLKS</code> class style.</p>\n\n<p>I'm afraid I don't know how to apply this in Python, but hopefully it might give you some hints.</p>\n" }, { "answer_id": 166144, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 2, "selected": false, "text": "<p>Windows MFC, including GUI programming, is accessible with python using the <a href=\"http://sourceforge.net/projects/pywin32/\" rel=\"nofollow noreferrer\">Python for Windows extensions</a> by Mark Hammond. <a href=\"http://www.onlamp.com/lpt/a/217\" rel=\"nofollow noreferrer\">An O'Reilly Book Excerpt</a> from Hammond's and Robinson's <a href=\"http://oreilly.com/catalog/9781565926219/\" rel=\"nofollow noreferrer\">book</a> shows how to hook mouse messages, .e.g:</p>\n\n<pre><code>self.HookMessage(self.OnMouseMove,win32con.WM_MOUSEMOVE)\n</code></pre>\n\n<p>Raw MFC is not easy or obvious, but searching the web for python examples may yield some usable examples.</p>\n" }, { "answer_id": 168996, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 6, "selected": true, "text": "<p>The only way to detect mouse events outside your program is to install a Windows hook using <a href=\"http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx\" rel=\"noreferrer\">SetWindowsHookEx</a>. The <a href=\"http://www.cs.unc.edu/Research/assist/developer.shtml\" rel=\"noreferrer\">pyHook</a> module encapsulates the nitty-gritty details. Here's a sample that will print the location of every mouse click:</p>\n\n<pre><code>import pyHook\nimport pythoncom\n\ndef onclick(event):\n print event.Position\n return True\n\nhm = pyHook.HookManager()\nhm.SubscribeMouseAllButtonsDown(onclick)\nhm.HookMouse()\npythoncom.PumpMessages()\nhm.UnhookMouse()\n</code></pre>\n\n<p>You can check the <strong>example.py</strong> script that is installed with the module for more info about the <strong>event</strong> parameter.</p>\n\n<p>pyHook might be tricky to use in a pure Python script, because it requires an active message pump. From the <a href=\"https://web.archive.org/web/20100501173949/http://mindtrove.info/articles/monitoring-global-input-with-pyhook/\" rel=\"noreferrer\">tutorial</a>:</p>\n\n<blockquote>\n <p>Any application that wishes to receive\n notifications of global input events\n must have a Windows message pump. The\n easiest way to get one of these is to\n use the PumpMessages method in the\n Win32 Extensions package for Python.\n [...] When run, this program just sits\n idle and waits for Windows events. If\n you are using a GUI toolkit (e.g. \n wxPython), this loop is unnecessary\n since the toolkit provides its own.</p>\n</blockquote>\n" }, { "answer_id": 41930485, "author": "Markacho", "author_id": 6274340, "author_profile": "https://Stackoverflow.com/users/6274340", "pm_score": 4, "selected": false, "text": "<p>I use win32api. It works when clicking on any windows.</p>\n\n<pre><code># Code to check if left or right mouse buttons were pressed\nimport win32api\nimport time\n\nstate_left = win32api.GetKeyState(0x01) # Left button down = 0 or 1. Button up = -127 or -128\nstate_right = win32api.GetKeyState(0x02) # Right button down = 0 or 1. Button up = -127 or -128\n\nwhile True:\n a = win32api.GetKeyState(0x01)\n b = win32api.GetKeyState(0x02)\n\n if a != state_left: # Button state changed\n state_left = a\n print(a)\n if a &lt; 0:\n print('Left Button Pressed')\n else:\n print('Left Button Released')\n\n if b != state_right: # Button state changed\n state_right = b\n print(b)\n if b &lt; 0:\n print('Right Button Pressed')\n else:\n print('Right Button Released')\n time.sleep(0.001)\n</code></pre>\n" }, { "answer_id": 46596592, "author": "diligar", "author_id": 3571147, "author_profile": "https://Stackoverflow.com/users/3571147", "pm_score": 3, "selected": false, "text": "<p>It's been a hot minute since this question was asked, but I thought I'd share my solution: I just used the built-in module <code>ctypes</code>. (I'm using Python 3.3 btw)</p>\n\n<pre><code>import ctypes\nimport time\n\ndef DetectClick(button, watchtime = 5):\n '''Waits watchtime seconds. Returns True on click, False otherwise'''\n if button in (1, '1', 'l', 'L', 'left', 'Left', 'LEFT'):\n bnum = 0x01\n elif button in (2, '2', 'r', 'R', 'right', 'Right', 'RIGHT'):\n bnum = 0x02\n\n start = time.time()\n while 1:\n if ctypes.windll.user32.GetKeyState(bnum) not in [0, 1]:\n # ^ this returns either 0 or 1 when button is not being held down\n return True\n elif time.time() - start &gt;= watchtime:\n break\n time.sleep(0.001)\n return False\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24718/" ]
How can I detect mouse clicks regardless of the window the mouse is in? Perferabliy in python, but if someone can explain it in any langauge I might be able to figure it out. I found this on microsoft's site: <http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx> But I don't see how I can detect or pick up the notifications listed. Tried using pygame's pygame.mouse.get\_pos() function as follows: ``` import pygame pygame.init() while True: print pygame.mouse.get_pos() ``` This just returns 0,0. I'm not familiar with pygame, is something missing? In anycase I'd prefer a method without the need to install a 3rd party module. (other than pywin32 <http://sourceforge.net/projects/pywin32/> )
The only way to detect mouse events outside your program is to install a Windows hook using [SetWindowsHookEx](http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx). The [pyHook](http://www.cs.unc.edu/Research/assist/developer.shtml) module encapsulates the nitty-gritty details. Here's a sample that will print the location of every mouse click: ``` import pyHook import pythoncom def onclick(event): print event.Position return True hm = pyHook.HookManager() hm.SubscribeMouseAllButtonsDown(onclick) hm.HookMouse() pythoncom.PumpMessages() hm.UnhookMouse() ``` You can check the **example.py** script that is installed with the module for more info about the **event** parameter. pyHook might be tricky to use in a pure Python script, because it requires an active message pump. From the [tutorial](https://web.archive.org/web/20100501173949/http://mindtrove.info/articles/monitoring-global-input-with-pyhook/): > > Any application that wishes to receive > notifications of global input events > must have a Windows message pump. The > easiest way to get one of these is to > use the PumpMessages method in the > Win32 Extensions package for Python. > [...] When run, this program just sits > idle and waits for Windows events. If > you are using a GUI toolkit (e.g. > wxPython), this loop is unnecessary > since the toolkit provides its own. > > >
165,551
<p>I would like to know if there is an easy way to detect if the text on the clipboard is in ISO 8859 or UTF-8 ?</p> <p>Here is my current code:</p> <pre><code> COleDataObject obj; if (obj.AttachClipboard()) { if (obj.IsDataAvailable(CF_TEXT)) { HGLOBAL hmem = obj.GetGlobalData(CF_TEXT); CMemFile sf((BYTE*) ::GlobalLock(hmem),(UINT) ::GlobalSize(hmem)); CString buffer; LPSTR str = buffer.GetBufferSetLength((int)::GlobalSize(hmem)); sf.Read(str,(UINT) ::GlobalSize(hmem)); ::GlobalUnlock(hmem); //this is my string class s-&gt;SetEncoding(ENCODING_8BIT); s-&gt;SetString(buffer); } } } </code></pre>
[ { "answer_id": 165568, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 0, "selected": false, "text": "<p>You could check to see obj.IsDataAvailable(CF_UNICODETEXT) to see if a unicode version of what's on the clipboard is available. </p>\n\n<p>-Adam</p>\n" }, { "answer_id": 165570, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>UTF-8 has a defined structure for non-ASCII bytes. You can scan for bytes >= 128, and if any are detected, check if they form a valid UTF-8 string.</p>\n\n<p>The valid UTF-8 byte formats can be found on <a href=\"http://en.wikipedia.org/wiki/UTF-8\" rel=\"nofollow noreferrer\">Wikipedia</a>:</p>\n\n<pre><code>Unicode Byte1 Byte2 Byte3 Byte4\nU+000000-U+00007F 0xxxxxxx\nU+000080-U+0007FF 110xxxxx 10xxxxxx\nU+000800-U+00FFFF 1110xxxx 10xxxxxx 10xxxxxx\nU+010000-U+10FFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n</code></pre>\n\n<hr>\n\n<p>old answer:</p>\n\n<p>You don't have to -- all ASCII text is valid UTF-8, so you can just decode it as UTF-8 and it will work as expected.</p>\n\n<p>To test if it contains non-ASCII characters, you can scan for bytes >= 128.</p>\n" }, { "answer_id": 165788, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "<p>I can be mistaken, but I think you cannot: if I open an UTF-8 file without Bom in my editor, it is displayed by default as ISO-8859-1 (my locale), and beside some strange use of foreign (for me) accented chars, I have no strong visual hint that it is UTF-8 (unless it is encoded in another way elsewhere, eg. charset declaration in HTML or XML): it is perfectly valid Ansi text.</p>\n\n<p>John wrote \"all ASCII text is valid UTF-8\" but the reverse is true.</p>\n\n<p>Windows XP+ uses naturally UTF-16, and have a clipboard format for it, but AFAIK it just ignore UTF-8, with no special treatment for it.<br>\n(Well, there is an API to convert UTF-8 to UTF-16 (or Ansi, etc.), actually).</p>\n" }, { "answer_id": 167045, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 3, "selected": true, "text": "<p>Check out the definition of CF_LOCALE at <a href=\"http://msdn.microsoft.com/en-us/library/ms649013(VS.85).aspx\" rel=\"nofollow noreferrer\">this Microsoft page</a>. It tells you the locale of the text in the clipboard. Better yet, if you use CF_UNICODETEXT instead, Windows will convert to UTF-16 for you.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
I would like to know if there is an easy way to detect if the text on the clipboard is in ISO 8859 or UTF-8 ? Here is my current code: ``` COleDataObject obj; if (obj.AttachClipboard()) { if (obj.IsDataAvailable(CF_TEXT)) { HGLOBAL hmem = obj.GetGlobalData(CF_TEXT); CMemFile sf((BYTE*) ::GlobalLock(hmem),(UINT) ::GlobalSize(hmem)); CString buffer; LPSTR str = buffer.GetBufferSetLength((int)::GlobalSize(hmem)); sf.Read(str,(UINT) ::GlobalSize(hmem)); ::GlobalUnlock(hmem); //this is my string class s->SetEncoding(ENCODING_8BIT); s->SetString(buffer); } } } ```
Check out the definition of CF\_LOCALE at [this Microsoft page](http://msdn.microsoft.com/en-us/library/ms649013(VS.85).aspx). It tells you the locale of the text in the clipboard. Better yet, if you use CF\_UNICODETEXT instead, Windows will convert to UTF-16 for you.
165,571
<p>I have a list of times in a database column (representing visits to a website).</p> <p>I need to group them in intervals and then get a 'cumulative frequency' table of those dates.</p> <p>For instance I might have:</p> <pre><code>9:01 9:04 9:11 9:13 9:22 9:24 9:28 </code></pre> <p>and i want to convert that into</p> <pre><code>9:05 - 2 9:15 - 4 9:25 - 6 9:30 - 7 </code></pre> <p>How can I do that? Can i even easily achieve this in SQL? I can quite easily do it in C#</p>
[ { "answer_id": 165610, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 1, "selected": false, "text": "<p>Create a table <code>periods</code> describing the periods you wish to divide the day up into.</p>\n\n<pre><code>SELECT periods.name, count(time)\n FROM periods, times\n WHERE period.start &lt;= times.time\n AND times.time &lt; period.end\n GROUP BY periods.name\n</code></pre>\n" }, { "answer_id": 165613, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 2, "selected": false, "text": "<p>I should point out that based on the stated \"intent\" of the problem, to do analysis on visitor traffic - I wrote this statement to summarize the counts in uniform groups.</p>\n\n<p>To do otherwise (as in the \"example\" groups) would be comparing the counts during a 5 minute interval to counts in a 10 minute interval - which doesn't make sense.</p>\n\n<p>You have to grok to the \"intent\" of the user requirement, not the literal \"reading\" of it. :-)</p>\n\n<pre><code> create table #myDates\n (\n myDate datetime\n );\n go\n\n insert into #myDates values ('10/02/2008 09:01:23');\n insert into #myDates values ('10/02/2008 09:03:23');\n insert into #myDates values ('10/02/2008 09:05:23');\n insert into #myDates values ('10/02/2008 09:07:23');\n insert into #myDates values ('10/02/2008 09:11:23');\n insert into #myDates values ('10/02/2008 09:14:23');\n insert into #myDates values ('10/02/2008 09:19:23');\n insert into #myDates values ('10/02/2008 09:21:23');\n insert into #myDates values ('10/02/2008 09:21:23');\n insert into #myDates values ('10/02/2008 09:21:23');\n insert into #myDates values ('10/02/2008 09:21:23');\n insert into #myDates values ('10/02/2008 09:21:23');\n insert into #myDates values ('10/02/2008 09:26:23');\n insert into #myDates values ('10/02/2008 09:27:23');\n insert into #myDates values ('10/02/2008 09:29:23');\n go\n\n declare @interval int;\n set @interval = 10;\n\n select\n convert(varchar(5), dateadd(minute,@interval - datepart(minute, myDate) % @interval, myDate), 108) timeGroup,\n count(*)\n from\n #myDates\n group by\n convert(varchar(5), dateadd(minute,@interval - datepart(minute, myDate) % @interval, myDate), 108)\n\nretuns:\n\ntimeGroup \n--------- ----------- \n09:10 4 \n09:20 3 \n09:30 8 \n</code></pre>\n" }, { "answer_id": 165618, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "<p>This uses quite a few SQL tricks (SQL Server 2005):</p>\n\n<pre><code>CREATE TABLE [dbo].[stackoverflow_165571](\n [visit] [datetime] NOT NULL\n) ON [PRIMARY]\nGO\n\n;WITH buckets AS (\n SELECT dateadd(mi, (1 + datediff(mi, 0, visit - 1 - dateadd(dd, 0, datediff(dd, 0, visit))) / 5) * 5, 0) AS visit_bucket\n ,COUNT(*) AS visit_count\n FROM stackoverflow_165571\n GROUP BY dateadd(mi, (1 + datediff(mi, 0, visit - 1 - dateadd(dd, 0, datediff(dd, 0, visit))) / 5) * 5, 0)\n)\nSELECT LEFT(CONVERT(varchar, l.visit_bucket, 8), 5) + ' - ' + CONVERT(varchar, SUM(r.visit_count))\nFROM buckets l\nLEFT JOIN buckets r\n ON r.visit_bucket &lt;= l.visit_bucket\nGROUP BY l.visit_bucket\nORDER BY l.visit_bucket\n</code></pre>\n\n<p>Note that it puts all the times on the same day, and assumes they are in a datetime column. The only thing it doesn't do as your example does is strip the leading zeroes from the time representation.</p>\n" }, { "answer_id": 165631, "author": "ManiacZX", "author_id": 18148, "author_profile": "https://Stackoverflow.com/users/18148", "pm_score": 1, "selected": false, "text": "<p>Create a table containing what intervals you want to be getting totals at then join the two tables together.</p>\n\n<p>Such as:</p>\n\n<pre><code>time_entry.time_entry\n-----------------------\n2008-10-02 09:01:00.000\n2008-10-02 09:04:00.000\n2008-10-02 09:11:00.000\n2008-10-02 09:13:00.000\n2008-10-02 09:22:00.000\n2008-10-02 09:24:00.000\n2008-10-02 09:28:00.000\n\ntime_interval.time_end\n-----------------------\n2008-10-02 09:05:00.000\n2008-10-02 09:15:00.000\n2008-10-02 09:25:00.000\n2008-10-02 09:30:00.000\n\nSELECT \n ti.time_end, \n COUNT(*) AS 'interval_total' \nFROM time_interval ti\nINNER JOIN time_entry te\n ON te.time_entry &lt; ti.time_end\nGROUP BY ti.time_end;\n\n\ntime_end interval_total\n----------------------- -------------\n2008-10-02 09:05:00.000 2\n2008-10-02 09:15:00.000 4\n2008-10-02 09:25:00.000 6\n2008-10-02 09:30:00.000 7\n</code></pre>\n\n<p>If instead of wanting cumulative totals you wanted totals within a range, then you add a time_start column to the time_interval table and change the query to</p>\n\n<pre><code>SELECT \n ti.time_end, \n COUNT(*) AS 'interval_total' \nFROM time_interval ti\nINNER JOIN time_entry te\n ON te.time_entry &gt;= ti.time_start\n AND te.time_entry &lt; ti.time_end\nGROUP BY ti.time_end;\n</code></pre>\n" }, { "answer_id": 165638, "author": "KristoferA", "author_id": 11241, "author_profile": "https://Stackoverflow.com/users/11241", "pm_score": 3, "selected": false, "text": "<pre><code>create table accu_times (time_val datetime not null, constraint pk_accu_times primary key (time_val));\ngo\n\ninsert into accu_times values ('9:01');\ninsert into accu_times values ('9:05');\ninsert into accu_times values ('9:11');\ninsert into accu_times values ('9:13');\ninsert into accu_times values ('9:22');\ninsert into accu_times values ('9:24');\ninsert into accu_times values ('9:28'); \ngo\n\nselect rounded_time,\n (\n select count(*)\n from accu_times as at2\n where at2.time_val &lt;= rt.rounded_time\n ) as accu_count\nfrom (\nselect distinct\n dateadd(minute, round((datepart(minute, at.time_val) + 2)*2, -1)/2,\n dateadd(hour, datepart(hour, at.time_val), 0)\n ) as rounded_time\nfrom accu_times as at\n) as rt\ngo\n\ndrop table accu_times\n</code></pre>\n\n<p>Results in:</p>\n\n<pre><code>rounded_time accu_count\n----------------------- -----------\n1900-01-01 09:05:00.000 2\n1900-01-01 09:15:00.000 4\n1900-01-01 09:25:00.000 6\n1900-01-01 09:30:00.000 7\n</code></pre>\n" }, { "answer_id": 166534, "author": "dland", "author_id": 18625, "author_profile": "https://Stackoverflow.com/users/18625", "pm_score": 2, "selected": false, "text": "<p>ooh, way too complicated all of that stuff.</p>\n\n<p>Normalise to seconds, divide by your bucket interval, truncate and remultiply:</p>\n\n<pre><code>select sec_to_time(floor(time_to_sec(d)/300)*300), count(*)\nfrom d\ngroup by sec_to_time(floor(time_to_sec(d)/300)*300)\n</code></pre>\n\n<p>Using Ron Savage's data, I get</p>\n\n<pre><code>+----------+----------+\n| i | count(*) |\n+----------+----------+\n| 09:00:00 | 1 |\n| 09:05:00 | 3 |\n| 09:10:00 | 1 |\n| 09:15:00 | 1 |\n| 09:20:00 | 6 |\n| 09:25:00 | 2 |\n| 09:30:00 | 1 |\n+----------+----------+\n</code></pre>\n\n<p>You may wish to use ceil() or round() instead of floor().</p>\n\n<p>Update: for a table created with</p>\n\n<pre><code>create table d (\n d datetime\n);\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24727/" ]
I have a list of times in a database column (representing visits to a website). I need to group them in intervals and then get a 'cumulative frequency' table of those dates. For instance I might have: ``` 9:01 9:04 9:11 9:13 9:22 9:24 9:28 ``` and i want to convert that into ``` 9:05 - 2 9:15 - 4 9:25 - 6 9:30 - 7 ``` How can I do that? Can i even easily achieve this in SQL? I can quite easily do it in C#
``` create table accu_times (time_val datetime not null, constraint pk_accu_times primary key (time_val)); go insert into accu_times values ('9:01'); insert into accu_times values ('9:05'); insert into accu_times values ('9:11'); insert into accu_times values ('9:13'); insert into accu_times values ('9:22'); insert into accu_times values ('9:24'); insert into accu_times values ('9:28'); go select rounded_time, ( select count(*) from accu_times as at2 where at2.time_val <= rt.rounded_time ) as accu_count from ( select distinct dateadd(minute, round((datepart(minute, at.time_val) + 2)*2, -1)/2, dateadd(hour, datepart(hour, at.time_val), 0) ) as rounded_time from accu_times as at ) as rt go drop table accu_times ``` Results in: ``` rounded_time accu_count ----------------------- ----------- 1900-01-01 09:05:00.000 2 1900-01-01 09:15:00.000 4 1900-01-01 09:25:00.000 6 1900-01-01 09:30:00.000 7 ```
165,575
<p>I have the simple class using auto-implemented properies: </p> <pre><code>Public Class foo { public foo() { } public string BarName {get; set;} } </code></pre> <p>I obviously use the variable BarName throughout my class and now need to add logic when the property value is set (it must be all upper case, go figure). Does this mean that I need to now create a private variable for BarName , e.g. _BarName, and change the current BarName variable used throughout my class to _BarName? </p> <pre><code>Public Class foo { public foo() {} private string _BarName = ""; public string BarName { get {return _BarName;} set {_BarName = Value.ToString().ToUpper();} } } </code></pre> <p>I am trying to make sure I understand the implications of using auto-implemented properties, and what it will entail down the road when/if I need to change something. I am assuming that the refactoring, as shown above, is not a <a href="http://blogs.msdn.com/abhinaba/archive/2006/04/11/572694.aspx" rel="nofollow noreferrer">breaking</a> change because the property is basically staying the same; it just took a little work inside the class to keep it that way and add the needed logic. </p> <p>Another example, which may be more meaningful is that I need to call some method when a setter or getter is used; more then changing the value. </p> <p>This seems a fair trade off the the lines and lines of code to setup properties. </p>
[ { "answer_id": 165581, "author": "Seth Petry-Johnson", "author_id": 23632, "author_profile": "https://Stackoverflow.com/users/23632", "pm_score": 3, "selected": false, "text": "<p>You don't need to change anything. Auto-implemented properties are just syntactic sugar. The compiler is generating the private variable and get/set logic for you, behind the scenes. If you add your own getter/setter logic the compiler will use your code instead of its auto-generated code, but as far as the <em>users</em> of that property are concerned, nothing has changed; any code referencing your property will continue to work.</p>\n" }, { "answer_id": 165587, "author": "Hamish Smith", "author_id": 15572, "author_profile": "https://Stackoverflow.com/users/15572", "pm_score": 0, "selected": false, "text": "<p>You are correct about the refactoring and it really shouldn't break anything.</p>\n\n<p>Whether or not you actually need to go through the references within the class to the property name and change those to refer to the private field would depend on whether the internal code needed to access the underlying representation of the data rather than how it was presented to consumers of the class. In most cases you could leave well enough alone. </p>\n\n<p>In your simple example it would be wise to leave well enough alone and ensure that no code internal to the class could subvert the conversion/formatting being performed in the setter.</p>\n\n<p>If on the other hand the getter was doing some magic to change the internal representation of the field into the way consumers needed to view the data then perhaps (in some cases) the internal code within the class would need to access the field. </p>\n\n<p>You would need to look at each occurrence of the access to the auto-property in the class and decide whether it should be touching the field or using the property.</p>\n" }, { "answer_id": 165588, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 3, "selected": false, "text": "<p>When using automatic properties you don't get direct access to the underlying \"backing\" variable and you don't get access to the actual logic that gets implemented in the property getter and setter. You only have access to the property (hence using BarName throughout your code).</p>\n\n<p>If you now need to implement specific logic in the setter, you can no longer use automatic properties and need to implement the property in the \"old fashioned\" way. In this case, you would need to implement your own private backing variable (the preferred method, at least for me, is to name the private backing variable the same name as the property, but with an initial lowercase (in this case, the backing variable would be named barName). You would then implement the appropriate logic in the getter/setter.</p>\n\n<p>In your example, you are correct that it is not a breaking change. This type of refactoring (moving from automatic properties to \"normal\" properties should never be a breaking change as you aren't changing the public interface (the name or accessibility of the public property).</p>\n" }, { "answer_id": 165592, "author": "David Lay", "author_id": 6359, "author_profile": "https://Stackoverflow.com/users/6359", "pm_score": 0, "selected": false, "text": "<p>Automatic properties are just syntactic sugar, the compiler in fact creates the private member for it, but since it's generated at compile time, you cannot access it. </p>\n\n<p>And later on, if you want to implement getters and setters for the property, only then you create a explicit private member for it and add the logic.</p>\n" }, { "answer_id": 165604, "author": "hurst", "author_id": 10991, "author_profile": "https://Stackoverflow.com/users/10991", "pm_score": 4, "selected": true, "text": "<blockquote>\n <p>Does this mean that I need to now\n create a private variable for BarName</p>\n</blockquote>\n\n<p>Yes</p>\n\n<blockquote>\n <p>and change the current BarName\n variable used throughout my class</p>\n</blockquote>\n\n<p>Do not change the rest of the code in your class to use the new private variable you create. <em>BarName</em>, as a property, is intended to hide the private variable (among other things), for the purpose of avoiding the sweeping changes you contemplate to the rest of your code.</p>\n\n<blockquote>\n <p>I am assuming that the refactoring, as\n shown above, is not a breaking change\n because the property is basically\n staying the same; it just took a\n little work to keep it that way and\n add the needed logic.</p>\n</blockquote>\n\n<p>Correct.</p>\n" }, { "answer_id": 165708, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 1, "selected": false, "text": "<p>Don't use automatic properties if you know that you are going to validate that object. These objects can be domain objects etc. Like if you have a Customer class then use private variables because you might need to validate the name, birthdate etc. But if you are using a Rss class then it will be okay to just use the automatic properties since there is no validation being perform and the class is just used to hold some data. </p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5836/" ]
I have the simple class using auto-implemented properies: ``` Public Class foo { public foo() { } public string BarName {get; set;} } ``` I obviously use the variable BarName throughout my class and now need to add logic when the property value is set (it must be all upper case, go figure). Does this mean that I need to now create a private variable for BarName , e.g. \_BarName, and change the current BarName variable used throughout my class to \_BarName? ``` Public Class foo { public foo() {} private string _BarName = ""; public string BarName { get {return _BarName;} set {_BarName = Value.ToString().ToUpper();} } } ``` I am trying to make sure I understand the implications of using auto-implemented properties, and what it will entail down the road when/if I need to change something. I am assuming that the refactoring, as shown above, is not a [breaking](http://blogs.msdn.com/abhinaba/archive/2006/04/11/572694.aspx) change because the property is basically staying the same; it just took a little work inside the class to keep it that way and add the needed logic. Another example, which may be more meaningful is that I need to call some method when a setter or getter is used; more then changing the value. This seems a fair trade off the the lines and lines of code to setup properties.
> > Does this mean that I need to now > create a private variable for BarName > > > Yes > > and change the current BarName > variable used throughout my class > > > Do not change the rest of the code in your class to use the new private variable you create. *BarName*, as a property, is intended to hide the private variable (among other things), for the purpose of avoiding the sweeping changes you contemplate to the rest of your code. > > I am assuming that the refactoring, as > shown above, is not a breaking change > because the property is basically > staying the same; it just took a > little work to keep it that way and > add the needed logic. > > > Correct.
165,595
<p>I have a Flex app that does a a fair amount of network traffic, it uses ExternalInterface to make some javascript calls (for SCORM), it loads XML files, images, video, audio and it has a series of modules that it could be loading at some point...</p> <p>So the problem is - we now have a requirement where the user needs to run this content locally on a machine that is not connected to the internet (which means they can't connect to Adobe's site to change their security settings.) As you can imagine, when the user doubles clicks on the html page to launch this thing, they are greeted with a security warning that the swf is trying to communicate with another domain other than the one it's in. We can't wrap it in an exe or an AIR app so I unless there is some way to tweak some obscure security settings we may be hosed. Any idea's?</p>
[ { "answer_id": 165680, "author": "jdecuyper", "author_id": 296, "author_profile": "https://Stackoverflow.com/users/296", "pm_score": -1, "selected": false, "text": "<p>Did you try to specify the authorized domain with:</p>\n\n<pre><code>System.security.allowDomain(\"www.yourdomain.com\");\n</code></pre>\n" }, { "answer_id": 166219, "author": "matt lohkamp", "author_id": 14026, "author_profile": "https://Stackoverflow.com/users/14026", "pm_score": 0, "selected": false, "text": "<p>I hesitate to say \"you can't do it\", but in my experience, there's no way to do what you're describing. Anyone, if I'm wrong, I'd love to know the trick.</p>\n" }, { "answer_id": 170471, "author": "imaginaryboy", "author_id": 2508, "author_profile": "https://Stackoverflow.com/users/2508", "pm_score": 0, "selected": false, "text": "<p>Sorry that I haven't actually tried this to see if it works or not ... but ...</p>\n\n<p>Page 20 (and/or 26) of <a href=\"http://www.adobe.com/devnet/flashplayer/articles/flash_player_9_security.pdf\" rel=\"nofollow noreferrer\">this</a> document may be of help. The document is referenced <a href=\"http://livedocs.adobe.com/flex/3/html/help.html?content=security2_25.html\" rel=\"nofollow noreferrer\">here</a>. In a nutshell it describes directories which contain cfg files which in turn contain lists of locations on disk which should be regarded as trusted. An installer for the application would then be responsible for creating appropriate .cfg files in the desired location (global or for the installing user).</p>\n" }, { "answer_id": 175546, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The short answer is that if your swf is compiled with use-network to true, it isn't going to work.</p>\n\n<p>Is it possible to compile a version with use-network to false? Or is it running on an Intranet that is closed off from the Internet and still communicating with the LMS?</p>\n" }, { "answer_id": 198038, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 4, "selected": true, "text": "<p>What you are trying to do is exactly the problem solved by AIR. You should really give it a try, it's not that hard to pick up. If you really really can't use AIR (you didn't specify why, so I assume it's just because you don't want to have to learn a new system), then modifying the security config file will solve the problem.</p>\n\n<p>Basically what you need to do is create a 'trust' file in the \"Global FlashPlayerTrust\" directory. This can be done by your installer (which installs all the javascript, SWF, html, etc files onto the local machine). You should create the directory if it does not exist. The directory for each OS is:</p>\n\n<ul>\n<li>Windows - %WINDIR%\\System32\\Macromed\\Flash\\FlashPlayerTrust</li>\n<li>Mac - /Library/Application Support/Macromedia/FlashPlayerTrust</li>\n<li>Linux - /etc/adobe/FlashPlayerTrust</li>\n</ul>\n\n<p>Next, you need to create the trust file. You can name it anything, so pick a unique name that would be unlikely to conflict with others. Something like CompanyName.cfg. It's a text file, with one path per line. You can trust either one SWF at a time, or an entire directory. Example:</p>\n\n<pre><code>C:\\Program Files\\MyCompany\\CoolApp\nC:\\Program Files\\MyCompany\\OtherApp\\Main.swf\n</code></pre>\n\n<p>To test that it's working, inside your flash movie you can check <code>System.security.sandboxType</code> (ActionScript 1 or 2), or <code>Security.sandboxType</code> (ActionScript 3). It should have the value of \"<code>localTrusted</code>\"</p>\n" }, { "answer_id": 2325123, "author": "Syam Lal S.", "author_id": 280219, "author_profile": "https://Stackoverflow.com/users/280219", "pm_score": 0, "selected": false, "text": "<p>It is possible. Please chek that the swfs you are calling from the main swf have the \"Access local files only\" property enabled or not.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3435/" ]
I have a Flex app that does a a fair amount of network traffic, it uses ExternalInterface to make some javascript calls (for SCORM), it loads XML files, images, video, audio and it has a series of modules that it could be loading at some point... So the problem is - we now have a requirement where the user needs to run this content locally on a machine that is not connected to the internet (which means they can't connect to Adobe's site to change their security settings.) As you can imagine, when the user doubles clicks on the html page to launch this thing, they are greeted with a security warning that the swf is trying to communicate with another domain other than the one it's in. We can't wrap it in an exe or an AIR app so I unless there is some way to tweak some obscure security settings we may be hosed. Any idea's?
What you are trying to do is exactly the problem solved by AIR. You should really give it a try, it's not that hard to pick up. If you really really can't use AIR (you didn't specify why, so I assume it's just because you don't want to have to learn a new system), then modifying the security config file will solve the problem. Basically what you need to do is create a 'trust' file in the "Global FlashPlayerTrust" directory. This can be done by your installer (which installs all the javascript, SWF, html, etc files onto the local machine). You should create the directory if it does not exist. The directory for each OS is: * Windows - %WINDIR%\System32\Macromed\Flash\FlashPlayerTrust * Mac - /Library/Application Support/Macromedia/FlashPlayerTrust * Linux - /etc/adobe/FlashPlayerTrust Next, you need to create the trust file. You can name it anything, so pick a unique name that would be unlikely to conflict with others. Something like CompanyName.cfg. It's a text file, with one path per line. You can trust either one SWF at a time, or an entire directory. Example: ``` C:\Program Files\MyCompany\CoolApp C:\Program Files\MyCompany\OtherApp\Main.swf ``` To test that it's working, inside your flash movie you can check `System.security.sandboxType` (ActionScript 1 or 2), or `Security.sandboxType` (ActionScript 3). It should have the value of "`localTrusted`"
165,603
<p>I was wondering if there was a way to get at the raw HTTP request data in PHP running on apache that doesn't involve using any additional extensions. I've seen the <a href="http://au2.php.net/http" rel="noreferrer">HTTP</a> functions in the manual, but I don't have the option of installing an extension in my environment.</p> <p>While I can access the information from $_SERVER, I would like to see the raw request exactly as it was sent to the server. PHP munges the header names to suit its own array key style, for eg. Some-Test-Header becomes HTTP_X_SOME_TEST_HEADER. This is not what I need.</p>
[ { "answer_id": 165623, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": true, "text": "<p>Do you mean the information contained in <code>$_SERVER</code>?</p>\n\n<pre><code>print_r($_SERVER);\n</code></pre>\n\n<p>Edit:</p>\n\n<p>Would this do then?</p>\n\n<pre><code>foreach(getallheaders() as $key=&gt;$value) {\n print $key.': '.$value.\"&lt;br /&gt;\";\n}\n</code></pre>\n" }, { "answer_id": 165647, "author": "Bretticus", "author_id": 411075, "author_profile": "https://Stackoverflow.com/users/411075", "pm_score": 4, "selected": false, "text": "<p>Use the following php wrapper:</p>\n\n<pre><code>$raw_post = file_get_contents(\"php://input\"); \n</code></pre>\n" }, { "answer_id": 36272667, "author": "tim", "author_id": 1135440, "author_profile": "https://Stackoverflow.com/users/1135440", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code> $request = $_SERVER['SERVER_PROTOCOL'] .' '. $_SERVER['REQUEST_METHOD'] .' '. $_SERVER['REQUEST_URI'] . PHP_EOL;\n\n foreach (getallheaders() as $key =&gt; $value) {\n $request .= trim($key) .': '. trim($value) . PHP_EOL;\n }\n\n $request .= PHP_EOL . file_get_contents('php://input');\n\n echo $request;\n</code></pre>\n" }, { "answer_id": 70671519, "author": "Sanjai Unnikrishnan", "author_id": 7766293, "author_profile": "https://Stackoverflow.com/users/7766293", "pm_score": 0, "selected": false, "text": "<pre><code>GET /\nhost: domain.com;\nall-other-headers: &lt;its-value&gt;;\nrequest-content: &lt;as-per-content-type&gt;\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15004/" ]
I was wondering if there was a way to get at the raw HTTP request data in PHP running on apache that doesn't involve using any additional extensions. I've seen the [HTTP](http://au2.php.net/http) functions in the manual, but I don't have the option of installing an extension in my environment. While I can access the information from $\_SERVER, I would like to see the raw request exactly as it was sent to the server. PHP munges the header names to suit its own array key style, for eg. Some-Test-Header becomes HTTP\_X\_SOME\_TEST\_HEADER. This is not what I need.
Do you mean the information contained in `$_SERVER`? ``` print_r($_SERVER); ``` Edit: Would this do then? ``` foreach(getallheaders() as $key=>$value) { print $key.': '.$value."<br />"; } ```
165,650
<p>I need to add a tooltip/alt to a "td" element inside of my tables with jquery.</p> <p>Can someone help me out?</p> <p>I tried:</p> <pre><code>var tTip ="Hello world"; $(this).attr("onmouseover", tip(tTip)); </code></pre> <p>where I have verified that I am using the "td" as "this".</p> <p>**Edit:**I am able to capture the "td" element through using the "alert" command and it worked. So for some reason the "tip" function doesn't work. Anyone know why this would be?</p>
[ { "answer_id": 165651, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": false, "text": "<pre><code>$(this).mouseover(function() {\n tip(tTip);\n});\n</code></pre>\n\n<p>a better way might be to put <code>title</code> attributes in your HTML. That way, if someone has javascript turned off, they'll still get a tool tip (albeit not as pretty/flexible as you can do with jQuery).</p>\n\n<pre><code>&lt;table id=\"myTable\"&gt;\n &lt;tbody&gt;\n &lt;tr&gt;\n &lt;td title=\"Tip 1\"&gt;Cell 1&lt;/td&gt;\n &lt;td title=\"Tip 2\"&gt;Cell 2&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>and then use this code:</p>\n\n<pre><code>$('#myTable td[title]')\n .hover(function() {\n showTooltip($(this));\n }, function() {\n hideTooltip();\n })\n;\n\nfunction showTooltip($el) {\n // insert code here to position your tooltip element (which i'll call $tip)\n $tip.html($el.attr('title'));\n}\nfunction hideTooltip() {\n $tip.hide();\n}\n</code></pre>\n" }, { "answer_id": 165654, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 1, "selected": false, "text": "<pre><code>var tTip =\"Hello world\";\n$(this).mouseover( function() { tip(tTip); });\n</code></pre>\n" }, { "answer_id": 165668, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 5, "selected": true, "text": "<p>you might want to have a look at <a href=\"http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/\" rel=\"noreferrer\">http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/</a></p>\n" }, { "answer_id": 165678, "author": "Kent Brewster", "author_id": 1151280, "author_profile": "https://Stackoverflow.com/users/1151280", "pm_score": -1, "selected": false, "text": "<p>If you really do want to put those tooltips on your table cells and not your table headers--where they'd make much more sense--please consider putting them on the content INSIDE the table cells, where it's much more meaningful.</p>\n" }, { "answer_id": 2635582, "author": "Avi", "author_id": 316255, "author_profile": "https://Stackoverflow.com/users/316255", "pm_score": 1, "selected": false, "text": "<h1>grdList - table id</h1>\n<p>td:nth-child(5) - column</p>\n<pre><code>$('#grdList tr td:nth-child(5)').each(function(i) {\n if (i &gt; 0) { //skip header\n var sContent = $(this).text();\n $(this).attr(&quot;title&quot;, $(this).html());\n if (sContent.length &gt; 20) {\n $(this).text(sContent.substring(0,20) + '...');\n }\n }\n});\n</code></pre>\n" }, { "answer_id": 2635606, "author": "Avi", "author_id": 316255, "author_profile": "https://Stackoverflow.com/users/316255", "pm_score": 2, "selected": false, "text": "<pre><code>$('#grdList tr td:nth-child(5)').each(function(i) {\n if (i &gt; 0) { //skip header\n var sContent = $(this).text();\n $(this).attr(\"title\", $(this).html());\n if (sContent.length &gt; 20) {\n $(this).text(sContent.substring(0,20) + '...');\n }\n }\n});\n</code></pre>\n\n<p>grdList - table id</p>\n\n<p>td:nth-child(5) - column 5</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7644/" ]
I need to add a tooltip/alt to a "td" element inside of my tables with jquery. Can someone help me out? I tried: ``` var tTip ="Hello world"; $(this).attr("onmouseover", tip(tTip)); ``` where I have verified that I am using the "td" as "this". \*\*Edit:\*\*I am able to capture the "td" element through using the "alert" command and it worked. So for some reason the "tip" function doesn't work. Anyone know why this would be?
you might want to have a look at <http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/>
165,713
<p>I need a function to return a suffix for days when displaying text like the "<code>th</code>" in "<code>Wednesday June 5th, 2008</code>".</p> <p>It only need work for the numbers 1 through 31 (no error checking required) and English.</p>
[ { "answer_id": 165714, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "<p>The following function works for C:</p>\n\n<pre><code>char *makeDaySuffix (unsigned int day) {\n //if ((day &lt; 1) || (day &gt; 31)) return \"\";\n switch (day) {\n case 1: case 21: case 31: return \"st\";\n case 2: case 22: return \"nd\";\n case 3: case 23: return \"rd\";\n }\n return \"th\";\n}\n</code></pre>\n\n<p>As requested, it only works for the numbers 1 through 31 inclusive. If you want (possibly, but not necessarily) raw speed, you could try:</p>\n\n<pre><code>char *makeDaySuffix (unsigned int day) {\n static const char * const suffix[] = {\n \"st\",\"nd\",\"rd\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\n \"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\"\n \"st\",\"nd\",\"rd\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\"\n \"st\"\n };\n //if ((day &lt; 1) || (day &gt; 31)) return \"\";\n return suffix[day-1];\n}\n</code></pre>\n\n<p>You'll note that I have bounds checking in there though commented out. If there's even the <em>slightest</em> possibility that an unexpected value will be passed in, you'll probably want to uncomment those lines.</p>\n\n<p>Just keep in mind that, with the compilers of today, naive assumptions about what is faster in a high-level language may not be correct: <em>measure, don't guess.</em></p>\n" }, { "answer_id": 165745, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 4, "selected": true, "text": "<p>Here is an alternative which should work for larger numbers too:</p>\n\n<pre><code>static const char *daySuffixLookup[] = { \"th\",\"st\",\"nd\",\"rd\",\"th\",\n \"th\",\"th\",\"th\",\"th\",\"th\" };\n\nconst char *daySuffix(int n)\n{\n if(n % 100 &gt;= 11 &amp;&amp; n % 100 &lt;= 13)\n return \"th\";\n\n return daySuffixLookup[n % 10];\n}\n</code></pre>\n" }, { "answer_id": 165882, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 2, "selected": false, "text": "<pre><code>const char *getDaySuffix(int day) {\n if (day%100 &gt; 10 &amp;&amp; day%100 &lt; 14)\n return \"th\";\n switch (day%10) {\n case 1: return \"st\";\n case 2: return \"nd\";\n case 3: return \"rd\";\n default: return \"th\";\n };\n}\n</code></pre>\n\n<p>This one works for any number, not just 1-31.</p>\n" }, { "answer_id": 166214, "author": "Roel", "author_id": 11449, "author_profile": "https://Stackoverflow.com/users/11449", "pm_score": 1, "selected": false, "text": "<p>See my question here: <a href=\"https://stackoverflow.com/questions/135946/i18n-able-way-to-get-number-ordinal-in-cmfc-on-windows-1-1st-2-2nd-etc\">How to convert Cardinal numbers into Ordinal ones</a> (it's not the C# one).</p>\n\n<p>Summary: looks like there's no way yet, with your limited requirements you can just use a simple function like the one posted.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14860/" ]
I need a function to return a suffix for days when displaying text like the "`th`" in "`Wednesday June 5th, 2008`". It only need work for the numbers 1 through 31 (no error checking required) and English.
Here is an alternative which should work for larger numbers too: ``` static const char *daySuffixLookup[] = { "th","st","nd","rd","th", "th","th","th","th","th" }; const char *daySuffix(int n) { if(n % 100 >= 11 && n % 100 <= 13) return "th"; return daySuffixLookup[n % 10]; } ```
165,723
<p>I've noticed RAII has been getting lots of attention on Stackoverflow, but in my circles (mostly C++) RAII is so obvious its like asking what's a class or a destructor.</p> <p>So I'm really curious if that's because I'm surrounded daily, by hard-core C++ programmers, and RAII just isn't that well known in general (including C++), or if all this questioning on Stackoverflow is due to the fact that I'm now in contact with programmers that didn't grow up with C++, and in other languages people just don't use/know about RAII?</p>
[ { "answer_id": 165731, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It's sort of tied to knowing when your destructor will be called though right? So it's not entirely language-agnostic, given that that's not a given in many GC'd languages.</p>\n" }, { "answer_id": 165736, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "<p>I think a lot of other languages (ones that don't have <code>delete</code>, for example) don't give the programmer quite the same control over object lifetimes, and so there must be other means to provide for deterministic disposal of resources. In C#, for example, using <code>using</code> with <code>IDisposable</code> is common.</p>\n" }, { "answer_id": 165742, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 0, "selected": false, "text": "<p>RAII is popular in C++ because it's one of the few (only?) languages that can allocate complex scope-local variables, but does not have a <code>finally</code> clause. C#, Java, Python, Ruby all have <code>finally</code> or an equivalent. C hasn't <code>finally</code>, but also can't execute code when a variable drops out of scope.</p>\n" }, { "answer_id": 165743, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "<p>For people who are commenting in this thread about RAII (resource acquisition is initialisation), here's a motivational example.</p>\n\n<pre><code>class StdioFile {\n FILE* file_;\n std::string mode_;\n\n static FILE* fcheck(FILE* stream) {\n if (!stream)\n throw std::runtime_error(\"Cannot open file\");\n return stream;\n }\n\n FILE* fdup() const {\n int dupfd(dup(fileno(file_)));\n if (dupfd == -1)\n throw std::runtime_error(\"Cannot dup file descriptor\");\n return fdopen(dupfd, mode_.c_str());\n }\n\npublic:\n StdioFile(char const* name, char const* mode)\n : file_(fcheck(fopen(name, mode))), mode_(mode)\n {\n }\n\n StdioFile(StdioFile const&amp; rhs)\n : file_(fcheck(rhs.fdup())), mode_(rhs.mode_)\n {\n }\n\n ~StdioFile()\n {\n fclose(file_);\n }\n\n StdioFile&amp; operator=(StdioFile const&amp; rhs) {\n FILE* dupstr = fcheck(rhs.fdup());\n if (fclose(file_) == EOF) {\n fclose(dupstr); // XXX ignore failed close\n throw std::runtime_error(\"Cannot close stream\");\n }\n file_ = dupstr;\n return *this;\n }\n\n int\n read(std::vector&lt;char&gt;&amp; buffer)\n {\n int result(fread(&amp;buffer[0], 1, buffer.size(), file_));\n if (ferror(file_))\n throw std::runtime_error(strerror(errno));\n return result;\n }\n\n int\n write(std::vector&lt;char&gt; const&amp; buffer)\n {\n int result(fwrite(&amp;buffer[0], 1, buffer.size(), file_));\n if (ferror(file_))\n throw std::runtime_error(strerror(errno));\n return result;\n }\n};\n\nint\nmain(int argc, char** argv)\n{\n StdioFile file(argv[1], \"r\");\n std::vector&lt;char&gt; buffer(1024);\n while (int hasRead = file.read(buffer)) {\n // process hasRead bytes, then shift them off the buffer\n }\n}\n</code></pre>\n\n<p>Here, when a <code>StdioFile</code> instance is created, the resource (a file stream, in this case) is acquired; when it's destroyed, the resource is released. There is no <code>try</code> or <code>finally</code> block required; if the reading causes an exception, <code>fclose</code> is called automatically, because it's in the destructor.</p>\n\n<p>The destructor is guaranteed to be called when the function leaves <code>main</code>, whether normally or by exception. In this case, the file stream is cleaned up. The world is safe once again. :-D</p>\n" }, { "answer_id": 165744, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": -1, "selected": false, "text": "<p>RAII is specific to C++. C++ has the requisite combination of stack-allocated objects, unmanaged object lifetimes, and exception handling.</p>\n" }, { "answer_id": 165749, "author": "Robert Gould", "author_id": 15124, "author_profile": "https://Stackoverflow.com/users/15124", "pm_score": 2, "selected": false, "text": "<p>First of all I'm very surprised it's not more well known! I totally thought RAII was, at least, obvious to C++ programmers. \nHowever now I guess I can understand why people actually ask about it. I'm surrounded, and my self must be, C++ freaks...</p>\n\n<p>So my secret.. I guess that would be, that I used to read Meyers, Sutter [EDIT:] and Andrei all the time years ago until I just grokked it.</p>\n" }, { "answer_id": 165760, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 4, "selected": false, "text": "<p>RAII stands for <a href=\"http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization\" rel=\"noreferrer\">Resource Acquisition Is Initialization</a>. This is not language-agnostic at all. This mantra is here because C++ works the way it works. In C++ an object is not constructed until its constructor completes. A destructor will not be invoked if the object has not been successfully constructed.</p>\n\n<p>Translated to practical language, a constructor should make sure it covers for the case it can't complete its job thoroughly. If, for example, an exception occurs during construction then the constructor must handle it gracefully, because the destructor will not be there to help. This is usually done by covering for the exceptions within the constructor or by forwarding this hassle to other objects. For example:</p>\n\n<pre><code>class OhMy {\npublic:\n OhMy() { p_ = new int[42]; jump(); } \n ~OhMy() { delete[] p_; }\n\nprivate:\n int* p_;\n\n void jump();\n};\n</code></pre>\n\n<p>If the <code>jump()</code> call in the constructor throws we're in trouble, because <code>p_</code> will leak. We can fix this like this:</p>\n\n<pre><code>class Few {\npublic:\n Few() : v_(42) { jump(); } \n ~Few();\n\nprivate:\n std::vector&lt;int&gt; v_;\n\n void jump();\n};\n</code></pre>\n\n<p>If people are not aware of this then it's because of one of two things:</p>\n\n<ul>\n<li>They don't know C++ well. In this case they should open <a href=\"http://www.research.att.com/~bs/3rd.html\" rel=\"noreferrer\">TCPPPL</a> again before they write their next class. Specifically, section 14.4.1 in the third edition of the book talks about this technique.</li>\n<li>They don't know C++ at all. That's fine. This idiom is very C++y. Either learn C++ or forget all about this and carry on with your lives. Preferably learn C++. ;)</li>\n</ul>\n" }, { "answer_id": 165764, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "<p>RAII.</p>\n\n<p>It starts with a constructor and destructor but it is more than that.<br>\nIt is all about safely controlling resources in the presence of exceptions.<br></p>\n\n<p>What makes RAII superior to finally and such mechanisms is that it makes code safer to use because it moves responsibility for using an object correctly from the user of the object to the designer of the object.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/161177/does-c-support-finally-blocks-and-whats-this-raii-i-keep-hearing-about#161247\">Read this</a></p>\n\n<p>Example to use <a href=\"https://stackoverflow.com/questions/165723/do-programmers-of-other-languages-besides-c-use-know-or-understand-raii#165743\">StdioFile</a> correctly using RAII.</p>\n\n<pre><code>void someFunc()\n{\n StdioFile file(\"Plop\",\"r\");\n\n // use file\n}\n// File closed automatically even if this function exits via an exception.\n</code></pre>\n\n<p>To get the same functionality with finally.</p>\n\n<pre><code>void someFunc()\n{\n // Assuming Java Like syntax;\n StdioFile file = new StdioFile(\"Plop\",\"r\");\n try\n {\n // use file\n }\n finally\n {\n // close file.\n file.close(); // \n // Using the finaliser is not enough as we can not garantee when\n // it will be called.\n }\n}\n</code></pre>\n\n<p>Because you have to explicitly add the try{} finally{} block this makes this method of coding more error prone (<b>i.e.</b> it is the user of the object that needs to think about exceptions). By using RAII exception safety has to be coded once when the object is implemented.</p>\n\n<p>To the question is this C++ specific.<br>\nShort Answer: No.<br></p>\n\n<p>Longer Answer:<br>\nIt requires Constructors/Destructors/Exceptions and objects that have a defined lifetime.</p>\n\n<p>Well technically it does not need exceptions. It just becomes much more useful when exceptions could potentially be used as it makes controlling the resource in the presence of exceptions very easy.<br>\nBut it is useful in all situations where control can leave a function early and not execute all the code (<b>e.g.</b> early return from a function. This is why multiple return points in C is a bad code smell while multiple return points in C++ is not a code smell [because we can clean up using RAII]).</p>\n\n<p>In C++ controlled lifetime is achieved by stack variables or smart pointers. But this is not the only time we can have a tightly controlled lifespan. For example Perl objects are not stack based but have a very controlled lifespan because of reference counting.</p>\n" }, { "answer_id": 165793, "author": "Torbjörn Gyllebring", "author_id": 21182, "author_profile": "https://Stackoverflow.com/users/21182", "pm_score": 1, "selected": false, "text": "<p>The thing with RAII is that it requires deterministic finalization something that is guaranteed for stackbased objects in C++. Languages like C# and Java that relies on garbage collection doesn't have this guarantee so it has to be \"bolted\" on somehow. In C# this is done by implementing IDisposable and much of the same usage patterns then crops up basicly that's one of the motivators for the \"using\" statement, it ensures Disposal and is very well known and used. </p>\n\n<p>So basicly the idiom is there, it just doesn't have a fancy name. </p>\n" }, { "answer_id": 165991, "author": "Pierre", "author_id": 24449, "author_profile": "https://Stackoverflow.com/users/24449", "pm_score": 1, "selected": false, "text": "<p>RAII is a way in C++ to make sure a cleanup procedure is executed after a block of code regardless of what happens in the code: the code executes till the end properly or raises an exception. An already cited example is automatically closing a file after its processing, see <a href=\"https://stackoverflow.com/questions/165723/do-programmers-of-other-languages-besides-c-use-know-or-understand-raii#165743\">answer here</a>.</p>\n\n<p>In other languages you use other mechanism to achieve that.</p>\n\n<p>In Java you have try { } finally {} constructs:</p>\n\n<pre><code>try {\n BufferedReader file = new BufferedReader(new FileReader(\"infilename\"));\n // do something with file\n}\nfinally {\n file.close();\n}\n</code></pre>\n\n<p>In Ruby you have the automatic block argument:</p>\n\n<pre><code>File.open(\"foo.txt\") do | file |\n # do something with file\nend\n</code></pre>\n\n<p>In Lisp you have <code>unwind-protect</code> and the predefined <code>with-XXX</code></p>\n\n<pre><code>(with-open-file (file \"foo.txt\")\n ;; do something with file\n)\n</code></pre>\n\n<p>In Scheme you have <code>dynamic-wind</code> and the predefined <code>with-XXXXX</code>:</p>\n\n<pre><code>(with-input-from-file \"foo.txt\"\n (lambda ()\n ;; do something \n)\n</code></pre>\n\n<p>in Python you have try finally</p>\n\n<pre><code>try\n file = open(\"foo.txt\")\n # do something with file\nfinally:\n file.close()\n</code></pre>\n\n<p>The C++ solution as RAII is rather clumsy in that it forces you to create one class for all kinds of cleanup you have to do. This may forces you to write a lot of small silly classes.</p>\n\n<p>Other examples of RAII are:</p>\n\n<ul>\n<li>unlocking a mutex after acquisition</li>\n<li>closing a database connection after opening</li>\n<li>freeing memory after allocation</li>\n<li>logging on entry and exit of a block of code</li>\n<li>...</li>\n</ul>\n" }, { "answer_id": 166461, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "<p>I use C++ RAII all the time, but I've also developed in Visual Basic 6 for a long time, and RAII has always been a widely-used concept there (although I've never heard anyone call it that).</p>\n<p>In fact, many VB6 programs rely on RAII quite heavily. One of the more curious uses that I've repeatedly seen is the following small class:</p>\n<pre><code>' WaitCursor.cls '\nPrivate m_OldCursor As MousePointerConstants\n\nPublic Sub Class_Inititialize()\n m_OldCursor = Screen.MousePointer\n Screen.MousePointer = vbHourGlass\nEnd Sub\n\nPublic Sub Class_Terminate()\n Screen.MousePointer = m_OldCursor\nEnd Sub\n</code></pre>\n<p>Usage:</p>\n<pre><code>Public Sub MyButton_Click()\n Dim WC As New WaitCursor\n\n ' … Time-consuming operation. '\nEnd Sub\n</code></pre>\n<p>Once the time-consuming operation terminates, the original cursor gets restored automatically.</p>\n" }, { "answer_id": 168103, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "<p>A modification of <a href=\"https://stackoverflow.com/questions/165723/do-programmers-of-other-languages-besides-c-use-know-or-understand-raii#165991\">@Pierre's answer</a>:</p>\n\n<p>In Python:</p>\n\n<pre><code>with open(\"foo.txt\", \"w\") as f:\n f.write(\"abc\")\n</code></pre>\n\n<p><code>f.close()</code> is called automatically whether an exception were raised or not.</p>\n\n<p>In general it can be done using <a href=\"http://www.python.org/doc/2.5.2/lib/module-contextlib.html\" rel=\"nofollow noreferrer\">contextlib.closing</a>, from the documenation:</p>\n\n<blockquote>\n <p><code>closing(thing)</code>: return a context\n manager that closes thing upon\n completion of the block. This is\n basically equivalent to:</p>\n\n<pre><code>from contextlib import contextmanager\n\n@contextmanager\ndef closing(thing):\n try:\n yield thing\n finally:\n thing.close()\n</code></pre>\n \n <p>And lets you write code like this:</p>\n\n<pre><code>from __future__ import with_statement # required for python version &lt; 2.6\nfrom contextlib import closing\nimport urllib\n\nwith closing(urllib.urlopen('http://www.python.org')) as page:\n for line in page:\n print line\n</code></pre>\n \n <p>without needing to explicitly close\n page. Even if an error occurs,\n page.close() will be called when the\n with block is exited.</p>\n</blockquote>\n" }, { "answer_id": 194364, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>CPython (the official Python written in C) supports RAII because of its use of reference counted objects with immediate scope based destruction (rather than when garbage is collected). Unfortunately, Jython (Python in Java) and PyPy do not support this very useful RAII idiom and it breaks a lot of legacy Python code. So for portable python you have to handle all the exceptions manually just like Java.</p>\n" }, { "answer_id": 194380, "author": "Michael Easter", "author_id": 12704, "author_profile": "https://Stackoverflow.com/users/12704", "pm_score": 0, "selected": false, "text": "<p>I have colleagues who are hard-core, \"read the spec\" C++ types. Many of them know RAII but I have never really heard it used outside of that scene.</p>\n" }, { "answer_id": 396344, "author": "ApplePieIsGood", "author_id": 44996, "author_profile": "https://Stackoverflow.com/users/44996", "pm_score": 3, "selected": false, "text": "<p>The problem with RAII is the acronym. It has no obvious correlation to the concept. What does this have to do with stack allocation? That is what it comes down to. C++ gives you the ability to allocate objects on the stack and guarantee that their destructors are called when the stack is unwound. In light of that, does RAII sound like a meaningful way of encapsulating that? No. I never heard of RAII until I came here a few weeks ago, and I even had to laugh hard when I read someone had posted that they would never hire a C++ programmer who'd didn't know what RAII was. Surely the concept is well known to most all competent professional C++ developers. It's just that the acronym is poorly conceived.</p>\n" }, { "answer_id": 396380, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 5, "selected": false, "text": "<p>There are plenty of reasons why RAII isn't better known. First, the name isn't particularly obvious. If I didn't already know what RAII was, I'd certainly never guess it from the name. (Resource acquisition is initialization? What does that have to do with the destructor or cleanup, which is what <em>really</em> characterizes RAII?)</p>\n\n<p>Another is that it doesn't work as well in languages without deterministic cleanup.</p>\n\n<p>In C++, we know exactly when the destructor is called, we know the order in which destructors are called, and we can define them to do anything we like.</p>\n\n<p>In most modern languages, everything is garbage-collected, which makes RAII trickier to implement. There's no reason why it wouldn't be possible to add RAII-extensions to, say, C#, but it's not as obvious as it is in C++. But as others have mentioned, Perl and other languages support RAII despite being garbage collected.</p>\n\n<p>That said, it is still possible to create your own RAII-styled wrapper in C# or other languages. I did it in C# a while ago.\nI had to write something to ensure that a database connection was closed immediately after use, a task which any C++ programmer would see as an obvious candidate for RAII.\nOf course we could wrap everything in <code>using</code>-statements whenever we used a db connection, but that's just messy and error-prone.</p>\n\n<p>My solution was to write a helper function which took a delegate as argument, and then when called, opened a database connection, and inside a using-statement, passed it to the delegate function, pseudocode:</p>\n\n<pre><code>T RAIIWrapper&lt;T&gt;(Func&lt;DbConnection, T&gt; f){\n using (var db = new DbConnection()){\n return f(db);\n }\n}\n</code></pre>\n\n<p>Still not as nice or obvious as C++-RAII, but it achieved roughly the same thing. Whenever we need a DbConnection, we have to call this helper function which guarantees that it'll be closed afterwards.</p>\n" }, { "answer_id": 596577, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 2, "selected": false, "text": "<p>Common Lisp has RAII:</p>\n\n<pre><code>(with-open-file (stream \"file.ext\" :direction :input)\n (do-something-with-stream stream))\n</code></pre>\n\n<p>See: <a href=\"http://www.psg.com/~dlamkins/sl/chapter09.html\" rel=\"nofollow noreferrer\">http://www.psg.com/~dlamkins/sl/chapter09.html</a></p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
I've noticed RAII has been getting lots of attention on Stackoverflow, but in my circles (mostly C++) RAII is so obvious its like asking what's a class or a destructor. So I'm really curious if that's because I'm surrounded daily, by hard-core C++ programmers, and RAII just isn't that well known in general (including C++), or if all this questioning on Stackoverflow is due to the fact that I'm now in contact with programmers that didn't grow up with C++, and in other languages people just don't use/know about RAII?
For people who are commenting in this thread about RAII (resource acquisition is initialisation), here's a motivational example. ``` class StdioFile { FILE* file_; std::string mode_; static FILE* fcheck(FILE* stream) { if (!stream) throw std::runtime_error("Cannot open file"); return stream; } FILE* fdup() const { int dupfd(dup(fileno(file_))); if (dupfd == -1) throw std::runtime_error("Cannot dup file descriptor"); return fdopen(dupfd, mode_.c_str()); } public: StdioFile(char const* name, char const* mode) : file_(fcheck(fopen(name, mode))), mode_(mode) { } StdioFile(StdioFile const& rhs) : file_(fcheck(rhs.fdup())), mode_(rhs.mode_) { } ~StdioFile() { fclose(file_); } StdioFile& operator=(StdioFile const& rhs) { FILE* dupstr = fcheck(rhs.fdup()); if (fclose(file_) == EOF) { fclose(dupstr); // XXX ignore failed close throw std::runtime_error("Cannot close stream"); } file_ = dupstr; return *this; } int read(std::vector<char>& buffer) { int result(fread(&buffer[0], 1, buffer.size(), file_)); if (ferror(file_)) throw std::runtime_error(strerror(errno)); return result; } int write(std::vector<char> const& buffer) { int result(fwrite(&buffer[0], 1, buffer.size(), file_)); if (ferror(file_)) throw std::runtime_error(strerror(errno)); return result; } }; int main(int argc, char** argv) { StdioFile file(argv[1], "r"); std::vector<char> buffer(1024); while (int hasRead = file.read(buffer)) { // process hasRead bytes, then shift them off the buffer } } ``` Here, when a `StdioFile` instance is created, the resource (a file stream, in this case) is acquired; when it's destroyed, the resource is released. There is no `try` or `finally` block required; if the reading causes an exception, `fclose` is called automatically, because it's in the destructor. The destructor is guaranteed to be called when the function leaves `main`, whether normally or by exception. In this case, the file stream is cleaned up. The world is safe once again. :-D
165,729
<p>The <code>end()</code> function in jQuery reverts the element set back to what it was before the last destructive change, so I can see how it's supposed to be used, but I've seen some code examples, eg: <a href="http://alistapart.com/articles/prettyaccessibleforms" rel="nofollow noreferrer">on alistapart</a> <em>(which were probably from older versions of jQuery - the article is from 2006)</em> which finished every statement off with <code>.end()</code>. eg:</p> <pre><code>$( 'form.cmxform' ).hide().end(); </code></pre> <ul> <li>Does this have any effect?</li> <li>Is it something I should also be doing?</li> <li>What does the above code even return?</li> </ul>
[ { "answer_id": 165748, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "<p>That <code>end()</code> doesn't do anything. There's no point to coding like that. It will return <code>$('#myBox')</code> -- the example is pretty poor. More interesting is something like this:</p>\n\n<pre><code>$('#myBox').show ().children ('.myClass').hide ().end ().blink ();\n</code></pre>\n\n<p>Which will show <code>myBox</code>, hide the specified children, and then blink the box. There are more interesting examples here:</p>\n\n<p><a href=\"http://simonwillison.net/2007/Aug/15/jquery/\" rel=\"noreferrer\">http://simonwillison.net/2007/Aug/15/jquery/</a></p>\n\n<p>such as:</p>\n\n<pre><code>$('form#login')\n // hide all the labels inside the form with the 'optional' class\n .find('label.optional').hide().end()\n // add a red border to any password fields in the form\n .find('input:password').css('border', '1px solid red').end()\n // add a submit handler to the form\n .submit(function(){\n return confirm('Are you sure you want to submit?');\n });\n</code></pre>\n" }, { "answer_id": 12859362, "author": "Luca Rainone", "author_id": 1049668, "author_profile": "https://Stackoverflow.com/users/1049668", "pm_score": 0, "selected": false, "text": "<p>From <a href=\"http://api.jquery.com/end/\" rel=\"nofollow\">jquery doc</a> there is an example:</p>\n\n<pre><code>$('ul.first').find('.foo')\n .css('background-color', 'red')\n.end().find('.bar')\n .css('background-color', 'green')\n.end();\n</code></pre>\n\n<p>and after it a clarification:</p>\n\n<blockquote>\n <p>The last end() is unnecessary, as we are discarding the jQuery object immediately thereafter. However, when the code is written in this form, the end() provides visual symmetry and a sense of completion —making the program, at least to the eyes of some developers, more readable, at the cost of a slight hit to performance as it is an additional function call.</p>\n</blockquote>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
The `end()` function in jQuery reverts the element set back to what it was before the last destructive change, so I can see how it's supposed to be used, but I've seen some code examples, eg: [on alistapart](http://alistapart.com/articles/prettyaccessibleforms) *(which were probably from older versions of jQuery - the article is from 2006)* which finished every statement off with `.end()`. eg: ``` $( 'form.cmxform' ).hide().end(); ``` * Does this have any effect? * Is it something I should also be doing? * What does the above code even return?
That `end()` doesn't do anything. There's no point to coding like that. It will return `$('#myBox')` -- the example is pretty poor. More interesting is something like this: ``` $('#myBox').show ().children ('.myClass').hide ().end ().blink (); ``` Which will show `myBox`, hide the specified children, and then blink the box. There are more interesting examples here: <http://simonwillison.net/2007/Aug/15/jquery/> such as: ``` $('form#login') // hide all the labels inside the form with the 'optional' class .find('label.optional').hide().end() // add a red border to any password fields in the form .find('input:password').css('border', '1px solid red').end() // add a submit handler to the form .submit(function(){ return confirm('Are you sure you want to submit?'); }); ```
165,751
<p>Let's just assume for now that you have narrowed down where the typical bottlenecks in your app are. For all you know, it might be the batch process you run to reindex your tables; it could be the SQL queries that runs over your effective-dated trees; it could be the XML marshalling of a few hundred composite objects. In other words, you might have something like this:</p> <pre><code>public Result takeAnAnnoyingLongTime(Input in) { // impl of above } </code></pre> <p>Unfortunately, even after you've identified your bottleneck, all you can do is chip away at it. No simple solution is available.</p> <p>How do you measure the performance of your bottleneck so that you know your fixes are headed in the right direction?</p>
[ { "answer_id": 165755, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<ol>\n<li>Profile it</li>\n<li>Find the top line in the profiler, attempt to make it faster.</li>\n<li>Profile it</li>\n<li>If it worked, go to 1. If it didn't work, go to 2.</li>\n</ol>\n" }, { "answer_id": 165756, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 2, "selected": false, "text": "<p>I'd measure them using the same tools / methods that allowed me to find them in the first place.</p>\n\n<p>Namely, sticking timing and logging calls all over the place. If the numbers start going down, then you just might be doing the right thing.</p>\n" }, { "answer_id": 165758, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 2, "selected": false, "text": "<p>As mentioned in this <a href=\"http://msdn.microsoft.com/en-us/magazine/cc500561.aspx\" rel=\"nofollow noreferrer\">msdn column</a>, performance tuning is compared to the job of painting Golden Gate Bridge: once you finish painting the entire thing, it's time to go back to the beginning and start again.</p>\n" }, { "answer_id": 165791, "author": "TimB", "author_id": 4193, "author_profile": "https://Stackoverflow.com/users/4193", "pm_score": 3, "selected": false, "text": "<p>Two points:</p>\n\n<ol>\n<li><p>Beware of the infamous \"optimizing the idle loop\" problem. (E.g. see the <a href=\"http://c2.com/cgi/wiki/wiki?OptimizationStories\" rel=\"noreferrer\">optimization story</a> under the heading \"Porsche-in-the-parking-lot\".) That is, just because a routine is taking a significant amount of time (as shown by your profiling), don't assume that it's responsible for slow performance as perceived by the user.</p></li>\n<li><p>The biggest performance gains often come not from that clever tweak or optimization to the implementation of the algorithm, but from realising that there's a better algorithm altogether. Some improvements are relatively obvious, while others require more detailed analysis of the algorithms, and possibly a major change to the data structures involved. This may include trading off processor time for I/O time, in which case you need to make sure that you're not optimizing only one of those measures.</p></li>\n</ol>\n\n<p>Bringing it back to the question asked, make sure that whatever you're measuring represents what the user actually experiences, otherwise your efforts could be a complete waste of time. </p>\n" }, { "answer_id": 165838, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It's an interesting question. I don't think anyone knows the answer. I believe that significant part of the problem is that for more complicated programs, no one can predict their complexity. Therefore, even if you have profiler results, it's very complicated to interpret it in terms of changes that should be made to the program, because you have no theoretical basis for what the optimal solution is.</p>\n\n<p>I think this is a reason why we have so bloated software. We optimize only so that quite simple cases would work on our fast machines. But once you put such pieces together into a large system, or you use order of magnitude larger input, wrong algorithms used (which were until then invisible both theoretically and practically) will start showing their true complexity.</p>\n\n<p>Example: You create a string class, which handles Unicode. You use it somewhere like computer-generated XML processing where it really doesn't matter. But Unicode processing is in there, taking part of the resources. By itself, the string class can be very fast, but call it million times, and the program will be slow. </p>\n\n<p>I believe that most of the current software bloat is of this nature. There is a way to reduce it, but it contradicts OOP. There is an interesting book <a href=\"http://www.cix.co.uk/~smallmemory/book.html\" rel=\"nofollow noreferrer\">There is an interesting book</a> about various techniques, it's memory oriented but most of them could be reverted to get more speed.</p>\n" }, { "answer_id": 173807, "author": "Will", "author_id": 15721, "author_profile": "https://Stackoverflow.com/users/15721", "pm_score": 0, "selected": false, "text": "<p>I'd identify two things:</p>\n\n<p>1) what complexity is it? The easiest way is to graph time-taken verses size of input.\n2) how is it bound? Is it memory, or disk, or IPC with other processes or machines, or..</p>\n\n<p>Now point (2) is the easier to tackle and explain: Lots of things go faster if you have more RAM or a faster machine or faster disks or move over to gig ethernet or such. If you identify your pain, you can put some money into hardware to make it tolerable.</p>\n" }, { "answer_id": 264028, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 1, "selected": false, "text": "<p>This is not a hard problem. The first thing you need to understand is that measuring performance is not how you find performance problems. Knowing how slow something is doesn't help you find out why. You need a diagnostic tool, and a good one. I've had a lot of experience doing this, and <a href=\"http://www.wikihow.com/Optimize-Your-Program%27s-Performance\" rel=\"nofollow noreferrer\">this</a> is the best method. It is not automatic, but it runs rings around most profilers.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17205/" ]
Let's just assume for now that you have narrowed down where the typical bottlenecks in your app are. For all you know, it might be the batch process you run to reindex your tables; it could be the SQL queries that runs over your effective-dated trees; it could be the XML marshalling of a few hundred composite objects. In other words, you might have something like this: ``` public Result takeAnAnnoyingLongTime(Input in) { // impl of above } ``` Unfortunately, even after you've identified your bottleneck, all you can do is chip away at it. No simple solution is available. How do you measure the performance of your bottleneck so that you know your fixes are headed in the right direction?
Two points: 1. Beware of the infamous "optimizing the idle loop" problem. (E.g. see the [optimization story](http://c2.com/cgi/wiki/wiki?OptimizationStories) under the heading "Porsche-in-the-parking-lot".) That is, just because a routine is taking a significant amount of time (as shown by your profiling), don't assume that it's responsible for slow performance as perceived by the user. 2. The biggest performance gains often come not from that clever tweak or optimization to the implementation of the algorithm, but from realising that there's a better algorithm altogether. Some improvements are relatively obvious, while others require more detailed analysis of the algorithms, and possibly a major change to the data structures involved. This may include trading off processor time for I/O time, in which case you need to make sure that you're not optimizing only one of those measures. Bringing it back to the question asked, make sure that whatever you're measuring represents what the user actually experiences, otherwise your efforts could be a complete waste of time.
165,783
<p>It seems pretty common to want to let your javascript know a particular dom node corresponds to a record in the database. So, how do you do it?</p> <p>One way I've seen that's pretty common is to use a class for the type and an id for the id:</p> <pre><code>&lt;div class="thing" id="5"&gt; &lt;script&gt; myThing = select(".thing#5") &lt;/script&gt; </code></pre> <p>There's a slight html standards issue with this though -- if you have more than one type of record on the page, you may end up duplicating IDs. But that doesn't do anything bad, does it?</p> <p>An alternative is to use data attributes:</p> <pre><code>&lt;div data-thing-id="5"&gt; &lt;script&gt; myThing = select("[data-thing-id=5]") &lt;/script&gt; </code></pre> <p>This gets around the duplicate IDs problem, but it does mean you have to deal with attributes instead of IDs, which is sometimes more difficult. What do you guys think?</p>
[ { "answer_id": 165787, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": false, "text": "<pre><code>&lt;div class=\"thing\" id=\"myapp-thing-5\"/&gt;\n\n// Get thing on the page for a particular ID\nvar myThing = select(\"#myapp-thing-5\");\n\n// Get ID for the first thing on the page\nvar thing_id = /myapp-thing-(\\d+)/.exec ($('.thing')[0].id)[1];\n</code></pre>\n" }, { "answer_id": 165798, "author": "Zack The Human", "author_id": 18265, "author_profile": "https://Stackoverflow.com/users/18265", "pm_score": 2, "selected": false, "text": "<p>Considering the fact that you can have multiple classes per element, couldn't you create a unique identifier as an additional class per element? That way, there could be more than one element with the same \"id\" without HTML ID attribute collisions.</p>\n\n<pre><code>&lt;div class=\"thing myapp-thing-5\" /&gt;\n&lt;div class=\"thing myapp-thing-668\" /&gt;\n&lt;div class=\"thing myapp-thing-5\" /&gt;\n</code></pre>\n\n<p>It would be easy to then find these nodes, and find their corresponding DB record with a little string manipulation.</p>\n" }, { "answer_id": 165818, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 4, "selected": false, "text": "<p><strong>You'll be giving up some control of the DOM</strong></p>\n\n<p>True, nothing will explode, but it's bad practice. If you put duplicate ids on the page you'll basically loose the ability to <strong>be sure about what you're getting</strong> when you try to access an element by its id.</p>\n\n<pre><code>var whoKnows = document.getElementById('duplicateId');\n</code></pre>\n\n<p>The behavior is actually different, depending on the browser. In any case, you can use classNames for duplicate values, and you'll be <strong>avoiding the problem altogether</strong>.</p>\n\n<p>The browser will try to overlook faults in your markup, but things become <strong>messy and more difficult</strong>. The best thing to do is keep your markup valid. You can describe both the type of the element and its unique database id in a className. You could even use <strong>multiple classNames</strong> to differentiate between them. There are a <strong>lot of valid possibilities</strong>:</p>\n\n<pre><code>&lt;div class=\"friend04\"/&gt;\n&lt;div class=\"featuredFriend04\" /&gt;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>&lt;div class=\"friend friend04\" /&gt;\n&lt;div class=\"featuredFriend friend04\" /&gt;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>&lt;div class=\"friend objectId04\" /&gt;\n&lt;div class=\"groupMember objectId04\" /&gt;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>&lt;div class=\"friend objectId04\" /&gt;\n&lt;div class=\"friend objectId04\" id=\"featured\" /&gt;\n</code></pre>\n\n<p>These are all completely legitimate &amp; valid snippets of XHTML. Notice how, in the last snippet, that I've still got an id working for me, which is nice. Accessing elements by their id is very quick and easy, so you definitely want to be able to leverage it when you can.</p>\n\n<p>You'll already spend enough of your time in javascript <strong>making sure that you've got the right values and types</strong>. Putting duplicate ids on the page will just make things harder for you. If you can find ways to write standards-compliant markup, it has many <strong>practical benefits</strong>.</p>\n" }, { "answer_id": 165822, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 0, "selected": false, "text": "<p>Non-standard attributes are fine, if you're using XHTML and take the time to extend the DTD you're using to cover the new attributes. Personally, I'd just use a more unique id, like some of the other people have suggested.</p>\n" }, { "answer_id": 165893, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 5, "selected": true, "text": "<p>Note that an ID cannot start with a digit, so:</p>\n\n<pre><code>&lt;div class=\"thing\" id=\"5\"&gt;\n</code></pre>\n\n<p>is invalid HTML. See <a href=\"https://stackoverflow.com/questions/70579/what-is-a-valid-value-for-id-attributes-in-html#70586\">What are valid values for the id attribute in HTML?</a></p>\n\n<p>In your case, I would use ID's like <code>thing5</code> or <code>thing.5</code>.</p>\n" }, { "answer_id": 165907, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 1, "selected": false, "text": "<p>In HTML5, you could do it like this:</p>\n\n<pre><code>\n&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;meta charset=\"utf-8\"&gt;\n &lt;title&gt;&lt;/title&gt;\n &lt;script&gt;\n window.addEventListener(\"DOMContentLoaded\", function() {\n var thing5 = document.evaluate('//*[@data-thing=\"5\"]', \n document, null, XPathResult.FIRST_ORDERED_NODE_TYPE ,null);\n alert(thing5.singleNodeValue.textContent);\n }, false);\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;div data-thing=\"5\"&gt;test&lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 166011, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 3, "selected": false, "text": "<p>IDs should be unique according to the standards and whilst most browsers don't barf when handed duplicate IDs it would not be a good idea to rely on that always being the case.</p>\n\n<p>Making the ID unique by adding a type name to the ID would work but you need to ask why you need it. Giving an element an id is very useful when the element needs to be found, getElementById is very fast. The reason its fast it that most browsers will build an index of IDs as its loads the DOM. However if you have zillions of IDs that you never actually need to use in something like getElementById then you've incurred a cost that is never paid back.</p>\n\n<p>I think you may find most of the time you want the object ID in an event fired by the element or one of its children. In which case I would use an additional attribute on the element and not the ID attribute.</p>\n\n<p>I would leave class attribute to do what its meant to do and not overload it with identification duties.</p>\n" }, { "answer_id": 166072, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 0, "selected": false, "text": "<p>I don't like <a href=\"https://stackoverflow.com/users/3560/john-millikin\">John Millikin's</a> solution. It's gonna be performance-intensive on large datasets.</p>\n\n<p>An optimization on his code could be replacing the regular expression with a call to <code>substring()</code> since the first few characters of the id-property are constant.</p>\n\n<p>I'd go with matching <code>class</code> and then a specific <code>id</code> though.</p>\n" }, { "answer_id": 166085, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 1, "selected": false, "text": "<p>If you set non-standard properties, be sure to either set them programmatically (as everything will be legal that way) or go through the trouble of revising the dtd !-)</p>\n\n<p>But I would use an ID with a meaningful word prepending the DB-id and then use .getElementById, as every necessary informtion is at hand ...</p>\n" }, { "answer_id": 167838, "author": "Kent Brewster", "author_id": 1151280, "author_profile": "https://Stackoverflow.com/users/1151280", "pm_score": 0, "selected": false, "text": "<p>Keeping track of your data via the DOM seems shaky to me; remember, those IDs are global variables, so if there's any chance somebody else's script can find its way onto your page, it's vulnerable. For best results, load your data into an object within an anonymous function and write the table (or the big nested list of DIVs) afterwards.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2653/" ]
It seems pretty common to want to let your javascript know a particular dom node corresponds to a record in the database. So, how do you do it? One way I've seen that's pretty common is to use a class for the type and an id for the id: ``` <div class="thing" id="5"> <script> myThing = select(".thing#5") </script> ``` There's a slight html standards issue with this though -- if you have more than one type of record on the page, you may end up duplicating IDs. But that doesn't do anything bad, does it? An alternative is to use data attributes: ``` <div data-thing-id="5"> <script> myThing = select("[data-thing-id=5]") </script> ``` This gets around the duplicate IDs problem, but it does mean you have to deal with attributes instead of IDs, which is sometimes more difficult. What do you guys think?
Note that an ID cannot start with a digit, so: ``` <div class="thing" id="5"> ``` is invalid HTML. See [What are valid values for the id attribute in HTML?](https://stackoverflow.com/questions/70579/what-is-a-valid-value-for-id-attributes-in-html#70586) In your case, I would use ID's like `thing5` or `thing.5`.
165,808
<p>I'm looking for very simple obfuscation (like encrypt and decrypt but not necessarily secure) functionality for some data. It's not mission critical. I need something to keep honest people honest, but something a little stronger than <a href="http://en.wikipedia.org/wiki/ROT13" rel="noreferrer">ROT13</a> or <a href="http://en.wikipedia.org/wiki/Base64" rel="noreferrer">Base64</a>.</p> <p>I'd prefer something that is already included in the <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> framework 2.0, so I don't have to worry about any external dependencies.</p> <p>I really don't want to have to mess around with public/private keys, etc. I don't know much about encryption, but I do know enough to know that anything I wrote would be less than worthless... In fact, I'd probably screw up the math and make it trivial to crack.</p>
[ { "answer_id": 165826, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 1, "selected": false, "text": "<p>The namespace <code>System.Security.Cryptography</code> contains the <code>TripleDESCryptoServiceProvider</code> and <code>RijndaelManaged</code> classes</p>\n\n<p>Don't forget to add a reference to the <code>System.Security</code> assembly.</p>\n" }, { "answer_id": 165850, "author": "ZeroBugBounce", "author_id": 11314, "author_profile": "https://Stackoverflow.com/users/11314", "pm_score": 5, "selected": false, "text": "<p>Yes, add the <code>System.Security</code> assembly, import the <code>System.Security.Cryptography</code> namespace. Here's a simple example of a symmetric (DES) algorithm encryption:</p>\n\n<pre><code>DESCryptoServiceProvider des = new DESCryptoServiceProvider();\ndes.GenerateKey();\nbyte[] key = des.Key; // save this!\n\nICryptoTransform encryptor = des.CreateEncryptor();\n// encrypt\nbyte[] enc = encryptor.TransformFinalBlock(new byte[] { 1, 2, 3, 4 }, 0, 4);\n\nICryptoTransform decryptor = des.CreateDecryptor();\n\n// decrypt\nbyte[] originalAgain = decryptor.TransformFinalBlock(enc, 0, enc.Length);\nDebug.Assert(originalAgain[0] == 1);\n</code></pre>\n" }, { "answer_id": 165869, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "<p>If you just want simple encryption (i.e., possible for a determined cracker to break, but locking out most casual users), just pick two passphrases of equal length, say:</p>\n\n<pre><code>deoxyribonucleicacid\nwhile (x&gt;0) { x-- };\n</code></pre>\n\n<p>and xor your data with both of them (looping the passphrases if necessary)<sup>(a)</sup>. For example:</p>\n\n<pre><code>1111-2222-3333-4444-5555-6666-7777\ndeoxyribonucleicaciddeoxyribonucle\nwhile (x&gt;0) { x-- };while (x&gt;0) { \n</code></pre>\n\n<p>Someone searching your binary may well think the DNA string is a key, but they're unlikely to think the C code is anything other than uninitialized memory saved with your binary.</p>\n\n<hr>\n\n<p><sup>(a)</sup> Keep in mind this is <em>very</em> simple encryption and, by some definitions, may not be considered encryption at all (since the intent of encryption is to <em>prevent</em> unauthorised access rather than just make it more difficult). Although, of course, even the strongest encryption is insecure when someone's standing over the key-holders with a steel pipe.</p>\n\n<p>As stated in the first sentence, this is a means to make it difficult enough for the casual attacker that they'll move on. It's similar to preventing burglaries on your home - you don't need to make it impregnable, you just need to make it less pregnable than the house next door :-)</p>\n" }, { "answer_id": 166196, "author": "Harald Scheirich", "author_id": 22080, "author_profile": "https://Stackoverflow.com/users/22080", "pm_score": 0, "selected": false, "text": "<p>I know you said you don't care about how secure it is, but if you chose <a href=\"http://en.wikipedia.org/wiki/Data_Encryption_Standard\" rel=\"nofollow noreferrer\">DES</a> you might as well take <a href=\"http://en.wikipedia.org/wiki/Advanced_Encryption_Standard\" rel=\"nofollow noreferrer\">AES</a> it is the more up-to-date encryption method.</p>\n" }, { "answer_id": 166451, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "<p>Encryption is easy: as others have pointed out, there are classes in the System.Security.Cryptography namespace that do all the work for you. Use them rather than any home-grown solution.</p>\n\n<p>But decryption is easy too. The issue you have is not the encryption algorithm, but protecting access to the key used for decryption.</p>\n\n<p>I would use one of the following solutions:</p>\n\n<ul>\n<li><p>DPAPI using the ProtectedData class with CurrentUser scope. This is easy as you don't need to worry about a key. Data can only be decrypted by the same user, so no good for sharing data between users or machines.</p></li>\n<li><p>DPAPI using the ProtectedData class with LocalMachine scope. Good for e.g. protecting configuration data on a single secure server. But anyone who can log into the machine can encrypt it, so no good unless the server is secure.</p></li>\n<li><p>Any symmetric algorithm. I typically use the static SymmetricAlgorithm.Create() method if I don't care what algorithm is used (in fact it's Rijndael by default). In this case you need to protect your key somehow. E.g. you can obfuscate it in some way and hide it in your code. But be aware that anyone who is smart enough to decompile your code will likely be able to find the key.</p></li>\n</ul>\n" }, { "answer_id": 212707, "author": "Mark Brittingham", "author_id": 15592, "author_profile": "https://Stackoverflow.com/users/15592", "pm_score": 10, "selected": true, "text": "<p>Other answers here work fine, but AES is a more secure and up-to-date encryption algorithm. This is a class that I obtained a few years ago to perform AES encryption that I have modified over time to be more friendly for web applications (e,g. I've built Encrypt/Decrypt methods that work with URL-friendly string). It also has the methods that work with byte arrays. </p>\n\n<p>NOTE: you should use different values in the Key (32 bytes) and Vector (16 bytes) arrays! You wouldn't want someone to figure out your keys by just assuming that you used this code as-is! All you have to do is change some of the numbers (must be &lt;= 255) in the Key and Vector arrays (I left one invalid value in the Vector array to make sure you do this...). You can use <a href=\"https://www.random.org/bytes/\" rel=\"noreferrer\">https://www.random.org/bytes/</a> to generate a new set easily:</p>\n\n<ul>\n<li><a href=\"https://www.random.org/cgi-bin/randbyte?nbytes=32&amp;format=d\" rel=\"noreferrer\">generate <code>Key</code></a></li>\n<li><a href=\"https://www.random.org/cgi-bin/randbyte?nbytes=16&amp;format=d\" rel=\"noreferrer\">generate <code>Vector</code></a></li>\n</ul>\n\n<p>Using it is easy: just instantiate the class and then call (usually) EncryptToString(string StringToEncrypt) and DecryptString(string StringToDecrypt) as methods. It couldn't be any easier (or more secure) once you have this class in place.</p>\n\n<hr>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Security.Cryptography;\nusing System.IO;\n\n\npublic class SimpleAES\n{\n // Change these keys\n private byte[] Key = __Replace_Me__({ 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 });\n\n // a hardcoded IV should not be used for production AES-CBC code\n // IVs should be unpredictable per ciphertext\n private byte[] Vector = __Replace_Me__({ 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 2521, 112, 79, 32, 114, 156 });\n\n\n private ICryptoTransform EncryptorTransform, DecryptorTransform;\n private System.Text.UTF8Encoding UTFEncoder;\n\n public SimpleAES()\n {\n //This is our encryption method\n RijndaelManaged rm = new RijndaelManaged();\n\n //Create an encryptor and a decryptor using our encryption method, key, and vector.\n EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector);\n DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector);\n\n //Used to translate bytes to text and vice versa\n UTFEncoder = new System.Text.UTF8Encoding();\n }\n\n /// -------------- Two Utility Methods (not used but may be useful) -----------\n /// Generates an encryption key.\n static public byte[] GenerateEncryptionKey()\n {\n //Generate a Key.\n RijndaelManaged rm = new RijndaelManaged();\n rm.GenerateKey();\n return rm.Key;\n }\n\n /// Generates a unique encryption vector\n static public byte[] GenerateEncryptionVector()\n {\n //Generate a Vector\n RijndaelManaged rm = new RijndaelManaged();\n rm.GenerateIV();\n return rm.IV;\n }\n\n\n /// ----------- The commonly used methods ------------------------------ \n /// Encrypt some text and return a string suitable for passing in a URL.\n public string EncryptToString(string TextValue)\n {\n return ByteArrToString(Encrypt(TextValue));\n }\n\n /// Encrypt some text and return an encrypted byte array.\n public byte[] Encrypt(string TextValue)\n {\n //Translates our text value into a byte array.\n Byte[] bytes = UTFEncoder.GetBytes(TextValue);\n\n //Used to stream the data in and out of the CryptoStream.\n MemoryStream memoryStream = new MemoryStream();\n\n /*\n * We will have to write the unencrypted bytes to the stream,\n * then read the encrypted result back from the stream.\n */\n #region Write the decrypted value to the encryption stream\n CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write);\n cs.Write(bytes, 0, bytes.Length);\n cs.FlushFinalBlock();\n #endregion\n\n #region Read encrypted value back out of the stream\n memoryStream.Position = 0;\n byte[] encrypted = new byte[memoryStream.Length];\n memoryStream.Read(encrypted, 0, encrypted.Length);\n #endregion\n\n //Clean up.\n cs.Close();\n memoryStream.Close();\n\n return encrypted;\n }\n\n /// The other side: Decryption methods\n public string DecryptString(string EncryptedString)\n {\n return Decrypt(StrToByteArray(EncryptedString));\n }\n\n /// Decryption when working with byte arrays. \n public string Decrypt(byte[] EncryptedValue)\n {\n #region Write the encrypted value to the decryption stream\n MemoryStream encryptedStream = new MemoryStream();\n CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);\n decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);\n decryptStream.FlushFinalBlock();\n #endregion\n\n #region Read the decrypted value from the stream.\n encryptedStream.Position = 0;\n Byte[] decryptedBytes = new Byte[encryptedStream.Length];\n encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);\n encryptedStream.Close();\n #endregion\n return UTFEncoder.GetString(decryptedBytes);\n }\n\n /// Convert a string to a byte array. NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so).\n // System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();\n // return encoding.GetBytes(str);\n // However, this results in character values that cannot be passed in a URL. So, instead, I just\n // lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100).\n public byte[] StrToByteArray(string str)\n {\n if (str.Length == 0)\n throw new Exception(\"Invalid string value in StrToByteArray\");\n\n byte val;\n byte[] byteArr = new byte[str.Length / 3];\n int i = 0;\n int j = 0;\n do\n {\n val = byte.Parse(str.Substring(i, 3));\n byteArr[j++] = val;\n i += 3;\n }\n while (i &lt; str.Length);\n return byteArr;\n }\n\n // Same comment as above. Normally the conversion would use an ASCII encoding in the other direction:\n // System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();\n // return enc.GetString(byteArr); \n public string ByteArrToString(byte[] byteArr)\n {\n byte val;\n string tempStr = \"\";\n for (int i = 0; i &lt;= byteArr.GetUpperBound(0); i++)\n {\n val = byteArr[i];\n if (val &lt; (byte)10)\n tempStr += \"00\" + val.ToString();\n else if (val &lt; (byte)100)\n tempStr += \"0\" + val.ToString();\n else\n tempStr += val.ToString();\n }\n return tempStr;\n }\n}\n</code></pre>\n" }, { "answer_id": 212742, "author": "stalepretzel", "author_id": 1615, "author_profile": "https://Stackoverflow.com/users/1615", "pm_score": 3, "selected": false, "text": "<p>[EDIT] Years later, I've come back to say: <strong>don't do this!</strong> See <a href=\"https://stackoverflow.com/questions/1135186/whats-wrong-with-xor-encryption\">What&#39;s wrong with XOR encryption?</a> for details.</p>\n\n<p>A very simple, easy two-way encrytpion is XOR encryption.</p>\n\n<ol>\n<li>Come up with a password. Let's have it be <code>mypass</code>.<br /></li>\n<li>Convert the password into binary (according to ASCII). The password becomes 01101101 01111001 01110000 01100001 01110011 01110011.<br /></li>\n<li>Take the message you want to encode. Convert that into binary, also.<br /></li>\n<li>Look at the length of the message. If the message length is 400 bytes, turn the password into a 400 byte string by repeating it over and over again. It would become 01101101 01111001 01110000 01100001 01110011 01110011 01101101 01111001 01110000 01100001 01110011 01110011 01101101 01111001 01110000 01100001 01110011 01110011... (or <code>mypassmypassmypass...</code>)<br /></li>\n<li>XOR the message with the long password.<br /></li>\n<li>Send the result.<br /></li>\n<li>Another time, XOR the encrypted message with the same password (<code>mypassmypassmypass...</code>).<br /></li>\n<li>There's your message!</li>\n</ol>\n" }, { "answer_id": 5081379, "author": "Achilleterzo", "author_id": 628738, "author_profile": "https://Stackoverflow.com/users/628738", "pm_score": 1, "selected": false, "text": "<p>I changed <a href=\"https://stackoverflow.com/a/212707\">this</a>:</p>\n\n<pre><code>public string ByteArrToString(byte[] byteArr)\n{\n byte val;\n string tempStr = \"\";\n for (int i = 0; i &lt;= byteArr.GetUpperBound(0); i++)\n {\n val = byteArr[i];\n if (val &lt; (byte)10)\n tempStr += \"00\" + val.ToString();\n else if (val &lt; (byte)100)\n tempStr += \"0\" + val.ToString();\n else\n tempStr += val.ToString();\n }\n return tempStr;\n}\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code> public string ByteArrToString(byte[] byteArr)\n {\n string temp = \"\";\n foreach (byte b in byteArr)\n temp += b.ToString().PadLeft(3, '0');\n return temp;\n }\n</code></pre>\n" }, { "answer_id": 5518092, "author": "Mud", "author_id": 501459, "author_profile": "https://Stackoverflow.com/users/501459", "pm_score": 8, "selected": false, "text": "<p>I cleaned up SimpleAES (above) for my use. Fixed convoluted encrypt/decrypt methods; separated methods for encoding byte buffers, strings, and URL-friendly strings; made use of existing libraries for URL encoding.</p>\n\n<p>The code is small, simpler, faster and the output is more concise. For instance, <code>[email protected]</code> produces:</p>\n\n<pre><code>SimpleAES: \"096114178117140150104121138042115022037019164188092040214235183167012211175176167001017163166152\"\nSimplerAES: \"YHKydYyWaHmKKnMWJROkvFwo1uu3pwzTr7CnARGjppg%3d\"\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>public class SimplerAES\n{\n private static byte[] key = __Replace_Me__({ 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 });\n\n // a hardcoded IV should not be used for production AES-CBC code\n // IVs should be unpredictable per ciphertext\n private static byte[] vector = __Replace_Me_({ 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 221, 112, 79, 32, 114, 156 });\n\n private ICryptoTransform encryptor, decryptor;\n private UTF8Encoding encoder;\n\n public SimplerAES()\n {\n RijndaelManaged rm = new RijndaelManaged();\n encryptor = rm.CreateEncryptor(key, vector);\n decryptor = rm.CreateDecryptor(key, vector);\n encoder = new UTF8Encoding();\n }\n\n public string Encrypt(string unencrypted)\n {\n return Convert.ToBase64String(Encrypt(encoder.GetBytes(unencrypted)));\n }\n\n public string Decrypt(string encrypted)\n {\n return encoder.GetString(Decrypt(Convert.FromBase64String(encrypted)));\n }\n\n public byte[] Encrypt(byte[] buffer)\n {\n return Transform(buffer, encryptor);\n }\n\n public byte[] Decrypt(byte[] buffer)\n {\n return Transform(buffer, decryptor);\n }\n\n protected byte[] Transform(byte[] buffer, ICryptoTransform transform)\n {\n MemoryStream stream = new MemoryStream();\n using (CryptoStream cs = new CryptoStream(stream, transform, CryptoStreamMode.Write))\n {\n cs.Write(buffer, 0, buffer.Length);\n }\n return stream.ToArray();\n }\n}\n</code></pre>\n" }, { "answer_id": 7314406, "author": "Simon", "author_id": 53158, "author_profile": "https://Stackoverflow.com/users/53158", "pm_score": 4, "selected": false, "text": "<p>A variant of Marks (excellent) answer </p>\n\n<ul>\n<li>Add \"using\"s</li>\n<li>Make the class IDisposable</li>\n<li>Remove the URL encoding code to make the example simpler. </li>\n<li>Add a simple test fixture to demonstrate usage</li>\n</ul>\n\n<p>Hope this helps</p>\n\n<pre><code>[TestFixture]\npublic class RijndaelHelperTests\n{\n [Test]\n public void UseCase()\n {\n //These two values should not be hard coded in your code.\n byte[] key = {251, 9, 67, 117, 237, 158, 138, 150, 255, 97, 103, 128, 183, 65, 76, 161, 7, 79, 244, 225, 146, 180, 51, 123, 118, 167, 45, 10, 184, 181, 202, 190};\n byte[] vector = {214, 11, 221, 108, 210, 71, 14, 15, 151, 57, 241, 174, 177, 142, 115, 137};\n\n using (var rijndaelHelper = new RijndaelHelper(key, vector))\n {\n var encrypt = rijndaelHelper.Encrypt(\"StringToEncrypt\");\n var decrypt = rijndaelHelper.Decrypt(encrypt);\n Assert.AreEqual(\"StringToEncrypt\", decrypt);\n }\n }\n}\n\npublic class RijndaelHelper : IDisposable\n{\n Rijndael rijndael;\n UTF8Encoding encoding;\n\n public RijndaelHelper(byte[] key, byte[] vector)\n {\n encoding = new UTF8Encoding();\n rijndael = Rijndael.Create();\n rijndael.Key = key;\n rijndael.IV = vector;\n }\n\n public byte[] Encrypt(string valueToEncrypt)\n {\n var bytes = encoding.GetBytes(valueToEncrypt);\n using (var encryptor = rijndael.CreateEncryptor())\n using (var stream = new MemoryStream())\n using (var crypto = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))\n {\n crypto.Write(bytes, 0, bytes.Length);\n crypto.FlushFinalBlock();\n stream.Position = 0;\n var encrypted = new byte[stream.Length];\n stream.Read(encrypted, 0, encrypted.Length);\n return encrypted;\n }\n }\n\n public string Decrypt(byte[] encryptedValue)\n {\n using (var decryptor = rijndael.CreateDecryptor())\n using (var stream = new MemoryStream())\n using (var crypto = new CryptoStream(stream, decryptor, CryptoStreamMode.Write))\n {\n crypto.Write(encryptedValue, 0, encryptedValue.Length);\n crypto.FlushFinalBlock();\n stream.Position = 0;\n var decryptedBytes = new Byte[stream.Length];\n stream.Read(decryptedBytes, 0, decryptedBytes.Length);\n return encoding.GetString(decryptedBytes);\n }\n }\n\n public void Dispose()\n {\n if (rijndael != null)\n {\n rijndael.Dispose();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 26177005, "author": "Andy C", "author_id": 1638719, "author_profile": "https://Stackoverflow.com/users/1638719", "pm_score": 5, "selected": false, "text": "<p>Just thought I'd add that I've improved Mud's SimplerAES by adding a random IV that's passed back inside the encrypted string. This improves the encryption as encrypting the same string will result in a different output each time.</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class StringEncryption\n{\n private readonly Random random;\n private readonly byte[] key;\n private readonly RijndaelManaged rm;\n private readonly UTF8Encoding encoder;\n\n public StringEncryption()\n {\n this.random = new Random();\n this.rm = new RijndaelManaged();\n this.encoder = new UTF8Encoding();\n this.key = Convert.FromBase64String(\"Your+Secret+Static+Encryption+Key+Goes+Here=\");\n }\n\n public string Encrypt(string unencrypted)\n {\n var vector = new byte[16];\n this.random.NextBytes(vector);\n var cryptogram = vector.Concat(this.Encrypt(this.encoder.GetBytes(unencrypted), vector));\n return Convert.ToBase64String(cryptogram.ToArray());\n }\n\n public string Decrypt(string encrypted)\n {\n var cryptogram = Convert.FromBase64String(encrypted);\n if (cryptogram.Length &lt; 17)\n {\n throw new ArgumentException(\"Not a valid encrypted string\", \"encrypted\");\n }\n\n var vector = cryptogram.Take(16).ToArray();\n var buffer = cryptogram.Skip(16).ToArray();\n return this.encoder.GetString(this.Decrypt(buffer, vector));\n }\n\n private byte[] Encrypt(byte[] buffer, byte[] vector)\n {\n var encryptor = this.rm.CreateEncryptor(this.key, vector);\n return this.Transform(buffer, encryptor);\n }\n\n private byte[] Decrypt(byte[] buffer, byte[] vector)\n {\n var decryptor = this.rm.CreateDecryptor(this.key, vector);\n return this.Transform(buffer, decryptor);\n }\n\n private byte[] Transform(byte[] buffer, ICryptoTransform transform)\n {\n var stream = new MemoryStream();\n using (var cs = new CryptoStream(stream, transform, CryptoStreamMode.Write))\n {\n cs.Write(buffer, 0, buffer.Length);\n }\n\n return stream.ToArray();\n }\n}\n</code></pre>\n\n<p>And bonus unit test</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>[Test]\npublic void EncryptDecrypt()\n{\n // Arrange\n var subject = new StringEncryption();\n var originalString = \"Testing123!£$\";\n\n // Act\n var encryptedString1 = subject.Encrypt(originalString);\n var encryptedString2 = subject.Encrypt(originalString);\n var decryptedString1 = subject.Decrypt(encryptedString1);\n var decryptedString2 = subject.Decrypt(encryptedString2);\n\n // Assert\n Assert.AreEqual(originalString, decryptedString1, \"Decrypted string should match original string\");\n Assert.AreEqual(originalString, decryptedString2, \"Decrypted string should match original string\");\n Assert.AreNotEqual(originalString, encryptedString1, \"Encrypted string should not match original string\");\n Assert.AreNotEqual(encryptedString1, encryptedString2, \"String should never be encrypted the same twice\");\n}\n</code></pre>\n" }, { "answer_id": 26518496, "author": "angularsen", "author_id": 134761, "author_profile": "https://Stackoverflow.com/users/134761", "pm_score": 4, "selected": false, "text": "<p>I combined what I found the best from several answers and comments.</p>\n\n<ul>\n<li>Random initialization vector prepended to crypto text (@jbtule)</li>\n<li>Use TransformFinalBlock() instead of MemoryStream (@RenniePet)</li>\n<li>No pre-filled keys to avoid anyone copy &amp; pasting a disaster</li>\n<li>Proper dispose and using patterns</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Simple encryption/decryption using a random initialization vector\n/// and prepending it to the crypto text.\n/// &lt;/summary&gt;\n/// &lt;remarks&gt;Based on multiple answers in http://stackoverflow.com/questions/165808/simple-two-way-encryption-for-c-sharp &lt;/remarks&gt;\npublic class SimpleAes : IDisposable\n{\n /// &lt;summary&gt;\n /// Initialization vector length in bytes.\n /// &lt;/summary&gt;\n private const int IvBytes = 16;\n\n /// &lt;summary&gt;\n /// Must be exactly 16, 24 or 32 bytes long.\n /// &lt;/summary&gt;\n private static readonly byte[] Key = Convert.FromBase64String(\"FILL ME WITH 24 (2 pad chars), 32 OR 44 (1 pad char) RANDOM CHARS\"); // Base64 has a blowup of four-thirds (33%)\n\n private readonly UTF8Encoding _encoder;\n private readonly ICryptoTransform _encryptor;\n private readonly RijndaelManaged _rijndael;\n\n public SimpleAes()\n {\n _rijndael = new RijndaelManaged {Key = Key};\n _rijndael.GenerateIV();\n _encryptor = _rijndael.CreateEncryptor();\n _encoder = new UTF8Encoding();\n }\n\n public string Decrypt(string encrypted)\n {\n return _encoder.GetString(Decrypt(Convert.FromBase64String(encrypted)));\n }\n\n public void Dispose()\n {\n _rijndael.Dispose();\n _encryptor.Dispose();\n }\n\n public string Encrypt(string unencrypted)\n {\n return Convert.ToBase64String(Encrypt(_encoder.GetBytes(unencrypted)));\n }\n\n private byte[] Decrypt(byte[] buffer)\n {\n // IV is prepended to cryptotext\n byte[] iv = buffer.Take(IvBytes).ToArray();\n using (ICryptoTransform decryptor = _rijndael.CreateDecryptor(_rijndael.Key, iv))\n {\n return decryptor.TransformFinalBlock(buffer, IvBytes, buffer.Length - IvBytes);\n }\n }\n\n private byte[] Encrypt(byte[] buffer)\n {\n // Prepend cryptotext with IV\n byte [] inputBuffer = _encryptor.TransformFinalBlock(buffer, 0, buffer.Length); \n return _rijndael.IV.Concat(inputBuffer).ToArray();\n }\n}\n</code></pre>\n\n<p>Update 2015-07-18: Fixed mistake in private Encrypt() method by comments of @bpsilver and @Evereq. IV was accidentally encrypted, is now prepended in clear text as expected by Decrypt().</p>\n" }, { "answer_id": 27877537, "author": "Thunder", "author_id": 232687, "author_profile": "https://Stackoverflow.com/users/232687", "pm_score": -1, "selected": false, "text": "<p>I think this is the worlds simplest one !</p>\n\n<pre><code>string encrypted = \"Text\".Aggregate(\"\", (c, a) =&gt; c + (char) (a + 2));\n</code></pre>\n\n<p>Test</p>\n\n<pre><code> Console.WriteLine((\"Hello\").Aggregate(\"\", (c, a) =&gt; c + (char) (a + 1)));\n //Output is Ifmmp\n Console.WriteLine((\"Ifmmp\").Aggregate(\"\", (c, a) =&gt; c + (char)(a - 1)));\n //Output is Hello\n</code></pre>\n" }, { "answer_id": 33759739, "author": "William", "author_id": 907734, "author_profile": "https://Stackoverflow.com/users/907734", "pm_score": 3, "selected": false, "text": "<p>I wanted to post my solution since none of the above the solutions are as simple as mine. Let me know what you think:</p>\n\n<pre><code> // This will return an encrypted string based on the unencrypted parameter\n public static string Encrypt(this string DecryptedValue)\n {\n HttpServerUtility.UrlTokenEncode(MachineKey.Protect(Encoding.UTF8.GetBytes(DecryptedValue.Trim())));\n }\n\n // This will return an unencrypted string based on the parameter\n public static string Decrypt(this string EncryptedValue)\n {\n Encoding.UTF8.GetString(MachineKey.Unprotect(HttpServerUtility.UrlTokenDecode(EncryptedValue)));\n }\n</code></pre>\n\n<h3>Optional</h3>\n\n<p>This assumes that the MachineKey of the server used to encrypt the value is the same as the one used to decrypt the value. If desired, you can specify a static MachineKey in the Web.config so that your application can decrypt/encrypt data regardless of where it is run (e.g. development vs. production server). You can <a href=\"https://support.microsoft.com/en-us/kb/2915218#bookmark-appendixa\" rel=\"noreferrer\">generate a static machine key following these instructions</a>.</p>\n" }, { "answer_id": 35345056, "author": "Matt", "author_id": 902630, "author_profile": "https://Stackoverflow.com/users/902630", "pm_score": 1, "selected": false, "text": "<p>Using the builtin .Net Cryptography library, this example shows how to use the Advanced Encryption Standard (AES).</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Security.Cryptography;\n\nnamespace Aes_Example\n{\n class AesExample\n {\n public static void Main()\n {\n try\n {\n\n string original = \"Here is some data to encrypt!\";\n\n // Create a new instance of the Aes\n // class. This generates a new key and initialization \n // vector (IV).\n using (Aes myAes = Aes.Create())\n {\n\n // Encrypt the string to an array of bytes.\n byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV);\n\n // Decrypt the bytes to a string.\n string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);\n\n //Display the original data and the decrypted data.\n Console.WriteLine(\"Original: {0}\", original);\n Console.WriteLine(\"Round Trip: {0}\", roundtrip);\n }\n\n }\n catch (Exception e)\n {\n Console.WriteLine(\"Error: {0}\", e.Message);\n }\n }\n static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key,byte[] IV)\n {\n // Check arguments.\n if (plainText == null || plainText.Length &lt;= 0)\n throw new ArgumentNullException(\"plainText\");\n if (Key == null || Key.Length &lt;= 0)\n throw new ArgumentNullException(\"Key\");\n if (IV == null || IV.Length &lt;= 0)\n throw new ArgumentNullException(\"Key\");\n byte[] encrypted;\n // Create an Aes object\n // with the specified key and IV.\n using (Aes aesAlg = Aes.Create())\n {\n aesAlg.Key = Key;\n aesAlg.IV = IV;\n\n // Create a decrytor to perform the stream transform.\n ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);\n\n // Create the streams used for encryption.\n using (MemoryStream msEncrypt = new MemoryStream())\n {\n using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))\n {\n using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))\n {\n\n //Write all data to the stream.\n swEncrypt.Write(plainText);\n }\n encrypted = msEncrypt.ToArray();\n }\n }\n }\n\n\n // Return the encrypted bytes from the memory stream.\n return encrypted;\n\n }\n\n static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)\n {\n // Check arguments.\n if (cipherText == null || cipherText.Length &lt;= 0)\n throw new ArgumentNullException(\"cipherText\");\n if (Key == null || Key.Length &lt;= 0)\n throw new ArgumentNullException(\"Key\");\n if (IV == null || IV.Length &lt;= 0)\n throw new ArgumentNullException(\"Key\");\n\n // Declare the string used to hold\n // the decrypted text.\n string plaintext = null;\n\n // Create an Aes object\n // with the specified key and IV.\n using (Aes aesAlg = Aes.Create())\n {\n aesAlg.Key = Key;\n aesAlg.IV = IV;\n\n // Create a decrytor to perform the stream transform.\n ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);\n\n // Create the streams used for decryption.\n using (MemoryStream msDecrypt = new MemoryStream(cipherText))\n {\n using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))\n {\n using (StreamReader srDecrypt = new StreamReader(csDecrypt))\n {\n\n // Read the decrypted bytes from the decrypting stream\n // and place them in a string.\n plaintext = srDecrypt.ReadToEnd();\n }\n }\n }\n\n }\n\n return plaintext;\n\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 42398918, "author": "joym8", "author_id": 1541224, "author_profile": "https://Stackoverflow.com/users/1541224", "pm_score": 0, "selected": false, "text": "<p>I've been using the accepted answer by <a href=\"https://stackoverflow.com/a/212707/1541224\">Mark Brittingham</a> and its has helped me a lot. Recently I had to send encrypted text to a different organization and that's where some issues came up. The OP does not require these options but since this is a popular question I'm posting my modification (<code>Encrypt</code> and <code>Decrypt</code> functions borrowed from <a href=\"https://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=vs.110).aspx\" rel=\"nofollow noreferrer\">here</a>):</p>\n\n<ol>\n<li>Different IV for every message - Concatenates IV bytes to the cipher bytes before obtaining the hex. <strong>Of course this is a convention that needs to be conveyed to the parties receiving the cipher text.</strong></li>\n<li>Allows two constructors - one for default <code>RijndaelManaged</code> values, and one where property values can be specified (based on mutual agreement between encrypting and decrypting parties)</li>\n</ol>\n\n<p><strong>Here is the class (test sample at the end):</strong></p>\n\n<pre><code>/// &lt;summary&gt;\n/// Based on https://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=vs.110).aspx\n/// Uses UTF8 Encoding\n/// http://security.stackexchange.com/a/90850\n/// &lt;/summary&gt;\npublic class AnotherAES : IDisposable\n{\n private RijndaelManaged rijn;\n\n /// &lt;summary&gt;\n /// Initialize algo with key, block size, key size, padding mode and cipher mode to be known.\n /// &lt;/summary&gt;\n /// &lt;param name=\"key\"&gt;ASCII key to be used for encryption or decryption&lt;/param&gt;\n /// &lt;param name=\"blockSize\"&gt;block size to use for AES algorithm. 128, 192 or 256 bits&lt;/param&gt;\n /// &lt;param name=\"keySize\"&gt;key length to use for AES algorithm. 128, 192, or 256 bits&lt;/param&gt;\n /// &lt;param name=\"paddingMode\"&gt;&lt;/param&gt;\n /// &lt;param name=\"cipherMode\"&gt;&lt;/param&gt;\n public AnotherAES(string key, int blockSize, int keySize, PaddingMode paddingMode, CipherMode cipherMode)\n {\n rijn = new RijndaelManaged();\n rijn.Key = Encoding.UTF8.GetBytes(key);\n rijn.BlockSize = blockSize;\n rijn.KeySize = keySize;\n rijn.Padding = paddingMode;\n rijn.Mode = cipherMode;\n }\n\n /// &lt;summary&gt;\n /// Initialize algo just with key\n /// Defaults for RijndaelManaged class: \n /// Block Size: 256 bits (32 bytes)\n /// Key Size: 128 bits (16 bytes)\n /// Padding Mode: PKCS7\n /// Cipher Mode: CBC\n /// &lt;/summary&gt;\n /// &lt;param name=\"key\"&gt;&lt;/param&gt;\n public AnotherAES(string key)\n {\n rijn = new RijndaelManaged();\n byte[] keyArray = Encoding.UTF8.GetBytes(key);\n rijn.Key = keyArray;\n }\n\n /// &lt;summary&gt;\n /// Based on https://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=vs.110).aspx\n /// Encrypt a string using RijndaelManaged encryptor.\n /// &lt;/summary&gt;\n /// &lt;param name=\"plainText\"&gt;string to be encrypted&lt;/param&gt;\n /// &lt;param name=\"IV\"&gt;initialization vector to be used by crypto algorithm&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public byte[] Encrypt(string plainText, byte[] IV)\n {\n if (rijn == null)\n throw new ArgumentNullException(\"Provider not initialized\");\n\n // Check arguments.\n if (plainText == null || plainText.Length &lt;= 0)\n throw new ArgumentNullException(\"plainText cannot be null or empty\");\n if (IV == null || IV.Length &lt;= 0)\n throw new ArgumentNullException(\"IV cannot be null or empty\");\n byte[] encrypted;\n\n // Create a decrytor to perform the stream transform.\n using (ICryptoTransform encryptor = rijn.CreateEncryptor(rijn.Key, IV))\n {\n // Create the streams used for encryption.\n using (MemoryStream msEncrypt = new MemoryStream())\n {\n using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))\n {\n using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))\n {\n //Write all data to the stream.\n swEncrypt.Write(plainText);\n }\n encrypted = msEncrypt.ToArray();\n }\n }\n }\n // Return the encrypted bytes from the memory stream.\n return encrypted;\n }//end EncryptStringToBytes\n\n /// &lt;summary&gt;\n /// Based on https://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=vs.110).aspx\n /// &lt;/summary&gt;\n /// &lt;param name=\"cipherText\"&gt;bytes to be decrypted back to plaintext&lt;/param&gt;\n /// &lt;param name=\"IV\"&gt;initialization vector used to encrypt the bytes&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public string Decrypt(byte[] cipherText, byte[] IV)\n {\n if (rijn == null)\n throw new ArgumentNullException(\"Provider not initialized\");\n\n // Check arguments.\n if (cipherText == null || cipherText.Length &lt;= 0)\n throw new ArgumentNullException(\"cipherText cannot be null or empty\");\n if (IV == null || IV.Length &lt;= 0)\n throw new ArgumentNullException(\"IV cannot be null or empty\");\n\n // Declare the string used to hold the decrypted text.\n string plaintext = null;\n\n // Create a decrytor to perform the stream transform.\n using (ICryptoTransform decryptor = rijn.CreateDecryptor(rijn.Key, IV))\n {\n // Create the streams used for decryption.\n using (MemoryStream msDecrypt = new MemoryStream(cipherText))\n {\n using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))\n {\n using (StreamReader srDecrypt = new StreamReader(csDecrypt))\n {\n // Read the decrypted bytes from the decrypting stream and place them in a string.\n plaintext = srDecrypt.ReadToEnd();\n }\n }\n }\n }\n\n return plaintext;\n }//end DecryptStringFromBytes\n\n /// &lt;summary&gt;\n /// Generates a unique encryption vector using RijndaelManaged.GenerateIV() method\n /// &lt;/summary&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public byte[] GenerateEncryptionVector()\n {\n if (rijn == null)\n throw new ArgumentNullException(\"Provider not initialized\");\n\n //Generate a Vector\n rijn.GenerateIV();\n return rijn.IV;\n }//end GenerateEncryptionVector\n\n\n /// &lt;summary&gt;\n /// Based on https://stackoverflow.com/a/1344255\n /// Generate a unique string given number of bytes required.\n /// This string can be used as IV. IV byte size should be equal to cipher-block byte size. \n /// Allows seeing IV in plaintext so it can be passed along a url or some message.\n /// &lt;/summary&gt;\n /// &lt;param name=\"numBytes\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static string GetUniqueString(int numBytes)\n {\n char[] chars = new char[62];\n chars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\".ToCharArray();\n byte[] data = new byte[1];\n using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())\n {\n data = new byte[numBytes];\n crypto.GetBytes(data);\n }\n StringBuilder result = new StringBuilder(numBytes);\n foreach (byte b in data)\n {\n result.Append(chars[b % (chars.Length)]);\n }\n return result.ToString();\n }//end GetUniqueKey()\n\n /// &lt;summary&gt;\n /// Converts a string to byte array. Useful when converting back hex string which was originally formed from bytes.\n /// &lt;/summary&gt;\n /// &lt;param name=\"hex\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static byte[] StringToByteArray(String hex)\n {\n int NumberChars = hex.Length;\n byte[] bytes = new byte[NumberChars / 2];\n for (int i = 0; i &lt; NumberChars; i += 2)\n bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);\n return bytes;\n }//end StringToByteArray\n\n /// &lt;summary&gt;\n /// Dispose RijndaelManaged object initialized in the constructor\n /// &lt;/summary&gt;\n public void Dispose()\n {\n if (rijn != null)\n rijn.Dispose();\n }//end Dispose()\n}//end class\n</code></pre>\n\n<p>and..</p>\n\n<p><strong>Here is the test sample:</strong></p>\n\n<pre><code>class Program\n{\n string key;\n static void Main(string[] args)\n {\n Program p = new Program();\n\n //get 16 byte key (just demo - typically you will have a predetermined key)\n p.key = AnotherAES.GetUniqueString(16);\n\n string plainText = \"Hello World!\";\n\n //encrypt\n string hex = p.Encrypt(plainText);\n\n //decrypt\n string roundTrip = p.Decrypt(hex);\n\n Console.WriteLine(\"Round Trip: {0}\", roundTrip);\n }\n\n string Encrypt(string plainText)\n {\n Console.WriteLine(\"\\nSending (encrypt side)...\");\n Console.WriteLine(\"Plain Text: {0}\", plainText);\n Console.WriteLine(\"Key: {0}\", key);\n string hex = string.Empty;\n string ivString = AnotherAES.GetUniqueString(16);\n Console.WriteLine(\"IV: {0}\", ivString);\n using (AnotherAES aes = new AnotherAES(key))\n {\n //encrypting side\n byte[] IV = Encoding.UTF8.GetBytes(ivString);\n\n //get encrypted bytes (IV bytes prepended to cipher bytes)\n byte[] encryptedBytes = aes.Encrypt(plainText, IV);\n byte[] encryptedBytesWithIV = IV.Concat(encryptedBytes).ToArray();\n\n //get hex string to send with url\n //this hex has both IV and ciphertext\n hex = BitConverter.ToString(encryptedBytesWithIV).Replace(\"-\", \"\");\n Console.WriteLine(\"sending hex: {0}\", hex);\n }\n\n return hex;\n }\n\n string Decrypt(string hex)\n {\n Console.WriteLine(\"\\nReceiving (decrypt side)...\");\n Console.WriteLine(\"received hex: {0}\", hex);\n string roundTrip = string.Empty;\n Console.WriteLine(\"Key \" + key);\n using (AnotherAES aes = new AnotherAES(key))\n {\n //get bytes from url\n byte[] encryptedBytesWithIV = AnotherAES.StringToByteArray(hex);\n\n byte[] IV = encryptedBytesWithIV.Take(16).ToArray();\n\n Console.WriteLine(\"IV: {0}\", System.Text.Encoding.Default.GetString(IV));\n\n byte[] cipher = encryptedBytesWithIV.Skip(16).ToArray();\n\n roundTrip = aes.Decrypt(cipher, IV);\n }\n return roundTrip;\n }\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/BFsDZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BFsDZ.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 46711265, "author": "Ashkan S", "author_id": 6519111, "author_profile": "https://Stackoverflow.com/users/6519111", "pm_score": 3, "selected": false, "text": "<p>Using TripleDESCryptoServiceProvider in <strong>System.Security.Cryptography</strong> :</p>\n\n<pre><code>public static class CryptoHelper\n{\n private const string Key = \"MyHashString\";\n private static TripleDESCryptoServiceProvider GetCryproProvider()\n {\n var md5 = new MD5CryptoServiceProvider();\n var key = md5.ComputeHash(Encoding.UTF8.GetBytes(Key));\n return new TripleDESCryptoServiceProvider() { Key = key, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 };\n }\n\n public static string Encrypt(string plainString)\n {\n var data = Encoding.UTF8.GetBytes(plainString);\n var tripleDes = GetCryproProvider();\n var transform = tripleDes.CreateEncryptor();\n var resultsByteArray = transform.TransformFinalBlock(data, 0, data.Length);\n return Convert.ToBase64String(resultsByteArray);\n }\n\n public static string Decrypt(string encryptedString)\n {\n var data = Convert.FromBase64String(encryptedString);\n var tripleDes = GetCryproProvider();\n var transform = tripleDes.CreateDecryptor();\n var resultsByteArray = transform.TransformFinalBlock(data, 0, data.Length);\n return Encoding.UTF8.GetString(resultsByteArray);\n }\n}\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232/" ]
I'm looking for very simple obfuscation (like encrypt and decrypt but not necessarily secure) functionality for some data. It's not mission critical. I need something to keep honest people honest, but something a little stronger than [ROT13](http://en.wikipedia.org/wiki/ROT13) or [Base64](http://en.wikipedia.org/wiki/Base64). I'd prefer something that is already included in the [.NET](http://en.wikipedia.org/wiki/.NET_Framework) framework 2.0, so I don't have to worry about any external dependencies. I really don't want to have to mess around with public/private keys, etc. I don't know much about encryption, but I do know enough to know that anything I wrote would be less than worthless... In fact, I'd probably screw up the math and make it trivial to crack.
Other answers here work fine, but AES is a more secure and up-to-date encryption algorithm. This is a class that I obtained a few years ago to perform AES encryption that I have modified over time to be more friendly for web applications (e,g. I've built Encrypt/Decrypt methods that work with URL-friendly string). It also has the methods that work with byte arrays. NOTE: you should use different values in the Key (32 bytes) and Vector (16 bytes) arrays! You wouldn't want someone to figure out your keys by just assuming that you used this code as-is! All you have to do is change some of the numbers (must be <= 255) in the Key and Vector arrays (I left one invalid value in the Vector array to make sure you do this...). You can use <https://www.random.org/bytes/> to generate a new set easily: * [generate `Key`](https://www.random.org/cgi-bin/randbyte?nbytes=32&format=d) * [generate `Vector`](https://www.random.org/cgi-bin/randbyte?nbytes=16&format=d) Using it is easy: just instantiate the class and then call (usually) EncryptToString(string StringToEncrypt) and DecryptString(string StringToDecrypt) as methods. It couldn't be any easier (or more secure) once you have this class in place. --- ``` using System; using System.Data; using System.Security.Cryptography; using System.IO; public class SimpleAES { // Change these keys private byte[] Key = __Replace_Me__({ 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 }); // a hardcoded IV should not be used for production AES-CBC code // IVs should be unpredictable per ciphertext private byte[] Vector = __Replace_Me__({ 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 2521, 112, 79, 32, 114, 156 }); private ICryptoTransform EncryptorTransform, DecryptorTransform; private System.Text.UTF8Encoding UTFEncoder; public SimpleAES() { //This is our encryption method RijndaelManaged rm = new RijndaelManaged(); //Create an encryptor and a decryptor using our encryption method, key, and vector. EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector); DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector); //Used to translate bytes to text and vice versa UTFEncoder = new System.Text.UTF8Encoding(); } /// -------------- Two Utility Methods (not used but may be useful) ----------- /// Generates an encryption key. static public byte[] GenerateEncryptionKey() { //Generate a Key. RijndaelManaged rm = new RijndaelManaged(); rm.GenerateKey(); return rm.Key; } /// Generates a unique encryption vector static public byte[] GenerateEncryptionVector() { //Generate a Vector RijndaelManaged rm = new RijndaelManaged(); rm.GenerateIV(); return rm.IV; } /// ----------- The commonly used methods ------------------------------ /// Encrypt some text and return a string suitable for passing in a URL. public string EncryptToString(string TextValue) { return ByteArrToString(Encrypt(TextValue)); } /// Encrypt some text and return an encrypted byte array. public byte[] Encrypt(string TextValue) { //Translates our text value into a byte array. Byte[] bytes = UTFEncoder.GetBytes(TextValue); //Used to stream the data in and out of the CryptoStream. MemoryStream memoryStream = new MemoryStream(); /* * We will have to write the unencrypted bytes to the stream, * then read the encrypted result back from the stream. */ #region Write the decrypted value to the encryption stream CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write); cs.Write(bytes, 0, bytes.Length); cs.FlushFinalBlock(); #endregion #region Read encrypted value back out of the stream memoryStream.Position = 0; byte[] encrypted = new byte[memoryStream.Length]; memoryStream.Read(encrypted, 0, encrypted.Length); #endregion //Clean up. cs.Close(); memoryStream.Close(); return encrypted; } /// The other side: Decryption methods public string DecryptString(string EncryptedString) { return Decrypt(StrToByteArray(EncryptedString)); } /// Decryption when working with byte arrays. public string Decrypt(byte[] EncryptedValue) { #region Write the encrypted value to the decryption stream MemoryStream encryptedStream = new MemoryStream(); CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write); decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length); decryptStream.FlushFinalBlock(); #endregion #region Read the decrypted value from the stream. encryptedStream.Position = 0; Byte[] decryptedBytes = new Byte[encryptedStream.Length]; encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length); encryptedStream.Close(); #endregion return UTFEncoder.GetString(decryptedBytes); } /// Convert a string to a byte array. NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so). // System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); // return encoding.GetBytes(str); // However, this results in character values that cannot be passed in a URL. So, instead, I just // lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100). public byte[] StrToByteArray(string str) { if (str.Length == 0) throw new Exception("Invalid string value in StrToByteArray"); byte val; byte[] byteArr = new byte[str.Length / 3]; int i = 0; int j = 0; do { val = byte.Parse(str.Substring(i, 3)); byteArr[j++] = val; i += 3; } while (i < str.Length); return byteArr; } // Same comment as above. Normally the conversion would use an ASCII encoding in the other direction: // System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); // return enc.GetString(byteArr); public string ByteArrToString(byte[] byteArr) { byte val; string tempStr = ""; for (int i = 0; i <= byteArr.GetUpperBound(0); i++) { val = byteArr[i]; if (val < (byte)10) tempStr += "00" + val.ToString(); else if (val < (byte)100) tempStr += "0" + val.ToString(); else tempStr += val.ToString(); } return tempStr; } } ```
165,828
<p>I need to queue events and tasks for external systems in a reliable/transactional way. Using things like MSMQ or ActiveMQ look very seductive, but the transactional part becomes complicated (MSDTC, etc).</p> <p>We could use the database (SQL Server 2005+, Oracle 9+) and achieve easier transactional support, but the queuing part becomes uglier.</p> <p>Neither route seems all that great and is filled with nasty gotchas and edge cases.</p> <p>Can someone offer some practical guidance in this matter?</p> <p>Think: E/C/A or a scheduled task engine that wakes up every so often and see if there are any scheduled tasks that need running at this time (i.e. next-run-date has passed, but expiration-date has not yet been reached).</p>
[ { "answer_id": 165835, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://quartznet.sourceforge.net/\" rel=\"nofollow noreferrer\">Quartz.Net</a> is an open source job scheduling system.</p>\n" }, { "answer_id": 165836, "author": "MotoWilliams", "author_id": 2730, "author_profile": "https://Stackoverflow.com/users/2730", "pm_score": 0, "selected": false, "text": "<p>Is WebSphere MQ (MQ Series) an option? Is supports transactional messaging.</p>\n" }, { "answer_id": 165873, "author": "Nathan", "author_id": 541, "author_profile": "https://Stackoverflow.com/users/541", "pm_score": 2, "selected": false, "text": "<p>I've seen MSMQ used transactionally and it didn't seem particularly complicated - a Transaction SCope wrapped the enqueue or dequeue calls along with database access and all was well as long as the queue was defined as transactional once it was created. I don't think this is true with ActiveMQ, which is a message broker, but MSMQ is installed locally on each endpoint machine so getting an item transactionally into the queue doesn't require a fancy distributed transaction.</p>\n\n<p>You are probably already be aware of this, but on .NET there are a few lightweight libraries that provide some nice abstractions over MSMQ (and theoretically other transports as well)</p>\n\n<p>nServiceBus : <a href=\"http://www.nservicebus.com\" rel=\"nofollow noreferrer\">www.nservicebus.com</a></p>\n\n<p>Mass Transit : <a href=\"http://code.google.com/p/masstransit/\" rel=\"nofollow noreferrer\">http://code.google.com/p/masstransit/</a></p>\n\n<p>Also, Oren Eini has an interesting if experimental file system based, transactional queue. The benefit of this library is that, unlike MSMQ, it can be deployed as a library and does not require the maintenance headache of deploying MSMQ.</p>\n\n<p>You can read about that here: <a href=\"http://ayende.com/Blog/archive/2008/08/01/Rhino.Queues.Storage.Disk.aspx\" rel=\"nofollow noreferrer\">http://ayende.com/Blog/archive/2008/08/01/Rhino.Queues.Storage.Disk.aspx</a></p>\n\n<p>Also, SQL Server 2005 does handle queuing fairly elegantly, using SQL Server Service Broker, but you'll need SQL Server installed at each endpoint, and I don't know if SSB crosses the firewall.</p>\n\n<p>Finally, if you don't get the answer you're looking for here I highly recommend the nSErviceBus discussion forum. Udi Dahan answers these kinds of questions along with his small band of message oriented followers, and it is the best resource I have found so far to get my queue oriented questions answered quickly and competently. That forum is here: <a href=\"http://tech.groups.yahoo.com/group/nservicebus/\" rel=\"nofollow noreferrer\">http://tech.groups.yahoo.com/group/nservicebus/</a></p>\n" }, { "answer_id": 165876, "author": "csmba", "author_id": 350, "author_profile": "https://Stackoverflow.com/users/350", "pm_score": 4, "selected": true, "text": "<p>our system has 60 computers, each running 12 tasks (threads) which need to \"get next job\". All in all, it comes to 50K \"jobs\" per day. do the math of how many transactions per minute and realize task time is variable, so it is possible to get multiple \"pop\" events at the exact same time.</p>\n\n<p>We had our first version using MSMQ. conclusion: <strong>stay away</strong>. While it did do just fine with the load and synchronization issues, it had 2 problems. one annoying and one deal breaker.</p>\n\n<p><em>Annoying:</em> as Enterprise software, MSMQ has security needs that just make it one more thing to set up and fight with the customers network admin.</p>\n\n<p><em>Deal breaker:</em> then came the time we wanted to take the next job, but not using a simple pop but something like \"get next BLUE job\" or \"get next YELLOW job\". can't do it!</p>\n\n<p>We went to plan B: Implemented our own Q with a single SQL 2005 table. <strong>could not be happier</strong></p>\n\n<p>I stressed test it with 200K messages per day, worked. We can make the \"next\" logic as complicated as we want.</p>\n\n<p>the catch: you need to be very careful with the SQL that takes the next item. Since you want it to be fast and NON locking. there are 2 very important SQL <strong>hints</strong> we used based on some research. The magic goes something like this:</p>\n\n<pre><code>SELECT TOP 1 @Id = callid\nFROM callqtbl WITH (READPAST, XLOCK)\nwhere 1=1 ORDER BY xx,yy\n</code></pre>\n" }, { "answer_id": 166016, "author": "Bruce", "author_id": 6310, "author_profile": "https://Stackoverflow.com/users/6310", "pm_score": 1, "selected": false, "text": "<p>This is what MSMQ is designed for - queuing with transactions. If that doesn't work for you, check out the \"Service Broker\" feature of SQL Server - its the \"queue in a SQL table\" that 'csmba' describes in his answer, but it is an integrated SQL Server component, nicely packaged and exposed for your use.</p>\n" }, { "answer_id": 275193, "author": "Dmitry Khalatov", "author_id": 18174, "author_profile": "https://Stackoverflow.com/users/18174", "pm_score": 0, "selected": false, "text": "<p>You can look at Oracle feature named <a href=\"http://download-west.oracle.com/docs/cd/B10500_01/appdev.920/a96587/qintro.htm\" rel=\"nofollow noreferrer\">Advanced Queuing</a> </p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10862/" ]
I need to queue events and tasks for external systems in a reliable/transactional way. Using things like MSMQ or ActiveMQ look very seductive, but the transactional part becomes complicated (MSDTC, etc). We could use the database (SQL Server 2005+, Oracle 9+) and achieve easier transactional support, but the queuing part becomes uglier. Neither route seems all that great and is filled with nasty gotchas and edge cases. Can someone offer some practical guidance in this matter? Think: E/C/A or a scheduled task engine that wakes up every so often and see if there are any scheduled tasks that need running at this time (i.e. next-run-date has passed, but expiration-date has not yet been reached).
our system has 60 computers, each running 12 tasks (threads) which need to "get next job". All in all, it comes to 50K "jobs" per day. do the math of how many transactions per minute and realize task time is variable, so it is possible to get multiple "pop" events at the exact same time. We had our first version using MSMQ. conclusion: **stay away**. While it did do just fine with the load and synchronization issues, it had 2 problems. one annoying and one deal breaker. *Annoying:* as Enterprise software, MSMQ has security needs that just make it one more thing to set up and fight with the customers network admin. *Deal breaker:* then came the time we wanted to take the next job, but not using a simple pop but something like "get next BLUE job" or "get next YELLOW job". can't do it! We went to plan B: Implemented our own Q with a single SQL 2005 table. **could not be happier** I stressed test it with 200K messages per day, worked. We can make the "next" logic as complicated as we want. the catch: you need to be very careful with the SQL that takes the next item. Since you want it to be fast and NON locking. there are 2 very important SQL **hints** we used based on some research. The magic goes something like this: ``` SELECT TOP 1 @Id = callid FROM callqtbl WITH (READPAST, XLOCK) where 1=1 ORDER BY xx,yy ```
165,866
<p>I have Apache 2 running on a VPS server (running Debian). I recently changed the timezone on the server (using dpkg-reconfigure tzdata) from America/New_York to America/Los_Angeles to match my move across country. I have also rebooted the virtual machine since making the change.</p> <p>However, the Apache processes seem to flitter between timezones. See this snippet from the access_log:</p> <pre><code>127.0.0.1 - - [02/Oct/2008:23:01:13 -0700] "GET /favicon.ico HTTP/1.0" 301 - "-" "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.3) Gecko/2008092414 Firefox/3.0.3" 127.0.0.1 - - [03/Oct/2008:02:01:25 -0400] "GET /tag/wikipedia/?page=1 HTTP/1.0" 200 5984 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 127.0.0.1 - - [03/Oct/2008:02:01:36 -0400] "GET /index.atom HTTP/1.0" 200 7648 "-" "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.2) Gecko/2008091618 Firefox/3.0.2" 127.0.0.1 - - [03/Oct/2008:02:01:45 -0400] "GET /tag/moblog/ HTTP/1.0" 200 6563 "-" "msnbot/1.1 (+http://search.msn.com/msnbot.htm)" 127.0.0.1 - - [02/Oct/2008:23:01:46 -0700] "GET /tag/opensource/ HTTP/1.0" 200 5954 "-" "msnbot/1.1 (+http://search.msn.com/msnbot.htm)" 127.0.0.1 - - [03/Oct/2008:02:01:56 -0400] "GET /tag/dopplr/ HTTP/1.0" 200 3407 "-" "msnbot/1.1 (+http://search.msn.com/msnbot.htm)" </code></pre> <p>It jumps from 23:01 to 02:01 and back. Any idea how I can keep it consistent?</p>
[ { "answer_id": 165879, "author": "nobody", "author_id": 19405, "author_profile": "https://Stackoverflow.com/users/19405", "pm_score": 0, "selected": false, "text": "<p>Possibly some of the Apache worker processes were started before you changes the timezone, and some afterwards. Have you completely stopped and re-started Apache since changing the system timezone setting?</p>\n" }, { "answer_id": 165924, "author": "Mihai Limbășan", "author_id": 14444, "author_profile": "https://Stackoverflow.com/users/14444", "pm_score": 1, "selected": false, "text": "<p>Are you by any chance using ntpd and the peers against which you synchronize are flaky?</p>\n" }, { "answer_id": 256527, "author": "rodbegbie", "author_id": 8265, "author_profile": "https://Stackoverflow.com/users/8265", "pm_score": 3, "selected": true, "text": "<p>As it turns out, I had two Django projects running on this Apache instance, one of which I had fixed to point to America/Los_Angeles, but the other I had left behind. Depending on which app was accessed first when a new Apache process was created, it would muck up the time zone!</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8265/" ]
I have Apache 2 running on a VPS server (running Debian). I recently changed the timezone on the server (using dpkg-reconfigure tzdata) from America/New\_York to America/Los\_Angeles to match my move across country. I have also rebooted the virtual machine since making the change. However, the Apache processes seem to flitter between timezones. See this snippet from the access\_log: ``` 127.0.0.1 - - [02/Oct/2008:23:01:13 -0700] "GET /favicon.ico HTTP/1.0" 301 - "-" "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.3) Gecko/2008092414 Firefox/3.0.3" 127.0.0.1 - - [03/Oct/2008:02:01:25 -0400] "GET /tag/wikipedia/?page=1 HTTP/1.0" 200 5984 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 127.0.0.1 - - [03/Oct/2008:02:01:36 -0400] "GET /index.atom HTTP/1.0" 200 7648 "-" "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.2) Gecko/2008091618 Firefox/3.0.2" 127.0.0.1 - - [03/Oct/2008:02:01:45 -0400] "GET /tag/moblog/ HTTP/1.0" 200 6563 "-" "msnbot/1.1 (+http://search.msn.com/msnbot.htm)" 127.0.0.1 - - [02/Oct/2008:23:01:46 -0700] "GET /tag/opensource/ HTTP/1.0" 200 5954 "-" "msnbot/1.1 (+http://search.msn.com/msnbot.htm)" 127.0.0.1 - - [03/Oct/2008:02:01:56 -0400] "GET /tag/dopplr/ HTTP/1.0" 200 3407 "-" "msnbot/1.1 (+http://search.msn.com/msnbot.htm)" ``` It jumps from 23:01 to 02:01 and back. Any idea how I can keep it consistent?
As it turns out, I had two Django projects running on this Apache instance, one of which I had fixed to point to America/Los\_Angeles, but the other I had left behind. Depending on which app was accessed first when a new Apache process was created, it would muck up the time zone!
165,883
<p>Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like <code>obj.attr</code> ? Or perhaps write get accessors ? What are the accepted naming styles for such things ?</p> <p><strong>Edit:</strong> Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used.</p> <hr> <p>If this question has already been asked (and I have a hunch it has, though searching didn't bring results), please point to it - and I will close this one.</p>
[ { "answer_id": 165892, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 2, "selected": false, "text": "<p>I think most just access them directly, no need for get/set methods.</p>\n\n<pre><code>&gt;&gt;&gt; class myclass:\n... x = 'hello'\n...\n&gt;&gt;&gt;\n&gt;&gt;&gt; class_inst = myclass()\n&gt;&gt;&gt; class_inst.x\n'hello'\n&gt;&gt;&gt; class_inst.x = 'world'\n&gt;&gt;&gt; class_inst.x\n'world'\n</code></pre>\n\n<p>BTW, you can use the dir() function to see what attributes/methods are attached to your instance:</p>\n\n<pre><code>&gt;&gt;&gt; dir(class_inst)\n['__doc__', '__module__', 'x']\n</code></pre>\n\n<p>Two leading underbars, \"__\" are used to make a attribute or function private.\nFor other conventions refer to PEP 08:\n<a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">http://www.python.org/dev/peps/pep-0008/</a></p>\n" }, { "answer_id": 165896, "author": "Ignacio Vazquez-Abrams", "author_id": 20862, "author_profile": "https://Stackoverflow.com/users/20862", "pm_score": 1, "selected": false, "text": "<p>Python does not need to define accessors right from the beginning, since converting attributes into properties is quick and painless. See the following for a vivid demonstration:</p>\n\n<p><a href=\"http://www.archive.org/details/SeanKellyRecoveryfromAddiction\" rel=\"nofollow noreferrer\">Recovery from Addiction</a></p>\n" }, { "answer_id": 165901, "author": "Vasil", "author_id": 7883, "author_profile": "https://Stackoverflow.com/users/7883", "pm_score": -1, "selected": false, "text": "<p>Some people use getters and setters. Depending on which coding style you use you can name them getSpam and seteggs. But you can also make you attributes readonly or assign only. That's a bit awkward to do. One way is overriding the </p>\n\n<pre><code>&gt; __getattr__\n</code></pre>\n\n<p>and </p>\n\n<pre><code>&gt; __setattr__\n</code></pre>\n\n<p>methods.</p>\n\n<h2>Edit:</h2>\n\n<p>While my answer is still true, it's not right, as I came to realize. There are better ways to make accessors in python and are not very awkward.</p>\n" }, { "answer_id": 165911, "author": "willurd", "author_id": 1943957, "author_profile": "https://Stackoverflow.com/users/1943957", "pm_score": 6, "selected": true, "text": "<p>The generally accepted way of doing things is just using simple attributes, like so</p>\n\n<pre><code>>>> class MyClass:\n... myAttribute = 0\n... \n>>> c = MyClass()\n>>> c.myAttribute \n0\n>>> c.myAttribute = 1\n>>> c.myAttribute\n1\n</code></pre>\n\n<p>If you do find yourself needing to be able to write getters and setters, then what you want to look for is \"python class properties\" and <a href=\"http://tomayko.com/writings/getters-setters-fuxors\" rel=\"noreferrer\">Ryan Tomayko's article on\nGetters/Setters/Fuxors</a> is a great place to start (albeit a little long)</p>\n" }, { "answer_id": 165925, "author": "Anders Waldenborg", "author_id": 24082, "author_profile": "https://Stackoverflow.com/users/24082", "pm_score": 0, "selected": false, "text": "<p>There is no real point of doing getter/setters in python, you can't protect stuff anyway and if you need to execute some extra code when getting/setting the property look at the property() builtin (python -c 'help(property)')</p>\n" }, { "answer_id": 166073, "author": "Anders Waldenborg", "author_id": 24082, "author_profile": "https://Stackoverflow.com/users/24082", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Edit: Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used.</p>\n</blockquote>\n\n<p>Single underscore doesn't mean anything special to python, it is just best practice, to tell \"hey you probably don't want to access this unless you know what you are doing\". Double underscore however makes python mangle the name internally making it accessible only from the class where it is defined.</p>\n\n<p>Double leading AND trailing underscore denotes a special function, such as <code>__add__</code> which is called when using the + operator.</p>\n\n<p>Read more in <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>, especially the \"Naming Conventions\" section.</p>\n" }, { "answer_id": 166098, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 6, "selected": false, "text": "<p>With regards to the single and double-leading underscores: both indicate the same concept of 'privateness'. That is to say, people will know the attribute (be it a method or a 'normal' data attribute or anything else) is not part of the public API of the object. People will know that to touch it directly is to invite disaster.</p>\n\n<p>On top of that, the double-leading underscore attributes (but not the single-leading underscore attributes) are <em>name-mangled</em> to make accessing them <em>by accident</em> from subclasses or anywhere else outside the current class less likely. You can still access them, but not as trivially. For example:</p>\n\n<pre><code>&gt;&gt;&gt; class ClassA:\n... def __init__(self):\n... self._single = \"Single\"\n... self.__double = \"Double\"\n... def getSingle(self):\n... return self._single\n... def getDouble(self):\n... return self.__double\n... \n&gt;&gt;&gt; class ClassB(ClassA):\n... def getSingle_B(self):\n... return self._single\n... def getDouble_B(self):\n... return self.__double\n... \n&gt;&gt;&gt; a = ClassA()\n&gt;&gt;&gt; b = ClassB()\n</code></pre>\n\n<p>You can now trivially access <code>a._single</code> and <code>b._single</code> and get the <code>_single</code> attribute created by <code>ClassA</code>:</p>\n\n<pre><code>&gt;&gt;&gt; a._single, b._single\n('Single', 'Single')\n&gt;&gt;&gt; a.getSingle(), b.getSingle(), b.getSingle_B()\n('Single', 'Single', 'Single')\n</code></pre>\n\n<p>But trying to access the <code>__double</code> attribute on the <code>a</code> or <code>b</code> instance directly won't work:</p>\n\n<pre><code>&gt;&gt;&gt; a.__double\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\nAttributeError: ClassA instance has no attribute '__double'\n&gt;&gt;&gt; b.__double\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\nAttributeError: ClassB instance has no attribute '__double'\n</code></pre>\n\n<p>And though methods defined in <code>ClassA</code> can get at it directly (when called on either instance):</p>\n\n<pre><code>&gt;&gt;&gt; a.getDouble(), b.getDouble()\n('Double', 'Double')\n</code></pre>\n\n<p>Methods defined on <code>ClassB</code> can not:</p>\n\n<pre><code>&gt;&gt;&gt; b.getDouble_B()\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n File \"&lt;stdin&gt;\", line 5, in getDouble_B\nAttributeError: ClassB instance has no attribute '_ClassB__double'\n</code></pre>\n\n<p>And right in that error you get a hint about what's happening. The <code>__double</code> attribute name, when accessed inside a class, is being name-mangled to include the name of the class that it is being accessed <em>in</em>. When <code>ClassA</code> tries to access <code>self.__double</code>, it actually turns -- at compiletime -- into an access of <code>self._ClassA__double</code>, and likewise for <code>ClassB</code>. (If a method in <code>ClassB</code> were to assign to <code>__double</code>, not included in the code for brevity, it would therefor not touch <code>ClassA</code>'s <code>__double</code> but create a new attribute.) There is no other protection of this attribute, so you can still access it directly if you know the right name:</p>\n\n<pre><code>&gt;&gt;&gt; a._ClassA__double, b._ClassA__double\n('Double', 'Double')\n</code></pre>\n\n<p><strong>So why is this a problem?</strong></p>\n\n<p>Well, it's a problem any time you want to inherit and change the behaviour of any code dealing with this attribute. You either have to reimplement everything that touches this double-underscore attribute directly, or you have to guess at the class name and mangle the name manually. The problem gets worse when this double-underscore attribute is actually a method: overriding the method <em>or calling the method in a subclass</em> means doing the name-mangling manually, or reimplementing all the code that calls the method to not use the double-underscore name. Not to mention accessing the attribute dynamically, with <code>getattr()</code>: you will have to manually mangle there, too.</p>\n\n<p>On the other hand, because the attribute is only trivially rewritten, it offers only superficial 'protection'. Any piece of code can still get at the attribute by manually mangling, although that will make <em>their</em> code dependant on the name of <em>your</em> class, and efforts on your side to refactor your code or rename your class (while still keeping the same user-visible name, a common practice in Python) would needlessly break their code. They can also 'trick' Python into doing the name-mangling for them by naming their class the same as yours: notice how there is no module name included in the mangled attribute name. And lastly, the double-underscore attribute is still visible in all attribute lists and all forms of introspection that don't take care to skip attributes starting with a (<em>single</em>) underscore.</p>\n\n<p>So, <em>if</em> you use double-underscore names, use them exceedingly sparingly, as they can turn out quite inconvenient, and never use them for methods <strong>or anything else a subclass may ever want to reimplement, override or access directly</strong>. And realize that double-leading underscore name-mangling offers <em>no real protection</em>. In the end, using a single leading underscore wins you just as much and gives you less (potential, future) pain. Use a single leading underscore.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like `obj.attr` ? Or perhaps write get accessors ? What are the accepted naming styles for such things ? **Edit:** Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used. --- If this question has already been asked (and I have a hunch it has, though searching didn't bring results), please point to it - and I will close this one.
The generally accepted way of doing things is just using simple attributes, like so ``` >>> class MyClass: ... myAttribute = 0 ... >>> c = MyClass() >>> c.myAttribute 0 >>> c.myAttribute = 1 >>> c.myAttribute 1 ``` If you do find yourself needing to be able to write getters and setters, then what you want to look for is "python class properties" and [Ryan Tomayko's article on Getters/Setters/Fuxors](http://tomayko.com/writings/getters-setters-fuxors) is a great place to start (albeit a little long)
165,887
<p>What's the easiest way to compute the amount of working days since a date? VB.NET preferred, but C# is okay.</p> <p>And by "working days", I mean all days excluding Saturday and Sunday. If the algorithm can also take into account a list of specific 'exclusion' dates that shouldn't count as working days, that would be gravy. </p> <p>Thanks in advance for the contributed genius.</p>
[ { "answer_id": 165897, "author": "Dave Neeley", "author_id": 9660, "author_profile": "https://Stackoverflow.com/users/9660", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://classicasp.aspfaq.com/date-time-routines-manipulation/how-do-i-count-the-number-of-business-days-between-two-dates.html\" rel=\"nofollow noreferrer\">Here's</a> a method for SQL Server. There's also a vbscript method on the page. Not exactly what you asked for, I know.</p>\n" }, { "answer_id": 165902, "author": "Andrew Kennan", "author_id": 22506, "author_profile": "https://Stackoverflow.com/users/22506", "pm_score": 4, "selected": false, "text": "<p>The easiest way is probably something like</p>\n\n<pre><code>DateTime start = new DateTime(2008, 10, 3);\nDateTime end = new DateTime(2008, 12, 31);\nint workingDays = 0;\nwhile( start &lt; end ) {\n if( start.DayOfWeek != DayOfWeek.Saturday\n &amp;&amp; start.DayOfWeek != DayOfWeek.Sunday ) {\n workingDays++;\n }\n start = start.AddDays(1);\n}\n</code></pre>\n\n<p>It may not be the most efficient but it does allow for the easy checking of a list of holidays.</p>\n" }, { "answer_id": 165917, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/b5xbyt6f.aspx\" rel=\"nofollow noreferrer\">DateDiff</a> along with <a href=\"http://msdn.microsoft.com/en-us/library/2105eww7.aspx\" rel=\"nofollow noreferrer\">a few other Date* functions</a> are unique to VB.NET and often the subject of envy from C# developers. Not sure it'll be very helpful in this case, though.</p>\n" }, { "answer_id": 165918, "author": "Nathan", "author_id": 541, "author_profile": "https://Stackoverflow.com/users/541", "pm_score": 1, "selected": false, "text": "<p>We combined two CodeProject articles to arrive at a complete solution. Our library is not concise enough to post as source code, but I can point you to the two projects we used to achieve what we needed. As always with CodeProject articles, read the comments, there may be important info in them.</p>\n\n<p>Calculating business days:<a href=\"http://www.codeproject.com/KB/cs/busdatescalculation.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/busdatescalculation.aspx</a></p>\n\n<p>An alternative business day calc: http://www.codeproject.com/KB/cs/datetimelib.aspx</p>\n\n<p>Calculating Holidays:<a href=\"http://www.codeproject.com/KB/dotnet/HolidayCalculator.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/dotnet/HolidayCalculator.aspx</a></p>\n" }, { "answer_id": 165922, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p>in general (no code) -</p>\n\n<ul>\n<li>subtract the dates to get the number of days</li>\n<li>divide by 7 to get the number of weeks</li>\n<li>subtract number of weeks times 2</li>\n<li>count the number of holiday dates that fall with the date range</li>\n<li>subtract that count</li>\n</ul>\n\n<p>fiddle with the start/end dates so that they fall monday to monday, then add back the difference</p>\n\n<p>[apologies for the no-code generalities, it's late]</p>\n\n<p>[c.f. endDate.Subtract(startDate).TotalDays]</p>\n" }, { "answer_id": 165929, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 5, "selected": true, "text": "<p>This'll do what you want it to. It should be easy enough to convert to VB.NET, it's been too long for me to be able to do it though.</p>\n\n<pre><code>DateTime start = DateTime.Now;\nDateTime end = start.AddDays(9);\nIEnumerable&lt;DateTime&gt; holidays = new DateTime[0];\n\n// basic data\nint days = (int)(end - start).TotalDays;\nint weeks = days / 7;\n\n// check for a weekend in a partial week from start.\nif (7- (days % 7) &lt;= (int)start.DayOfWeek)\n days--;\nif (7- (days % 7) &lt;= (int)start.DayOfWeek)\n days--;\n\n// lose the weekends\ndays -= weeks * 2;\n\nforeach (DateTime dt in holidays)\n{\n if (dt &gt; start &amp;&amp; dt &lt; end)\n days--;\n}\n</code></pre>\n" }, { "answer_id": 6914432, "author": "Chris Betlach", "author_id": 874937, "author_profile": "https://Stackoverflow.com/users/874937", "pm_score": 2, "selected": false, "text": "<p>Here is a sample of Steve's formula in VB without the holiday subtraction:</p>\n\n<pre><code>Function CalcBusinessDays(ByVal DStart As Date, ByVal DEnd As Date) As Decimal\n\n Dim Days As Decimal = DateDiff(DateInterval.Day, DStart, DEnd)\n Dim Weeks As Integer = Days / 7\n Dim BusinessDays As Decimal = Days - (Weeks * 2)\n Return BusinessDays\n Days = Nothing\n Weeks = Nothing\n BusinessDays = Nothing\n\nEnd Function\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17235/" ]
What's the easiest way to compute the amount of working days since a date? VB.NET preferred, but C# is okay. And by "working days", I mean all days excluding Saturday and Sunday. If the algorithm can also take into account a list of specific 'exclusion' dates that shouldn't count as working days, that would be gravy. Thanks in advance for the contributed genius.
This'll do what you want it to. It should be easy enough to convert to VB.NET, it's been too long for me to be able to do it though. ``` DateTime start = DateTime.Now; DateTime end = start.AddDays(9); IEnumerable<DateTime> holidays = new DateTime[0]; // basic data int days = (int)(end - start).TotalDays; int weeks = days / 7; // check for a weekend in a partial week from start. if (7- (days % 7) <= (int)start.DayOfWeek) days--; if (7- (days % 7) <= (int)start.DayOfWeek) days--; // lose the weekends days -= weeks * 2; foreach (DateTime dt in holidays) { if (dt > start && dt < end) days--; } ```
165,931
<p>In a program I work on, I have a lot of code as follows:</p> <pre><code>pthread_mutex_lock( &amp;frame-&gt;mutex ); frame-&gt;variable = variable; pthread_mutex_unlock( &amp;frame-&gt;mutex ); </code></pre> <p>This is clearly a waste of CPU cycles if the middle instruction can just be replaced with an atomic store. I know that gcc is quite capable of this, but I haven't been able to find much documentation on such simple thread-safe atomic operations. How would I replace this set of code with an atomic operation?</p> <p>(I know that simple stores should theoretically be atomic, but I don't want to have to hope that the optimizer isn't screwing up their atomic-ness at some point in the process.)</p> <p>Clarification: I do not need them to be strictly atomic; these variables are solely used for thread synchronization. That is, Thread B reads the value, checks if its correct, and if its not correct, it sleeps. So even if Thread A updates the value and Thread B doesn't realize its updated, that isn't a problem, since that just means Thread B sleeps when it didn't really need to, and when it wakes up, the value will be correct.</p>
[ { "answer_id": 165948, "author": "Mihai Limbășan", "author_id": 14444, "author_profile": "https://Stackoverflow.com/users/14444", "pm_score": 4, "selected": false, "text": "<p>You could check the gcc documentation. For the current gcc version (4.3.2) it would be chapter 5.47 <a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Atomic-Builtins.html\" rel=\"noreferrer\">Built-in functions for atomic memory access</a> - for other gcc versions please check your docs. It should be in chapter 5- Extensions to the C Language Family.</p>\n\n<p>Incidentally, the C compiler makes absolutely no guarantee as to simple store operations being atomic. You cannot rely on that assumption. In order for a machine opcode to be executed atomically, it needs the LOCK prefix.</p>\n" }, { "answer_id": 165979, "author": "zvrba", "author_id": 2583, "author_profile": "https://Stackoverflow.com/users/2583", "pm_score": 1, "selected": false, "text": "<p>AFAIK, you can't prefix MOV instructions with LOCK; this is allowed only for RMW operations. But if he <em>does</em> use a simple store, he might also need a memory barrier, which is implicit with mutex, as well as with instructions that allow LOCK.</p>\n" }, { "answer_id": 171110, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "<p>On x86 and most other architectures, aligned 4-byte reads and writes are always atomic. The optimizer may skip/reorder reads and writes within a single thread, though.</p>\n\n<p>What you want to do is inform the compiler that other threads may have touched this memory location. (A side effect of <code>pthread_mutex_lock</code> is telling the compiler that other threads may have touched any part of memory.) You may see <code>volatile</code> recommended, but this not in the C specification, and GCC doesn't interpret <code>volatile</code> that way.</p>\n\n<pre><code>asm(\"\" : \"=m\" (variable));\nframe-&gt;variable = variable;\n</code></pre>\n\n<p>is a GCC-specific mechanism to say that \"<code>variable</code> has been written to, reload it\".</p>\n" }, { "answer_id": 2202776, "author": "Valeriu Paloş", "author_id": 266533, "author_profile": "https://Stackoverflow.com/users/266533", "pm_score": 4, "selected": false, "text": "<p>Up to a certain point, atomic operations in C were provided straight from the kernel sources via the atomic.h header.</p>\n\n<p>However, having kernel headers being used directly in user-space code is a very bad practice, so the atomic.h header file was removed some time ago. Instead we ca now make use of the \"GCC Atomic Builtins\" which are a far better and more reliable approach.</p>\n\n<p>There is a <a href=\"http://golubenco.org/?p=7\" rel=\"noreferrer\">very good explanation provided by Tudor Golubenco on his blog</a>. He even provides a drop-in replacement for the initial atomic.h file, in case you have some code that needs it.</p>\n\n<p>Unfortunately I'm new to stackoverflow, so I can only use one link in my comments, so check Tudor's post and get enlightened.</p>\n" }, { "answer_id": 2202932, "author": "erick2red", "author_id": 253287, "author_profile": "https://Stackoverflow.com/users/253287", "pm_score": 0, "selected": false, "text": "<p>As i can see, you're using gnu platform for development, so it's safe to say that glic provides a datatype int ranged with atomic capabilities, <code>'sig_atomic_t'</code> . So this approach can assure you atomic operations at kernel levels. not gcc levels.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11206/" ]
In a program I work on, I have a lot of code as follows: ``` pthread_mutex_lock( &frame->mutex ); frame->variable = variable; pthread_mutex_unlock( &frame->mutex ); ``` This is clearly a waste of CPU cycles if the middle instruction can just be replaced with an atomic store. I know that gcc is quite capable of this, but I haven't been able to find much documentation on such simple thread-safe atomic operations. How would I replace this set of code with an atomic operation? (I know that simple stores should theoretically be atomic, but I don't want to have to hope that the optimizer isn't screwing up their atomic-ness at some point in the process.) Clarification: I do not need them to be strictly atomic; these variables are solely used for thread synchronization. That is, Thread B reads the value, checks if its correct, and if its not correct, it sleeps. So even if Thread A updates the value and Thread B doesn't realize its updated, that isn't a problem, since that just means Thread B sleeps when it didn't really need to, and when it wakes up, the value will be correct.
You could check the gcc documentation. For the current gcc version (4.3.2) it would be chapter 5.47 [Built-in functions for atomic memory access](http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Atomic-Builtins.html) - for other gcc versions please check your docs. It should be in chapter 5- Extensions to the C Language Family. Incidentally, the C compiler makes absolutely no guarantee as to simple store operations being atomic. You cannot rely on that assumption. In order for a machine opcode to be executed atomically, it needs the LOCK prefix.
165,951
<p>Say I have a third party Application that does background work, but prints out all errors and messages to the console. This means, that currently, we have to keep a user logged on to the server, and restart the application (double-click) every time we reboot.</p> <p><em>Not so very cool.</em></p> <p>I was kind of sure, that there was an easy way to do this - a generic service wrapper, that can be configured with a log file for <code>stdout</code> and <code>stderr</code>.</p> <p>I did check <code>svchost.exe</code>, but <a href="http://www.google.ch/url?sa=t&amp;source=web&amp;ct=res&amp;cd=2&amp;url=http%3A%2F%2Fsupport.microsoft.com%2Fkb%2F314056&amp;ei=38DlSPGDLYbS0gWaupyXCw&amp;usg=AFQjCNFuvFUsrk_qf9ATt6N_Csh4dMJZnw&amp;sig2=UZLsm65gFNCdsUqszVgHWQ" rel="noreferrer">according to this site</a>, its only for DLL stuff. Pity.</p> <p><strong>EDIT:</strong> The application needs to be started from a batch file. FireDaemon seems to do the trick, but I think it is a bit overkill, for something that can be done in &lt;10 lines of python code... Oh well, <em>Not Invented Here</em>...</p>
[ { "answer_id": 165955, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 5, "selected": true, "text": "<p>Check out <a href=\"http://support.microsoft.com/kb/137890\" rel=\"noreferrer\"><code>srvany.exe</code></a> from the <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd&amp;displaylang=en\" rel=\"noreferrer\">Resource Kit</a>. This will let run anything as a service.</p>\n\n<p>You can pass parameters in the service definition to your executable via <code>srvany.exe</code> so you could run a batch file as a service by seting the registry as follows:</p>\n\n<pre><code>[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\MyService\\Parameters]\n\"Application\"=\"C:\\\\Windows\\\\System32\\\\cmd.exe\"\n\"AppParameters\"=\"/C C:\\\\My\\\\Batch\\\\Script.cmd\"\n\"AppDirectory\"=\"C:\\\\My\\\\Batch\"\n</code></pre>\n\n<p>Note: if you set up these keys in <code>RegEdit</code> rather than using a file you only need single backslashes in the values.</p>\n" }, { "answer_id": 165962, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 1, "selected": false, "text": "<p>Check out FireDaemon. There is a free version (FireDaemon lite I think) that only allows 1 service installed at a time, but this is a very useful tool for setting up services. It also wraps around batch files correctly, if this is required.</p>\n" }, { "answer_id": 165972, "author": "Torbjörn Gyllebring", "author_id": 21182, "author_profile": "https://Stackoverflow.com/users/21182", "pm_score": 2, "selected": false, "text": "<p>Why not simply implement a very thin service wrapper, here's a quickstart guide for writing a Service in .NET <a href=\"http://blogs.msdn.com/bclteam/archive/2005/03/15/396428.aspx\" rel=\"nofollow noreferrer\">Writing a Useful Windows Service in .NET in Five Minutes</a></p>\n\n<p>When you got that running you can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx\" rel=\"nofollow noreferrer\">Process</a> class to start the application and configure it so that you can handle stdout/stderr yourself (<a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.aspx\" rel=\"nofollow noreferrer\">ProcessStartInfo</a> is your friend).</p>\n" }, { "answer_id": 190124, "author": "Jason", "author_id": 26347, "author_profile": "https://Stackoverflow.com/users/26347", "pm_score": 0, "selected": false, "text": "<p>I second the firedaemon option. You may also want to set the option to allow the service to interact with the desktop to allow it to display the cli output window. They no longer offer a free version but if you search around the web for firedaemon lite you can find the older free lite version or maybe go the for pay route.</p>\n" }, { "answer_id": 10875847, "author": "Brad", "author_id": 362536, "author_profile": "https://Stackoverflow.com/users/362536", "pm_score": 3, "selected": false, "text": "<p>I'd recommend <a href=\"https://nssm.cc/download/?page=download\" rel=\"nofollow noreferrer\">NSSM: The Non-Sucking Service Manager</a>.</p>\n<ul>\n<li>32/64-bit EXEs</li>\n<li>Public Domain (!)</li>\n<li>Properly implements service stop messages, and sends the proper signal to your applications for graceful shutdown.</li>\n</ul>\n" }, { "answer_id": 70867180, "author": "Some One", "author_id": 15613541, "author_profile": "https://Stackoverflow.com/users/15613541", "pm_score": 0, "selected": false, "text": "<p>NSSM is long-dead. It's recommended to use <a href=\"https://github.com/winsw/winsw\" rel=\"nofollow noreferrer\">WinSW</a> on Windows 10 or Windows 11</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ]
Say I have a third party Application that does background work, but prints out all errors and messages to the console. This means, that currently, we have to keep a user logged on to the server, and restart the application (double-click) every time we reboot. *Not so very cool.* I was kind of sure, that there was an easy way to do this - a generic service wrapper, that can be configured with a log file for `stdout` and `stderr`. I did check `svchost.exe`, but [according to this site](http://www.google.ch/url?sa=t&source=web&ct=res&cd=2&url=http%3A%2F%2Fsupport.microsoft.com%2Fkb%2F314056&ei=38DlSPGDLYbS0gWaupyXCw&usg=AFQjCNFuvFUsrk_qf9ATt6N_Csh4dMJZnw&sig2=UZLsm65gFNCdsUqszVgHWQ), its only for DLL stuff. Pity. **EDIT:** The application needs to be started from a batch file. FireDaemon seems to do the trick, but I think it is a bit overkill, for something that can be done in <10 lines of python code... Oh well, *Not Invented Here*...
Check out [`srvany.exe`](http://support.microsoft.com/kb/137890) from the [Resource Kit](http://www.microsoft.com/downloads/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd&displaylang=en). This will let run anything as a service. You can pass parameters in the service definition to your executable via `srvany.exe` so you could run a batch file as a service by seting the registry as follows: ``` [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyService\Parameters] "Application"="C:\\Windows\\System32\\cmd.exe" "AppParameters"="/C C:\\My\\Batch\\Script.cmd" "AppDirectory"="C:\\My\\Batch" ``` Note: if you set up these keys in `RegEdit` rather than using a file you only need single backslashes in the values.
165,987
<p>My division has been tasked with recording the morning presentation audio for future use, using the built-in Windows Sound Recorder. Because of human nature, we don't always remember to start it on time. </p> <p>Windows doesn't have a built-in equivalent to the Unix <strong>cron</strong> function. Besides installing a new software program (which will take time, possibly cost money, and require IA certification), is there an easy way to automate the recording?</p> <p>I'm not adverse to writing a simple Python script for it, but I haven't programmed for Windows before; I don't know the APIs or anything required for this type of program.</p> <hr> <p><strong>Edit</strong> Thanks for the responses. I feel like an imbecile. I don't normally use Windows computers so I wasn't aware that Windows had the Task Scheduler.</p> <p>However, when I tested it with the recorder program, all it did was open the program; it didn't actually start recording. How do I get it to actually start recording when it is opened?</p>
[ { "answer_id": 166000, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": -1, "selected": false, "text": "<p>Start-Programs-Accessories-System Tools-Scheduled Tasks</p>\n" }, { "answer_id": 166147, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 0, "selected": false, "text": "<p>There is no command line parameter to start in recording mode.\nYou have to Start recording manually!</p>\n" }, { "answer_id": 166555, "author": "Craig Norton", "author_id": 24804, "author_profile": "https://Stackoverflow.com/users/24804", "pm_score": 3, "selected": true, "text": "<pre><code>set WshShell = WScript.CreateObject(\"WScript.Shell\") \nWScript.Sleep(100)\nWshShell.Run \"%SystemRoot%\\system32\\sndrec32.exe\" \nWScript.Sleep(100)\nWshShell.AppActivate \"Sound - Sound Recorder\" \nWScript.Sleep(100)\nWshShell.SendKeys \" \" \nWScript.Sleep(100)\n</code></pre>\n\n<p>Save the above text as RunSoundRecorder.vbs. This will start the sound record application and start it recording. Just point the task scheduler at this file.</p>\n\n<p>Incase you want to make changes:<br>\nThe third line is the exe to run<br>\nThe fifth line is the what is in the application title bar.</p>\n" }, { "answer_id": 169552, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 1, "selected": false, "text": "<p>Use <a href=\"http://www.autoitscript.com/autoit3/\" rel=\"nofollow noreferrer\">AutoIt3</a></p>\n\n<pre><code>Run ( @SystemDir + \"\\sndrec32.exe\", \"workingdir\" )\nSleep(5000) ;five seconds\nWinActivate( \"Sound - Sound Recorder\" )\nSleep(100)\nSend( \" \" )\n</code></pre>\n\n<p><em>Note: I have not tested this, because I don't use Windows very often anymore.</em></p>\n\n<p>Definitely worth checking out if you want to automate any Win32 Gui. It actually seems like it has received even more features since I last used it.</p>\n\n<p>Features: ( taken from <a href=\"http://www.autoitscript.com/autoit3/\" rel=\"nofollow noreferrer\">www.autoitscript.com/autoit3/</a> )</p>\n\n<ul>\n<li>Easy to learn BASIC-like syntax</li>\n<li>Simulate keystrokes and mouse movements</li>\n<li>Manipulate windows and processes</li>\n<li>Interact with all standard windows controls</li>\n<li>Scripts can be compiled into standalone executables</li>\n<li>Create Graphical User Interfaces (GUIs)</li>\n<li>COM support</li>\n<li>Regular expressions</li>\n<li>Directly call external DLL and Windows API functions</li>\n<li>Scriptable RunAs functions</li>\n<li>Detailed helpfile and large community-based support forums</li>\n<li>Compatible with Windows 95 / 98 / ME / NT4 / 2000 / XP / 2003 / Vista / 2008</li>\n<li>Unicode and x64 support</li>\n<li>Digitally signed for peace of mind</li>\n<li>Works with Windows Vista's User Account Control (UAC)</li>\n</ul>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/165987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
My division has been tasked with recording the morning presentation audio for future use, using the built-in Windows Sound Recorder. Because of human nature, we don't always remember to start it on time. Windows doesn't have a built-in equivalent to the Unix **cron** function. Besides installing a new software program (which will take time, possibly cost money, and require IA certification), is there an easy way to automate the recording? I'm not adverse to writing a simple Python script for it, but I haven't programmed for Windows before; I don't know the APIs or anything required for this type of program. --- **Edit** Thanks for the responses. I feel like an imbecile. I don't normally use Windows computers so I wasn't aware that Windows had the Task Scheduler. However, when I tested it with the recorder program, all it did was open the program; it didn't actually start recording. How do I get it to actually start recording when it is opened?
``` set WshShell = WScript.CreateObject("WScript.Shell") WScript.Sleep(100) WshShell.Run "%SystemRoot%\system32\sndrec32.exe" WScript.Sleep(100) WshShell.AppActivate "Sound - Sound Recorder" WScript.Sleep(100) WshShell.SendKeys " " WScript.Sleep(100) ``` Save the above text as RunSoundRecorder.vbs. This will start the sound record application and start it recording. Just point the task scheduler at this file. Incase you want to make changes: The third line is the exe to run The fifth line is the what is in the application title bar.
166,004
<p>I am facing a performance issue on a multi-core (8+) architecture with software written in C++ / VistualStudio / WindowsXP.</p> <p>Suddenly I realized that I have no idea of the performances of my L1 and L2 cache and CPU->to->Memory bandwidth.</p> <p>I have tested several tools (including VTune, Glowcode, etc, etc) but all of them fails when tested on load in a multicore architecture (which is the very reason why I need them!).</p> <p>Can you suggest any other tool which is not so fancy in doing graphs but can give me at least few indications of my cache/memory performances or can suggest snippets of code to manually instrument my application?</p> <p>Thanks!</p>
[ { "answer_id": 166000, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": -1, "selected": false, "text": "<p>Start-Programs-Accessories-System Tools-Scheduled Tasks</p>\n" }, { "answer_id": 166147, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 0, "selected": false, "text": "<p>There is no command line parameter to start in recording mode.\nYou have to Start recording manually!</p>\n" }, { "answer_id": 166555, "author": "Craig Norton", "author_id": 24804, "author_profile": "https://Stackoverflow.com/users/24804", "pm_score": 3, "selected": true, "text": "<pre><code>set WshShell = WScript.CreateObject(\"WScript.Shell\") \nWScript.Sleep(100)\nWshShell.Run \"%SystemRoot%\\system32\\sndrec32.exe\" \nWScript.Sleep(100)\nWshShell.AppActivate \"Sound - Sound Recorder\" \nWScript.Sleep(100)\nWshShell.SendKeys \" \" \nWScript.Sleep(100)\n</code></pre>\n\n<p>Save the above text as RunSoundRecorder.vbs. This will start the sound record application and start it recording. Just point the task scheduler at this file.</p>\n\n<p>Incase you want to make changes:<br>\nThe third line is the exe to run<br>\nThe fifth line is the what is in the application title bar.</p>\n" }, { "answer_id": 169552, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 1, "selected": false, "text": "<p>Use <a href=\"http://www.autoitscript.com/autoit3/\" rel=\"nofollow noreferrer\">AutoIt3</a></p>\n\n<pre><code>Run ( @SystemDir + \"\\sndrec32.exe\", \"workingdir\" )\nSleep(5000) ;five seconds\nWinActivate( \"Sound - Sound Recorder\" )\nSleep(100)\nSend( \" \" )\n</code></pre>\n\n<p><em>Note: I have not tested this, because I don't use Windows very often anymore.</em></p>\n\n<p>Definitely worth checking out if you want to automate any Win32 Gui. It actually seems like it has received even more features since I last used it.</p>\n\n<p>Features: ( taken from <a href=\"http://www.autoitscript.com/autoit3/\" rel=\"nofollow noreferrer\">www.autoitscript.com/autoit3/</a> )</p>\n\n<ul>\n<li>Easy to learn BASIC-like syntax</li>\n<li>Simulate keystrokes and mouse movements</li>\n<li>Manipulate windows and processes</li>\n<li>Interact with all standard windows controls</li>\n<li>Scripts can be compiled into standalone executables</li>\n<li>Create Graphical User Interfaces (GUIs)</li>\n<li>COM support</li>\n<li>Regular expressions</li>\n<li>Directly call external DLL and Windows API functions</li>\n<li>Scriptable RunAs functions</li>\n<li>Detailed helpfile and large community-based support forums</li>\n<li>Compatible with Windows 95 / 98 / ME / NT4 / 2000 / XP / 2003 / Vista / 2008</li>\n<li>Unicode and x64 support</li>\n<li>Digitally signed for peace of mind</li>\n<li>Works with Windows Vista's User Account Control (UAC)</li>\n</ul>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20042/" ]
I am facing a performance issue on a multi-core (8+) architecture with software written in C++ / VistualStudio / WindowsXP. Suddenly I realized that I have no idea of the performances of my L1 and L2 cache and CPU->to->Memory bandwidth. I have tested several tools (including VTune, Glowcode, etc, etc) but all of them fails when tested on load in a multicore architecture (which is the very reason why I need them!). Can you suggest any other tool which is not so fancy in doing graphs but can give me at least few indications of my cache/memory performances or can suggest snippets of code to manually instrument my application? Thanks!
``` set WshShell = WScript.CreateObject("WScript.Shell") WScript.Sleep(100) WshShell.Run "%SystemRoot%\system32\sndrec32.exe" WScript.Sleep(100) WshShell.AppActivate "Sound - Sound Recorder" WScript.Sleep(100) WshShell.SendKeys " " WScript.Sleep(100) ``` Save the above text as RunSoundRecorder.vbs. This will start the sound record application and start it recording. Just point the task scheduler at this file. Incase you want to make changes: The third line is the exe to run The fifth line is the what is in the application title bar.
166,033
<p>What is meant by ‘value semantics’, and what is meant by ‘implicit pointer semantics’?</p>
[ { "answer_id": 166039, "author": "David Pierre", "author_id": 18296, "author_profile": "https://Stackoverflow.com/users/18296", "pm_score": 5, "selected": true, "text": "<p>Java is using implicit pointer semantics for Object types and value semantics for primitives.</p>\n\n<p>Value semantics means that you deal directly with values and that you pass copies around.\nThe point here is that when you have a value, you can trust it won't change behind your back.</p>\n\n<p>With pointer semantics, you don't have a value, you have an 'address'.\nSomeone else could alter what is there, you can't know.</p>\n\n<p>Pointer Semantics in C++ : </p>\n\n<pre><code>void foo(Bar * b) ...\n... b-&gt;bar() ...\n</code></pre>\n\n<p>You need an * to ask for pointer semantics and -> to call methods on the pointee.</p>\n\n<p>Implicit Pointer Semantics in Java :</p>\n\n<pre><code>void foo(Bar b) ...\n... b.bar() ...\n</code></pre>\n\n<p>Since you don't have the choice of using value semantics, the * isn't needed nor the distinction between -> and ., hence the implicit.</p>\n" }, { "answer_id": 166041, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 1, "selected": false, "text": "<p>Java uses <code>implicit pointer semantics</code> on <em>variable access</em> (you can not directly edit the reference, it autmatically (implicit) gets resolved to the Object on access) and also uses <code>Pass-by-Value semantics</code> on <em>method parameters passing</em>. </p>\n\n<p>Read <a href=\"http://web.archive.org/web/20070526204705/http://www.ibm.com:80/developerworks/java/library/j-passbyval\" rel=\"nofollow noreferrer\">Pass-by-value semantics in Java applications</a>:</p>\n\n<blockquote>\n <p>In Java applications, when an object\n reference is a parameter to a method,\n you are passing a copy of the\n reference (pass by value), not the\n reference itself. Note that the\n calling method's object reference and\n the copy are pointing to the same\n object. This is an important\n distinction. A Java application does\n nothing differently when passing\n parameters of varying types like C++\n does. Java applications pass all\n parameters by value, thus making\n copies of all parameters regardless of\n type.</p>\n</blockquote>\n\n<p>Short: All parameters in Java are passed by value. But that doesn't mean an Object gets copied (like the default in PHP4), but the reference to that object gets copied.</p>\n\n<p>You'll see all explanations and in-depth examples on <a href=\"http://web.archive.org/web/20070526204705/http://www.ibm.com:80/developerworks/java/library/j-passbyval\" rel=\"nofollow noreferrer\">Pass-by-value semantics in Java applications</a></p>\n" }, { "answer_id": 166048, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "<p>Basically, value semantics means that assigning one value to another creates a copy:</p>\n\n<pre><code>int x = 1;\nint y = x;\nx = 2; // y remains the same!\n</code></pre>\n\n<p>A special case is a function call which gets passed an argument:</p>\n\n<pre><code>void f(int x) {\n x = 5;\n}\n\nint a = 1;\nf(a);\n// a is still 1\n</code></pre>\n\n<p>This is actually the same for Java and C++. However, Java knows only a few primitive types, among them <code>int</code>, <code>double</code>, <code>boolean</code> and <code>char</code>, along with enums which behave in this manner. All other types use reference semantics which means that an assignment of one value to another actually redirects a pointer instead of copying the underlying value:</p>\n\n<pre><code>class Foo {\n int x;\n\n public Foo(int x) { this.x = x; }\n}\n\nFoo a = new Foo(42);\nFoo b = a; // b and a share the same instance!\na.x = 32;\n//b.x is now also changed.\n</code></pre>\n\n<p>There are a few caveats however. For example, many reference types (<code>String</code>, <code>Integer</code> …) are actually immutables. Their value cannot be changed and any assignment to them overrides the old value.</p>\n\n<p>Also, arguments still get passed by value. This means that the value of an object passed to a function can be changed but its reference can't:</p>\n\n<pre><code>void f(Foo foo) {\n foo.x = 42;\n}\n\nvoid g(Foo foo) {\n foo = new Foo(42);\n}\n\nFoo a = new Foo(23);\nf(a);\n// a.x is now 42!\n\nFoo b = new Foo(1);\ng(b);\n// b remains unchanged!\n</code></pre>\n" }, { "answer_id": 166052, "author": "Bartosz Blimke", "author_id": 18715, "author_profile": "https://Stackoverflow.com/users/18715", "pm_score": 1, "selected": false, "text": "<p>Java is pass by value.\nC++ can use both, value and reference semantics.</p>\n\n<p><a href=\"http://javadude.com/articles/passbyvalue.htm\" rel=\"nofollow noreferrer\">http://javadude.com/articles/passbyvalue.htm</a></p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
What is meant by ‘value semantics’, and what is meant by ‘implicit pointer semantics’?
Java is using implicit pointer semantics for Object types and value semantics for primitives. Value semantics means that you deal directly with values and that you pass copies around. The point here is that when you have a value, you can trust it won't change behind your back. With pointer semantics, you don't have a value, you have an 'address'. Someone else could alter what is there, you can't know. Pointer Semantics in C++ : ``` void foo(Bar * b) ... ... b->bar() ... ``` You need an \* to ask for pointer semantics and -> to call methods on the pointee. Implicit Pointer Semantics in Java : ``` void foo(Bar b) ... ... b.bar() ... ``` Since you don't have the choice of using value semantics, the \* isn't needed nor the distinction between -> and ., hence the implicit.
166,044
<p>When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it <a href="http://malektips.com/dos0017.html" rel="noreferrer">here</a>, which describes a callable "wait.bat", implemented as follows:</p> <pre><code>@ping 127.0.0.1 -n 2 -w 1000 &gt; nul @ping 127.0.0.1 -n %1% -w 1000&gt; nul </code></pre> <p>You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.</p> <p><a href="http://malektips.com/xp_dos_0002.html" rel="noreferrer">Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command</a> (at last!). In the meantime, for those of us still using Windows&nbsp;XP, Windows 2000 or (sadly) <a href="http://en.wikipedia.org/wiki/Windows_NT" rel="noreferrer">Windows NT</a>, is there a better way?</p> <p>I modified the <code>sleep.py</code> script in the <a href="https://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290">accepted answer</a>, so that it defaults to one second if no arguments are passed on the command line:</p> <pre class="lang-py prettyprint-override"><code>import time, sys time.sleep(float(sys.argv[1]) if len(sys.argv) &gt; 1 else 1) </code></pre>
[ { "answer_id": 166053, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"https://en.wikipedia.org/wiki/Resource_Kit\" rel=\"nofollow noreferrer\">Resource Kit</a> has always included this. At least since Windows 2000.</p>\n\n<p>Also, the Cygwin package has a <code>sleep</code> - plop that into your PATH and include the <code>cygwin.dll</code> (or whatever it's called) and way to go!</p>\n" }, { "answer_id": 166058, "author": "Luk", "author_id": 5789, "author_profile": "https://Stackoverflow.com/users/5789", "pm_score": 4, "selected": false, "text": "<p><code>SLEEP.exe</code> is included in most Resource Kits e.g. <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd&amp;displaylang=en\" rel=\"noreferrer\">The Windows Server 2003 Resource Kit</a> which can be installed on Windows XP too.</p>\n\n<pre><code>Usage: sleep time-to-sleep-in-seconds\n sleep [-m] time-to-sleep-in-milliseconds\n sleep [-c] commited-memory ratio (1%-100%)\n</code></pre>\n" }, { "answer_id": 166093, "author": "John Sibly", "author_id": 1078, "author_profile": "https://Stackoverflow.com/users/1078", "pm_score": 4, "selected": false, "text": "<p>I faced a similar problem, but I just knocked up a very short C++ console application to do the same thing. Just run <em>MySleep.exe 1000</em> - perhaps easier than downloading/installing the whole resource kit.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;tchar.h&gt;\n#include &lt;stdio.h&gt;\n#include \"Windows.h\"\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n if (argc == 2)\n {\n _tprintf(_T(\"Sleeping for %s ms\\n\"), argv[1]);\n Sleep(_tstoi(argv[1]));\n }\n else\n {\n _tprintf(_T(\"Wrong number of arguments.\\n\"));\n }\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 166187, "author": "Tooony", "author_id": 23864, "author_profile": "https://Stackoverflow.com/users/23864", "pm_score": 2, "selected": false, "text": "<p>The usage of <a href=\"http://en.wikipedia.org/wiki/Ping_%28networking_utility%29\" rel=\"nofollow noreferrer\">ping</a> is good, as long as you just want to \"wait for a bit\". This since you are dependent on other functions underneath, like your network working and the fact that there is nothing answering on 127.0.0.1. ;-) Maybe it is not very likely it fails, but it is not impossible... </p>\n\n<p>If you want to be sure that you are waiting exactly the specified time, you should use the <code>sleep</code> functionality (which also have the advantage that it doesn't use CPU power or wait for a network to become ready).</p>\n\n<p>To find an already made executable for sleep is the most convenient way. Just drop it into your Windows folder or any other part of your standard path and it is always available.</p>\n\n<p>Otherwise, if you have a compiling environment you can easily make one yourself.\nThe <code>Sleep</code> function is available in <code>kernel32.dll</code>, so you just need to use that one. :-)\nFor VB / VBA declare the following in the beginning of your source to declare a sleep function:</p>\n\n<pre><code>private Declare Sub Sleep Lib \"kernel32\" Alias \"Sleep\" (byval dwMilliseconds as Long)\n</code></pre>\n\n<p>For C#:</p>\n\n<pre><code>[DllImport(\"kernel32.dll\")]\nstatic extern void Sleep(uint dwMilliseconds);\n</code></pre>\n\n<p>You'll find here more about this functionality (available since Windows 2000) in <em><a href=\"http://msdn.microsoft.com/en-us/library/ms686298%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">Sleep function</a></em> (MSDN).</p>\n\n<p>In standard C, <code>sleep()</code> is included in the standard library and in Microsoft's Visual Studio C the function is named <code>Sleep()</code>, if memory serves me. ;-) Those two takes the argument in seconds, not in milliseconds as the two previous declarations.</p>\n" }, { "answer_id": 166290, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 5, "selected": true, "text": "<h1>UPDATE</h1>\n<p>The <code>timeout</code> command, available from Windows Vista and onwards should be the command used, as described in another <a href=\"https://stackoverflow.com/a/5483958/6899\">answer</a> to this question. What follows here is an <em>old</em> answer.</p>\n<h3>Old answer</h3>\n<p>If you have Python installed, or don't mind installing it (it has other uses too :), just create the following <strong>sleep.py</strong> script and add it somewhere in your PATH:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import time, sys\n\ntime.sleep(float(sys.argv[1]))\n</code></pre>\n<p>It will allow sub-second pauses (for example, 1.5 sec, 0.1, etc.), should you have such a need. If you want to call it as <code>sleep</code> rather than <code>sleep.py</code>, then you can add the <code>.PY</code> extension to your PATHEXT environment variable. On Windows XP, you can edit it in:</p>\n<p>My Computer → Properties (menu) → Advanced (tab) → Environment Variables (button) → System variables (frame)</p>\n" }, { "answer_id": 1092731, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 2, "selected": false, "text": "<p>I have been using this C# sleep program. It might be more convenient for you if C# is your preferred language:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\n\nnamespace sleep\n{\n class Program\n {\n static void Main(string[] args)\n {\n if (args.Length == 1)\n {\n double time = Double.Parse(args[0]);\n Thread.Sleep((int)(time*1000));\n }\n else\n {\n Console.WriteLine(\"Usage: sleep &lt;seconds&gt;\\nExample: sleep 10\");\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 1202058, "author": "Peter Mortensen", "author_id": 63550, "author_profile": "https://Stackoverflow.com/users/63550", "pm_score": 2, "selected": false, "text": "<p>Even more lightweight than the Python solution is a Perl\none-liner.</p>\n\n<p>To sleep for seven seconds put this in the BAT script:</p>\n\n<pre><code>perl -e \"sleep 7\"\n</code></pre>\n\n<p>This solution only provides a resolution of one second.</p>\n\n<p>If you need higher resolution then use the Time::HiRes\nmodule from CPAN. It provides <code>usleep()</code> which sleeps in\nmicroseconds and <code>nanosleep()</code> which sleeps in nanoseconds\n(both functions takes only integer arguments). See the\nStack&nbsp;Overflow question <em><a href=\"https://stackoverflow.com/questions/896904\">How do I sleep for a millisecond in Perl?</a></em> for further details.</p>\n\n<p>I have used <a href=\"https://en.wikipedia.org/wiki/ActivePerl\" rel=\"nofollow noreferrer\">ActivePerl</a> for many years. It is very easy to\ninstall.</p>\n" }, { "answer_id": 1304768, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": false, "text": "<p>You can use ping:</p>\n<pre><code>ping 127.0.0.1 -n 11 -w 1000 &gt;nul: 2&gt;nul:\n</code></pre>\n<p>It will wait 10 seconds.</p>\n<p>The reason you have to use 11 is because the first ping goes out immediately, not after one second. The number should always be one more than the number of seconds you want to wait.</p>\n<p>Keep in mind that the purpose of the <code>-w</code> is not to control how often packets are sent, it's to ensure that you wait no <em>more</em> than some time in the event that there are network problems. There are unlikely to be problems if you're pinging 127.0.0.1 so this is probably moot.</p>\n<p>The <code>ping</code> command on its own will normally send one packet per second. This is not actually documented in the Windows docs but it appears to follow the same rules as the Linux version (where it is documented).</p>\n" }, { "answer_id": 1811248, "author": "mlsteeves", "author_id": 68034, "author_profile": "https://Stackoverflow.com/users/68034", "pm_score": 3, "selected": false, "text": "<p>Over at Server Fault, <a href=\"https://serverfault.com/questions/38318/better-way-to-wait-a-few-seconds-in-a-bat-file\">a similar question was asked</a>, and the solution there was:</p>\n\n<pre><code>choice /d y /t 5 &gt; nul\n</code></pre>\n" }, { "answer_id": 1811314, "author": "Blake7", "author_id": 184135, "author_profile": "https://Stackoverflow.com/users/184135", "pm_score": 3, "selected": false, "text": "<p>You could use the Windows <em>cscript WSH</em> layer and this <em>wait.js</em> JavaScript file:</p>\n\n<pre><code>if (WScript.Arguments.Count() == 1)\n WScript.Sleep(WScript.Arguments(0)*1000);\nelse\n WScript.Echo(\"Usage: cscript wait.js seconds\");\n</code></pre>\n" }, { "answer_id": 5437271, "author": "Brent Stewart", "author_id": 353186, "author_profile": "https://Stackoverflow.com/users/353186", "pm_score": 3, "selected": false, "text": "<p>Just put this in your batch file where you want the wait.</p>\n\n<pre><code>@ping 127.0.0.1 -n 11 -w 1000 &gt; null\n</code></pre>\n" }, { "answer_id": 5438142, "author": "Joey", "author_id": 73070, "author_profile": "https://Stackoverflow.com/users/73070", "pm_score": 3, "selected": false, "text": "<p>Depending on your compatibility needs, either use <code>ping</code>:</p>\n\n<pre><code>ping -n &lt;numberofseconds+1&gt; localhost &gt;nul 2&gt;&amp;1\n</code></pre>\n\n<p>e.g. to wait 5 seconds, use </p>\n\n<pre><code>ping -n 6 localhost &gt;nul 2&gt;&amp;1\n</code></pre>\n\n<p>or on Windows 7 or later use <code>timeout</code>:</p>\n\n<pre><code>timeout 6 &gt;nul\n</code></pre>\n" }, { "answer_id": 5483958, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 8, "selected": false, "text": "<p>The <a href=\"http://technet.microsoft.com/en-us/library/cc754891.aspx\" rel=\"noreferrer\"><code>timeout</code></a> command is available from Windows&nbsp;Vista onwards:</p>\n\n<pre><code>c:\\&gt; timeout /?\n\nTIMEOUT [/T] timeout [/NOBREAK]\n\nDescription:\n This utility accepts a timeout parameter to wait for the specified\n time period (in seconds) or until any key is pressed. It also\n accepts a parameter to ignore the key press.\n\nParameter List:\n /T timeout Specifies the number of seconds to wait.\n Valid range is -1 to 99999 seconds.\n\n /NOBREAK Ignore key presses and wait specified time.\n\n /? Displays this help message.\n\nNOTE: A timeout value of -1 means to wait indefinitely for a key press.\n\nExamples:\n TIMEOUT /?\n TIMEOUT /T 10\n TIMEOUT /T 300 /NOBREAK\n TIMEOUT /T -1\n</code></pre>\n\n<p>Note: It does not work with input redirection - trivial example:</p>\n\n<pre><code>C:\\&gt;echo 1 | timeout /t 1 /nobreak\nERROR: Input redirection is not supported, exiting the process immediately.\n</code></pre>\n" }, { "answer_id": 5822491, "author": "Chris Moschini", "author_id": 176877, "author_profile": "https://Stackoverflow.com/users/176877", "pm_score": 1, "selected": false, "text": "<p>I am impressed with this one:</p>\n\n<p><a href=\"http://www.computerhope.com/batch.htm#02\" rel=\"nofollow noreferrer\">http://www.computerhope.com/batch.htm#02</a></p>\n\n<pre><code>choice /n /c y /d y /t 5 &gt; NUL\n</code></pre>\n\n<p>Technically, you're telling the <code>choice</code> command to accept only y. It defaults to y, to do so in 5 seconds, to draw no prompt, and to dump anything it does say to NUL (like null terminal on Linux).</p>\n" }, { "answer_id": 6806192, "author": "Aacini", "author_id": 778560, "author_profile": "https://Stackoverflow.com/users/778560", "pm_score": 4, "selected": false, "text": "<p>I disagree with the answers I found here.</p>\n\n<p>I use the following method entirely based on Windows&nbsp;XP capabilities to do a delay in a batch file:</p>\n\n<p>DELAY.BAT:</p>\n\n<pre><code>@ECHO OFF\nREM DELAY seconds\n\nREM GET ENDING SECOND\nFOR /F \"TOKENS=1-3 DELIMS=:.\" %%A IN (\"%TIME%\") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, ENDING=(H*60+M)*60+S+%1\n\nREM WAIT FOR SUCH A SECOND\n:WAIT\nFOR /F \"TOKENS=1-3 DELIMS=:.\" %%A IN (\"%TIME%\") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, CURRENT=(H*60+M)*60+S\nIF %CURRENT% LSS %ENDING% GOTO WAIT\n</code></pre>\n\n<p>You may also insert the day in the calculation so the method also works when the delay interval pass over midnight.</p>\n" }, { "answer_id": 6852798, "author": "daniel", "author_id": 866502, "author_profile": "https://Stackoverflow.com/users/866502", "pm_score": 4, "selected": false, "text": "<p>Using the <code>ping</code> method as outlined is how I do it when I can't (or don't want to) add more executables or install any other software.</p>\n\n<p>You should be pinging something that isn't there, and using the <code>-w</code> flag so that it fails after that amount of time, not pinging something that <em>is</em> there (like localhost) <code>-n</code> times. This allows you to handle time less than a second, and I think it's slightly more accurate.</p>\n\n<p>e.g.</p>\n\n<p>(test that 1.1.1.1 isn't taken)</p>\n\n<pre><code>ECHO Waiting 15 seconds\n\nPING 1.1.1.1 -n 1 -w 15000 &gt; NUL\n or\nPING -n 15 -w 1000 127.1 &gt;NUL\n</code></pre>\n" }, { "answer_id": 8775655, "author": "Alex Robinson", "author_id": 972805, "author_profile": "https://Stackoverflow.com/users/972805", "pm_score": 2, "selected": false, "text": "<p>Or command line Python, for example, for 6 and a half seconds:</p>\n\n<pre><code>python -c \"import time;time.sleep(6.5)\"\n</code></pre>\n" }, { "answer_id": 14404448, "author": "SuperKael", "author_id": 1792474, "author_profile": "https://Stackoverflow.com/users/1792474", "pm_score": 2, "selected": false, "text": "<p>In Notepad, write:</p>\n\n<pre><code>@echo off\nset /a WAITTIME=%1+1\nPING 127.0.0.1 -n %WAITTIME% &gt; nul\ngoto:eof\n</code></pre>\n\n<p>Now save as wait.bat in the folder C:\\WINDOWS\\System32,\nthen whenever you want to wait, use:</p>\n\n<pre><code>CALL WAIT.bat &lt;whole number of seconds without quotes&gt;\n</code></pre>\n" }, { "answer_id": 14574706, "author": "Hossy", "author_id": 2020158, "author_profile": "https://Stackoverflow.com/users/2020158", "pm_score": 2, "selected": false, "text": "<p>I like <a href=\"https://stackoverflow.com/a/6806192/2020158\">Aacini's response</a>. I added to it to handle the day and also enable it to handle <a href=\"http://en.wikipedia.org/wiki/Centisecond\" rel=\"nofollow noreferrer\" title=\"Centisecond\">centiseconds</a> (<code>%TIME%</code> outputs <code>H:MM:SS.CC</code>):</p>\n\n<pre><code>:delay\nSET DELAYINPUT=%1\nSET /A DAYS=DELAYINPUT/8640000\nSET /A DELAYINPUT=DELAYINPUT-(DAYS*864000)\n\n::Get ending centisecond (10 milliseconds)\nFOR /F \"tokens=1-4 delims=:.\" %%A IN (\"%TIME%\") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, X=1%%D%%100, ENDING=((H*60+M)*60+S)*100+X+DELAYINPUT\nSET /A DAYS=DAYS+ENDING/8640000\nSET /A ENDING=ENDING-(DAYS*864000)\n\n::Wait for such a centisecond\n:delay_wait\nFOR /F \"tokens=1-4 delims=:.\" %%A IN (\"%TIME%\") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, X=1%%D%%100, CURRENT=((H*60+M)*60+S)*100+X\nIF DEFINED LASTCURRENT IF %CURRENT% LSS %LASTCURRENT% SET /A DAYS=DAYS-1\nSET LASTCURRENT=%CURRENT%\nIF %CURRENT% LSS %ENDING% GOTO delay_wait\nIF %DAYS% GTR 0 GOTO delay_wait\nGOTO :EOF\n</code></pre>\n" }, { "answer_id": 16803440, "author": "Niall Connaughton", "author_id": 114200, "author_profile": "https://Stackoverflow.com/users/114200", "pm_score": 3, "selected": false, "text": "<p>If you've got <a href=\"http://en.wikipedia.org/wiki/Windows_PowerShell\" rel=\"nofollow noreferrer\">PowerShell</a> on your system, you can just execute this command:</p>\n\n<pre><code>powershell -command \"Start-Sleep -s 1\"\n</code></pre>\n\n<hr>\n\n<p>Edit: from <a href=\"https://stackoverflow.com/a/16803409/114200\">my answer on a similar thread</a>, people raised an issue where the amount of time powershell takes to start is significant compared to how long you're trying to wait for. If the accuracy of the wait time is important (ie a second or two extra delay is not acceptable), you can use this approach:</p>\n\n<pre><code>powershell -command \"$sleepUntil = [DateTime]::Parse('%date% %time%').AddSeconds(5); $sleepDuration = $sleepUntil.Subtract((get-date)).TotalMilliseconds; start-sleep -m $sleepDuration\"\n</code></pre>\n\n<p>This takes the time when the windows command was issued, and the powershell script sleeps until 5 seconds after that time. So as long as powershell takes less time to start than your sleep duration, this approach will work (it's around 600ms on my machine).</p>\n" }, { "answer_id": 18644875, "author": "djangofan", "author_id": 118228, "author_profile": "https://Stackoverflow.com/users/118228", "pm_score": 0, "selected": false, "text": "<p>You can get fancy by putting the PAUSE message in the title bar:</p>\n\n<pre><code>@ECHO off\nSET TITLETEXT=Sleep\nTITLE %TITLETEXT%\nCALL :sleep 5\nGOTO :END\n:: Function Section\n:sleep ARG\nECHO Pausing...\nFOR /l %%a in (%~1,-1,1) DO (TITLE Script %TITLETEXT% -- time left^\n %%as&amp;PING.exe -n 2 -w 1000 127.1&gt;NUL)\nEXIT /B 0\n:: End of script\n:END\npause\n::this is EOF\n</code></pre>\n" }, { "answer_id": 20994851, "author": "npocmaka", "author_id": 388389, "author_profile": "https://Stackoverflow.com/users/388389", "pm_score": 0, "selected": false, "text": "<p>From Windows&nbsp;Vista on you have the <a href=\"http://ss64.com/nt/timeout.html\" rel=\"nofollow noreferrer\">TIMEOUT</a> and <a href=\"http://ss64.com/nt/sleep.html\" rel=\"nofollow noreferrer\">SLEEP</a> commands, but to use them on Windows&nbsp;XP or Windows Server 2003, you'll need the <a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=17657\" rel=\"nofollow noreferrer\">Windows Server 2003 resource tool kit</a>.</p>\n\n<p><a href=\"http://www.robvanderwoude.com/wait.php\" rel=\"nofollow noreferrer\">Here</a> you have a good overview of sleep alternatives (the ping approach is the most popular as it will work on every Windows machine), but there's (at least) one not mentioned which (ab)uses the <a href=\"https://ss64.com/nt/w32tm.html\" rel=\"nofollow noreferrer\"><code>W32TM</code></a> (Time Service) command:</p>\n\n<pre><code>w32tm /stripchart /computer:localhost /period:1 /dataonly /samples:N &gt;nul 2&gt;&amp;1\n</code></pre>\n\n<p>Where you should replace the N with the seconds you want to pause. Also, it will work on every Windows system without prerequisites.</p>\n\n<p>Typeperf can also be used:</p>\n\n<pre><code>typeperf \"\\System\\Processor Queue Length\" -si N -sc 1 &gt;nul\n</code></pre>\n\n<p>With mshta and javascript (can be used for sleep under a second):</p>\n\n<pre><code>start \"\" /wait /min /realtime mshta \"javascript:setTimeout(function(){close();},5000)\"\n</code></pre>\n\n<p>This should be even more precise (for waiting under a second) - self compiling executable relying on <code>.net</code>:</p>\n\n<pre><code>@if (@X)==(@Y) @end /* JScript comment\n@echo off\nsetlocal\n::del %~n0.exe /q /f\n::\n:: For precision better call this like\n:: call waitMS 500\n:: in order to skip compilation in case there's already built .exe\n:: as without pointed extension first the .exe will be called due to the ordering in PATEXT variable\n::\n::\nfor /f \"tokens=* delims=\" %%v in ('dir /b /s /a:-d /o:-n \"%SystemRoot%\\Microsoft.NET\\Framework\\*jsc.exe\"') do (\n set \"jsc=%%v\"\n)\n\nif not exist \"%~n0.exe\" (\n \"%jsc%\" /nologo /w:0 /out:\"%~n0.exe\" \"%~dpsfnx0\"\n)\n\n\n%~n0.exe %*\n\nendlocal &amp; exit /b %errorlevel%\n\n\n*/\n\n\nimport System;\nimport System.Threading;\n\nvar arguments:String[] = Environment.GetCommandLineArgs();\nfunction printHelp(){\n Console.WriteLine(arguments[0]+\" N\");\n Console.WriteLine(\" N - milliseconds to wait\");\n Environment.Exit(0); \n}\n\nif(arguments.length&lt;2){\n printHelp();\n}\n\ntry{\n var wait:Int32=Int32.Parse(arguments[1]);\n System.Threading.Thread.Sleep(wait);\n}catch(err){\n Console.WriteLine('Invalid Number passed');\n Environment.Exit(1);\n}\n</code></pre>\n" }, { "answer_id": 21252806, "author": "EpicNinjaCheese", "author_id": 3218259, "author_profile": "https://Stackoverflow.com/users/3218259", "pm_score": 1, "selected": false, "text": "<p>You can also use a .vbs file to do specific timeouts:</p>\n\n<p>The code below creates the .vbs file. Put this near the top of you rbatch code:</p>\n\n<pre><code>echo WScript.sleep WScript.Arguments(0) &gt;\"%cd%\\sleeper.vbs\"\n</code></pre>\n\n<p>The code below then opens the .vbs and specifies how long to wait for:</p>\n\n<pre><code>start /WAIT \"\" \"%cd%\\sleeper.vbs\" \"1000\"\n</code></pre>\n\n<p>In the above code, the \"1000\" is the value of time delay to be sent to the .vbs file in milliseconds, for example, 1000&nbsp;ms = 1&nbsp;s. You can alter this part to be however long you want.</p>\n\n<p>The code below deletes the .vbs file after you are done with it. Put this at the end of your batch file:</p>\n\n<pre><code>del /f /q \"%cd%\\sleeper.vbs\"\n</code></pre>\n\n<p>And here is the code all together so it's easy to copy:</p>\n\n<pre><code>echo WScript.sleep WScript.Arguments(0) &gt;\"%cd%\\sleeper.vbs\"\nstart /WAIT \"\" \"%cd%\\sleeper.vbs\" \"1000\"\ndel /f /q \"%cd%\\sleeper.vbs\"\n</code></pre>\n" }, { "answer_id": 21433296, "author": "Anonymous Coward", "author_id": 3106507, "author_profile": "https://Stackoverflow.com/users/3106507", "pm_score": 0, "selected": false, "text": "<p>This was tested on Windows&nbsp;XP SP3 and Windows&nbsp;7 and uses CScript. I put in some safe guards to avoid del \"\" prompting. (<code>/q</code> would be dangerous)</p>\n\n<p>Wait one second:</p>\n\n<blockquote>\n <p>sleepOrDelayExecution 1000</p>\n</blockquote>\n\n<p>Wait 500 ms and then run stuff after:</p>\n\n<pre><code>sleepOrDelayExecution 500 dir \\ /s\n</code></pre>\n\n<h3>sleepOrDelayExecution.bat:</h3>\n\n<pre><code>@echo off\nif \"%1\" == \"\" goto end\nif NOT %1 GTR 0 goto end\nsetlocal\nset sleepfn=\"%temp%\\sleep%random%.vbs\"\necho WScript.Sleep(%1) &gt;%sleepfn%\nif NOT %sleepfn% == \"\" if NOT EXIST %sleepfn% goto end\ncscript %sleepfn% &gt;nul\nif NOT %sleepfn% == \"\" if EXIST %sleepfn% del %sleepfn%\nfor /f \"usebackq tokens=1*\" %%i in (`echo %*`) DO @ set params=%%j\n%params%\n:end\n</code></pre>\n" }, { "answer_id": 21586700, "author": "Tato", "author_id": 3276779, "author_profile": "https://Stackoverflow.com/users/3276779", "pm_score": 2, "selected": false, "text": "<p>The best solution that should work on all Windows versions after Windows 2000 would be:</p>\n\n<pre><code>timeout numbersofseconds /nobreak &gt; nul\n</code></pre>\n" }, { "answer_id": 21941058, "author": "mafu", "author_id": 39590, "author_profile": "https://Stackoverflow.com/users/39590", "pm_score": 3, "selected": false, "text": "<p>There is a better way to sleep using ping. You'll want to ping an address that does not exist, so you can specify a timeout with millisecond precision. Luckily, such an address is defined in a standard (RFC 3330), and it is <code>192.0.2.x</code>. This is not made-up, it really is an address with the sole purpose of not-existing. To be clear, this applies even in local networks.</p>\n<blockquote>\n<p>192.0.2.0/24 - This block is assigned as &quot;TEST-NET&quot; for use in\ndocumentation and example code. It is often used in conjunction with\ndomain names example.com or example.net in vendor and protocol\ndocumentation. Addresses within this block should not appear on the\npublic Internet.</p>\n</blockquote>\n<p>To sleep for 123 milliseconds, use <strong><code>ping 192.0.2.1 -n 1 -w 123 &gt;nul</code></strong></p>\n<p>Update: As per the comments, there is also <code>127.255.255.255</code>.</p>\n" }, { "answer_id": 24022832, "author": "mgthomas99", "author_id": 3704301, "author_profile": "https://Stackoverflow.com/users/3704301", "pm_score": 3, "selected": false, "text": "<pre><code>timeout /t &lt;seconds&gt; &lt;options&gt;\n</code></pre>\n\n<p>For example, to make the script perform a non-uninterruptible 2-second wait:</p>\n\n<pre><code>timeout /t 2 /nobreak &gt;NUL\n</code></pre>\n\n<p>Which means the script will wait 2 seconds before continuing.</p>\n\n<p>By default, a keystroke will interrupt the timeout, so use the <code>/nobreak</code> switch if you don't want the user to be able to interrupt (cancel) the wait. Furthermore, the timeout will provide per-second notifications to notify the user how long is left to wait; this can be removed by piping the command to <code>NUL</code>.</p>\n\n<p><strong>edit:</strong> As <a href=\"https://stackoverflow.com/users/355230/martineau\">@martineau</a> <a href=\"https://stackoverflow.com/questions/166044/sleeping-in-a-batch-file#comment37041186_24022832\">points out in the comments</a>, the <code>timeout</code> command is only available on Windows 7 and above. Furthermore, the <code>ping</code> command uses less processor time than <code>timeout</code>. I still believe in using <code>timeout</code> where possible, though, as it is more readable than the <code>ping</code> 'hack'. Read more <a href=\"https://ss64.com/nt/timeout.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 24990713, "author": "FluorescentGreen5", "author_id": 3881189, "author_profile": "https://Stackoverflow.com/users/3881189", "pm_score": -1, "selected": false, "text": "<pre><code>ping -n X 127.0.0.1 &gt; nul\n</code></pre>\n\n<p>Replace X with the number of seconds + 1.</p>\n\n<p>For example, if you were to wait 10 seconds, replace X with 11. To wait 5 seconds, use 6.</p>\n\n<p>Read earlier answers for milliseconds.</p>\n" }, { "answer_id": 41981822, "author": "Andry", "author_id": 2672125, "author_profile": "https://Stackoverflow.com/users/2672125", "pm_score": 1, "selected": false, "text": "<p>The pathping.exe can sleep less than second.</p>\n\n<pre><code>@echo off\nsetlocal EnableDelayedExpansion \necho !TIME! &amp; pathping localhost -n -q 1 -p %~1 2&gt;&amp;1 &gt; nul &amp; echo !TIME!\n</code></pre>\n\n<p>.</p>\n\n<pre><code>&gt; sleep 10\n17:01:33,57\n17:01:33,60\n\n&gt; sleep 20\n17:03:56,54\n17:03:56,58\n\n&gt; sleep 50\n17:04:30,80\n17:04:30,87\n\n&gt; sleep 100\n17:07:06,12\n17:07:06,25\n\n&gt; sleep 200\n17:07:08,42\n17:07:08,64\n\n&gt; sleep 500\n17:07:11,05\n17:07:11,57\n\n&gt; sleep 800\n17:07:18,98\n17:07:19,81\n\n&gt; sleep 1000\n17:07:22,61\n17:07:23,62\n\n&gt; sleep 1500\n17:07:27,55\n17:07:29,06\n</code></pre>\n" }, { "answer_id": 53272431, "author": "codesniffer", "author_id": 5155476, "author_profile": "https://Stackoverflow.com/users/5155476", "pm_score": 0, "selected": false, "text": "<p>Since others are suggesting 3rd party programs (Python, Perl, custom app, etc), another option is GNU CoreUtils for Windows available at <a href=\"http://gnuwin32.sourceforge.net/packages/coreutils.htm\" rel=\"nofollow noreferrer\">http://gnuwin32.sourceforge.net/packages/coreutils.htm</a>.</p>\n\n<p>2 options for deployment:</p>\n\n<ol>\n<li>Install full package (which will include the full suite of CoreUtils, dependencies, documentation, etc).</li>\n<li>Install only the 'sleep.exe' binary and necessary dependencies (use depends.exe to get dependencies).</li>\n</ol>\n\n<p>One benefit of deploying CoreUtils is that you'll additionally get a host of other programs that are helpful for scripting (Windows batch leaves a lot to be desired).</p>\n" }, { "answer_id": 59511984, "author": "nonopolarity", "author_id": 325418, "author_profile": "https://Stackoverflow.com/users/325418", "pm_score": 1, "selected": false, "text": "<p>Just for fun, if you have Node.js installed, you can use</p>\n\n<pre><code>node -e 'setTimeout(a =&gt; a, 5000)'\n</code></pre>\n\n<p>to sleep for 5 seconds. It works on a Mac with Node v12.14.0.</p>\n" }, { "answer_id": 62525634, "author": "Lumito", "author_id": 13248902, "author_profile": "https://Stackoverflow.com/users/13248902", "pm_score": 2, "selected": false, "text": "<p>There are lots of ways to accomplish a '<em>sleep</em>' in cmd/batch:</p>\n<p>My favourite one:</p>\n<pre><code>TIMEOUT /NOBREAK 5 &gt;NUL 2&gt;NUL\n</code></pre>\n<p>This will stop the console for 5 seconds, without any output.</p>\n<p>Most used:</p>\n<pre><code>ping localhost -n 5 &gt;NUL 2&gt;NUL\n</code></pre>\n<p>This will try to make a connection to <code>localhost</code> 5 times. Since it is hosted on your computer, it will always reach the host, so every second it will try the new every second. The <code>-n</code> flag indicates how many times the script will try the connection. In this case is 5, so it will last 5 seconds.</p>\n<p>Variants of the last one:</p>\n<pre><code>ping 1.1.1.1 -n 5 &gt;nul\n</code></pre>\n<p>In this script there are some differences comparing it with the last one. This will not try to call <code>localhost</code>. Instead, it will try to connect to <code>1.1.1.1</code>, a very fast website. The action will last 5 seconds <strong>only if you have an active internet connection. Else it will last approximately 15 to complete the action</strong>. I do not recommend using this method.</p>\n<pre><code>ping 127.0.0.1 -n 5 &gt;nul\n</code></pre>\n<p>This is exactly the same as example 2 (most used). Also, you can also use:</p>\n<pre><code>ping [::1] -n 5 &gt;nul\n</code></pre>\n<p>This instead, uses IPv6's <code>localhost</code> version.</p>\n<p>There are lots of methods to perform this action. However, I prefer method 1 for Windows Vista and later versions and the most used method (method 2) for earlier versions of the OS.</p>\n" }, { "answer_id": 71616409, "author": "aakash4dev", "author_id": 17576982, "author_profile": "https://Stackoverflow.com/users/17576982", "pm_score": 0, "selected": false, "text": "<p>use <code>timeout</code></p>\n<p>e.g.- <code>timeout 10</code> will await for 10 seconds before executing next command in <code>cmd</code> or <code>powershell</code></p>\n" }, { "answer_id": 72579329, "author": "Vopel", "author_id": 11777065, "author_profile": "https://Stackoverflow.com/users/11777065", "pm_score": 0, "selected": false, "text": "<p>There are many answers on this issue noting the use of ping, but most of them point to loopback addresses or addresses that are now seen as valid addresses for DNS.</p>\n<p>Instead of that, you should use a TEST-NET IP address reserved for documentation use only, per the IETF.<br />\n(<a href=\"https://en.wikipedia.org/wiki/Reserved_IP_addresses\" rel=\"nofollow noreferrer\">more information on that here</a>)</p>\n<p>Here is a fully commented batch script to demonstrate the use of a sleep function using ping:</p>\n<pre><code>@echo off\n:: turns off command-echoing\n\necho/Script will now wait for 2.5 seconds &amp; echo/\n:: prints a line followed by a linebreak\n\ncall:sleep 2500\n:: waits for two-and-a-half seconds (2500 milliseconds)\n\necho/Done! Press any key to continue ... &amp; pause &gt;NUL\n:: prints a line and pauses\n\ngoto:EOF\n:: prevents the batch file from executing functions beyond this point\n\n\n::--FUNCTIONS--::\n\n:SLEEP\n:: call this function with the time to wait (in milliseconds)\n\nping 203.0.113.0 -n 1 -w &quot;%~1&quot; &gt;NUL\n:: 203.0.113.0 = TEST-NET-3 reserved IP; -n = ping count; -w = timeout\n\ngoto:EOF\n:: ends the call subroutine\n</code></pre>\n<p>And of course, you can also just use the command directly if you don't want to make a function:<br />\n<code>ping 203.0.113.0 -n 1 -w </code><em>timeInMilliseconds</em><code> &gt;NUL</code></p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2193/" ]
When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it [here](http://malektips.com/dos0017.html), which describes a callable "wait.bat", implemented as follows: ``` @ping 127.0.0.1 -n 2 -w 1000 > nul @ping 127.0.0.1 -n %1% -w 1000> nul ``` You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep. [Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command](http://malektips.com/xp_dos_0002.html) (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) [Windows NT](http://en.wikipedia.org/wiki/Windows_NT), is there a better way? I modified the `sleep.py` script in the [accepted answer](https://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290), so that it defaults to one second if no arguments are passed on the command line: ```py import time, sys time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1) ```
UPDATE ====== The `timeout` command, available from Windows Vista and onwards should be the command used, as described in another [answer](https://stackoverflow.com/a/5483958/6899) to this question. What follows here is an *old* answer. ### Old answer If you have Python installed, or don't mind installing it (it has other uses too :), just create the following **sleep.py** script and add it somewhere in your PATH: ```py import time, sys time.sleep(float(sys.argv[1])) ``` It will allow sub-second pauses (for example, 1.5 sec, 0.1, etc.), should you have such a need. If you want to call it as `sleep` rather than `sleep.py`, then you can add the `.PY` extension to your PATHEXT environment variable. On Windows XP, you can edit it in: My Computer → Properties (menu) → Advanced (tab) → Environment Variables (button) → System variables (frame)
166,051
<p>So most Java resources when speaking of packages mention a <code>com.yourcompany.project</code> setup. However, I do not work for a company, and don't have a website. Are there any naming conventions that are common? An email address, perhaps?</p>
[ { "answer_id": 166069, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 5, "selected": true, "text": "<p>Use a top-level domain like 'bernard' or something else unique. The important part is that the domain is unique so that you avoid clashes, and not that it starts with a real Internet top-level domain like org or com. E.g.</p>\n\n<pre><code>import java.util.*;\nimport bernard.myProject.*;\nimport org.apache.commons.lang.*;\n</code></pre>\n" }, { "answer_id": 166117, "author": "Rafał Dowgird", "author_id": 12166, "author_profile": "https://Stackoverflow.com/users/12166", "pm_score": 2, "selected": false, "text": "<p>Good advice on this topic found on the <a href=\"http://c2.com/ppr/wiki/JavaIdioms/JavaPackageNames.html\" rel=\"nofollow noreferrer\">web</a>: <em>\"Start your package names with your email address, reversed.[...] Or, host your code at a site which will give you a slice of their domain.\"</em></p>\n" }, { "answer_id": 166294, "author": "belugabob", "author_id": 13397, "author_profile": "https://Stackoverflow.com/users/13397", "pm_score": 2, "selected": false, "text": "<p>Why not register a domain?</p>\n\n<p>They're fairly cheap and doing so will guarantee that you don't clash with anybody else (or at least give you the satisfaction that if a clash does occur, it's the other person who will have to rewrite their code).</p>\n\n<p>Either register your own name, or try to make up a name that you may use as the basis for a business at a later date.</p>\n\n<ul>\n<li><code>bernard.surname.net</code></li>\n<li><code>madeupname.net</code></li>\n</ul>\n\n<p>This will cost you less than 10GBP per year.</p>\n\n<p>Personally, I'd go for the made up name approach, as it's likely to look more professional (unless you choose something really strange).</p>\n\n<p>An added advantage is that a lot of domains will come with email capabilities, giving you a better email address than [email protected].</p>\n" }, { "answer_id": 166326, "author": "Donal Tobin", "author_id": 22148, "author_profile": "https://Stackoverflow.com/users/22148", "pm_score": 2, "selected": false, "text": "<p>What you can do also is register a domain (actually a sub-domain) through a service such as DynDns (or one of the equivalents) and then use that domain name. You will be the sole controller and it is <strong>free</strong> and easy to maintain. They have a choice of 88 top domains at the moment (October 2008).\n<a href=\"http://www.dyndns.com/\" rel=\"nofollow noreferrer\">dyndns</a>\n<a href=\"http://www.dyndns.com/services/dns/dyndns/\" rel=\"nofollow noreferrer\">dynamic dns service</a></p>\n" }, { "answer_id": 169467, "author": "brianegge", "author_id": 14139, "author_profile": "https://Stackoverflow.com/users/14139", "pm_score": 3, "selected": false, "text": "<p>If your creating an open source project, you could register it with Sourceforge and use net.sourceforge.myproject. This is common with a lot of Java projects. An example is PMD <a href=\"http://pmd.sourceforge.net/\" rel=\"noreferrer\">http://pmd.sourceforge.net/</a>.</p>\n" }, { "answer_id": 169807, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 0, "selected": false, "text": "<p>For my own personal work when I don't have a namespace, I go for something simple like <code>org.&lt;myname&gt;.*</code></p>\n" }, { "answer_id": 190084, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 0, "selected": false, "text": "<p>I've been in a couple different companies who write house java classes. Often they're just <code>com.blah.blah.blah</code> without regard to whether there's a actual domain name behind it. </p>\n" }, { "answer_id": 818306, "author": "thSoft", "author_id": 90874, "author_profile": "https://Stackoverflow.com/users/90874", "pm_score": 0, "selected": false, "text": "<p>IMHO, best if it does not depend on any external information, such as hosting provider or company (it could be released to the open source community), since package-level refactoring is not quite desirable, especially in the case of frameworks and libraries. I suggest choosing your project name carefully and unambiguously, then using org.&lt;project name> as the root package.</p>\n" }, { "answer_id": 818367, "author": "Michael Borgwardt", "author_id": 16883, "author_profile": "https://Stackoverflow.com/users/16883", "pm_score": 3, "selected": false, "text": "<p>Note that the \"reverse domain name\" thing is just a convention: useful since it definitely avoids clashes if everyone adhers to it, but you don't have to follow it. </p>\n\n<p><strong>Just choose a name that you can be reasonably sure nobody else will use and which is not registered as trademark by anyone</strong> - because that's the one way you could actually get into legal trouble.</p>\n\n<p>And that means it's in fact a rather bad idea to use some sort of \"subdomain\" of a free service you're using, like deviantart or a dyndns or free mail service! Because most (if not all) of those domains are trademarked terms, and if your projects ever gets widely distributed, it could be seen as violating the trademark. Just because they allow you to use that name as an email address (or whatever) doesn't mean you can use it for anything else - in fact, their EULA almost certainly restricts usage to exactly that one purpose. </p>\n" }, { "answer_id": 818394, "author": "Uri", "author_id": 23072, "author_profile": "https://Stackoverflow.com/users/23072", "pm_score": 0, "selected": false, "text": "<p>Many people have their own websites and relatively unique names (or login names).</p>\n\n<p>If your name is Bernard Something, you may own BernardSomething.com,\nmaking com.bernardsomething.xxxx (or com.bsomething.xxx) a legitimate package name IMHO for personal code. </p>\n\n<p>That being said, If your project name is unique, you may want to name the package after that.</p>\n\n<p>And of course, get the domain after your name if you don't own it yet!</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ]
So most Java resources when speaking of packages mention a `com.yourcompany.project` setup. However, I do not work for a company, and don't have a website. Are there any naming conventions that are common? An email address, perhaps?
Use a top-level domain like 'bernard' or something else unique. The important part is that the domain is unique so that you avoid clashes, and not that it starts with a real Internet top-level domain like org or com. E.g. ``` import java.util.*; import bernard.myProject.*; import org.apache.commons.lang.*; ```
166,080
<p>Am working on sybase ASE 15. Looking for something like this</p> <pre><code>Select * into #tmp exec my_stp; </code></pre> <p>my_stp returns 10 data rows with two columns in each row.</p>
[ { "answer_id": 166172, "author": "Valerion", "author_id": 16156, "author_profile": "https://Stackoverflow.com/users/16156", "pm_score": -1, "selected": false, "text": "<p>Not sure about Sybase, but in SQL Server the following should work:</p>\n\n<p>INSERT INTO #tmp (col1,col2,col3...) exec my_stp</p>\n" }, { "answer_id": 175830, "author": "AdamH", "author_id": 21081, "author_profile": "https://Stackoverflow.com/users/21081", "pm_score": 3, "selected": false, "text": "<p>In ASE 15 I believe you can use functions, but they're not going to help with multirow datasets.</p>\n\n<p>If your stored proc is returning data with a \"select col1,col2 from somewhere\" then there's no way of grabbing that data, it just flows back to the client.</p>\n\n<p>What you can do is insert the data directly into the temp table. This can be a little tricky as if you create the temp table within the sproc it is deleted once the sproc finishes running and you don't get to see the contents. The trick for this is to create the temp table outside of the sproc, but to reference it from the sproc. The hard bit here is that every time you recreate the sproc you must create the temp table, or you'll get \"table not found\" errors.</p>\n\n<pre><code>\n --You must use this whole script to recreate the sproc \n create table #mine\n (col1 varchar(3),\n col2 varchar(3))\n go\n create procedure my_stp\n as\n insert into #mine values(\"aaa\",\"aaa\")\n insert into #mine values(\"bbb\",\"bbb\")\n insert into #mine values(\"ccc\",\"ccc\")\n insert into #mine values(\"ccc\",\"ccc\")\n go\n drop table #mine\n go\n</code></pre>\n\n<p>The to run the code:</p>\n\n<pre><code>\ncreate table #mine\n(col1 varchar(3),\ncol2 varchar(3))\ngo\n\nexec my_stp\ngo\n\nselect * from #mine\ndrop table #mine\ngo\n</code></pre>\n" }, { "answer_id": 5570045, "author": "Jakub Korab", "author_id": 263052, "author_profile": "https://Stackoverflow.com/users/263052", "pm_score": 3, "selected": false, "text": "<p>I've just faced this problem, and better late than never...</p>\n\n<p>It's doable, but a monstrous pain in the butt, involving a Sybase \"<a href=\"http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc36272.1550/html/commands/X35636.htm\" rel=\"nofollow\">proxy table</a>\" which is a standin for another local or remote object (table, procedure, view). The following works in 12.5, newer versions hopefully have a better way of doing it.</p>\n\n<p>Let's say you have a stored proc defined as:</p>\n\n<pre><code>create procedure mydb.mylogin.sp_extractSomething (\n@timestamp datetime) as\nselect column_a, column_b\n from sometable\n where timestamp = @timestamp\n</code></pre>\n\n<p>First switch to the tempdb: </p>\n\n<pre><code>use tempdb\n</code></pre>\n\n<p>Then create a proxy table where the columns match the result set:</p>\n\n<pre><code>create existing table myproxy_extractSomething (\ncolumn_a int not null, -- make sure that the types match up exactly!\ncolumn_b varchar(20) not null,\n_timestamp datetime null,\nprimary key (column_a)) external procedure at \"loopback.mydb.mylogin.sp_extractSomething\"\n</code></pre>\n\n<p>Points of note:</p>\n\n<ul>\n<li>\"loopback\" is the Sybase equivalent\nof localhost, but you can substitute\nit for any server registered in the\nserver's sysservers table. </li>\n<li>The _timestamp parameter gets translated to @timestamp when Sybase executes the stored proc, and all parameter columns declared like this must be defined as null.</li>\n</ul>\n\n<p>You can then select from the table like this from your own db:</p>\n\n<pre><code>declare @myTimestamp datetime\nset @myTimestamp = getdate()\n\nselect * \nfrom tempdb..myproxy_extractSomething\nwhere _timestamp = @myTimestamp\n</code></pre>\n\n<p>Which is straightforward enough. To then insert into a temporary table, create it first:</p>\n\n<pre><code>create table #myTempExtract (\n column_a int not null, -- again, make sure that the types match up exactly\n column_b varchar(20) not null,\n primary key (column_a)\n)\n</code></pre>\n\n<p>and combine:</p>\n\n<pre><code>insert into #myTempExtract (column_a, column_b)\nselect column_a, column_b\n from tempdb..myproxy_extractSomething\n where _timestamp = @myTimestamp\n</code></pre>\n" }, { "answer_id": 25579964, "author": "sankardevisharath", "author_id": 3931743, "author_profile": "https://Stackoverflow.com/users/3931743", "pm_score": -1, "selected": false, "text": "<p>If my_stp is populating data by computing values from different tables, you can create an equivalent view which does exactly the same as my_stp. </p>\n\n<pre><code>CREATE VIEW My_view\n AS\n/*\n My_stp body\n*/\n\n\nThen select data from view \nSELECT * INTO #x FROM my_view\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21246/" ]
Am working on sybase ASE 15. Looking for something like this ``` Select * into #tmp exec my_stp; ``` my\_stp returns 10 data rows with two columns in each row.
In ASE 15 I believe you can use functions, but they're not going to help with multirow datasets. If your stored proc is returning data with a "select col1,col2 from somewhere" then there's no way of grabbing that data, it just flows back to the client. What you can do is insert the data directly into the temp table. This can be a little tricky as if you create the temp table within the sproc it is deleted once the sproc finishes running and you don't get to see the contents. The trick for this is to create the temp table outside of the sproc, but to reference it from the sproc. The hard bit here is that every time you recreate the sproc you must create the temp table, or you'll get "table not found" errors. ``` --You must use this whole script to recreate the sproc create table #mine (col1 varchar(3), col2 varchar(3)) go create procedure my_stp as insert into #mine values("aaa","aaa") insert into #mine values("bbb","bbb") insert into #mine values("ccc","ccc") insert into #mine values("ccc","ccc") go drop table #mine go ``` The to run the code: ``` create table #mine (col1 varchar(3), col2 varchar(3)) go exec my_stp go select * from #mine drop table #mine go ```
166,083
<p>I have the following preprocessor divective:</p> <pre><code>#ifndef NDEBUG #define TRACE printf #else #define TRACE(...) #endif </code></pre> <p>and example of usage is:</p> <pre><code>TRACE("TRACE: some parameter = %i\n", param); </code></pre> <p>In C all works perfectly well when I build both debug and release versions, but in C++ compiler emits the following:</p> <p>warning: invalid character in macro parameter name</p> <p>error: badly punctuated parameter list in `#define'</p> <p>and points these warning and error to the 'TRACE(...)' directive.</p> <p>How to write this in C++ correctly?</p>
[ { "answer_id": 166087, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": true, "text": "<p>You could do:</p>\n\n<pre><code>inline void TRACE(...) {}\n</code></pre>\n" }, { "answer_id": 166124, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "<p><code>#define TRACE false ||</code></p>\n\n<p>This turns TRACE(x,y,z) into false || (x,y,z). Since x,y and z will be expressions, (x,y,z) evaluates to z (comma operator). z must be a built-in type (to be legally passed to a printf-style function) so it should be valid on the right side of ||. It won't be evaluated, but it must be a legal expression (e.g. you can't reference class members which only exist in DEBUG builds)</p>\n\n<p>Vararg macros are a C99 invention, they're not in C++98 but might very well be in C++0x</p>\n\n<p>[edit] - Using || to guarantee non-evaluation</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4378/" ]
I have the following preprocessor divective: ``` #ifndef NDEBUG #define TRACE printf #else #define TRACE(...) #endif ``` and example of usage is: ``` TRACE("TRACE: some parameter = %i\n", param); ``` In C all works perfectly well when I build both debug and release versions, but in C++ compiler emits the following: warning: invalid character in macro parameter name error: badly punctuated parameter list in `#define' and points these warning and error to the 'TRACE(...)' directive. How to write this in C++ correctly?
You could do: ``` inline void TRACE(...) {} ```
166,089
<p>I'm interested: What is C#'s analog of <code>std::pair</code> in C++? I found <code>System.Web.UI.Pair</code> class, but I'd prefer something template-based.</p> <p>Thank you!</p>
[ { "answer_id": 166094, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 10, "selected": true, "text": "<p>Tuples <a href=\"http://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx\" rel=\"noreferrer\">are available since .NET4.0</a> and support generics:</p>\n\n<pre><code>Tuple&lt;string, int&gt; t = new Tuple&lt;string, int&gt;(\"Hello\", 4);\n</code></pre>\n\n<hr>\n\n<p>In previous versions you can use <code>System.Collections.Generic.KeyValuePair&lt;K, V&gt;</code> or a solution like the following:</p>\n\n<pre><code>public class Pair&lt;T, U&gt; {\n public Pair() {\n }\n\n public Pair(T first, U second) {\n this.First = first;\n this.Second = second;\n }\n\n public T First { get; set; }\n public U Second { get; set; }\n};\n</code></pre>\n\n<p>And use it like this:</p>\n\n<pre><code>Pair&lt;String, int&gt; pair = new Pair&lt;String, int&gt;(\"test\", 2);\nConsole.WriteLine(pair.First);\nConsole.WriteLine(pair.Second);\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>test\n2\n</code></pre>\n\n<p>Or even this chained pairs:</p>\n\n<pre><code>Pair&lt;Pair&lt;String, int&gt;, bool&gt; pair = new Pair&lt;Pair&lt;String, int&gt;, bool&gt;();\npair.First = new Pair&lt;String, int&gt;();\npair.First.First = \"test\";\npair.First.Second = 12;\npair.Second = true;\n\nConsole.WriteLine(pair.First.First);\nConsole.WriteLine(pair.First.Second);\nConsole.WriteLine(pair.Second);\n</code></pre>\n\n<p>That outputs:</p>\n\n<pre><code>test\n12\ntrue\n</code></pre>\n" }, { "answer_id": 166095, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 3, "selected": false, "text": "<p>If it's about dictionaries and the like, you're looking for System.Collections.Generic.KeyValuePair&lt;TKey, TValue&gt;.</p>\n" }, { "answer_id": 166100, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "<p>Unfortunately, there is none. You can use the <code>System.Collections.Generic.KeyValuePair&lt;K, V&gt;</code> in many situations.</p>\n\n<p>Alternatively, you can use anonymous types to handle tuples, at least locally:</p>\n\n<pre><code>var x = new { First = \"x\", Second = 42 };\n</code></pre>\n\n<p>The last alternative is to create an own class.</p>\n" }, { "answer_id": 166101, "author": "Grimtron", "author_id": 17378, "author_profile": "https://Stackoverflow.com/users/17378", "pm_score": 2, "selected": false, "text": "<p>Depending on what you want to accomplish, you might want to try out <a href=\"http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx\" rel=\"nofollow noreferrer\">KeyValuePair</a>. </p>\n\n<p>The fact that you cannot change the key of an entry can of course be rectified by simply replacing the entire entry by a new instance of KeyValuePair.</p>\n" }, { "answer_id": 201999, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I was asking the same question just now after a quick google I found that There is a pair class in .NET except its in the System.Web.UI ^ ~ ^ (<a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx\" rel=\"nofollow noreferrer\"><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx</a></a>)\ngoodness knows why they put it there instead of the collections framework</p>\n" }, { "answer_id": 493969, "author": "Erik Forbes", "author_id": 16942, "author_profile": "https://Stackoverflow.com/users/16942", "pm_score": 2, "selected": false, "text": "<p>I created a C# implementation of Tuples, which solves the problem generically for between two and five values - <a href=\"http://shadowcoding.blogspot.com/2008/12/tuples.html\" rel=\"nofollow noreferrer\">here's the blog post</a>, which contains a link to the source.</p>\n" }, { "answer_id": 1226383, "author": "Jay Walker", "author_id": 61378, "author_profile": "https://Stackoverflow.com/users/61378", "pm_score": 7, "selected": false, "text": "<p><code>System.Web.UI</code> contained the <code>Pair</code> class because it was used heavily in ASP.NET 1.1 as an internal ViewState structure.</p>\n\n<p><strong>Update Aug 2017:</strong> C# 7.0 / .NET Framework 4.7 provides a syntax to declare a Tuple with named items using the <a href=\"https://msdn.microsoft.com/en-us/library/system.valuetuple.aspx\" rel=\"noreferrer\"><code>System.ValueTuple</code></a> struct.</p>\n\n<pre><code>//explicit Item typing\n(string Message, int SomeNumber) t = (\"Hello\", 4);\n//or using implicit typing \nvar t = (Message:\"Hello\", SomeNumber:4);\n\nConsole.WriteLine(\"{0} {1}\", t.Message, t.SomeNumber);\n</code></pre>\n\n<p>see <a href=\"https://msdn.microsoft.com/en-us/magazine/mt493248.aspx\" rel=\"noreferrer\">MSDN</a> for more syntax examples. </p>\n\n<p><strong>Update Jun 2012:</strong> <a href=\"http://msdn.microsoft.com/en-us/library/system.tuple.aspx\" rel=\"noreferrer\"><code>Tuples</code></a> have been a part of .NET since version 4.0.</p>\n\n<p>Here is <a href=\"http://msdn.microsoft.com/en-us/magazine/dd942829.aspx\" rel=\"noreferrer\">an earlier article describing inclusion in.NET4.0</a> and support for generics:</p>\n\n<pre><code>Tuple&lt;string, int&gt; t = new Tuple&lt;string, int&gt;(\"Hello\", 4);\n</code></pre>\n" }, { "answer_id": 1226394, "author": "Kenan E. K.", "author_id": 133143, "author_profile": "https://Stackoverflow.com/users/133143", "pm_score": 4, "selected": false, "text": "<p>C# has <a href=\"http://msdn.microsoft.com/en-us/library/system.tuple.aspx\" rel=\"noreferrer\">tuples</a> as of version 4.0.</p>\n" }, { "answer_id": 1615099, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 1, "selected": false, "text": "<p>On order to get the above to work (I needed a pair as the key of a dictionary). I had to add:</p>\n\n<pre><code> public override Boolean Equals(Object o)\n {\n Pair&lt;T, U&gt; that = o as Pair&lt;T, U&gt;;\n if (that == null)\n return false;\n else\n return this.First.Equals(that.First) &amp;&amp; this.Second.Equals(that.Second);\n }\n</code></pre>\n\n<p>and once I did that I also added</p>\n\n<pre><code> public override Int32 GetHashCode()\n {\n return First.GetHashCode() ^ Second.GetHashCode();\n }\n</code></pre>\n\n<p>to suppress a compiler warning.</p>\n" }, { "answer_id": 1760430, "author": "James Webster", "author_id": 28381, "author_profile": "https://Stackoverflow.com/users/28381", "pm_score": 1, "selected": false, "text": "<p>The PowerCollections library (formerly available from Wintellect but now hosted on Codeplex @ <a href=\"http://powercollections.codeplex.com\" rel=\"nofollow noreferrer\">http://powercollections.codeplex.com</a>) has a generic Pair structure.</p>\n" }, { "answer_id": 2063581, "author": "Antony", "author_id": 250661, "author_profile": "https://Stackoverflow.com/users/250661", "pm_score": 3, "selected": false, "text": "<p>Some answers seem just wrong, </p>\n\n<ol>\n<li>you can't use dictionary how would store the pairs (a,b) and (a,c). Pairs concept should not be confused with associative look up of key and values</li>\n<li>lot of the above code seems suspect</li>\n</ol>\n\n<p>Here is my pair class</p>\n\n<pre><code>public class Pair&lt;X, Y&gt;\n{\n private X _x;\n private Y _y;\n\n public Pair(X first, Y second)\n {\n _x = first;\n _y = second;\n }\n\n public X first { get { return _x; } }\n\n public Y second { get { return _y; } }\n\n public override bool Equals(object obj)\n {\n if (obj == null)\n return false;\n if (obj == this)\n return true;\n Pair&lt;X, Y&gt; other = obj as Pair&lt;X, Y&gt;;\n if (other == null)\n return false;\n\n return\n (((first == null) &amp;&amp; (other.first == null))\n || ((first != null) &amp;&amp; first.Equals(other.first)))\n &amp;&amp;\n (((second == null) &amp;&amp; (other.second == null))\n || ((second != null) &amp;&amp; second.Equals(other.second)));\n }\n\n public override int GetHashCode()\n {\n int hashcode = 0;\n if (first != null)\n hashcode += first.GetHashCode();\n if (second != null)\n hashcode += second.GetHashCode();\n\n return hashcode;\n }\n}\n</code></pre>\n\n<p>Here is some test code:</p>\n\n<pre><code>[TestClass]\npublic class PairTest\n{\n [TestMethod]\n public void pairTest()\n {\n string s = \"abc\";\n Pair&lt;int, string&gt; foo = new Pair&lt;int, string&gt;(10, s);\n Pair&lt;int, string&gt; bar = new Pair&lt;int, string&gt;(10, s);\n Pair&lt;int, string&gt; qux = new Pair&lt;int, string&gt;(20, s);\n Pair&lt;int, int&gt; aaa = new Pair&lt;int, int&gt;(10, 20);\n\n Assert.IsTrue(10 == foo.first);\n Assert.AreEqual(s, foo.second);\n Assert.AreEqual(foo, bar);\n Assert.IsTrue(foo.GetHashCode() == bar.GetHashCode());\n Assert.IsFalse(foo.Equals(qux));\n Assert.IsFalse(foo.Equals(null));\n Assert.IsFalse(foo.Equals(aaa));\n\n Pair&lt;string, string&gt; s1 = new Pair&lt;string, string&gt;(\"a\", \"b\");\n Pair&lt;string, string&gt; s2 = new Pair&lt;string, string&gt;(null, \"b\");\n Pair&lt;string, string&gt; s3 = new Pair&lt;string, string&gt;(\"a\", null);\n Pair&lt;string, string&gt; s4 = new Pair&lt;string, string&gt;(null, null);\n Assert.IsFalse(s1.Equals(s2));\n Assert.IsFalse(s1.Equals(s3));\n Assert.IsFalse(s1.Equals(s4));\n Assert.IsFalse(s2.Equals(s1));\n Assert.IsFalse(s3.Equals(s1));\n Assert.IsFalse(s2.Equals(s3));\n Assert.IsFalse(s4.Equals(s1));\n Assert.IsFalse(s1.Equals(s4));\n }\n}\n</code></pre>\n" }, { "answer_id": 5262467, "author": "Serge Mikhailov", "author_id": 653898, "author_profile": "https://Stackoverflow.com/users/653898", "pm_score": 2, "selected": false, "text": "<p>Since .NET 4.0 you have <code>System.Tuple&lt;T1, T2&gt;</code> class:</p>\n\n<pre><code>// pair is implicitly typed local variable (method scope)\nvar pair = System.Tuple.Create(\"Current century\", 21);\n</code></pre>\n" }, { "answer_id": 15183399, "author": "parliament", "author_id": 1267778, "author_profile": "https://Stackoverflow.com/users/1267778", "pm_score": 2, "selected": false, "text": "<p>I typically extend the <code>Tuple</code> class into my own generic wrapper as follows:</p>\n\n<pre><code>public class Statistic&lt;T&gt; : Tuple&lt;string, T&gt;\n{\n public Statistic(string name, T value) : base(name, value) { }\n public string Name { get { return this.Item1; } }\n public T Value { get { return this.Item2; } }\n}\n</code></pre>\n\n<p>and use it like so:</p>\n\n<pre><code>public class StatSummary{\n public Statistic&lt;double&gt; NetProfit { get; set; }\n public Statistic&lt;int&gt; NumberOfTrades { get; set; }\n\n public StatSummary(double totalNetProfit, int numberOfTrades)\n {\n this.TotalNetProfit = new Statistic&lt;double&gt;(\"Total Net Profit\", totalNetProfit);\n this.NumberOfTrades = new Statistic&lt;int&gt;(\"Number of Trades\", numberOfTrades);\n }\n}\n\nStatSummary summary = new StatSummary(750.50, 30);\nConsole.WriteLine(\"Name: \" + summary.NetProfit.Name + \" Value: \" + summary.NetProfit.Value);\nConsole.WriteLine(\"Name: \" + summary.NumberOfTrades.Value + \" Value: \" + summary.NumberOfTrades.Value);\n</code></pre>\n" }, { "answer_id": 43632362, "author": "Pawel Gradecki", "author_id": 7708157, "author_profile": "https://Stackoverflow.com/users/7708157", "pm_score": 3, "selected": false, "text": "<p>Apart from custom class or .Net 4.0 Tuples, since C# 7.0 there is a new feature called ValueTuple, which is a struct that can be used in this case. Instead of writing:</p>\n\n<pre><code>Tuple&lt;string, int&gt; t = new Tuple&lt;string, int&gt;(\"Hello\", 4);\n</code></pre>\n\n<p>and access values through <code>t.Item1</code> and <code>t.Item2</code>, you can simply do it like that:</p>\n\n<pre><code>(string message, int count) = (\"Hello\", 4);\n</code></pre>\n\n<p>or even:</p>\n\n<pre><code>(var message, var count) = (\"Hello\", 4);\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
I'm interested: What is C#'s analog of `std::pair` in C++? I found `System.Web.UI.Pair` class, but I'd prefer something template-based. Thank you!
Tuples [are available since .NET4.0](http://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx) and support generics: ``` Tuple<string, int> t = new Tuple<string, int>("Hello", 4); ``` --- In previous versions you can use `System.Collections.Generic.KeyValuePair<K, V>` or a solution like the following: ``` public class Pair<T, U> { public Pair() { } public Pair(T first, U second) { this.First = first; this.Second = second; } public T First { get; set; } public U Second { get; set; } }; ``` And use it like this: ``` Pair<String, int> pair = new Pair<String, int>("test", 2); Console.WriteLine(pair.First); Console.WriteLine(pair.Second); ``` This outputs: ``` test 2 ``` Or even this chained pairs: ``` Pair<Pair<String, int>, bool> pair = new Pair<Pair<String, int>, bool>(); pair.First = new Pair<String, int>(); pair.First.First = "test"; pair.First.Second = 12; pair.Second = true; Console.WriteLine(pair.First.First); Console.WriteLine(pair.First.Second); Console.WriteLine(pair.Second); ``` That outputs: ``` test 12 true ```
166,099
<p>Starting new .NET projects always involves a bit of work. You have to create the solution, add projects for different tiers (Domain, DAL, Web, Test), set up references, solution structure, copy javascript files, css templates and master pages etc etc.</p> <p>What I'd like is <strong>an easy way of cloning any given solution</strong>. </p> <p>If you use copy/paste, the problem is that you need to then go through renaming namespaces, assembly names, solution names, GUIDs etc. </p> <p>Is there a way of automating this?</p> <p>Something like this would be great:</p> <pre><code>solutionclone.exe --solution=c:\code\abc\template.sln --to=c:\code\xyz --newname=MySolution </code></pre> <p>I'm aware that Visual Studio has project templates, but I've not seen solution templates.</p>
[ { "answer_id": 166135, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 2, "selected": false, "text": "<p>As you already found out: Copy the .sln File and make sure the paths/guids match.</p>\n\n<p>Because the .sln are <code>text/plain</code> just use your favourite scripting language to script a cloner.</p>\n\n<p>Maybe this is a good time to learn Python/Ruby/Perl/<a href=\"http://en.wikipedia.org/wiki/Windows_Script_Host\" rel=\"nofollow noreferrer\">Windows Script Host</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb165951.aspx\" rel=\"nofollow noreferrer\">MSDN Solution (.sln) File Definition</a></p>\n" }, { "answer_id": 166381, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 0, "selected": false, "text": "<p>I believe the <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=B91066B3-D1D6-4990-A45F-34CF8DBDC60C&amp;displaylang=en\" rel=\"nofollow noreferrer\">Guidance Automation Toolkit</a> allows you to do this, but may not be an \"easy\" way.</p>\n\n<p>I have the same problem as you and intend to look at it in detail \"real soon now\".</p>\n" }, { "answer_id": 166473, "author": "Stuart McConnell", "author_id": 22111, "author_profile": "https://Stackoverflow.com/users/22111", "pm_score": 1, "selected": false, "text": "<p>Look at <a href=\"http://www.codeplex.com/treesurgeon/\" rel=\"nofollow noreferrer\" title=\"Tree Surgeon\">Tree Surgeon</a> on CodePlex, it creates a development tree for you. </p>\n" }, { "answer_id": 3342357, "author": "Andrej Golcov", "author_id": 122997, "author_profile": "https://Stackoverflow.com/users/122997", "pm_score": 0, "selected": false, "text": "<p>May be you should check <strong>Warmup</strong> open source project. Find brief description on <a href=\"http://devlicious.com/blogs/rob_reynolds/archive/2010/02/01/warmup-getting-started.aspx\" rel=\"nofollow noreferrer\">http://devlicious.com/blogs/rob_reynolds/archive/2010/02/01/warmup-getting-started.aspx</a>.</p>\n\n<p>IMHO, advantage of <strong>Warmup</strong> approach is that it can clone the whole tree with solution directly from SVN or GIT.</p>\n\n<p>Note! I haven't use it personally, but plan to give it a try in the next project.\nPlease leave a comment if you use it.</p>\n" }, { "answer_id": 6871125, "author": "Daniel Saidi", "author_id": 804034, "author_profile": "https://Stackoverflow.com/users/804034", "pm_score": 3, "selected": false, "text": "<p>I have created a small application for this. It works just like the previously mentioned Solutionclone app, except that it is both a command line application as well as a WPF application.</p>\n\n<p>Cloney copies a source folder to a target one, without any Git or Svn integration. It will also replace the old namespace everywhere (in file names as well as within files) with the new namespace (the name of the target folder) and exclude certain files (e.g. *.suo, *.user, *.vssscc) and folders (e.g. .git, .svn).</p>\n\n<p>You can grab the source code or download an executable at <a href=\"https://github.com/danielsaidi/cloney\" rel=\"nofollow\">https://github.com/danielsaidi/cloney</a>.</p>\n\n<p>Cloney can also be added to the Windows Explorer context menu, which makes it possible to clone .NET solutions by just right-clicking the .sln file.</p>\n" }, { "answer_id": 13598140, "author": "Chris", "author_id": 34942, "author_profile": "https://Stackoverflow.com/users/34942", "pm_score": 0, "selected": false, "text": "<p>Old post, I know, but I recently had a need to do this, and although there are several homegrown tools out there to do it, I wanted something more lightweight that I could toss around wherever I feel like it. Since I like python for interpreted language scripting, I wrote a single file tool in python to do the job. It's only dependency is python3 and chardet2.</p>\n\n<p><a href=\"https://gist.github.com/4159114\" rel=\"nofollow\">https://gist.github.com/4159114</a></p>\n" }, { "answer_id": 13598219, "author": "just.another.programmer", "author_id": 794234, "author_profile": "https://Stackoverflow.com/users/794234", "pm_score": 0, "selected": false, "text": "<p>You can use a multi project template to get solution like behavior. The folder structure will be slightly off putting all the projects into a level below the .sln file.</p>\n\n<p>You can also implement a custom IWizard to have complete control.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1136215/" ]
Starting new .NET projects always involves a bit of work. You have to create the solution, add projects for different tiers (Domain, DAL, Web, Test), set up references, solution structure, copy javascript files, css templates and master pages etc etc. What I'd like is **an easy way of cloning any given solution**. If you use copy/paste, the problem is that you need to then go through renaming namespaces, assembly names, solution names, GUIDs etc. Is there a way of automating this? Something like this would be great: ``` solutionclone.exe --solution=c:\code\abc\template.sln --to=c:\code\xyz --newname=MySolution ``` I'm aware that Visual Studio has project templates, but I've not seen solution templates.
I have created a small application for this. It works just like the previously mentioned Solutionclone app, except that it is both a command line application as well as a WPF application. Cloney copies a source folder to a target one, without any Git or Svn integration. It will also replace the old namespace everywhere (in file names as well as within files) with the new namespace (the name of the target folder) and exclude certain files (e.g. \*.suo, \*.user, \*.vssscc) and folders (e.g. .git, .svn). You can grab the source code or download an executable at <https://github.com/danielsaidi/cloney>. Cloney can also be added to the Windows Explorer context menu, which makes it possible to clone .NET solutions by just right-clicking the .sln file.
166,113
<p>If I want to call <code>Bar()</code> instead of <code>Foo()</code>, does <code>Bar()</code> return me a copy (additional overhead) of what Foo() returns, or it returns the same object which <code>Foo()</code> places on the temporary stack?</p> <pre><code>vector&lt;int&gt; Foo(){ vector&lt;int&gt; result; result.push_back(1); return result; } vector&lt;int&gt; Bar(){ return Foo(); } </code></pre>
[ { "answer_id": 166116, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 2, "selected": false, "text": "<p>Normally it returns a copy of the returned <code>vector&lt;int&gt;</code>. However this highly depends on the optimization done by the compiler. See the following discussion.</p>\n\n<p><strong>Debug Build</strong></p>\n\n<pre><code>vector&lt;int&gt; Foo(){ \n004118D0 push ebp \n004118D1 mov ebp,esp \n004118D3 push 0FFFFFFFFh \n004118D5 push offset __ehhandler$?Foo@@YA?AV?$vector@HV?$allocator@H@std@@@std@@XZ (419207h) \n004118DA mov eax,dword ptr fs:[00000000h] \n004118E0 push eax \n004118E1 sub esp,0F4h \n004118E7 push ebx \n004118E8 push esi \n004118E9 push edi \n004118EA lea edi,[ebp-100h] \n004118F0 mov ecx,3Dh \n004118F5 mov eax,0CCCCCCCCh \n004118FA rep stos dword ptr es:[edi] \n004118FC mov eax,dword ptr [___security_cookie (41E098h)] \n00411901 xor eax,ebp \n00411903 push eax \n00411904 lea eax,[ebp-0Ch] \n00411907 mov dword ptr fs:[00000000h],eax \n0041190D mov dword ptr [ebp-0F0h],0 \n vector&lt;int&gt; result; \n00411917 lea ecx,[ebp-24h] \n0041191A call std::vector&lt;int,std::allocator&lt;int&gt; &gt;::vector&lt;int,std::allocator&lt;int&gt; &gt; (411050h) \n0041191F mov dword ptr [ebp-4],1 \n result.push_back(1); \n00411926 mov dword ptr [ebp-0FCh],1 \n00411930 lea eax,[ebp-0FCh] \n00411936 push eax \n00411937 lea ecx,[ebp-24h] \n0041193A call std::vector&lt;int,std::allocator&lt;int&gt; &gt;::push_back (41144Ch) \n return result; \n0041193F lea eax,[ebp-24h] \n00411942 push eax \n00411943 mov ecx,dword ptr [ebp+8] \n00411946 call std::vector&lt;int,std::allocator&lt;int&gt; &gt;::vector&lt;int,std::allocator&lt;int&gt; &gt; (41104Bh) \n0041194B mov ecx,dword ptr [ebp-0F0h] \n00411951 or ecx,1 \n00411954 mov dword ptr [ebp-0F0h],ecx \n0041195A mov byte ptr [ebp-4],0 \n0041195E lea ecx,[ebp-24h] \n00411961 call std::vector&lt;int,std::allocator&lt;int&gt; &gt;::~vector&lt;int,std::allocator&lt;int&gt; &gt; (411415h) \n00411966 mov eax,dword ptr [ebp+8] \n} \n</code></pre>\n\n<p>Here we can see that for <code>vector&lt;int&gt; result;</code> a new object is created on the stack at <code>[ebp-24h]</code></p>\n\n<pre><code>00411917 lea ecx,[ebp-24h] \n0041191A call std::vector&lt;int,std::allocator&lt;int&gt; &gt;::vector&lt;int,std::allocator&lt;int&gt; &gt; (411050h)\n</code></pre>\n\n<p>When we get to <code>return result;</code> a new copy is created in storage allocated by the caller at <code>[ebp+8]</code></p>\n\n<pre><code>00411943 mov ecx,dword ptr [ebp+8] \n00411946 call std::vector&lt;int,std::allocator&lt;int&gt; &gt;::vector&lt;int,std::allocator&lt;int&gt; &gt; (41104Bh) \n</code></pre>\n\n<p>And the destructor is called for the local parameter <code>vector&lt;int&gt; result</code> at <code>[ebp-24h]</code></p>\n\n<pre><code>0041195E lea ecx,[ebp-24h] \n00411961 call std::vector&lt;int,std::allocator&lt;int&gt; &gt;::~vector&lt;int,std::allocator&lt;int&gt; &gt; (411415h) \n</code></pre>\n\n<p><strong>Release Build</strong></p>\n\n<pre><code>vector&lt;int&gt; Foo(){ \n00401110 push 0FFFFFFFFh \n00401112 push offset __ehhandler$?Foo@@YA?AV?$vector@HV?$allocator@H@std@@@std@@XZ (401F89h) \n00401117 mov eax,dword ptr fs:[00000000h] \n0040111D push eax \n0040111E sub esp,14h \n00401121 push esi \n00401122 mov eax,dword ptr [___security_cookie (403018h)] \n00401127 xor eax,esp \n00401129 push eax \n0040112A lea eax,[esp+1Ch] \n0040112E mov dword ptr fs:[00000000h],eax \n00401134 mov esi,dword ptr [esp+2Ch] \n00401138 xor eax,eax \n0040113A mov dword ptr [esp+8],eax \n vector&lt;int&gt; result; \n0040113E mov dword ptr [esi+4],eax \n00401141 mov dword ptr [esi+8],eax \n00401144 mov dword ptr [esi+0Ch],eax \n result.push_back(1); \n return result; \n00401147 push eax \n00401148 mov dword ptr [esp+28h],eax \n0040114C mov ecx,1 \n00401151 push esi \n00401152 lea eax,[esp+14h] \n00401156 mov dword ptr [esp+10h],ecx \n0040115A mov dword ptr [esp+14h],ecx \n0040115E push eax \n0040115F lea ecx,[esp+1Ch] \n00401163 push ecx \n00401164 mov eax,esi \n00401166 call std::vector&lt;int,std::allocator&lt;int&gt; &gt;::insert (401200h) \n0040116B mov eax,esi \n} \n0040116D mov ecx,dword ptr [esp+1Ch] \n00401171 mov dword ptr fs:[0],ecx \n00401178 pop ecx \n00401179 pop esi \n0040117A add esp,20h \n0040117D ret\n</code></pre>\n\n<p>The line <code>vector&lt;int&gt; result</code> does not call the vector allocator because it is done at call site in <code>Bar</code>. The optimization makes no copy of the result from Foo.</p>\n" }, { "answer_id": 166118, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 4, "selected": true, "text": "<p>Both may happen. However, most compiler will not do copy as soon as you optimize.</p>\n\n<p>Your code indicate there should be a copy. However, the compiler is allowed to remove any copy that do not change the semantic and the program.</p>\n\n<p>Note: This is why you should NEVER have a copy constructor that does anything but copying correctly as you can never be sure if a copy will be actually done or not.</p>\n" }, { "answer_id": 166130, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>This is a trivial case for NRVO – names return value optimization (a misnomer in this case since there's no name). Stan Lippman hat a <a href=\"http://blogs.msdn.com/slippman/archive/2004/02/03/66739.aspx\" rel=\"nofollow noreferrer\">blog entry</a> with a nice explanation of the mechanism involved.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20646/" ]
If I want to call `Bar()` instead of `Foo()`, does `Bar()` return me a copy (additional overhead) of what Foo() returns, or it returns the same object which `Foo()` places on the temporary stack? ``` vector<int> Foo(){ vector<int> result; result.push_back(1); return result; } vector<int> Bar(){ return Foo(); } ```
Both may happen. However, most compiler will not do copy as soon as you optimize. Your code indicate there should be a copy. However, the compiler is allowed to remove any copy that do not change the semantic and the program. Note: This is why you should NEVER have a copy constructor that does anything but copying correctly as you can never be sure if a copy will be actually done or not.
166,125
<p>I'm currently trying to pass a mono threaded program to multithread. This software do heavy usage of "refCounted" objects, which lead to some issues in multithread. I'm looking for some design pattern or something that might solve my problem.</p> <p>The main problem is object deletion between thread, normally deletion only decrement the reference counting, and when refcount is equal to zero, then the object is deleted. This work well in monothread program, and allow some great performance improvement with copy of big object.</p> <p>However, in multithread, two threads might want to delete the same object concurrently, as the object is protected by a mutex, only one thread delete the object and block the other one. But when it releases the mutex, then the other thread continue its execution with invalid (freed object), which lead to memory corruption.</p> <p>Here is an example with this class RefCountedObject</p> <pre><code>class RefCountedObject { public: RefCountedObject() : _refCount( new U32(1) ) {} RefCountedObject( const RefCountedObject&amp; obj ) : _refCount( obj._refCount ) { ACE_Guard&lt; ACE_Mutex &gt; guard( _refCountMutex ); ++(*_refCount); } ~RefCountedObject() { Destroy(); } RefCountedObject&amp; operator=( const RefCountedObject&amp; obj ) { if( this != &amp;obj ) { Destroy(); ACE_Guard&lt; ACE_Mutex &gt; guard( _refCountMutex ); _refCount = obj._refCount; ++(*_refCount); } return *this; } private: void Destroy() { ACE_Guard&lt; ACE_Mutex &gt; guard( _refCountMutex ); // thread2 are waiting here --(*_refCount); // This cause a free memory write by the thread2 if( 0 == *_refCount ) delete _refCount; } private: mutable U32* _refCount; mutable ACE_Mutex _refCountMutex; // BAD: this mutex only protect the refCount pointer, not the refCount itself }; </code></pre> <p>Suppose that two threads want to delete the same RefCountedObject, both are in ~RefCountedObject and call Destroy(), the first thread has locked the mutex and the other one is waiting. After the deletion of the object by the first thread, the second will continue its execution and cause a free memory write.</p> <p>Anyone has experience with a similar problem and found a solution ?</p> <hr> <p>Thanks all for your help, I realize my mistake: The mutex is only protecting refCount pointer, not the refCount itself! I've created a RefCount class which is mutex protected. The mutex is now shared between all refCounted object.</p> <p>Now all works fine.</p>
[ { "answer_id": 166137, "author": "Len Holgate", "author_id": 7925, "author_profile": "https://Stackoverflow.com/users/7925", "pm_score": 2, "selected": false, "text": "<p>Surely each thread simply needs to manage the reference counts correctly... That is, if ThreadA and ThreadB are both working with Obj1 then BOTH ThreadA and ThreadB should own a reference to the object and BOTH should call release when they're done with the object. </p>\n\n<p>In a single threaded application it's likely that you have a point where a reference counted object is created, you then do work on the object and eventually call release. In a multi-threaded program you would create the object and then pass it to your threads (however you do that). Before passing the object to the thread you should call AddRef() on your object to give the thread its own reference count. The thread that allocated the object can then call release as it's done with the object. The threads that are working with the object will then call release when they're done and when the last reference is released the object will be cleaned up.</p>\n\n<p>Note that you dont want the code that's running on the threads themselves to call AddRef() on the object as you then have a race condition between the creating thread calling release on the object before the threads that you've dispatched to get a chance to run and call AddRef().</p>\n" }, { "answer_id": 166146, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "<p>Any object that you are sharing between threads should be protected with a mutex, and the same applies to refcount <em>handles</em> ! That means you will never be deleting the last one handle to an object from two threads. You might be concurrently deleting two distinct handles that happen to point to one object. </p>\n\n<p>In Windows, you could use InterlockedDecrement. This ensures that precisely one of the two decrements will return 0. Only that thread will delete the refcounted object.</p>\n\n<p>Any other thread cannot have been copying one of the two handles either. By common MT rules one thread may not delete an object still used by another thread, and this extends to refcount handles too. </p>\n" }, { "answer_id": 166167, "author": "grrussel", "author_id": 8516, "author_profile": "https://Stackoverflow.com/users/8516", "pm_score": 0, "selected": false, "text": "<p>One solution is to make the reference counter an atomic value, so that each concurrent call to destroy can safely proceed with only 1 deletion actually occurring, the other merely decrementing the atomic reference count.</p>\n\n<p>The Intel Thread Building Blocks library (TBB) provides atomic values.</p>\n\n<p>Also, so does the ACE library in the <code>ACE_Atomic_Op</code> template.</p>\n\n<p>The Boost library provides a reference counting smart pointer library that already implements this.</p>\n\n<p><a href=\"http://www.dre.vanderbilt.edu/Doxygen/Current/html/ace/a00029.html\" rel=\"nofollow noreferrer\">http://www.dre.vanderbilt.edu/Doxygen/Current/html/ace/a00029.html</a>\n <a href=\"http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm\" rel=\"nofollow noreferrer\">http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm</a></p>\n" }, { "answer_id": 166200, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 0, "selected": false, "text": "<p>I believe something along this line would solve your problem:<br>\n<pre><code><code>private:\n void Destroy()\n {<br>\n ACE_Guard&lt; ACE_Mutex &gt; guard( _refCountMutex ); // thread2 are waiting here\n if (_refCount != 0) {\n --(*_refCount); // This cause a free memory write by the thread2\n if( 0 == *_refCount ) {\n delete _refCount;\n _refcount = 0;\n }\n }\n }\nprivate:\n mutable U32* _refCount;\n mutable ACE_Mutex _refCountMutex;</code></pre></code></p>\n" }, { "answer_id": 166225, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 3, "selected": true, "text": "<p>If the count is part of the object then you have an inherent problem if one thread can be trying to <em>increase</em> the reference count whilst another is trying to remove the <em>last</em> reference. There needs to be an extra value on the ref count for each globally accessible pointer to the object, so you can always safely increase the ref count if you've got a pointer.</p>\n\n<p>One option would be to use <code>boost::shared_ptr</code> <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/shared_ptr.htm\" rel=\"nofollow noreferrer\">(see the docs)</a>. You can use the free functions <code>atomic_load</code>, <code>atomic_store</code>, <code>atomic_exchange</code> and <code>atomic_compare_exchange</code> (which are conspicuously absent from the docs) to ensure suitable protection when accessing global pointers to shared objects. Once your thread has got a <code>shared_ptr</code> referring to a particular object you can use the normal non-atomic functions to access it.</p>\n\n<p>Another option is to use Joe Seigh's atomic ref-counted pointer from his <a href=\"http://atomic-ptr-plus.sourceforge.net/\" rel=\"nofollow noreferrer\">atomic_ptr_plus project</a></p>\n" }, { "answer_id": 166232, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 1, "selected": false, "text": "<p>thinking about your issue a little... what you're saying is that you have 1 object (if the refcount is 1) and yet 2 threads both call delete() on it. I think this is where your problem truly lies.</p>\n\n<p>The other way round this issue, if you want a threaded object you can safely reuse between threads, is to check that the refcount is greater than 1 before freeing internal memory. Currently you free it and then check whether the refcount is 0.</p>\n" }, { "answer_id": 167473, "author": "twk", "author_id": 23524, "author_profile": "https://Stackoverflow.com/users/23524", "pm_score": 1, "selected": false, "text": "<p>This isn't an answer, but just a bit of advice. In a situation like this, before you start fixing anything, please make sure you can reliably duplicate these problems. Sometimes this is a simple as running your unit tests in a loop for a while. Sometimes putting some clever Sleeps into your program to force race conditions is helpful. </p>\n\n<p>Ref counting problems tend to linger, so an investment in your test harness will pay off in the long run. </p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1578/" ]
I'm currently trying to pass a mono threaded program to multithread. This software do heavy usage of "refCounted" objects, which lead to some issues in multithread. I'm looking for some design pattern or something that might solve my problem. The main problem is object deletion between thread, normally deletion only decrement the reference counting, and when refcount is equal to zero, then the object is deleted. This work well in monothread program, and allow some great performance improvement with copy of big object. However, in multithread, two threads might want to delete the same object concurrently, as the object is protected by a mutex, only one thread delete the object and block the other one. But when it releases the mutex, then the other thread continue its execution with invalid (freed object), which lead to memory corruption. Here is an example with this class RefCountedObject ``` class RefCountedObject { public: RefCountedObject() : _refCount( new U32(1) ) {} RefCountedObject( const RefCountedObject& obj ) : _refCount( obj._refCount ) { ACE_Guard< ACE_Mutex > guard( _refCountMutex ); ++(*_refCount); } ~RefCountedObject() { Destroy(); } RefCountedObject& operator=( const RefCountedObject& obj ) { if( this != &obj ) { Destroy(); ACE_Guard< ACE_Mutex > guard( _refCountMutex ); _refCount = obj._refCount; ++(*_refCount); } return *this; } private: void Destroy() { ACE_Guard< ACE_Mutex > guard( _refCountMutex ); // thread2 are waiting here --(*_refCount); // This cause a free memory write by the thread2 if( 0 == *_refCount ) delete _refCount; } private: mutable U32* _refCount; mutable ACE_Mutex _refCountMutex; // BAD: this mutex only protect the refCount pointer, not the refCount itself }; ``` Suppose that two threads want to delete the same RefCountedObject, both are in ~RefCountedObject and call Destroy(), the first thread has locked the mutex and the other one is waiting. After the deletion of the object by the first thread, the second will continue its execution and cause a free memory write. Anyone has experience with a similar problem and found a solution ? --- Thanks all for your help, I realize my mistake: The mutex is only protecting refCount pointer, not the refCount itself! I've created a RefCount class which is mutex protected. The mutex is now shared between all refCounted object. Now all works fine.
If the count is part of the object then you have an inherent problem if one thread can be trying to *increase* the reference count whilst another is trying to remove the *last* reference. There needs to be an extra value on the ref count for each globally accessible pointer to the object, so you can always safely increase the ref count if you've got a pointer. One option would be to use `boost::shared_ptr` [(see the docs)](http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/shared_ptr.htm). You can use the free functions `atomic_load`, `atomic_store`, `atomic_exchange` and `atomic_compare_exchange` (which are conspicuously absent from the docs) to ensure suitable protection when accessing global pointers to shared objects. Once your thread has got a `shared_ptr` referring to a particular object you can use the normal non-atomic functions to access it. Another option is to use Joe Seigh's atomic ref-counted pointer from his [atomic\_ptr\_plus project](http://atomic-ptr-plus.sourceforge.net/)
166,127
<p>I have a web page where I'd like to remap Ctrl+N to a different behavior. I followed YUI's example of register Key Listeners and my function is called but Firefox still creates a new browser window. Things seem to work fine on IE7. How do I stop the new window from showing up?</p> <p>Example:</p> <pre><code>var kl2 = new YAHOO.util.KeyListener(document, { ctrl:true, keys:78 }, {fn:function(event) { YAHOO.util.Event.stopEvent(event); // Doesn't help alert('Click');}}); kl2.enable(); </code></pre> <p>It is possible to remove default behavior. Google Docs overrides Ctrl+S to save your document instead of bringing up Firefox's save dialog. I tried the example above with Ctrl+S but Firefox's save dialog still pops up. Since Google can stop the save dialog from coming up I'm sure there's a way to prevent most default keyboard shortcuts.</p>
[ { "answer_id": 166376, "author": "Gene", "author_id": 22673, "author_profile": "https://Stackoverflow.com/users/22673", "pm_score": 0, "selected": false, "text": "<p>I'm just guessing here but I don't think it can be done.</p>\n\n<p>If it's possible it definitely shouldn't be. Generic keyboard shortcuts are something you should not mess with. What's next? Hook the window close button to open a new window...</p>\n" }, { "answer_id": 288799, "author": "Stuart Grimshaw", "author_id": 11470, "author_profile": "https://Stackoverflow.com/users/11470", "pm_score": 0, "selected": false, "text": "<p>Using YUI's event util, you could try and use the <a href=\"http://developer.yahoo.com/yui/docs/YAHOO.util.Event.html#method_stopEvent\" rel=\"nofollow noreferrer\">stopEvent</a> method:</p>\n\n<p>However, because most users are used to those keypresses doing a particular thing in the browser (new window in your example), I always avoid clashes, which in effect means I don't use any of the meta or control keys.</p>\n\n<p>I simply use letters, on their own, which is fine until you have text entry boxes, so this bit of advice might be less useful to you.</p>\n" }, { "answer_id": 577147, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Although overriding default browser shortcuts is not trivial, in some cases it is worth to do this since it gives a more professional look of the application. Take a look at this script:</p>\n\n<p><a href=\"http://www.openjs.com/scripts/events/keyboard_shortcuts/index.php#disable_in_input\" rel=\"nofollow noreferrer\">http://www.openjs.com/scripts/events/keyboard_shortcuts/index.php#disable_in_input</a></p>\n\n<p>It turns out to work fine for me..</p>\n" }, { "answer_id": 786261, "author": "Tac-Tics", "author_id": 92971, "author_profile": "https://Stackoverflow.com/users/92971", "pm_score": 4, "selected": true, "text": "<p>The trick is the 'fn' function is whack.</p>\n\n<p>Experimentally, you can see that the function type for fn takes two parameters. The first param actually contains the TYPE of event. The second one contains... and this is screwy: an array containing the codepoint at index 0 and the actual event object at index 1.</p>\n\n<p>So changing your code around a bit, it <em>should</em> look like this:</p>\n\n<pre><code>function callback(type, args)\n{\n var event = args[1]; // the actual event object\n alert('Click');\n\n // like stopEvent, but the event still propogates to other YUI handlers\n YAHOO.util.Event.preventDefault(event);\n}\nvar kl2 = new YAHOO.util.KeyListener(document, { ctrl:true, keys:78 }, {fn:callback});\nkl2.enable();\n</code></pre>\n\n<p>Also, for the love of lisp, don't use raw code points in your code. Use 'N'.charCodeAt(0) instead of \"78\". Or wrap it up as a function </p>\n\n<pre><code>function ord(char)\n{\n return char.charCodeAt(0);\n}\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680/" ]
I have a web page where I'd like to remap Ctrl+N to a different behavior. I followed YUI's example of register Key Listeners and my function is called but Firefox still creates a new browser window. Things seem to work fine on IE7. How do I stop the new window from showing up? Example: ``` var kl2 = new YAHOO.util.KeyListener(document, { ctrl:true, keys:78 }, {fn:function(event) { YAHOO.util.Event.stopEvent(event); // Doesn't help alert('Click');}}); kl2.enable(); ``` It is possible to remove default behavior. Google Docs overrides Ctrl+S to save your document instead of bringing up Firefox's save dialog. I tried the example above with Ctrl+S but Firefox's save dialog still pops up. Since Google can stop the save dialog from coming up I'm sure there's a way to prevent most default keyboard shortcuts.
The trick is the 'fn' function is whack. Experimentally, you can see that the function type for fn takes two parameters. The first param actually contains the TYPE of event. The second one contains... and this is screwy: an array containing the codepoint at index 0 and the actual event object at index 1. So changing your code around a bit, it *should* look like this: ``` function callback(type, args) { var event = args[1]; // the actual event object alert('Click'); // like stopEvent, but the event still propogates to other YUI handlers YAHOO.util.Event.preventDefault(event); } var kl2 = new YAHOO.util.KeyListener(document, { ctrl:true, keys:78 }, {fn:callback}); kl2.enable(); ``` Also, for the love of lisp, don't use raw code points in your code. Use 'N'.charCodeAt(0) instead of "78". Or wrap it up as a function ``` function ord(char) { return char.charCodeAt(0); } ```
166,132
<p>I want to store the data returned by <code>$_SERVER["REMOTE_ADDR"]</code> in PHP into a DB field, pretty simple task, really. The problem is that I can't find any proper information about the maximum length of the <strong>textual representation</strong> of an IPv6 address, which is what a webserver provides through <code>$_SERVER["REMOTE_ADDR"]</code>. </p> <p>I'm not interested in converting the textual representation into the 128 bits the address is usually encoded in, I just want to know how many characters maximum are needed to store any IPv6 address returned by <code>$_SERVER["REMOTE_ADDR"]</code>.</p>
[ { "answer_id": 166143, "author": "Gilles", "author_id": 10024, "author_profile": "https://Stackoverflow.com/users/10024", "pm_score": 4, "selected": false, "text": "<p>Answered my own question: </p>\n\n<blockquote>\n <p>IPv6 addresses are normally written as eight groups of four hexadecimal digits, where each group is separated by a colon (:).</p>\n</blockquote>\n\n<p>So that's 39 characters max.</p>\n" }, { "answer_id": 166157, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 11, "selected": true, "text": "<p><strong>45 characters</strong>.</p>\n<p>You might expect an address to be</p>\n<pre><code>0000:0000:0000:0000:0000:0000:0000:0000\n</code></pre>\n<blockquote>\n<p>8 * 4 + 7 = 39</p>\n</blockquote>\n<p>8 groups of 4 digits with 7 <code>:</code> between them.</p>\n<p>But if you have an <a href=\"https://www.rfc-editor.org/rfc/rfc4291#section-2.5.5.2\" rel=\"noreferrer\">IPv4-mapped IPv6 address</a>, the last two groups can be written in base 10 separated by <code>.</code>, eg. <code>[::ffff:192.168.100.228]</code>. Written out fully:</p>\n<pre><code>0000:0000:0000:0000:0000:ffff:192.168.100.228\n</code></pre>\n<blockquote>\n<p>(6 * 4 + 5) + 1 + (4 * 3 + 3) = 29 + 1 + 15 = <strong>45</strong></p>\n</blockquote>\n<p>Note, this is an input/display convention - it's still a 128 bit address and for storage it would probably be best to standardise on the raw colon separated format, i.e. <code>[0000:0000:0000:0000:0000:ffff:c0a8:64e4]</code> for the address above.</p>\n" }, { "answer_id": 20451843, "author": "QMaster", "author_id": 1830909, "author_profile": "https://Stackoverflow.com/users/1830909", "pm_score": 3, "selected": false, "text": "<p>I think @Deepak answer in this link is more close to correct answer. <a href=\"https://stackoverflow.com/questions/1076714/max-length-for-client-ip-address\">Max length for client ip address</a>. So correct size is 45 not 39. Sometimes we try to scrounge in fields size but it seems to better if we prepare enough storage size.</p>\n" }, { "answer_id": 20473371, "author": "Yury", "author_id": 685653, "author_profile": "https://Stackoverflow.com/users/685653", "pm_score": 7, "selected": false, "text": "<p>On Linux, see constant <code>INET6_ADDRSTRLEN</code> (include <code>&lt;arpa/inet.h&gt;</code>, see <code>man inet_ntop</code>). On my system (header \"in.h\"):</p>\n\n<pre><code>#define INET6_ADDRSTRLEN 46\n</code></pre>\n\n<p>The last character is for terminating NULL, as I belive, so the max length is 45, as other answers.</p>\n" }, { "answer_id": 42294147, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 2, "selected": false, "text": "<p>Watch out for certain headers such as <code>HTTP_X_FORWARDED_FOR</code> that appear to contain a single IP address. They may actually contain multiple addresses (a chain of proxies I assume).</p>\n\n<p>They will appear to be <a href=\"http://www.jamescrowley.co.uk/2007/06/19/gotcha-http-x-forwarded-for-returns-multiple-ip-addresses/\" rel=\"nofollow noreferrer\">comma delimited</a> - and can be a lot longer than 45 characters total - so check before storing in DB.</p>\n" }, { "answer_id": 42605399, "author": "Sean F", "author_id": 6801443, "author_profile": "https://Stackoverflow.com/users/6801443", "pm_score": 4, "selected": false, "text": "<p>As indicated a standard ipv6 address is at most 45 chars, but an ipv6 address can also include an ending % followed by a &quot;scope&quot; or &quot;zone&quot; string, which has no fixed length but is generally a small positive integer or a network interface name, so in reality it can be bigger than 45 characters. Network interface names are typically &quot;eth0&quot;, &quot;eth1&quot;, &quot;wlan0&quot;, a small number of chars. The <a href=\"https://stackoverflow.com/questions/24932172/what-length-can-a-network-interface-name-have\">max interface name length in linux is 15 chars</a>, so choosing 61 bytes will cover all interface names on linux.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10024/" ]
I want to store the data returned by `$_SERVER["REMOTE_ADDR"]` in PHP into a DB field, pretty simple task, really. The problem is that I can't find any proper information about the maximum length of the **textual representation** of an IPv6 address, which is what a webserver provides through `$_SERVER["REMOTE_ADDR"]`. I'm not interested in converting the textual representation into the 128 bits the address is usually encoded in, I just want to know how many characters maximum are needed to store any IPv6 address returned by `$_SERVER["REMOTE_ADDR"]`.
**45 characters**. You might expect an address to be ``` 0000:0000:0000:0000:0000:0000:0000:0000 ``` > > 8 \* 4 + 7 = 39 > > > 8 groups of 4 digits with 7 `:` between them. But if you have an [IPv4-mapped IPv6 address](https://www.rfc-editor.org/rfc/rfc4291#section-2.5.5.2), the last two groups can be written in base 10 separated by `.`, eg. `[::ffff:192.168.100.228]`. Written out fully: ``` 0000:0000:0000:0000:0000:ffff:192.168.100.228 ``` > > (6 \* 4 + 5) + 1 + (4 \* 3 + 3) = 29 + 1 + 15 = **45** > > > Note, this is an input/display convention - it's still a 128 bit address and for storage it would probably be best to standardise on the raw colon separated format, i.e. `[0000:0000:0000:0000:0000:ffff:c0a8:64e4]` for the address above.
166,134
<p>In PHP, which is quicker; using <code>include('somefile.php')</code> or querying a MySQL database with a simple <code>SELECT</code> query to get the same information?</p> <p>For example, say you had a JavaScript autocomplete search field which needed 3,000 terms to match against. Is it quicker to read those terms in from another file using <code>include</code> or to read them from a MySQL database using a simple <code>SELECT</code> query?</p> <p><strong>Edit:</strong> This is assuming that the database and the file I want to include are on the same local machine as my code.</p>
[ { "answer_id": 166142, "author": "Enrico Murru", "author_id": 68336, "author_profile": "https://Stackoverflow.com/users/68336", "pm_score": -1, "selected": false, "text": "<p>I exactly don't know, but in my opinio using MySQL, even if can be slower, sould be used if the content is dynamic. But I'm pretty sure it is faster, for big contents, using include.</p>\n" }, { "answer_id": 166152, "author": "daniels", "author_id": 9789, "author_profile": "https://Stackoverflow.com/users/9789", "pm_score": 0, "selected": false, "text": "<p>definitely include as long as the file isn't too big and you end up using too much memory in which case a database would be recommended</p>\n" }, { "answer_id": 166166, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": 2, "selected": false, "text": "<p>It's very hard/impossible to give an exact answer, as there are too many unknown variables - what if the filesystem is mounted on an <a href=\"http://en.wikipedia.org/wiki/Network_file_system\" rel=\"nofollow noreferrer\">NFS</a> that resides on the other side of the world? Or you have the whole MySQL database in memory. The size of the database should be factored in too.</p>\n\n<p>But, on a more answer-y note, <strong>a safe guess would be that MySQL is faster</strong>, given good indexes, good database structure/normalization and not too fancy/complex queries. I/O operations are always expensive (read: slow), while, as previously mentioned, the whole dataset is already cached in memory by MySQL.</p>\n\n<p>Besides, I imagine you thought of doing further string manipulation with those included files, which makes things even more troublesome - I'm convinced MySQL's string searching algorithms are much better optimized than what you could come up with in PHP.</p>\n" }, { "answer_id": 166169, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 0, "selected": false, "text": "<p>Reading in raw data to a script from a file will generally be faster than from a database.</p>\n\n<p>However it sounds like you are wanting to query that data in order to find a match to return to the javascript. You may find in that case that MySQL will be faster for the actual querying/searching of the data (especially if correctly indexed etc.) as this is something a database is good at.</p>\n\n<p>Reading in a big file is also less scalable as you will be using lots of server memory while the script executes.</p>\n" }, { "answer_id": 166215, "author": "Gravstar", "author_id": 17381, "author_profile": "https://Stackoverflow.com/users/17381", "pm_score": 5, "selected": true, "text": "<p>It depends. If your file is stored locally in your server and the database is installed in another machine, then the faster is to include the file.</p>\n\n<p>Buuuuut, because it depends on your system it could be not true. I suggest to you to make a PHP test script and run it 100 times from the command line, and repeat the test through HTTP (using cURL)</p>\n\n<p>Example:</p>\n\n<p><strong>use_include.php</strong></p>\n\n<pre><code>&lt;?php\n\n start = microtime(true);\n\n include( 'somefile.php' );\n\n echo microtime(true)-start;\n\n?&gt;\n</code></pre>\n\n<p><strong>use_myphp.php</strong></p>\n\n<pre><code>&lt;?php\n\n start = microtime(true);\n\n __put_here_your_mysql_statements_to_retrieve_the_file__\n\n echo microtime(true)-start;\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 166245, "author": "Bob Somers", "author_id": 1384, "author_profile": "https://Stackoverflow.com/users/1384", "pm_score": 1, "selected": false, "text": "<p>If this is something you're going to be fetching on a regular basis it might be worthwhile to prefetch the data (from disk or the database, doesn't matter) and have your script pull it from a RAM cache like memcached.</p>\n" }, { "answer_id": 166293, "author": "Tooony", "author_id": 23864, "author_profile": "https://Stackoverflow.com/users/23864", "pm_score": 2, "selected": false, "text": "<p>The difference in time is more down to the system design than the underlying technique I'd dare say. Both a MySQL result and a file can be cached in memory, and the performance difference there would be so small it is neglectable.</p>\n\n<p>Instead I would ask myself what the difference in maintenance would be. Are you likely to ever change the data? If not, just pop it in a plain file. Are you likely to change bits of the content ever so often? If so, a database is way easier to manipulate. Same thing for the structure of the data, if it needs \"restructuring\", maybe it is more efficient to put it in a database?</p>\n\n<p>So: Do what you feel is most convenient for you and the future maintainer of the code and data. :-)</p>\n" }, { "answer_id": 166342, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Including a file should almost always be quicker. If your database is on another machine (e.g. in shared hosting) or in a multi-server setup the lookup will have to make an extra hop.</p>\n\n<p>However, in practice the difference is probably not going to matter. If the list is dynamic then storing it in MySQL will make your life easier. Static lists (e.g. countries or states) can be stored in a PHP include. If the list is quite short (a few hundred entries) and often used, you could load it straight into JavaScript and do away with AJAX.</p>\n\n<p>If you are going the MySQL route and are worried about speed then use caching.</p>\n\n<pre><code>$query = $_GET['query'];\n$key = 'query' . $query;\nif (!$results = apc_fetch($key))\n{ \n $statement = $db-&gt;prepare(\"SELECT name FROM list WHERE name LIKE :query\");\n $statement-&gt;bindValue(':query', \"$query%\");\n $statement-&gt;execute();\n $results = $statement-&gt;fetchAll();\n apc_store($key, $results);\n}\n\necho json_encode($results);\n</code></pre>\n" }, { "answer_id": 167137, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Why not do it both ways and see which is faster? Both solutions are pretty trivial.</p>\n" }, { "answer_id": 167177, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 0, "selected": false, "text": "<p>If you expect the number of terms to become larger at a later date, you're better off using MySQL with a <a href=\"http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html\" rel=\"nofollow noreferrer\">fulltext search</a> field.</p>\n" }, { "answer_id": 167578, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 1, "selected": false, "text": "<p>I recently had this issue. I had some data in mysql that I was querying on every page request. For my data set, it was faster to write a fixed record length file than to use MySQL.</p>\n\n<p>There were a few different factors that made a file faster than MySQL for me:</p>\n\n<ol>\n<li>File size was small -- under 100kb of text data</li>\n<li>I was randomly picking and not searching -- indexes made no difference</li>\n<li>Connection time -- opening the file and reading it in was faster than connecting to the database when the server load was high. This was especially true since the OS cached the file in memory</li>\n</ol>\n\n<p>Bottom line was that I benchmarked it and compared results. For my workload, the file system was faster. I suspect if my data set ever grows, that will change. I'm going to be keeping an eye on performance and I'm ready to change how it works in the future.</p>\n" }, { "answer_id": 167708, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 0, "selected": false, "text": "<p>If you use a PHP bytecode cache like APC or Xcache, including the file is likely to be faster. If you're using PHP and you want performance, a bytecode cache is absolutely a requirement.</p>\n\n<p>It sounds like you're considering keeping static data around in a PHP script that you include, to avoid hitting the database. You're basically doing a rudimentary cache. This can work okay, as long as you have some way to refresh that file if/when the data does change. You might also look want to learn about the MySQL Query Cache to make SQL queries against static data faster. Or Memcached for keeping static data in memory.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21709/" ]
In PHP, which is quicker; using `include('somefile.php')` or querying a MySQL database with a simple `SELECT` query to get the same information? For example, say you had a JavaScript autocomplete search field which needed 3,000 terms to match against. Is it quicker to read those terms in from another file using `include` or to read them from a MySQL database using a simple `SELECT` query? **Edit:** This is assuming that the database and the file I want to include are on the same local machine as my code.
It depends. If your file is stored locally in your server and the database is installed in another machine, then the faster is to include the file. Buuuuut, because it depends on your system it could be not true. I suggest to you to make a PHP test script and run it 100 times from the command line, and repeat the test through HTTP (using cURL) Example: **use\_include.php** ``` <?php start = microtime(true); include( 'somefile.php' ); echo microtime(true)-start; ?> ``` **use\_myphp.php** ``` <?php start = microtime(true); __put_here_your_mysql_statements_to_retrieve_the_file__ echo microtime(true)-start; ?> ```
166,159
<p>I recall there is a difference between some methods/properties called directly on the <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable(VS.71).aspx" rel="noreferrer">DataTable</a> class, and the identically named methods/properties on the <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable.rows(VS.71).aspx" rel="noreferrer">DataTable.Rows</a> property. (Might have been the RowCount/Count property for which I read this.) The difference is one of them disregards <a href="http://msdn.microsoft.com/en-us/library/system.data.datarow.rowstate(VS.71).aspx" rel="noreferrer">DataRow.RowState</a>, and the other respects/uses it.</p> <p>In this particular case I'm wondering about the difference between <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable.clear(VS.71).aspx" rel="noreferrer">DataTable.Clear</a> and <a href="http://msdn.microsoft.com/en-us/library/system.data.datarowcollection.clear(VS.71).aspx" rel="noreferrer">DataTable.Rows.Clear</a>. I can imagine one of them actually removes all rows, and the other one just marks them as deleted.</p> <p>So my question is, <strong>is there a difference between the two Clear methods, and if so what is the difference?</strong></p> <p>(Oh, this is for .NET 1.1 btw, in case the semantics changed from one version to another.)</p>
[ { "answer_id": 166190, "author": "Jaymz", "author_id": 24761, "author_profile": "https://Stackoverflow.com/users/24761", "pm_score": 2, "selected": false, "text": "<p>AFAIK, the main difference between <code>datatable.clear</code> and <code>datatable.rows.clear</code>, is that <code>datatable.clear</code> clears both rows and columns. So if you want to keep the table structure (i.e. columns), use <code>datatable.rows.clear</code>. And if you want to start from scratch, use <code>datatable.clear</code>, or even <code>datatable.reset</code> to go right back to the beginning.</p>\n\n<p><code>datatable.reset</code> is effectively the next level up from <code>datatable.clear</code>. Using <code>datatable.clear</code> will fail if there are any constraints applied that would be violated, but using <code>datatable.reset</code> will get rid of anything and everything that has been put in place since the datatable was created.</p>\n" }, { "answer_id": 166241, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 2, "selected": false, "text": "<p>I don't believe that DataTable.Clear does clear columns. This code writes \"1\" to standard output:</p>\n\n<pre><code>var d = new DataTable();\nd.Columns.Add(\"Hello\", typeof(string));\nd.Clear();\nConsole.WriteLine(d.Columns.Count);\n</code></pre>\n" }, { "answer_id": 166259, "author": "Joe Chin", "author_id": 5906, "author_profile": "https://Stackoverflow.com/users/5906", "pm_score": -1, "selected": false, "text": "<p>The both do the same thing. One is just an inherited method from the Collections class. And the Table.Clear() just calls that method.</p>\n" }, { "answer_id": 166362, "author": "Tobi", "author_id": 5422, "author_profile": "https://Stackoverflow.com/users/5422", "pm_score": 3, "selected": false, "text": "<p>I've been testing the different methods now in .NET 1.1/VS2003, seems Matt Hamilton is right.</p>\n\n<ul>\n<li>DataTable.Clear and DataTable.Rows.Clear seem to behave identical with respect to the two things I tested: both remove all rows (they don't mark them as deleted, they really remove them from the table), and neither removes the columns of the table.</li>\n<li>DataTable.Reset clears rows and columns.</li>\n<li>DataTable.Rows.Count does include deleted rows. (This might be 1.1 specific)</li>\n<li>foreach iterates over deleted rows. (I'm pretty sure deleted rows are skipped in 2.0.)</li>\n</ul>\n" }, { "answer_id": 166677, "author": "Richard Szalay", "author_id": 3603, "author_profile": "https://Stackoverflow.com/users/3603", "pm_score": 0, "selected": false, "text": "<p>There is no difference between them. DataRowCollection.Clear() calls Table.Clear()</p>\n\n<p>Table.Clear() checks that the table can be cleared (constraints can prevent this), removes the rows and rebuilds any indexes.</p>\n" }, { "answer_id": 778232, "author": "SLaks", "author_id": 34397, "author_profile": "https://Stackoverflow.com/users/34397", "pm_score": 4, "selected": true, "text": "<p>In .Net 1.1, <code>DataRowCollection.Clear</code> calls <code>DataTable.Clear</code></p>\n\n<p>However, in .Net 2.0, there is a difference.\nIf I understand the source correctly, <code>DataTable.Clear</code> will clear unattached rows (created using <code>DataTable.NewRow</code>) whereas DataRowCollection.Clear won't.</p>\n\n<p>The difference is in <code>RecordManager.Clear</code> (source below, from the <a href=\"http://referencesource.microsoft.com/netframework.aspx\" rel=\"noreferrer\">.Net Reference Source</a> for v3.5 SP 0); <code>clearAll</code> is true only when called from <code>DataTable.Clear</code>.</p>\n\n<pre><code> internal void Clear(bool clearAll) { \n if (clearAll) {\n for(int record = 0; record &lt; recordCapacity; ++record) { \n rows[record] = null;\n }\n int count = table.columnCollection.Count;\n for(int i = 0; i &lt; count; ++i) { \n //\n\n DataColumn column = table.columnCollection[i]; \n for(int record = 0; record &lt; recordCapacity; ++record) {\n column.FreeRecord(record); \n }\n }\n lastFreeRecord = 0;\n freeRecordList.Clear(); \n }\n else { // just clear attached rows \n freeRecordList.Capacity = freeRecordList.Count + table.Rows.Count; \n for(int record = 0; record &lt; recordCapacity; ++record) {\n if (rows[record]!= null &amp;&amp; rows[record].rowID != -1) { \n int tempRecord = record;\n FreeRecord(ref tempRecord);\n }\n } \n }\n } \n</code></pre>\n" }, { "answer_id": 8998641, "author": "Himalaya Garg", "author_id": 1129978, "author_profile": "https://Stackoverflow.com/users/1129978", "pm_score": -1, "selected": false, "text": "<p>Do Below and Its working absolutely fine....</p>\n\n<pre><code>DataRow[] d_row = dt_result.Select(\"isfor_report='True'\");\nDataTable dt = dt_result.Clone(); \nforeach (DataRow dr in d_row)\n{\n dt.ImportRow(dr);\n}\ngv_view_result.DataSource = dt;\ngv_view_result.DataBind();\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5422/" ]
I recall there is a difference between some methods/properties called directly on the [DataTable](http://msdn.microsoft.com/en-us/library/system.data.datatable(VS.71).aspx) class, and the identically named methods/properties on the [DataTable.Rows](http://msdn.microsoft.com/en-us/library/system.data.datatable.rows(VS.71).aspx) property. (Might have been the RowCount/Count property for which I read this.) The difference is one of them disregards [DataRow.RowState](http://msdn.microsoft.com/en-us/library/system.data.datarow.rowstate(VS.71).aspx), and the other respects/uses it. In this particular case I'm wondering about the difference between [DataTable.Clear](http://msdn.microsoft.com/en-us/library/system.data.datatable.clear(VS.71).aspx) and [DataTable.Rows.Clear](http://msdn.microsoft.com/en-us/library/system.data.datarowcollection.clear(VS.71).aspx). I can imagine one of them actually removes all rows, and the other one just marks them as deleted. So my question is, **is there a difference between the two Clear methods, and if so what is the difference?** (Oh, this is for .NET 1.1 btw, in case the semantics changed from one version to another.)
In .Net 1.1, `DataRowCollection.Clear` calls `DataTable.Clear` However, in .Net 2.0, there is a difference. If I understand the source correctly, `DataTable.Clear` will clear unattached rows (created using `DataTable.NewRow`) whereas DataRowCollection.Clear won't. The difference is in `RecordManager.Clear` (source below, from the [.Net Reference Source](http://referencesource.microsoft.com/netframework.aspx) for v3.5 SP 0); `clearAll` is true only when called from `DataTable.Clear`. ``` internal void Clear(bool clearAll) { if (clearAll) { for(int record = 0; record < recordCapacity; ++record) { rows[record] = null; } int count = table.columnCollection.Count; for(int i = 0; i < count; ++i) { // DataColumn column = table.columnCollection[i]; for(int record = 0; record < recordCapacity; ++record) { column.FreeRecord(record); } } lastFreeRecord = 0; freeRecordList.Clear(); } else { // just clear attached rows freeRecordList.Capacity = freeRecordList.Count + table.Rows.Count; for(int record = 0; record < recordCapacity; ++record) { if (rows[record]!= null && rows[record].rowID != -1) { int tempRecord = record; FreeRecord(ref tempRecord); } } } } ```
166,160
<p>How can I scale the content of an iframe (in my example it is an HTML page, and is not a popup) in a page of my web site?</p> <p>For example, I want to display the content that appears in the iframe at 80% of the original size.</p>
[ { "answer_id": 166271, "author": "Alexandros Marinos", "author_id": 24461, "author_profile": "https://Stackoverflow.com/users/24461", "pm_score": 0, "selected": false, "text": "<p>I do not think HTML has such functionality. The only thing I can imagine would do the trick is to do some server-side processing. Perhaps you could get an image snapshot of the webpage you want to serve, scale it on the server and serve it to the client. This would be a non-interactive page however. (maybe an imagemap could have the link, but still.) </p>\n\n<p>Another idea would be to have a server-side component that would alter the HTML. SOrt of like the firefox 2.0 zoom feature. this of course is not perfect zooming, but is better than nothing.</p>\n\n<p>Other than that, I am out of ideas.</p>\n" }, { "answer_id": 166287, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": -1, "selected": false, "text": "<p>As said, I doubt you can do it.<br>\nMaybe you can scale at least the text itself, by setting a style <code>font-size: 80%;</code>.<br>\nUntested, not sure it works, and won't resize boxes or images.</p>\n" }, { "answer_id": 166343, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 3, "selected": false, "text": "<p>With CSS:</p>\n<pre><code>html{\n zoom:0.4;\n}\n</code></pre>\n<p>?-)</p>\n" }, { "answer_id": 166942, "author": "Jon", "author_id": 20460, "author_profile": "https://Stackoverflow.com/users/20460", "pm_score": 1, "selected": false, "text": "<p>If your html is styled with css, you can probably link different style sheets for different sizes.</p>\n" }, { "answer_id": 171518, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 2, "selected": false, "text": "<p>I think you can do this by calculating the height and width you want with javascript (via document.body.clientWidth etc.) and then injecting the iframe into your HTML like this:</p>\n\n<pre>\nvar element = document.getElementById(\"myid\");\nelement.innerHTML += \"&lt;iframe src='http://www.google.com' height='200' width='\" + document.body.clientWidth * 0.8 + \"'/&gt;\";\n</pre>\n\n<p>I didn't test this in IE6 but it seems to work with the good ones :)</p>\n" }, { "answer_id": 2224816, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 6, "selected": false, "text": "<p>I found a solution that works in IE and Firefox (at least on the current versions). On Safari/Chrome, the iframe is resized to 75% of its original size, but the content within the iframe is not scaled at all. In Opera, this doesn't seem to work. This feels a bit esoteric, so if there is a better way to do it I'd welcome suggestions.</p>\n\n<pre><code>&lt;style&gt;\n#wrap { width: 600px; height: 390px; padding: 0; overflow: hidden; }\n#frame { width: 800px; height: 520px; border: 1px solid black; }\n#frame { zoom: 0.75; -moz-transform: scale(0.75); -moz-transform-origin: 0 0; }\n&lt;/style&gt;\n\n...\n\n&lt;p&gt;Some text before the frame&lt;/p&gt;\n&lt;div id=\"wrap\"&gt;\n&lt;iframe id=\"frame\" src=\"test2.html\"&gt;&lt;/iframe&gt;\n&lt;/div&gt;\n&lt;p&gt;Some text after the frame&lt;/p&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>Note: I had to use the <code>wrap</code> element for Firefox. For some reason, in Firefox when you scale the object down by 75%, it still uses the original size of the image for layout reasons. (Try removing the div from the sample code above and you'll see what I mean.)</p>\n\n<p>I found some of this from <a href=\"https://stackoverflow.com/questions/1156278/css-how-to-scale-entire-web-page-with-css/1156526#1156526\">this question</a>.</p>\n" }, { "answer_id": 3131624, "author": "lxs", "author_id": 304282, "author_profile": "https://Stackoverflow.com/users/304282", "pm_score": 8, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/166160/how-can-i-scale-the-content-of-iframe/2224816#2224816\">Kip's solution</a> should work on Opera and Safari if you change the CSS to:</p>\n\n<pre><code>&lt;style&gt;\n #wrap { width: 600px; height: 390px; padding: 0; overflow: hidden; }\n #frame { width: 800px; height: 520px; border: 1px solid black; }\n #frame {\n -ms-zoom: 0.75;\n -moz-transform: scale(0.75);\n -moz-transform-origin: 0 0;\n -o-transform: scale(0.75);\n -o-transform-origin: 0 0;\n -webkit-transform: scale(0.75);\n -webkit-transform-origin: 0 0;\n }\n&lt;/style&gt;\n</code></pre>\n\n<p>You might also want to specify overflow: hidden on #frame to prevent scrollbars.</p>\n" }, { "answer_id": 7504903, "author": "r3cgm", "author_id": 943317, "author_profile": "https://Stackoverflow.com/users/943317", "pm_score": 3, "selected": false, "text": "<p>Followup to <a href=\"https://stackoverflow.com/questions/166160/how-can-i-scale-the-content-of-iframe/3131624#3131624\">lxs's answer</a>: I noticed a problem where having both the <code>zoom</code> and <code>--webkit-transform</code> tags at the same time seems to confound Chrome (version 15.0.874.15) by doing a double-zoom sort of effect. I was able to work around the issue by replacing <code>zoom</code> with <code>-ms-zoom</code> (targeted only at IE), leaving Chrome to make use of just the <code>--webkit-transform</code> tag, and that cleared things up.</p>\n" }, { "answer_id": 11959481, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>For those of you having trouble getting this to work in IE, it is helpful to use <code>-ms-zoom</code> as suggested below and use the zoom function on the <code>#wrap</code> div, not the <code>iframe</code> id. In my experience, with the <code>zoom</code> function trying to scale the iframe div of <code>#frame</code>, it would scale the iframe size and not the content within it (which is what you're going for). </p>\n\n<p>Looks like this. Works for me on IE8, Chrome and FF.</p>\n\n<pre><code>#wrap {\n overflow: hidden;\n position: relative;\n width:800px;\n height:850px;\n -ms-zoom: 0.75;\n}\n</code></pre>\n" }, { "answer_id": 12588274, "author": "Jon Fergus", "author_id": 1544609, "author_profile": "https://Stackoverflow.com/users/1544609", "pm_score": 3, "selected": false, "text": "<p>Thought I'd share what I came up with, using much of what was given above. I haven't checked Chrome, but it works in IE, Firefox and Safari, so far as I can tell.</p>\n\n<p>The specifics offsets and zoom factor in this example worked for shrinking and centering two websites in iframes for Facebook tabs (810px width).</p>\n\n<p>The two sites used were a wordpress site and a ning network. I'm not very good with html, so this could probably have been done better, but the result seems good.</p>\n\n<pre><code>&lt;style&gt;\n #wrap { width: 1620px; height: 3500px; padding: 0; position:relative; left:-100px; top:0px; overflow: hidden; }\n #frame { width: 1620px; height: 3500px; position:relative; left:-65px; top:0px; }\n #frame { -ms-zoom: 0.7; -moz-transform: scale(0.7); -moz-transform-origin: 0px 0; -o-transform: scale(0.7); -o-transform-origin: 0 0; -webkit-transform: scale(0.7); -webkit-transform-origin: 0 0; }\n&lt;/style&gt;\n&lt;div id=\"wrap\"&gt;\n &lt;iframe id=\"frame\" src=\"http://www.example.com\"&gt;&lt;/iframe&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 13380454, "author": "Matthew Wilcoxson", "author_id": 266375, "author_profile": "https://Stackoverflow.com/users/266375", "pm_score": 4, "selected": false, "text": "<p>You don't need to wrap the iframe with an additional tag. Just make sure you increase the width and height of the iframe by the same amount you scale down the iframe.</p>\n\n<p>e.g. to scale the iframe content to 80% :</p>\n\n<pre><code>#frame { /* Example size! */\n height: 400px; /* original height */\n width: 100%; /* original width */\n}\n#frame {\n height: 500px; /* new height (400 * (1/0.8) ) */\n width: 125%; /* new width (100 * (1/0.8) )*/\n\n transform: scale(0.8); \n transform-origin: 0 0;\n}\n</code></pre>\n\n<p>Basically, to get the same size iframe you need to scale the dimensions.</p>\n" }, { "answer_id": 13544834, "author": "Stefan Gruenwald", "author_id": 1751920, "author_profile": "https://Stackoverflow.com/users/1751920", "pm_score": 2, "selected": false, "text": "<p>The #wrap #frame solution works fine, as long as the numbers in #wrap is #frame times the scale factor. It shows only that part of the scaled down frame. You can see it here scaling down websites and putting it into a pinterest like form (with the woodmark jQuery plugin):</p>\n\n<p><a href=\"http://www.genautica.com/sandbox/woodmark-index.html\" rel=\"nofollow\">http://www.genautica.com/sandbox/woodmark-index.html</a></p>\n" }, { "answer_id": 13880714, "author": "Mathias Asberg", "author_id": 1055866, "author_profile": "https://Stackoverflow.com/users/1055866", "pm_score": 2, "selected": false, "text": "<p>This was my solution on a page with 890px width </p>\n\n<pre><code>#frame { \noverflow: hidden;\nposition: relative;\nwidth:1044px;\nheight:1600px;\n-ms-zoom: 0.85;\n-moz-transform: scale(0.85);\n-moz-transform-origin: 0px 0;\n-o-transform: scale(0.85);\n-o-transform-origin: 0 0;\n-webkit-transform: scale(0.85);\n-webkit-transform-origin: 0 0; \n\n}\n</code></pre>\n" }, { "answer_id": 15592305, "author": "Eric Sassaman", "author_id": 765303, "author_profile": "https://Stackoverflow.com/users/765303", "pm_score": 5, "selected": false, "text": "<p>After struggling with this for hours trying to get it to work in IE8, 9, and 10 here's what worked for me.</p>\n\n<p>This stripped-down CSS works in FF 26, Chrome 32, Opera 18, and IE9 -11 as of 1/7/2014:</p>\n\n<pre><code>.wrap\n{\n width: 320px;\n height: 192px;\n padding: 0;\n overflow: hidden;\n}\n\n.frame\n{\n width: 1280px;\n height: 786px;\n border: 0;\n\n -ms-transform: scale(0.25);\n -moz-transform: scale(0.25);\n -o-transform: scale(0.25);\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n\n -ms-transform-origin: 0 0;\n -moz-transform-origin: 0 0;\n -o-transform-origin: 0 0;\n -webkit-transform-origin: 0 0;\n transform-origin: 0 0;\n}\n</code></pre>\n\n<p>For IE8, set the width/height to match the iframe, and add -ms-zoom to the .wrap container div:</p>\n\n<pre><code>.wrap\n{\n width: 1280px; /* same size as frame */\n height: 768px;\n -ms-zoom: 0.25; /* for IE 8 ONLY */\n}\n</code></pre>\n\n<p>Just use your favorite method for browser sniffing to conditionally include the appropriate CSS, see <a href=\"https://stackoverflow.com/questions/639999/is-there-a-way-to-do-browser-specific-conditional-css-inside-a-css-file\">Is there a way to do browser specific conditional CSS inside a *.css file?</a> for some ideas.</p>\n\n<p>IE7 was a lost cause since -ms-zoom did not exist until IE8.</p>\n\n<p>Here's the actual HTML I tested with:</p>\n\n<pre><code>&lt;div class=\"wrap\"&gt;\n &lt;iframe class=\"frame\" src=\"http://time.is\"&gt;&lt;/iframe&gt;\n&lt;/div&gt;\n&lt;div class=\"wrap\"&gt;\n &lt;iframe class=\"frame\" src=\"http://apple.com\"&gt;&lt;/iframe&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/esassaman/PnWFY/\" rel=\"noreferrer\">http://jsfiddle.net/esassaman/PnWFY/</a></p>\n" }, { "answer_id": 21711582, "author": "user3298597", "author_id": 3298597, "author_profile": "https://Stackoverflow.com/users/3298597", "pm_score": 3, "selected": false, "text": "<p>If you want the iframe and its contents to scale when the window resizes, you can set the following to the window's resize event as well as the iframes onload event.</p>\n\n<pre><code>function()\n{\n var _wrapWidth=$('#wrap').width();\n var _frameWidth=$($('#frame')[0].contentDocument).width();\n\n if(!this.contentLoaded)\n this.initialWidth=_frameWidth;\n this.contentLoaded=true;\n var frame=$('#frame')[0];\n\n var percent=_wrapWidth/this.initialWidth;\n\n frame.style.width=100.0/percent+\"%\";\n frame.style.height=100.0/percent+\"%\";\n\n frame.style.zoom=percent;\n frame.style.webkitTransform='scale('+percent+')';\n frame.style.webkitTransformOrigin='top left';\n frame.style.MozTransform='scale('+percent+')';\n frame.style.MozTransformOrigin='top left';\n frame.style.oTransform='scale('+percent+')';\n frame.style.oTransformOrigin='top left';\n };\n</code></pre>\n\n<p>This will make the iframe and its content scale to 100% width of the wrap div (or whatever percent you want). As an added bonus, you don't have to set the css of the frame to hard coded values since they'll all be set dynamically, you'll just need to worry about how you want the wrap div to display. </p>\n\n<p>I've tested this and it works on chrome, IE11, and firefox.</p>\n" }, { "answer_id": 35984409, "author": "Graham", "author_id": 6060213, "author_profile": "https://Stackoverflow.com/users/6060213", "pm_score": 2, "selected": false, "text": "<p>So probably not the best solution, but seems to work OK.</p>\n\n<pre><code>&lt;IFRAME ID=myframe SRC=.... &gt;&lt;/IFRAME&gt;\n\n&lt;SCRIPT&gt;\n window.onload = function(){document.getElementById('myframe').contentWindow.document.body.style = 'zoom:50%;';};\n&lt;/SCRIPT&gt;\n</code></pre>\n\n<p>Obviously not trying to fix the parent, just adding the \"zoom:50%\" style to the body of the child with a bit of javascript.</p>\n\n<p>Maybe could set the style of the \"HTML\" element, but didn't try that.</p>\n" }, { "answer_id": 48490950, "author": "MrP01", "author_id": 5832850, "author_profile": "https://Stackoverflow.com/users/5832850", "pm_score": 5, "selected": false, "text": "<p>I just tested and for me, none of the other solutions worked.\nI simply tried this and it worked perfectly on Firefox and Chrome.</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div class='wrap'&gt;\n &lt;iframe ...&gt;&lt;/iframe&gt;\n&lt;/div&gt;\n</code></pre>\n<p>and the css:</p>\n<pre class=\"lang-css prettyprint-override\"><code>.wrap {\n width: 640px;\n height: 480px;\n overflow: hidden;\n}\n\niframe {\n width: 76.92% !important;\n height: 76.92% !important;\n -webkit-transform: scale(1.3);\n transform: scale(1.3);\n -webkit-transform-origin: 0 0;\n transform-origin: 0 0;\n}\n</code></pre>\n<p>This scales all the content by 23.08%, the equivalent of the original being 30% larger than the embedded version. (The width/height percentages of course need to be adjusted accordingly <code>(1/scale_factor)</code>).</p>\n" }, { "answer_id": 70929773, "author": "Tofnet", "author_id": 14521222, "author_profile": "https://Stackoverflow.com/users/14521222", "pm_score": 0, "selected": false, "text": "<p>These solutions don't work properly for me (blur) with a Flexbox and an iFrame at 100% but if the Iframe uses the rem em or percent units then there is a solution that looks great:</p>\n<pre><code> window.onload = function(){\n let ifElem = document.getElementById(&quot;iframe-id&quot;);\n ifElem.contentWindow.document.documentElement.style.fontSize=&quot;80%&quot;;\n }\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24765/" ]
How can I scale the content of an iframe (in my example it is an HTML page, and is not a popup) in a page of my web site? For example, I want to display the content that appears in the iframe at 80% of the original size.
[Kip's solution](https://stackoverflow.com/questions/166160/how-can-i-scale-the-content-of-iframe/2224816#2224816) should work on Opera and Safari if you change the CSS to: ``` <style> #wrap { width: 600px; height: 390px; padding: 0; overflow: hidden; } #frame { width: 800px; height: 520px; border: 1px solid black; } #frame { -ms-zoom: 0.75; -moz-transform: scale(0.75); -moz-transform-origin: 0 0; -o-transform: scale(0.75); -o-transform-origin: 0 0; -webkit-transform: scale(0.75); -webkit-transform-origin: 0 0; } </style> ``` You might also want to specify overflow: hidden on #frame to prevent scrollbars.
166,174
<p>I have a list of objects, each containing an Id, Code and Description.</p> <p>I need to convert this list into a Hashtable, using <strong>Description</strong> as the key and <strong>Id</strong> as the value.</p> <p>This is so the Hashtable can then be serialised to JSON.</p> <p>Is there a way to convert from List&lt;Object&gt; to Hashtable without writing a loop to go through each item in the list?</p>
[ { "answer_id": 166202, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 3, "selected": false, "text": "<p>If you have access to Linq, you can use the <a href=\"http://msdn.microsoft.com/en-us/library/bb549277.aspx\" rel=\"noreferrer\">ToDictionary</a> function.</p>\n" }, { "answer_id": 166207, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 6, "selected": true, "text": "<p>Let's assume that your List contains objects of type Foo (with an int Id and a string Description).</p>\n\n<p>You can use Linq to turn that list into a Dictionary like this:</p>\n\n<pre><code>var dict = myList.Cast&lt;Foo&gt;().ToDictionary(o =&gt; o.Description, o =&gt; o.Id);\n</code></pre>\n" }, { "answer_id": 166251, "author": "noocyte", "author_id": 11220, "author_profile": "https://Stackoverflow.com/users/11220", "pm_score": 0, "selected": false, "text": "<pre class=\"lang-cs prettyprint-override\"><code>theList.ForEach(delegate(theObject obj) { dic.Add(obj.Id, obj.Description); });\n</code></pre>\n" }, { "answer_id": 166700, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "<p>Also look at the <code>System.Collections.ObjectModel.KeyedCollection&lt;TKey, TItem&gt;</code>. It seems like a better match for what you want to do.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4734/" ]
I have a list of objects, each containing an Id, Code and Description. I need to convert this list into a Hashtable, using **Description** as the key and **Id** as the value. This is so the Hashtable can then be serialised to JSON. Is there a way to convert from List<Object> to Hashtable without writing a loop to go through each item in the list?
Let's assume that your List contains objects of type Foo (with an int Id and a string Description). You can use Linq to turn that list into a Dictionary like this: ``` var dict = myList.Cast<Foo>().ToDictionary(o => o.Description, o => o.Id); ```
166,198
<p>I'm writing a little debug app for a bit of kit we're developing and I'd like to roll it out to a few users to see if they can provoke any crashes. Does anyone know a way of effectively wrapping a wxPython app to catch any and all unhandled exceptions that would cause the app to crash?</p> <p>Ideally I'd want to capture all output (not just errors) and log it to a file. Any unhandled exceptions ought to log to the current file and then allow the exception to pass on as per usual (i.e. the logging process ought to be transparent).</p> <p>I'm sure someone must have done something along these lines before, but I've not managed to turn up anything that looks useful via google.</p>
[ { "answer_id": 166213, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 1, "selected": false, "text": "<p>There are various ways. You can put a try..catch block in the wxApplication::OnInit, however, that would not always work with Gtk. </p>\n\n<p>A nice alternative would be to override the Application::HandleEvent in your wxApplication derived class, and write a code like this:</p>\n\n<pre><code>void Application::HandleEvent(wxEvtHandler* handler, wxEventFunction func, wxEvent&amp; event) const\n{\n try\n {\n wxAppConsole::HandleEvent(handler, func, event);\n }\n catch (const std::exception&amp; e)\n {\n wxMessageBox(std2wx(e.what()), _(\"Unhandled Error\"),\n wxOK | wxICON_ERROR, wxGetTopLevelParent(wxGetActiveWindow()));\n }\n}\n</code></pre>\n\n<p>It's a C++ example, but you can surely translate to Python easily.</p>\n" }, { "answer_id": 166246, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 4, "selected": true, "text": "<p>For logging standard output, you can use a stdout wrapper, such as this one:</p>\n\n<pre><code>from __future__ import with_statement\n\nclass OutWrapper(object):\n def __init__(self, realOutput, logFileName):\n self._realOutput = realOutput\n self._logFileName = logFileName\n\n def _log(self, text):\n with open(self._logFileName, 'a') as logFile:\n logFile.write(text)\n\n def write(self, text):\n self._log(text)\n self._realOutput.write(text)\n</code></pre>\n\n<p>You then have to initialize it in your main Python file (the one that runs everything):</p>\n\n<pre><code>import sys \nsys.stdout = OutWrapper(sys.stdout, r'c:\\temp\\log.txt')\n</code></pre>\n\n<p>As to logging exceptions, the easiest thing to do is to wrap <code>MainLoop</code> method of wx.App in a try..except, then extract the exception information, save it in some way, and then re-raise the exception through <code>raise</code>, e.g.:</p>\n\n<pre><code>try:\n app.MainLoop()\nexcept:\n exc_info = sys.exc_info()\n saveExcInfo(exc_info) # this method you have to write yourself\n raise\n</code></pre>\n" }, { "answer_id": 190233, "author": "monopocalypse", "author_id": 17142, "author_profile": "https://Stackoverflow.com/users/17142", "pm_score": 3, "selected": false, "text": "<p>For the exception handling, assuming your log file is opened as log:</p>\n\n<pre><code>import sys\nimport traceback\n\ndef excepthook(type, value, tb):\n message = 'Uncaught exception:\\n'\n message += ''.join(traceback.format_exception(type, value, tb))\n log.write(message)\n\nsys.excepthook = excepthook\n</code></pre>\n" }, { "answer_id": 372826, "author": "Abgan", "author_id": 46308, "author_profile": "https://Stackoverflow.com/users/46308", "pm_score": 2, "selected": false, "text": "<p>You can use</p>\n\n<blockquote>\n <p>sys.excepthook</p>\n</blockquote>\n\n<p>(see <a href=\"http://docs.python.org/library/sys.html#sys.excepthook\" rel=\"nofollow noreferrer\">Python docs</a>)</p>\n\n<p>and assign some custom object to it, that would catch all exceptions not caught earlier in your code. You can then log any message to any file you wish, together with traceback and do whatever you like with the exception (reraise it, display error message and allow user to continue using your app etc).</p>\n\n<p>As for logging stdout - the best way for me was to write something similar to DzinX's OutWrapper.</p>\n\n<p>If you're at debugging stage, consider flushing your log files after each entry. This harms performance a lot, but if you manage to cause segfault in some underlying C code, your logs won't mislead you.</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15369/" ]
I'm writing a little debug app for a bit of kit we're developing and I'd like to roll it out to a few users to see if they can provoke any crashes. Does anyone know a way of effectively wrapping a wxPython app to catch any and all unhandled exceptions that would cause the app to crash? Ideally I'd want to capture all output (not just errors) and log it to a file. Any unhandled exceptions ought to log to the current file and then allow the exception to pass on as per usual (i.e. the logging process ought to be transparent). I'm sure someone must have done something along these lines before, but I've not managed to turn up anything that looks useful via google.
For logging standard output, you can use a stdout wrapper, such as this one: ``` from __future__ import with_statement class OutWrapper(object): def __init__(self, realOutput, logFileName): self._realOutput = realOutput self._logFileName = logFileName def _log(self, text): with open(self._logFileName, 'a') as logFile: logFile.write(text) def write(self, text): self._log(text) self._realOutput.write(text) ``` You then have to initialize it in your main Python file (the one that runs everything): ``` import sys sys.stdout = OutWrapper(sys.stdout, r'c:\temp\log.txt') ``` As to logging exceptions, the easiest thing to do is to wrap `MainLoop` method of wx.App in a try..except, then extract the exception information, save it in some way, and then re-raise the exception through `raise`, e.g.: ``` try: app.MainLoop() except: exc_info = sys.exc_info() saveExcInfo(exc_info) # this method you have to write yourself raise ```
166,210
<p>I'll regularly get an extract from a DB/2 database with dates and timestaps formatted like this:</p> <pre><code>2002-01-15-00.00.00.000000 2008-01-05-12.36.05.190000 9999-12-31-24.00.00.000000 </code></pre> <p>Is there an easier way to convert this into the Excel date format than decomposing with substrings?</p> <pre><code>DB2date = DateValue(Left(a, 4) + "/" + Mid(a, 6, 2) + "/" + Mid(a, 9, 2)) </code></pre> <p>thanks for your help!</p>
[ { "answer_id": 166216, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 1, "selected": false, "text": "<p>I'm sure you could cook something up with Regex's if you really cared to. It wouldn't be any 'better' though, probably worse. </p>\n\n<p>If you'll forgive a bit of C# (I havn't touched VB in years, so I don't know the function calls anymore) you could also do:</p>\n\n<pre><code>DB2string = \"2002-01-15-00.00.00.000000\";\nDB2date = DateValue(DB2string.SubString(0, 10).Replace('-', '/'));\n</code></pre>\n\n<p>But again, you're not really gaining anything. Can you give an example of where your current code would break?</p>\n" }, { "answer_id": 166253, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": true, "text": "<p>It's not clear if you talk about formula functions or VBA functions.</p>\n\n<h2>Formula functions</h2>\n\n<p>Don't use the DateValue function, which expects a string; use the Date function, which expects numeric Year, Month, Day:</p>\n\n<pre><code>=DATE(INT(LEFT(A1,4)),INT(MID(A1,6,2)),INT(MID(A1,9,2)))\n</code></pre>\n\n<p>assuming that the date-as-string is in A1.</p>\n\n<h2>VBA functions</h2>\n\n<p>Similar calculation as above, just use the <strong>DateSerial</strong> function instead:</p>\n\n<pre><code>dt= DateSerial(Int(Left$(dt$, 4), Int(Mid$(dt$, 6, 2)), Int(Mid$(dt$, 9, 2)))\n</code></pre>\n" }, { "answer_id": 166281, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 1, "selected": false, "text": "<p>in VBA, <code>dateValue()</code> can convert the first part of the string into a date:</p>\n\n<pre><code>? dateValue(\"2002-01-15\")\n\n 15/01/2002\n</code></pre>\n\n<p>So the right way to get it for you will be</p>\n\n<pre><code>? dateValue(left(\"2002-01-15-00.00.00.000000\",10))\n</code></pre>\n\n<p>This will always give you the right answer as long as DB2 always give you a \"YYYY-MM-DD\" date. The format of the result (dd/mm/yy, mm-ddd-yyyy, etc) will depend on the local settings of your computer/specific settings of your cell.</p>\n\n<p>If you want to extract the \"time\" part of your string, there is this <code>timeValue()</code> function that will eventually make the job.</p>\n" }, { "answer_id": 167497, "author": "blairxy", "author_id": 19478, "author_profile": "https://Stackoverflow.com/users/19478", "pm_score": 1, "selected": false, "text": "<p>If you want to include the time information you have more to do; DateValue discards it.<br>\nTimeValue can evaluate the time part down to seconds, so you can add them:</p>\n\n<pre><code>= DateValue(Mid(a, 1, 10)) + TimeValue(Mid(a, 12, 8))\n</code></pre>\n\n<p>But your sample data presents another problem: it has both time values \"00.00.00\" and \"24.00.00\".<br>\nThe second one gags the TimeValue function, so you will need to code for the special case. </p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15296/" ]
I'll regularly get an extract from a DB/2 database with dates and timestaps formatted like this: ``` 2002-01-15-00.00.00.000000 2008-01-05-12.36.05.190000 9999-12-31-24.00.00.000000 ``` Is there an easier way to convert this into the Excel date format than decomposing with substrings? ``` DB2date = DateValue(Left(a, 4) + "/" + Mid(a, 6, 2) + "/" + Mid(a, 9, 2)) ``` thanks for your help!
It's not clear if you talk about formula functions or VBA functions. Formula functions ----------------- Don't use the DateValue function, which expects a string; use the Date function, which expects numeric Year, Month, Day: ``` =DATE(INT(LEFT(A1,4)),INT(MID(A1,6,2)),INT(MID(A1,9,2))) ``` assuming that the date-as-string is in A1. VBA functions ------------- Similar calculation as above, just use the **DateSerial** function instead: ``` dt= DateSerial(Int(Left$(dt$, 4), Int(Mid$(dt$, 6, 2)), Int(Mid$(dt$, 9, 2))) ```
166,217
<p>I'm trying to create a named_scope that uses a join, but although the generated SQL looks right, the result are garbage. For example:</p> <pre><code>class Clip &lt; ActiveRecord::Base named_scope :visible, { :joins =&gt; "INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id", :conditions=&gt;"shows.visible = 1 AND clips.owner_type = 'Series' " } </code></pre> <p>(A Clip is owned by a Series, a Series belongs to a Show, a Show can be visible or invisible).</p> <p>Clip.all does:</p> <pre><code>SELECT * FROM `clips` </code></pre> <p>Clip.visible.all does:</p> <pre><code>SELECT * FROM `clips` INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id WHERE (shows.visible = 1 AND clips.owner_type = 'Series' ) </code></pre> <p>This looks okay. But the resulting array of Clip models includes a Clip with an ID that's not in the database - it's picked up a show ID instead. Where am I going wrong?</p>
[ { "answer_id": 166255, "author": "MatthewFord", "author_id": 21596, "author_profile": "https://Stackoverflow.com/users/21596", "pm_score": 3, "selected": false, "text": "<p>This is a bug:</p>\n\n<p><a href=\"http://rails.lighthouseapp.com/projects/8994/tickets/1077-chaining-scopes-with-duplicate-joins-causes-alias-problem\" rel=\"noreferrer\">http://rails.lighthouseapp.com/projects/8994/tickets/1077-chaining-scopes-with-duplicate-\njoins-causes-alias-problem</a></p>\n" }, { "answer_id": 166329, "author": "Ben Scofield", "author_id": 6478, "author_profile": "https://Stackoverflow.com/users/6478", "pm_score": 6, "selected": true, "text": "<p>The problem is that \"SELECT *\" - the query picks up all the columns from clips, series, and shows, in that order. Each table has an id column, and result in conflicts between the named columns in the results. The last id column pulled back (from shows) overrides the one you want. You should be using a :select option with the :joins, like: </p>\n\n<pre><code>named_scope :visible, {\n :select =&gt; \"episodes.*\",\n :joins =&gt; \"INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id\", \n :conditions=&gt;\"shows.visible = 1 AND clips.owner_type = 'Series' \"\n}\n</code></pre>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18666/" ]
I'm trying to create a named\_scope that uses a join, but although the generated SQL looks right, the result are garbage. For example: ``` class Clip < ActiveRecord::Base named_scope :visible, { :joins => "INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id", :conditions=>"shows.visible = 1 AND clips.owner_type = 'Series' " } ``` (A Clip is owned by a Series, a Series belongs to a Show, a Show can be visible or invisible). Clip.all does: ``` SELECT * FROM `clips` ``` Clip.visible.all does: ``` SELECT * FROM `clips` INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id WHERE (shows.visible = 1 AND clips.owner_type = 'Series' ) ``` This looks okay. But the resulting array of Clip models includes a Clip with an ID that's not in the database - it's picked up a show ID instead. Where am I going wrong?
The problem is that "SELECT \*" - the query picks up all the columns from clips, series, and shows, in that order. Each table has an id column, and result in conflicts between the named columns in the results. The last id column pulled back (from shows) overrides the one you want. You should be using a :select option with the :joins, like: ``` named_scope :visible, { :select => "episodes.*", :joins => "INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id", :conditions=>"shows.visible = 1 AND clips.owner_type = 'Series' " } ```
166,221
<p>I would like to upload a file asynchronously with jQuery. </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function () { $("#uploadbutton").click(function () { var filename = $("#file").val(); $.ajax({ type: "POST", url: "addFile.do", enctype: 'multipart/form-data', data: { file: filename }, success: function () { alert("Data Uploaded: "); } }); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"&gt;&lt;/script&gt; &lt;span&gt;File&lt;/span&gt; &lt;input type="file" id="file" name="file" size="10"/&gt; &lt;input id="uploadbutton" type="button" value="Upload"/&gt;</code></pre> </div> </div> </p> <p>Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?</p>
[ { "answer_id": 166267, "author": "Mattias", "author_id": 261, "author_profile": "https://Stackoverflow.com/users/261", "pm_score": 7, "selected": false, "text": "<p>Note: This answer is outdated, it is now possible to upload files using XHR.</p>\n\n<hr>\n\n<p>You cannot upload files using <a href=\"http://en.wikipedia.org/wiki/XMLHttpRequest\" rel=\"noreferrer\">XMLHttpRequest</a> (Ajax). You can simulate the effect using an iframe or Flash. The excellent <a href=\"http://malsup.com/jquery/form/\" rel=\"noreferrer\">jQuery Form Plugin</a> that posts your files through an iframe to get the effect.</p>\n" }, { "answer_id": 166284, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 8, "selected": false, "text": "<h2>2019 Update: It <em>still</em> depends on the browsers <em>your</em> demographic uses.</h2>\n<p>An important thing to understand with the &quot;new&quot; HTML5 <code>file</code> API is that it <a href=\"http://caniuse.com/fileapi\" rel=\"noreferrer\">wasn't supported until IE 10</a>. If the specific market you're aiming at has a higher-than-average propensity toward older versions of Windows, you might not have access to it.</p>\n<p>As of 2017, about 5% of browsers are one of IE 6, 7, 8 or 9. If you head into a big corporation (e.g., this is a B2B tool or something you're delivering for training) that number can skyrocket. In 2016, I dealt with a company using IE8 on over 60% of their machines.</p>\n<p>It's 2019 as of this edit, almost 11 years after my initial answer. IE9 and lower are <em>globally</em> around the 1% mark but there are still clusters of higher usage.</p>\n<p>The important take-away from this —whatever the feature— is, <strong>check what browser <em>your</em> users use</strong>. If you don't, you'll learn a quick and painful lesson in why &quot;works for me&quot; isn't good enough in a deliverable to a client. <a href=\"https://caniuse.com/\" rel=\"noreferrer\">caniuse</a> is a useful tool but note where they get their demographics from. They may not align with yours. This is never truer than enterprise environments.</p>\n<p>My answer from 2008 follows.</p>\n<hr />\n<p>However, there are viable non-JS methods of file uploads. You can create an iframe on the page (that you hide with CSS) and then target your form to post to that iframe. The main page doesn't need to move.</p>\n<p>It's a &quot;real&quot; post so it's not wholly interactive. If you need status you need something server-side to process that. This varies massively depending on your server. <a href=\"http://en.wikipedia.org/wiki/ASP.NET\" rel=\"noreferrer\">ASP.NET</a> has nicer mechanisms. PHP plain fails, but you can use <a href=\"http://en.wikipedia.org/wiki/Perl\" rel=\"noreferrer\">Perl</a> or Apache modifications to get around it.</p>\n<p>If you need multiple file uploads, it's best to do each file one at a time (to overcome maximum file upload limits). Post the first form to the iframe, monitor its progress using the above and when it has finished, post the second form to the iframe, and so on.</p>\n<p>Or use a Java/Flash solution. They're a lot more flexible in what they can do with their posts...</p>\n" }, { "answer_id": 215476, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 5, "selected": false, "text": "<p>A solution I found was to have the <code>&lt;form&gt;</code> target a hidden iFrame. The iFrame can then run JS to display to the user that it's complete (on page load).</p>\n" }, { "answer_id": 309393, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<p>I recommend using the <a href=\"http://fineuploader.com/demos.html\" rel=\"noreferrer\">Fine Uploader</a> plugin for this purpose. Your <code>JavaScript</code> code would be:</p>\n\n<pre><code>$(document).ready(function() {\n $(\"#uploadbutton\").jsupload({\n action: \"addFile.do\",\n onComplete: function(response){\n alert( \"server response: \" + response);\n }\n });\n});\n</code></pre>\n" }, { "answer_id": 1275048, "author": "wbharding", "author_id": 153610, "author_profile": "https://Stackoverflow.com/users/153610", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://www.williambharding.com/blog/rails/rails-ajax-image-uploading-made-simple-with-jquery/\" rel=\"noreferrer\">I've written this up in a Rails environment</a>. It's only about five lines of JavaScript, if you use the lightweight jQuery-form plugin.</p>\n\n<p>The challenge is in getting AJAX upload working as the standard <code>remote_form_for</code> doesn't understand multi-part form submission. It's not going to send the file data Rails seeks back with the AJAX request. </p>\n\n<p>That's where the jQuery-form plugin comes into play. </p>\n\n<p>Here’s the Rails code for it:</p>\n\n<pre><code>&lt;% remote_form_for(:image_form, \n :url =&gt; { :controller =&gt; \"blogs\", :action =&gt; :create_asset }, \n :html =&gt; { :method =&gt; :post, \n :id =&gt; 'uploadForm', :multipart =&gt; true }) \n do |f| %&gt;\n Upload a file: &lt;%= f.file_field :uploaded_data %&gt;\n&lt;% end %&gt;\n</code></pre>\n\n<p>Here’s the associated JavaScript:</p>\n\n<pre><code>$('#uploadForm input').change(function(){\n $(this).parent().ajaxSubmit({\n beforeSubmit: function(a,f,o) {\n o.dataType = 'json';\n },\n complete: function(XMLHttpRequest, textStatus) {\n // XMLHttpRequest.responseText will contain the URL of the uploaded image.\n // Put it in an image element you create, or do with it what you will.\n // For example, if you have an image elemtn with id \"my_image\", then\n // $('#my_image').attr('src', XMLHttpRequest.responseText);\n // Will set that image tag to display the uploaded image.\n },\n });\n});\n</code></pre>\n\n<p>And here’s the Rails controller action, pretty vanilla:</p>\n\n<pre><code> @image = Image.new(params[:image_form])\n @image.save\n render :text =&gt; @image.public_filename\n</code></pre>\n\n<p>I’ve been using this for the past few weeks with Bloggity, and it’s worked like a champ.</p>\n" }, { "answer_id": 6867400, "author": "Jordan Feldstein", "author_id": 311901, "author_profile": "https://Stackoverflow.com/users/311901", "pm_score": 6, "selected": false, "text": "<p>This <a href=\"https://github.com/jfeldstein/jQuery.AjaxFileUpload.js\">AJAX file upload jQuery plugin</a> uploads the file somehwere, and passes the\nresponse to a callback, nothing else. </p>\n\n<ul>\n<li>It does not depend on specific HTML, just give it a <code>&lt;input type=\"file\"&gt;</code></li>\n<li>It does not require your server to respond in any particular way</li>\n<li>It does not matter how many files you use, or where they are on the page</li>\n</ul>\n\n<p>-- Use as little as --</p>\n\n<pre><code>$('#one-specific-file').ajaxfileupload({\n 'action': '/upload.php'\n});\n</code></pre>\n\n<p>-- or as much as --</p>\n\n<pre><code>$('input[type=\"file\"]').ajaxfileupload({\n 'action': '/upload.php',\n 'params': {\n 'extra': 'info'\n },\n 'onComplete': function(response) {\n console.log('custom handler for file:');\n alert(JSON.stringify(response));\n },\n 'onStart': function() {\n if(weWantedTo) return false; // cancels upload\n },\n 'onCancel': function() {\n console.log('no file selected');\n }\n});\n</code></pre>\n" }, { "answer_id": 8758614, "author": "olanod", "author_id": 931340, "author_profile": "https://Stackoverflow.com/users/931340", "pm_score": 11, "selected": false, "text": "<p>With <a href=\"http://en.wikipedia.org/wiki/HTML5\" rel=\"noreferrer\">HTML5</a> you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use <a href=\"http://en.wikipedia.org/wiki/Adobe_Flash\" rel=\"noreferrer\">Flash</a> nor Iframes or plugins and after some research I came up with the solution.</p>\n\n<p>The HTML:</p>\n\n<pre><code>&lt;form enctype=\"multipart/form-data\"&gt;\n &lt;input name=\"file\" type=\"file\" /&gt;\n &lt;input type=\"button\" value=\"Upload\" /&gt;\n&lt;/form&gt;\n&lt;progress&gt;&lt;/progress&gt;\n</code></pre>\n\n<p>First, you can do some validation if you want. For example, in the <code>.on('change')</code> event of the file:</p>\n\n<pre><code>$(':file').on('change', function () {\n var file = this.files[0];\n\n if (file.size &gt; 1024) {\n alert('max upload size is 1k');\n }\n\n // Also see .name, .type\n});\n</code></pre>\n\n<p>Now the <code>$.ajax()</code> submit with the button's click:</p>\n\n<pre><code>$(':button').on('click', function () {\n $.ajax({\n // Your server script to process the upload\n url: 'upload.php',\n type: 'POST',\n\n // Form data\n data: new FormData($('form')[0]),\n\n // Tell jQuery not to process data or worry about content-type\n // You *must* include these options!\n cache: false,\n contentType: false,\n processData: false,\n\n // Custom XMLHttpRequest\n xhr: function () {\n var myXhr = $.ajaxSettings.xhr();\n if (myXhr.upload) {\n // For handling the progress of the upload\n myXhr.upload.addEventListener('progress', function (e) {\n if (e.lengthComputable) {\n $('progress').attr({\n value: e.loaded,\n max: e.total,\n });\n }\n }, false);\n }\n return myXhr;\n }\n });\n});\n</code></pre>\n\n<p>As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with <a href=\"http://en.wikipedia.org/wiki/Google_Chrome\" rel=\"noreferrer\">Google Chrome</a> as some of the HTML5 components of the examples aren't available in every browser.</p>\n" }, { "answer_id": 14520473, "author": "Techie", "author_id": 1263783, "author_profile": "https://Stackoverflow.com/users/1263783", "pm_score": 6, "selected": false, "text": "<p>I have been using the below script to upload images which happens to work fine.</p>\n\n<h1>HTML</h1>\n\n<pre><code>&lt;input id=\"file\" type=\"file\" name=\"file\"/&gt;\n&lt;div id=\"response\"&gt;&lt;/div&gt;\n</code></pre>\n\n<h1>JavaScript</h1>\n\n<pre><code>jQuery('document').ready(function(){\n var input = document.getElementById(\"file\");\n var formdata = false;\n if (window.FormData) {\n formdata = new FormData();\n }\n input.addEventListener(\"change\", function (evt) {\n var i = 0, len = this.files.length, img, reader, file;\n\n for ( ; i &lt; len; i++ ) {\n file = this.files[i];\n\n if (!!file.type.match(/image.*/)) {\n if ( window.FileReader ) {\n reader = new FileReader();\n reader.onloadend = function (e) {\n //showUploadedItem(e.target.result, file.fileName);\n };\n reader.readAsDataURL(file);\n }\n\n if (formdata) {\n formdata.append(\"image\", file);\n formdata.append(\"extra\",'extra-data');\n }\n\n if (formdata) {\n jQuery('div#response').html('&lt;br /&gt;&lt;img src=\"ajax-loader.gif\"/&gt;');\n\n jQuery.ajax({\n url: \"upload.php\",\n type: \"POST\",\n data: formdata,\n processData: false,\n contentType: false,\n success: function (res) {\n jQuery('div#response').html(\"Successfully uploaded\");\n }\n });\n }\n }\n else\n {\n alert('Not a vaild image!');\n }\n }\n\n }, false);\n});\n</code></pre>\n\n<h1>Explanation</h1>\n\n<p>I use response <code>div</code> to show the uploading animation and response after upload is done.</p>\n\n<p>Best part is you can send extra data such as ids &amp; etc with the file when you use this script. I have mention it <code>extra-data</code> as in the script.</p>\n\n<p>At the PHP level this will work as normal file upload. extra-data can be retrieved as <code>$_POST</code> data.</p>\n\n<p>Here you are not using a plugin and stuff. You can change the code as you want. You are not blindly coding here. This is the core functionality of any jQuery file upload. Actually Javascript.</p>\n" }, { "answer_id": 14919756, "author": "mpen", "author_id": 65387, "author_profile": "https://Stackoverflow.com/users/65387", "pm_score": 6, "selected": false, "text": "<p>You can do it in vanilla JavaScript pretty easily. Here's a snippet from my current project:</p>\n\n<pre><code>var xhr = new XMLHttpRequest();\nxhr.upload.onprogress = function(e) {\n var percent = (e.position/ e.totalSize);\n // Render a pretty progress bar\n};\nxhr.onreadystatechange = function(e) {\n if(this.readyState === 4) {\n // Handle file upload complete\n }\n};\nxhr.open('POST', '/upload', true);\nxhr.setRequestHeader('X-FileName',file.name); // Pass the filename along\nxhr.send(file);\n</code></pre>\n" }, { "answer_id": 17131994, "author": "farnoush resa", "author_id": 2044399, "author_profile": "https://Stackoverflow.com/users/2044399", "pm_score": 5, "selected": false, "text": "<p>jQuery <a href=\"http://www.uploadify.com/download/\">Uploadify</a> is another good plugin which I have used before to upload files. The JavaScript code is as simple as the following: code. However, the new version does not work in Internet&nbsp;Explorer.</p>\n\n<pre><code>$('#file_upload').uploadify({\n 'swf': '/public/js/uploadify.swf',\n 'uploader': '/Upload.ashx?formGuid=' + $('#formGuid').val(),\n 'cancelImg': '/public/images/uploadify-cancel.png',\n 'multi': true,\n 'onQueueComplete': function (queueData) {\n // ...\n },\n 'onUploadStart': function (file) {\n // ...\n }\n});\n</code></pre>\n\n<p>I have done a lot of searching and I have come to another solution for uploading files without any plugin and only with ajax. The solution is as below:</p>\n\n<pre><code>$(document).ready(function () {\n $('#btn_Upload').live('click', AjaxFileUpload);\n});\n\nfunction AjaxFileUpload() {\n var fileInput = document.getElementById(\"#Uploader\");\n var file = fileInput.files[0];\n var fd = new FormData();\n fd.append(\"files\", file);\n var xhr = new XMLHttpRequest();\n xhr.open(\"POST\", 'Uploader.ashx');\n xhr.onreadystatechange = function () {\n if (xhr.readyState == 4) {\n alert('success');\n }\n else if (uploadResult == 'success')\n alert('error');\n };\n xhr.send(fd);\n}\n</code></pre>\n" }, { "answer_id": 17310042, "author": "user1091949", "author_id": 1091949, "author_profile": "https://Stackoverflow.com/users/1091949", "pm_score": 5, "selected": false, "text": "<p>Simple Ajax Uploader is another option:</p>\n\n<p><a href=\"https://github.com/LPology/Simple-Ajax-Uploader\" rel=\"noreferrer\">https://github.com/LPology/Simple-Ajax-Uploader</a></p>\n\n<ul>\n<li>Cross-browser -- works in IE7+, Firefox, Chrome, Safari, Opera</li>\n<li>Supports multiple, concurrent uploads -- even in non-HTML5 browsers</li>\n<li>No flash or external CSS -- just one 5Kb Javascript file</li>\n<li>Optional, built-in support for fully cross-browser progress bars (using PHP's APC extension)</li>\n<li>Flexible and highly customizable -- use any element as upload button, style your own progress indicators</li>\n<li>No forms required, just provide an element that will serve as upload button</li>\n<li>MIT license -- free to use in commercial project</li>\n</ul>\n\n<p>Example usage:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var uploader = new ss.SimpleUpload({\n button: $('#uploadBtn'), // upload button\n url: '/uploadhandler', // URL of server-side upload handler\n name: 'userfile', // parameter name of the uploaded file\n onSubmit: function() {\n this.setProgressBar( $('#progressBar') ); // designate elem as our progress bar\n },\n onComplete: function(file, response) {\n // do whatever after upload is finished\n }\n});\n</code></pre>\n" }, { "answer_id": 23606275, "author": "Amit", "author_id": 2396721, "author_profile": "https://Stackoverflow.com/users/2396721", "pm_score": 4, "selected": false, "text": "<p>You can use</p>\n\n<pre><code>$(function() {\n $(\"#file_upload_1\").uploadify({\n height : 30,\n swf : '/uploadify/uploadify.swf',\n uploader : '/uploadify/uploadify.php',\n width : 120\n });\n});\n</code></pre>\n\n<p><a href=\"http://www.uploadify.com/demos/\" rel=\"noreferrer\">Demo</a></p>\n" }, { "answer_id": 24361311, "author": "ashish", "author_id": 1321613, "author_profile": "https://Stackoverflow.com/users/1321613", "pm_score": 4, "selected": false, "text": "<p>To upload file asynchronously with Jquery use below steps:</p>\n<p><strong>step 1</strong> In your project open Nuget manager and add package (jquery fileupload(only you need to write it in search box it will come up and install it.))\nURL: <a href=\"https://github.com/blueimp/jQuery-File-Upload\" rel=\"noreferrer\">https://github.com/blueimp/jQuery-File-Upload</a></p>\n<p><strong>step 2</strong> Add below scripts in the HTML files, which are already added to the project by running above package:</p>\n<blockquote>\n<p>jquery.ui.widget.js</p>\n<p>jquery.iframe-transport.js</p>\n<p>jquery.fileupload.js</p>\n</blockquote>\n<p><strong>step 3</strong> Write file upload control as per below code:</p>\n<pre><code>&lt;input id=&quot;upload&quot; name=&quot;upload&quot; type=&quot;file&quot; /&gt;\n</code></pre>\n<p><strong>step 4</strong> write a js method as uploadFile as below:</p>\n<pre><code> function uploadFile(element) {\n \n $(element).fileupload({\n \n dataType: 'json',\n url: '../DocumentUpload/upload',\n autoUpload: true,\n add: function (e, data) { \n // write code for implementing, while selecting a file. \n // data represents the file data. \n //below code triggers the action in mvc controller\n data.formData =\n {\n files: data.files[0]\n };\n data.submit();\n },\n done: function (e, data) { \n // after file uploaded\n },\n progress: function (e, data) {\n \n // progress\n },\n fail: function (e, data) {\n \n //fail operation\n },\n stop: function () {\n \n code for cancel operation\n }\n });\n \n };\n</code></pre>\n<p><strong>step 5</strong> In ready function call element file upload to initiate the process as per below:</p>\n<pre><code>$(document).ready(function()\n{\n uploadFile($('#upload'));\n\n});\n</code></pre>\n<p><strong>step 6</strong> Write MVC controller and Action as per below:</p>\n<pre><code>public class DocumentUploadController : Controller\n { \n \n [System.Web.Mvc.HttpPost]\n public JsonResult upload(ICollection&lt;HttpPostedFileBase&gt; files)\n {\n bool result = false;\n\n if (files != null || files.Count &gt; 0)\n {\n try\n {\n foreach (HttpPostedFileBase file in files)\n {\n if (file.ContentLength == 0)\n throw new Exception(&quot;Zero length file!&quot;); \n else \n //code for saving a file\n\n }\n }\n catch (Exception)\n {\n result = false;\n }\n }\n\n\n return new JsonResult()\n {\n Data=result\n };\n\n\n }\n\n }\n</code></pre>\n" }, { "answer_id": 24373219, "author": "tnt-rox", "author_id": 913620, "author_profile": "https://Stackoverflow.com/users/913620", "pm_score": 3, "selected": false, "text": "<p>Convert file to base64 using |HTML5's <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/FileReader#readAsDataURL%28%29\">readAsDataURL()</a> or <a href=\"http://scotch.io/quick-tips/js/how-to-encode-and-decode-strings-with-base64-in-javascript\">some base64 encoder</a>. \n<a href=\"http://jsfiddle.net/eliseosoto/JHQnk/\">Fiddle here</a></p>\n\n<pre><code>var reader = new FileReader();\n\n reader.onload = function(readerEvt) {\n var binaryString = readerEvt.target.result;\n document.getElementById(\"base64textarea\").value = btoa(binaryString);\n };\n\n reader.readAsBinaryString(file);\n</code></pre>\n\n<p>Then to retrieve:</p>\n\n<pre><code>window.open(\"data:application/octet-stream;base64,\" + base64);\n</code></pre>\n" }, { "answer_id": 24422523, "author": "ArtisticPhoenix", "author_id": 3684882, "author_profile": "https://Stackoverflow.com/users/3684882", "pm_score": 6, "selected": false, "text": "<p>The simplest and most robust way I have done this in the past, is to simply target a hidden iFrame tag with your form - then it will submit within the iframe without reloading the page.</p>\n\n<p>That is if you don't want to use a plugin, JavaScript or any other forms of \"magic\" other than HTML. Of course you can combine this with JavaScript or what have you...</p>\n\n<pre><code>&lt;form target=\"iframe\" action=\"\" method=\"post\" enctype=\"multipart/form-data\"&gt;\n &lt;input name=\"file\" type=\"file\" /&gt;\n &lt;input type=\"button\" value=\"Upload\" /&gt;\n&lt;/form&gt;\n\n&lt;iframe name=\"iframe\" id=\"iframe\" style=\"display:none\" &gt;&lt;/iframe&gt;\n</code></pre>\n\n<p>You can also read the contents of the iframe <code>onLoad</code> for server errors or success responses and then output that to user.</p>\n\n<p><strong>Chrome, iFrames, and onLoad</strong> </p>\n\n<p><em>-note- you only need to keep reading if you are interested in how to setup a UI blocker when doing uploading/downloading</em></p>\n\n<p>Currently Chrome doesn't trigger the onLoad event for the iframe when it's used to transfer files. Firefox, IE, and Edge all fire the onload event for file transfers.</p>\n\n<p>The only solution that I found works for Chrome was to use a cookie. </p>\n\n<p>To do that basically when the upload/download is started:</p>\n\n<ul>\n<li>[Client Side] Start an interval to look for the existence of a cookie</li>\n<li>[Server Side] Do whatever you need to with the file data</li>\n<li>[Server Side] Set cookie for client side interval</li>\n<li>[Client Side] Interval sees the cookie and uses it like the onLoad event. For example you can start a UI blocker and then onLoad ( or when cookie is made ) you remove the UI blocker.</li>\n</ul>\n\n<p>Using a cookie for this is ugly but it works. </p>\n\n<p>I made a jQuery plugin to handle this issue for Chrome when downloading, you can find here</p>\n\n<p><a href=\"https://github.com/ArtisticPhoenix/jQuery-Plugins/blob/master/iDownloader.js\" rel=\"noreferrer\">https://github.com/ArtisticPhoenix/jQuery-Plugins/blob/master/iDownloader.js</a></p>\n\n<p>The same basic principal applies to uploading, as well.</p>\n\n<p>To use the downloader ( include the JS, obviously )</p>\n\n<pre><code> $('body').iDownloader({\n \"onComplete\" : function(){\n $('#uiBlocker').css('display', 'none'); //hide ui blocker on complete\n }\n });\n\n $('somebuttion').click( function(){\n $('#uiBlocker').css('display', 'block'); //block the UI\n $('body').iDownloader('download', 'htttp://example.com/location/of/download');\n });\n</code></pre>\n\n<p>And on the server side, just before transferring the file data, create the cookie</p>\n\n<pre><code> setcookie('iDownloader', true, time() + 30, \"/\");\n</code></pre>\n\n<p>The plugin will see the cookie, and then trigger the <code>onComplete</code> callback.</p>\n" }, { "answer_id": 25195443, "author": "Zayn Ali", "author_id": 2610720, "author_profile": "https://Stackoverflow.com/users/2610720", "pm_score": 6, "selected": false, "text": "<p>You can upload simply with jQuery <code>.ajax()</code>.</p>\n\n<p>HTML:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;form id=\"upload-form\"&gt;\n &lt;div&gt;\n &lt;label for=\"file\"&gt;File:&lt;/label&gt;\n &lt;input type=\"file\" id=\"file\" name=\"file\" /&gt;\n &lt;progress class=\"progress\" value=\"0\" max=\"100\"&gt;&lt;/progress&gt;\n &lt;/div&gt;\n &lt;hr /&gt;\n &lt;input type=\"submit\" value=\"Submit\" /&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>CSS</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.progress { display: none; }\n</code></pre>\n\n<p>Javascript:</p>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>$(document).ready(function(ev) {\n $(\"#upload-form\").on('submit', (function(ev) {\n ev.preventDefault();\n $.ajax({\n xhr: function() {\n var progress = $('.progress'),\n xhr = $.ajaxSettings.xhr();\n\n progress.show();\n\n xhr.upload.onprogress = function(ev) {\n if (ev.lengthComputable) {\n var percentComplete = parseInt((ev.loaded / ev.total) * 100);\n progress.val(percentComplete);\n if (percentComplete === 100) {\n progress.hide().val(0);\n }\n }\n };\n\n return xhr;\n },\n url: 'upload.php',\n type: 'POST',\n data: new FormData(this),\n contentType: false,\n cache: false,\n processData: false,\n success: function(data, status, xhr) {\n // ...\n },\n error: function(xhr, status, error) {\n // ...\n }\n });\n }));\n});\n</code></pre>\n" }, { "answer_id": 25487973, "author": "404", "author_id": 3614389, "author_profile": "https://Stackoverflow.com/users/3614389", "pm_score": 7, "selected": false, "text": "<p>Wrapping up for future readers.</p>\n\n<h1>Asynchronous File Upload</h1>\n\n<h2>With HTML5</h2>\n\n<p>You can upload files <strong>with jQuery</strong> using the <code>$.ajax()</code> method if <a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects\" rel=\"noreferrer\">FormData</a> and the <a href=\"https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications\" rel=\"noreferrer\">File API</a> are supported (both HTML5 features). </p>\n\n<p>You can also send files <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files\" rel=\"noreferrer\">without FormData</a> but either way the File API must be present to process files in such a way that they can be sent with <em>XMLHttpRequest</em> (Ajax).</p>\n\n<pre><code>$.ajax({\n url: 'file/destination.html', \n type: 'POST',\n data: new FormData($('#formWithFiles')[0]), // The form with the file inputs.\n processData: false,\n contentType: false // Using FormData, no need to process data.\n}).done(function(){\n console.log(\"Success: Files sent!\");\n}).fail(function(){\n console.log(\"An error occurred, the files couldn't be sent!\");\n});\n</code></pre>\n\n<p>For a quick, pure JavaScript (<strong>no jQuery</strong>) example see \"<a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects#Sending_files_using_a_FormData_object\" rel=\"noreferrer\">Sending files using a FormData object</a>\".</p>\n\n<h2>Fallback</h2>\n\n<p>When HTML5 isn't supported (no <em>File API</em>) the only other pure JavaScript solution (no <em>Flash</em> or any other browser plugin) is the <strong>hidden iframe</strong> technique, which allows to emulate an asynchronous request without using the <em>XMLHttpRequest</em> object.</p>\n\n<p>It consists of setting an iframe as the target of the form with the file inputs. When the user submits a request is made and the files are uploaded but the response is displayed inside the iframe instead of re-rendering the main page. Hiding the iframe makes the whole process transparent to the user and emulates an asynchronous request.</p>\n\n<p>If done properly it should work virtually on any browser, but it has some caveats as how to obtain the response from the iframe. </p>\n\n<p>In this case you may prefer to use a wrapper plugin like <a href=\"//github.com/matiasgagliano/bifrost\" rel=\"noreferrer\">Bifröst</a> which uses the <em>iframe technique</em> but also provides a <a href=\"//api.jquery.com/jQuery.ajaxTransport\" rel=\"noreferrer\">jQuery Ajax transport</a> allowing to <strong>send files</strong> with just the <code>$.ajax()</code> method like this:</p>\n\n<pre><code>$.ajax({\n url: 'file/destination.html', \n type: 'POST',\n // Set the transport to use (iframe means to use Bifröst)\n // and the expected data type (json in this case).\n dataType: 'iframe json', \n fileInputs: $('input[type=\"file\"]'), // The file inputs containing the files to send.\n data: { msg: 'Some extra data you might need.'}\n}).done(function(){\n console.log(\"Success: Files sent!\");\n}).fail(function(){\n console.log(\"An error occurred, the files couldn't be sent!\");\n});\n</code></pre>\n\n<h2>Plugins</h2>\n\n<p><a href=\"//github.com/matiasgagliano/bifrost\" rel=\"noreferrer\">Bifröst</a> is just a small wrapper that adds fallback support to jQuery's ajax method, but many of the aforementioned plugins like <a href=\"//malsup.com/jquery/form/\" rel=\"noreferrer\">jQuery Form Plugin</a> or <a href=\"//github.com/blueimp/jQuery-File-Upload\" rel=\"noreferrer\">jQuery File Upload</a> include the whole stack from HTML5 to different fallbacks and some useful features to ease out the process. Depending on your needs and requirements you might want to consider a bare implementation or either of this plugins.</p>\n" }, { "answer_id": 31300228, "author": "Allende", "author_id": 462889, "author_profile": "https://Stackoverflow.com/users/462889", "pm_score": 3, "selected": false, "text": "<p>Look for <em>Handling the upload process for a file, asynchronously</em> in here:\n<a href=\"https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications</a></p>\n\n<p>Sample from the link</p>\n\n<pre><code>&lt;?php\nif (isset($_FILES['myFile'])) {\n // Example:\n move_uploaded_file($_FILES['myFile']['tmp_name'], \"uploads/\" . $_FILES['myFile']['name']);\n exit;\n}\n?&gt;&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;title&gt;dnd binary upload&lt;/title&gt;\n &lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"&gt;\n &lt;script type=\"text/javascript\"&gt;\n function sendFile(file) {\n var uri = \"/index.php\";\n var xhr = new XMLHttpRequest();\n var fd = new FormData();\n\n xhr.open(\"POST\", uri, true);\n xhr.onreadystatechange = function() {\n if (xhr.readyState == 4 &amp;&amp; xhr.status == 200) {\n // Handle response.\n alert(xhr.responseText); // handle response.\n }\n };\n fd.append('myFile', file);\n // Initiate a multipart/form-data upload\n xhr.send(fd);\n }\n\n window.onload = function() {\n var dropzone = document.getElementById(\"dropzone\");\n dropzone.ondragover = dropzone.ondragenter = function(event) {\n event.stopPropagation();\n event.preventDefault();\n }\n\n dropzone.ondrop = function(event) {\n event.stopPropagation();\n event.preventDefault();\n\n var filesArray = event.dataTransfer.files;\n for (var i=0; i&lt;filesArray.length; i++) {\n sendFile(filesArray[i]);\n }\n }\n }\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;div&gt;\n &lt;div id=\"dropzone\" style=\"margin:30px; width:500px; height:300px; border:1px dotted grey;\"&gt;Drag &amp; drop your file here...&lt;/div&gt;\n &lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 31678000, "author": "Vivek Aasaithambi", "author_id": 2700880, "author_profile": "https://Stackoverflow.com/users/2700880", "pm_score": 4, "selected": false, "text": "<pre><code>var formData=new FormData();\nformData.append(\"fieldname\",\"value\");\nformData.append(\"image\",$('[name=\"filename\"]')[0].files[0]);\n\n$.ajax({\n url:\"page.php\",\n data:formData,\n type: 'POST',\n dataType:\"JSON\",\n cache: false,\n contentType: false,\n processData: false,\n success:function(data){ }\n});\n</code></pre>\n\n<p>You can use form data to post all your values including images.</p>\n" }, { "answer_id": 33508768, "author": "Erick Lanford Xenes", "author_id": 5190625, "author_profile": "https://Stackoverflow.com/users/5190625", "pm_score": 4, "selected": false, "text": "<p>This is my solution.</p>\n\n<pre><code>&lt;form enctype=\"multipart/form-data\"&gt; \n\n &lt;div class=\"form-group\"&gt;\n &lt;label class=\"control-label col-md-2\" for=\"apta_Description\"&gt;Description&lt;/label&gt;\n &lt;div class=\"col-md-10\"&gt;\n &lt;input class=\"form-control text-box single-line\" id=\"apta_Description\" name=\"apta_Description\" type=\"text\" value=\"\"&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n &lt;input name=\"file\" type=\"file\" /&gt;\n &lt;input type=\"button\" value=\"Upload\" /&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>and the js</p>\n\n<pre><code>&lt;script&gt;\n\n $(':button').click(function () {\n var formData = new FormData($('form')[0]);\n $.ajax({\n url: '@Url.Action(\"Save\", \"Home\")', \n type: 'POST', \n success: completeHandler,\n data: formData,\n cache: false,\n contentType: false,\n processData: false\n });\n }); \n\n function completeHandler() {\n alert(\":)\");\n } \n&lt;/script&gt;\n</code></pre>\n\n<p>Controller</p>\n\n<pre><code>[HttpPost]\npublic ActionResult Save(string apta_Description, HttpPostedFileBase file)\n{\n [...]\n}\n</code></pre>\n" }, { "answer_id": 36314992, "author": "Siddhartha Chowdhury", "author_id": 4475433, "author_profile": "https://Stackoverflow.com/users/4475433", "pm_score": 5, "selected": false, "text": "<p>Here's just another solution of how to upload file (<strong>without any plugin</strong>) </p>\n\n<p>Using simple <strong>Javascripts</strong> and <strong>AJAX</strong> (with progress-bar)</p>\n\n<p><strong>HTML part</strong></p>\n\n<pre><code>&lt;form id=\"upload_form\" enctype=\"multipart/form-data\" method=\"post\"&gt;\n &lt;input type=\"file\" name=\"file1\" id=\"file1\"&gt;&lt;br&gt;\n &lt;input type=\"button\" value=\"Upload File\" onclick=\"uploadFile()\"&gt;\n &lt;progress id=\"progressBar\" value=\"0\" max=\"100\" style=\"width:300px;\"&gt;&lt;/progress&gt;\n &lt;h3 id=\"status\"&gt;&lt;/h3&gt;\n &lt;p id=\"loaded_n_total\"&gt;&lt;/p&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p><strong>JS part</strong></p>\n\n<pre><code>function _(el){\n return document.getElementById(el);\n}\nfunction uploadFile(){\n var file = _(\"file1\").files[0];\n // alert(file.name+\" | \"+file.size+\" | \"+file.type);\n var formdata = new FormData();\n formdata.append(\"file1\", file);\n var ajax = new XMLHttpRequest();\n ajax.upload.addEventListener(\"progress\", progressHandler, false);\n ajax.addEventListener(\"load\", completeHandler, false);\n ajax.addEventListener(\"error\", errorHandler, false);\n ajax.addEventListener(\"abort\", abortHandler, false);\n ajax.open(\"POST\", \"file_upload_parser.php\");\n ajax.send(formdata);\n}\nfunction progressHandler(event){\n _(\"loaded_n_total\").innerHTML = \"Uploaded \"+event.loaded+\" bytes of \"+event.total;\n var percent = (event.loaded / event.total) * 100;\n _(\"progressBar\").value = Math.round(percent);\n _(\"status\").innerHTML = Math.round(percent)+\"% uploaded... please wait\";\n}\nfunction completeHandler(event){\n _(\"status\").innerHTML = event.target.responseText;\n _(\"progressBar\").value = 0;\n}\nfunction errorHandler(event){\n _(\"status\").innerHTML = \"Upload Failed\";\n}\nfunction abortHandler(event){\n _(\"status\").innerHTML = \"Upload Aborted\";\n}\n</code></pre>\n\n<p><strong>PHP part</strong></p>\n\n<pre><code>&lt;?php\n$fileName = $_FILES[\"file1\"][\"name\"]; // The file name\n$fileTmpLoc = $_FILES[\"file1\"][\"tmp_name\"]; // File in the PHP tmp folder\n$fileType = $_FILES[\"file1\"][\"type\"]; // The type of file it is\n$fileSize = $_FILES[\"file1\"][\"size\"]; // File size in bytes\n$fileErrorMsg = $_FILES[\"file1\"][\"error\"]; // 0 for false... and 1 for true\nif (!$fileTmpLoc) { // if file not chosen\n echo \"ERROR: Please browse for a file before clicking the upload button.\";\n exit();\n}\nif(move_uploaded_file($fileTmpLoc, \"test_uploads/$fileName\")){ // assuming the directory name 'test_uploads'\n echo \"$fileName upload is complete\";\n} else {\n echo \"move_uploaded_file function failed\";\n}\n?&gt;\n</code></pre>\n\n<p><a href=\"https://github.com/SiddharthaChowdhury/Async-File-Upload-using-PHP-Javascript-AJAX\" rel=\"noreferrer\"><strong>Here's the EXAMPLE application</strong></a></p>\n" }, { "answer_id": 38450087, "author": "Daniel Nyamasyo", "author_id": 6579192, "author_profile": "https://Stackoverflow.com/users/6579192", "pm_score": 4, "selected": false, "text": "<p>You can see a solved solution with a working demo <a href=\"http://whats-online.info/science-and-tutorials/30/select-preview-rename-and-upload-image-using-jquery-Ajax/\" rel=\"noreferrer\"><strong>here</strong></a> that allows you to preview and submit form files to the server. For your case, you need to use <a href=\"http://en.wikipedia.org/wiki/Ajax_%28programming%29\" rel=\"noreferrer\">Ajax</a> to facilitate the file upload to the server:</p>\n\n<pre><code>&lt;from action=\"\" id=\"formContent\" method=\"post\" enctype=\"multipart/form-data\"&gt;\n &lt;span&gt;File&lt;/span&gt;\n &lt;input type=\"file\" id=\"file\" name=\"file\" size=\"10\"/&gt;\n &lt;input id=\"uploadbutton\" type=\"button\" value=\"Upload\"/&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>The data being submitted is a formdata. On your jQuery, use a form submit function instead of a button click to submit the form file as shown below.</p>\n\n<pre><code>$(document).ready(function () {\n $(\"#formContent\").submit(function(e){\n\n e.preventDefault();\n var formdata = new FormData(this);\n\n $.ajax({\n url: \"ajax_upload_image.php\",\n type: \"POST\",\n data: formdata,\n mimeTypes:\"multipart/form-data\",\n contentType: false,\n cache: false,\n processData: false,\n success: function(){\n\n alert(\"successfully submitted\");\n\n });\n });\n});\n</code></pre>\n\n<p><a href=\"http://whats-online.info/science-and-tutorials/30/select-preview-rename-and-upload-image-using-jquery-Ajax/\" rel=\"noreferrer\">View more details</a></p>\n" }, { "answer_id": 40037182, "author": "MEAbid", "author_id": 5906922, "author_profile": "https://Stackoverflow.com/users/5906922", "pm_score": 4, "selected": false, "text": "<p>Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, <a href=\"http://jquery.malsup.com/form/\" rel=\"noreferrer\">http://jquery.malsup.com/form/</a>.</p>\n<h3>Example</h3>\n<pre><code>var $bar = $('.ProgressBar');\n$('.Form').ajaxForm({\n dataType: 'json',\n\n beforeSend: function(xhr) {\n var percentVal = '0%';\n $bar.width(percentVal);\n },\n\n uploadProgress: function(event, position, total, percentComplete) {\n var percentVal = percentComplete + '%';\n $bar.width(percentVal)\n },\n\n success: function(response) {\n // Response\n }\n});\n</code></pre>\n<p><strong>I hope it would be helpful</strong></p>\n" }, { "answer_id": 48908672, "author": "lat94", "author_id": 7004017, "author_profile": "https://Stackoverflow.com/users/7004017", "pm_score": 2, "selected": false, "text": "<p>It is an old question, but still has no answer correct answer, so:</p>\n\n<p>Have you tried <a href=\"https://github.com/blueimp/jQuery-File-Upload/wiki/Submit-files-asynchronously\" rel=\"nofollow noreferrer\">jQuery-File-Upload</a>?</p>\n\n<p>Here is an example from the link above that might solve your problem:</p>\n\n<pre><code>$('#fileupload').fileupload({\n add: function (e, data) {\n var that = this;\n $.getJSON('/example/url', function (result) {\n data.formData = result; // e.g. {id: 123}\n $.blueimp.fileupload.prototype\n .options.add.call(that, e, data);\n });\n } \n});\n</code></pre>\n" }, { "answer_id": 49235322, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 3, "selected": false, "text": "<p>Using <strong>HTML5</strong> and <strong>JavaScript</strong>, uploading async is quite easy, I create the uploading logic along with your html, this is not fully working as it needs the api, but demonstrate how it works, if you have the endpoint called <code>/upload</code> from root of your website, this code should work for you:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const asyncFileUpload = () =&gt; {\n const fileInput = document.getElementById(\"file\");\n const file = fileInput.files[0];\n const uri = \"/upload\";\n const xhr = new XMLHttpRequest();\n xhr.upload.onprogress = e =&gt; {\n const percentage = e.loaded / e.total;\n console.log(percentage);\n };\n xhr.onreadystatechange = e =&gt; {\n if (xhr.readyState === 4 &amp;&amp; xhr.status === 200) {\n console.log(\"file uploaded\");\n }\n };\n xhr.open(\"POST\", uri, true);\n xhr.setRequestHeader(\"X-FileName\", file.name);\n xhr.send(file);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;form&gt;\n &lt;span&gt;File&lt;/span&gt;\n &lt;input type=\"file\" id=\"file\" name=\"file\" size=\"10\" /&gt;\n &lt;input onclick=\"asyncFileUpload()\" id=\"upload\" type=\"button\" value=\"Upload\" /&gt;\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Also some further information about XMLHttpReques:</p>\n<blockquote>\n<p><strong>The XMLHttpRequest Object</strong></p>\n<p>All modern browsers support the XMLHttpRequest object.\nThe XMLHttpRequest object can be used to exchange data with a web\nserver behind the scenes. This means that it is possible to update\nparts of a web page, without reloading the whole page.</p>\n</blockquote>\n<br>\n<blockquote>\n<p><strong>Create an XMLHttpRequest Object</strong></p>\n<p>All modern browsers (Chrome, Firefox,\nIE7+, Edge, Safari, Opera) have a built-in XMLHttpRequest object.</p>\n<p>Syntax for creating an XMLHttpRequest object:</p>\n<p>variable = new XMLHttpRequest();</p>\n</blockquote>\n<br> \n<blockquote>\n<p><strong>Access Across Domains</strong></p>\n<p>For security reasons, modern browsers do not\nallow access across domains.</p>\n<p>This means that both the web page and the XML file it tries to load,\nmust be located on the same server.</p>\n<p>The examples on W3Schools all open XML files located on the W3Schools\ndomain.</p>\n<p>If you want to use the example above on one of your own web pages, the\nXML files you load must be located on your own server.</p>\n</blockquote>\n<p>For more details, you can continue reading <a href=\"https://www.w3schools.com/js/js_ajax_http.asp\" rel=\"nofollow noreferrer\">here</a>...</p>\n" }, { "answer_id": 50446598, "author": "BlackBeard", "author_id": 5349542, "author_profile": "https://Stackoverflow.com/users/5349542", "pm_score": 3, "selected": false, "text": "<p>You can use <strong>newer</strong> <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch\" rel=\"noreferrer\">Fetch API</a> by JavaScript. Like this: </p>\n\n<pre><code>function uploadButtonCLicked(){\n var input = document.querySelector('input[type=\"file\"]')\n\n fetch('/url', {\n method: 'POST',\n body: input.files[0]\n }).then(res =&gt; res.json()) // you can do something with response\n .catch(error =&gt; console.error('Error:', error))\n .then(response =&gt; console.log('Success:', response));\n} \n</code></pre>\n\n<p><strong>Advantage:</strong> Fetch API is <strong>natively supported</strong> by all modern browsers, so you don't have to import anything. Also, note that fetch() returns a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise\" rel=\"noreferrer\">Promise</a> which is then handled by using <code>.then(..code to handle response..)</code> asynchronously. </p>\n" }, { "answer_id": 51894789, "author": "Alister", "author_id": 1432509, "author_profile": "https://Stackoverflow.com/users/1432509", "pm_score": 4, "selected": false, "text": "<p>A modern approach <strong>without Jquery</strong> is to use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/FileList\" rel=\"noreferrer\">FileList</a> object you get back from <code>&lt;input type=\"file\"&gt;</code> when user selects a file(s) and then use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\" rel=\"noreferrer\">Fetch</a> to post the FileList wrapped around a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/FormData\" rel=\"noreferrer\">FormData</a> object.</p>\n\n<pre><code>// The input DOM element // &lt;input type=\"file\"&gt;\nconst inputElement = document.querySelector('input[type=file]');\n\n// Listen for a file submit from user\ninputElement.addEventListener('change', () =&gt; {\n const data = new FormData();\n data.append('file', inputElement.files[0]);\n data.append('imageName', 'flower');\n\n // You can then post it to your server.\n // Fetch can accept an object of type FormData on its body\n fetch('/uploadImage', {\n method: 'POST',\n body: data\n });\n});\n</code></pre>\n" }, { "answer_id": 52085124, "author": "Joe Clinton", "author_id": 10276599, "author_profile": "https://Stackoverflow.com/users/10276599", "pm_score": 2, "selected": false, "text": "<p>You can do the Asynchronous Multiple File uploads using JavaScript or jQuery and that to without using any plugin. You can also show the real time progress of file upload in the progress control. I have come across 2 nice links -</p>\n\n<ol>\n<li><a href=\"http://www.yogihosting.com/multi-file-upload-with-progress-bar-in-asp-net/\" rel=\"noreferrer\">ASP.NET Web Forms based Mulitple File Upload Feature with Progress Bar</a></li>\n<li><a href=\"http://www.yogihosting.com/jquery-file-upload/\" rel=\"noreferrer\">ASP.NET MVC based Multiple File Upload made in jQuery</a></li>\n</ol>\n\n<p>The server side language is C# but you can do some modification for making it work with other language like PHP.</p>\n\n<p><strong>File Upload ASP.NET Core MVC:</strong></p>\n\n<p>In the View create file upload control in html:</p>\n\n<pre><code>&lt;form method=\"post\" asp-action=\"Add\" enctype=\"multipart/form-data\"&gt;\n &lt;input type=\"file\" multiple name=\"mediaUpload\" /&gt;\n &lt;button type=\"submit\"&gt;Submit&lt;/button&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Now create action method in your controller:</p>\n\n<pre><code>[HttpPost]\npublic async Task&lt;IActionResult&gt; Add(IFormFile[] mediaUpload)\n{\n //looping through all the files\n foreach (IFormFile file in mediaUpload)\n {\n //saving the files\n string path = Path.Combine(hostingEnvironment.WebRootPath, \"some-folder-path\"); \n using (var stream = new FileStream(path, FileMode.Create))\n {\n await file.CopyToAsync(stream);\n }\n }\n}\n</code></pre>\n\n<p>hostingEnvironment variable is of type IHostingEnvironment which can be injected to the controller using dependency injection, like:</p>\n\n<pre><code>private IHostingEnvironment hostingEnvironment;\npublic MediaController(IHostingEnvironment environment)\n{\n hostingEnvironment = environment;\n}\n</code></pre>\n" }, { "answer_id": 52663864, "author": "Supun Kavinda", "author_id": 9059939, "author_profile": "https://Stackoverflow.com/users/9059939", "pm_score": 3, "selected": false, "text": "<p>For PHP, look for <a href=\"https://developer.hyvor.com/php/image-upload-ajax-php-mysql\" rel=\"noreferrer\">https://developer.hyvor.com/php/image-upload-ajax-php-mysql</a></p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n &lt;title&gt;Image Upload with AJAX, PHP and MYSQL&lt;/title&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;form onsubmit=\"submitForm(event);\"&gt;\n &lt;input type=\"file\" name=\"image\" id=\"image-selecter\" accept=\"image/*\"&gt;\n &lt;input type=\"submit\" name=\"submit\" value=\"Upload Image\"&gt;\n&lt;/form&gt;\n&lt;div id=\"uploading-text\" style=\"display:none;\"&gt;Uploading...&lt;/div&gt;\n&lt;img id=\"preview\"&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p><strong>JAVASCRIPT</strong></p>\n\n<pre><code>var previewImage = document.getElementById(\"preview\"), \n uploadingText = document.getElementById(\"uploading-text\");\n\nfunction submitForm(event) {\n // prevent default form submission\n event.preventDefault();\n uploadImage();\n}\n\nfunction uploadImage() {\n var imageSelecter = document.getElementById(\"image-selecter\"),\n file = imageSelecter.files[0];\n if (!file) \n return alert(\"Please select a file\");\n // clear the previous image\n previewImage.removeAttribute(\"src\");\n // show uploading text\n uploadingText.style.display = \"block\";\n // create form data and append the file\n var formData = new FormData();\n formData.append(\"image\", file);\n // do the ajax part\n var ajax = new XMLHttpRequest();\n ajax.onreadystatechange = function() {\n if (this.readyState === 4 &amp;&amp; this.status === 200) {\n var json = JSON.parse(this.responseText);\n if (!json || json.status !== true) \n return uploadError(json.error);\n\n showImage(json.url);\n }\n }\n ajax.open(\"POST\", \"upload.php\", true);\n ajax.send(formData); // send the form data\n}\n</code></pre>\n\n<p><strong>PHP</strong></p>\n\n<pre><code>&lt;?php\n$host = 'localhost';\n$user = 'user';\n$password = 'password';\n$database = 'database';\n$mysqli = new mysqli($host, $user, $password, $database);\n\n\n try {\n if (empty($_FILES['image'])) {\n throw new Exception('Image file is missing');\n }\n $image = $_FILES['image'];\n // check INI error\n if ($image['error'] !== 0) {\n if ($image['error'] === 1) \n throw new Exception('Max upload size exceeded');\n\n throw new Exception('Image uploading error: INI Error');\n }\n // check if the file exists\n if (!file_exists($image['tmp_name']))\n throw new Exception('Image file is missing in the server');\n $maxFileSize = 2 * 10e6; // in bytes\n if ($image['size'] &gt; $maxFileSize)\n throw new Exception('Max size limit exceeded'); \n // check if uploaded file is an image\n $imageData = getimagesize($image['tmp_name']);\n if (!$imageData) \n throw new Exception('Invalid image');\n $mimeType = $imageData['mime'];\n // validate mime type\n $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];\n if (!in_array($mimeType, $allowedMimeTypes)) \n throw new Exception('Only JPEG, PNG and GIFs are allowed');\n\n // nice! it's a valid image\n // get file extension (ex: jpg, png) not (.jpg)\n $fileExtention = strtolower(pathinfo($image['name'] ,PATHINFO_EXTENSION));\n // create random name for your image\n $fileName = round(microtime(true)) . mt_rand() . '.' . $fileExtention; // anyfilename.jpg\n // Create the path starting from DOCUMENT ROOT of your website\n $path = '/examples/image-upload/images/' . $fileName;\n // file path in the computer - where to save it \n $destination = $_SERVER['DOCUMENT_ROOT'] . $path;\n\n if (!move_uploaded_file($image['tmp_name'], $destination))\n throw new Exception('Error in moving the uploaded file');\n\n // create the url\n $protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';\n $domain = $protocol . $_SERVER['SERVER_NAME'];\n $url = $domain . $path;\n $stmt = $mysqli -&gt; prepare('INSERT INTO image_uploads (url) VALUES (?)');\n if (\n $stmt &amp;&amp;\n $stmt -&gt; bind_param('s', $url) &amp;&amp;\n $stmt -&gt; execute()\n ) {\n exit(\n json_encode(\n array(\n 'status' =&gt; true,\n 'url' =&gt; $url\n )\n )\n );\n } else \n throw new Exception('Error in saving into the database');\n\n} catch (Exception $e) {\n exit(json_encode(\n array (\n 'status' =&gt; false,\n 'error' =&gt; $e -&gt; getMessage()\n )\n ));\n}\n</code></pre>\n" }, { "answer_id": 53300507, "author": "Karthik Ravichandran", "author_id": 6212857, "author_profile": "https://Stackoverflow.com/users/6212857", "pm_score": 3, "selected": false, "text": "<p>You can pass additional parameters along with file name on making asynchronous upload using XMLHttpRequest (without flash and iframe dependency). Append the additional parameter value with FormData and send the upload request.</p>\n\n<hr>\n\n<pre><code>var formData = new FormData();\nformData.append('parameter1', 'value1');\nformData.append('parameter2', 'value2'); \nformData.append('file', $('input[type=file]')[0].files[0]);\n\n$.ajax({\n url: 'post back url',\n data: formData,\n// other attributes of AJAX\n});\n</code></pre>\n\n<hr>\n\n<p>Also, Syncfusion JavaScript UI file upload provides solution for this scenario simply using event argument. you can find documentation <a href=\"https://ej2.syncfusion.com/documentation/uploader/how-to/#add-additional-data-on-upload\" rel=\"noreferrer\">here</a> and further details about this control here enter link description <a href=\"https://www.syncfusion.com/javascript-ui-controls/file-upload\" rel=\"noreferrer\">here</a></p>\n" }, { "answer_id": 53881813, "author": "kvz", "author_id": 151666, "author_profile": "https://Stackoverflow.com/users/151666", "pm_score": 2, "selected": false, "text": "<p>You could also consider using something like <a href=\"https://uppy.io\" rel=\"nofollow noreferrer\">https://uppy.io</a>.</p>\n\n<p>It does file uploading without navigating away from the page and offers a few bonuses like drag &amp; drop, resuming uploads in case of browser crashes/flaky networks, and importing from e.g. Instagram.\nIt's open source and does not rely on jQuery/React/Angular/Vue, but can be used with it. Disclaimer: as its creator I'm biased ;)</p>\n" }, { "answer_id": 55573259, "author": "Michael Wang", "author_id": 10567845, "author_profile": "https://Stackoverflow.com/users/10567845", "pm_score": -1, "selected": false, "text": "<p>You can use the following code.</p>\n\n<pre><code>async: false(true)\n</code></pre>\n" }, { "answer_id": 56901361, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 2, "selected": false, "text": "<p>Try</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>async function saveFile() \r\n{\r\n let formData = new FormData(); \r\n formData.append(\"file\", file.files[0]);\r\n await fetch('addFile.do', {method: \"POST\", body: formData}); \r\n alert(\"Data Uploaded: \");\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;span&gt;File&lt;/span&gt;\r\n&lt;input type=\"file\" id=\"file\" name=\"file\" size=\"10\"/&gt;\r\n&lt;input type=\"button\" value=\"Upload\" onclick=\"saveFile()\"/&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The <code>content-type='multipart/form-data'</code> is set by browser automatically, the file name is added automatically too to <code>filename</code> FormData parameter (and can be easy read by server). Here is more developed example with err handling and json adding</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>async function saveFile(inp) \r\n{\r\n let user = { name:'john', age:34 };\r\n let formData = new FormData();\r\n let photo = inp.files[0]; \r\n \r\n formData.append(\"photo\", photo);\r\n formData.append(\"user\", JSON.stringify(user)); \r\n \r\n try {\r\n let r = await fetch('/upload/image', {method: \"POST\", body: formData}); \r\n console.log('HTTP response code:',r.status); \r\n alert('success');\r\n } catch(e) {\r\n console.log('Huston we have problem...:', e);\r\n }\r\n \r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input type=\"file\" onchange=\"saveFile(this)\" &gt;\r\n&lt;br&gt;&lt;br&gt;\r\nBefore selecting the file Open chrome console &gt; network tab to see the request details.\r\n&lt;br&gt;&lt;br&gt;\r\n&lt;small&gt;Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...&lt;/small&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 60454377, "author": "Diego Vinícius", "author_id": 6373505, "author_profile": "https://Stackoverflow.com/users/6373505", "pm_score": 2, "selected": false, "text": "<p>What if using promises which ajax and checking if the file is valid and well saved in your backend, so you can use some animation in front while user is navigating thought your page.</p>\n\n<p>You can even make it paralel upload or stacking with recursive approach</p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
I would like to upload a file asynchronously with jQuery. ```js $(document).ready(function () { $("#uploadbutton").click(function () { var filename = $("#file").val(); $.ajax({ type: "POST", url: "addFile.do", enctype: 'multipart/form-data', data: { file: filename }, success: function () { alert("Data Uploaded: "); } }); }); }); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <span>File</span> <input type="file" id="file" name="file" size="10"/> <input id="uploadbutton" type="button" value="Upload"/> ``` Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?
With [HTML5](http://en.wikipedia.org/wiki/HTML5) you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use [Flash](http://en.wikipedia.org/wiki/Adobe_Flash) nor Iframes or plugins and after some research I came up with the solution. The HTML: ``` <form enctype="multipart/form-data"> <input name="file" type="file" /> <input type="button" value="Upload" /> </form> <progress></progress> ``` First, you can do some validation if you want. For example, in the `.on('change')` event of the file: ``` $(':file').on('change', function () { var file = this.files[0]; if (file.size > 1024) { alert('max upload size is 1k'); } // Also see .name, .type }); ``` Now the `$.ajax()` submit with the button's click: ``` $(':button').on('click', function () { $.ajax({ // Your server script to process the upload url: 'upload.php', type: 'POST', // Form data data: new FormData($('form')[0]), // Tell jQuery not to process data or worry about content-type // You *must* include these options! cache: false, contentType: false, processData: false, // Custom XMLHttpRequest xhr: function () { var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { // For handling the progress of the upload myXhr.upload.addEventListener('progress', function (e) { if (e.lengthComputable) { $('progress').attr({ value: e.loaded, max: e.total, }); } }, false); } return myXhr; } }); }); ``` As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with [Google Chrome](http://en.wikipedia.org/wiki/Google_Chrome) as some of the HTML5 components of the examples aren't available in every browser.
166,231
<p><a href="http://en.wikipedia.org/wiki/Tcl" rel="noreferrer">Tcl/Tk</a> is a simple way to script small GUIs.</p> <p>Can anyone give a nice example with a <em>button</em> and a <em>text</em> widget. When the button is pressed should a shell command be executed and the output piped to the <em>text</em> widget.</p> <p>If you have other nice and clean examples for useful tasks, please add them too.</p>
[ { "answer_id": 166247, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 2, "selected": false, "text": "<p>I can give a start...please suggest improvements. I.e I'd like it to scroll as the command is outputting</p>\n\n<pre><code>#!/usr/bin/wish\n\nproc push_button {} {\n put_text\n .main see end\n}\n\nproc put_text {} {\n set f [ open \"| date\" r]\n while {[gets $f x] &gt;= 0} {\n .main insert end \"$x\\n\" \n }\n catch {close $f}\n}\n\nbutton .but -text \"Push Me\" -command \"push_button\"\ntext .main -relief sunken -bd 2 -yscrollcommand \".scroll set\"\nscrollbar .scroll -command \".main yview\"\n\npack .but\npack .main -side left -fill y\npack .scroll -side right -fill y\n</code></pre>\n" }, { "answer_id": 166972, "author": "erichui", "author_id": 6034, "author_profile": "https://Stackoverflow.com/users/6034", "pm_score": 2, "selected": false, "text": "<p>Some suggestions:</p>\n\n<p>To append the output to the <strong>text</strong> widget, instead of specifying line 999999, you can use the index <strong>end</strong>, which refers to the position just after the last newline. For example,</p>\n\n<pre><code>.main insert end \"$x\\n\"\n</code></pre>\n\n<p>To have the text scroll as the command is outputting, use the <strong>see</strong> command. For example, after appending to the .main text widget</p>\n\n<pre><code>.main see end\n</code></pre>\n\n<p>You may also want to consider grabbing the command output asynchronously, by using the <strong>fileevent</strong> command.</p>\n" }, { "answer_id": 172061, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 5, "selected": true, "text": "<p>Here's a more complete example using fileevents. This will auto-scroll all the time. For usability purposes you probably only want to auto-scroll if the bottom of the text is visible (ie: if the user hasn't moved the scrollbar) but I'll leave that as an exercise for the reader to keep this already long example from getting any longer.</p>\n\n<pre><code>package require Tk\n\nproc main {} {\n if {[lsearch -exact [font names] TkDefaultFont] == -1} {\n # older versions of Tk don't define this font, so pick something\n # suitable\n font create TkDefaultFont -family Helvetica -size 12\n }\n # in 8.5 we can use {*} but this will work in earlier versions\n eval font create TkBoldFont [font actual TkDefaultFont] -weight bold\n\n buildUI\n}\n\nproc buildUI {} {\n frame .toolbar\n scrollbar .vsb -command [list .t yview]\n text .t \\\n -width 80 -height 20 \\\n -yscrollcommand [list .vsb set] \\\n -highlightthickness 0\n .t tag configure command -font TkBoldFont\n .t tag configure error -font TkDefaultFont -foreground firebrick\n .t tag configure output -font TkDefaultFont -foreground black\n\n grid .toolbar -sticky nsew\n grid .t .vsb -sticky nsew\n grid rowconfigure . 1 -weight 1\n grid columnconfigure . 0 -weight 1\n\n set i 0\n foreach {label command} {\n date {date} \n uptime {uptime} \n ls {ls -l}\n } {\n button .b$i -text $label -command [list runCommand $command]\n pack .b$i -in .toolbar -side left\n incr i\n }\n}\n\nproc output {type text} {\n .t configure -state normal\n .t insert end $text $type \"\\n\"\n .t see end\n .t configure -state disabled\n}\n\nproc runCommand {cmd} {\n output command $cmd\n set f [open \"| $cmd\" r]\n fconfigure $f -blocking false\n fileevent $f readable [list handleFileEvent $f]\n}\n\nproc closePipe {f} {\n # turn blocking on so we can catch any errors\n fconfigure $f -blocking true\n if {[catch {close $f} err]} {\n output error $err\n }\n}\n\nproc handleFileEvent {f} {\n set status [catch { gets $f line } result]\n if { $status != 0 } {\n # unexpected error\n output error $result\n closePipe $f\n\n } elseif { $result &gt;= 0 } {\n # we got some output\n output normal $line\n\n } elseif { [eof $f] } {\n # End of file\n closePipe $f\n\n } elseif { [fblocked $f] } {\n # Read blocked, so do nothing\n }\n}\n\n\nmain\n</code></pre>\n" }, { "answer_id": 597834, "author": "raspi", "author_id": 71964, "author_profile": "https://Stackoverflow.com/users/71964", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://wiki.tcl.tk/\" rel=\"nofollow noreferrer\">wiki.tcl.tk</a> is good website for all kinds of <a href=\"http://wiki.tcl.tk/1291\" rel=\"nofollow noreferrer\">examples</a></p>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/166231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/842/" ]
[Tcl/Tk](http://en.wikipedia.org/wiki/Tcl) is a simple way to script small GUIs. Can anyone give a nice example with a *button* and a *text* widget. When the button is pressed should a shell command be executed and the output piped to the *text* widget. If you have other nice and clean examples for useful tasks, please add them too.
Here's a more complete example using fileevents. This will auto-scroll all the time. For usability purposes you probably only want to auto-scroll if the bottom of the text is visible (ie: if the user hasn't moved the scrollbar) but I'll leave that as an exercise for the reader to keep this already long example from getting any longer. ``` package require Tk proc main {} { if {[lsearch -exact [font names] TkDefaultFont] == -1} { # older versions of Tk don't define this font, so pick something # suitable font create TkDefaultFont -family Helvetica -size 12 } # in 8.5 we can use {*} but this will work in earlier versions eval font create TkBoldFont [font actual TkDefaultFont] -weight bold buildUI } proc buildUI {} { frame .toolbar scrollbar .vsb -command [list .t yview] text .t \ -width 80 -height 20 \ -yscrollcommand [list .vsb set] \ -highlightthickness 0 .t tag configure command -font TkBoldFont .t tag configure error -font TkDefaultFont -foreground firebrick .t tag configure output -font TkDefaultFont -foreground black grid .toolbar -sticky nsew grid .t .vsb -sticky nsew grid rowconfigure . 1 -weight 1 grid columnconfigure . 0 -weight 1 set i 0 foreach {label command} { date {date} uptime {uptime} ls {ls -l} } { button .b$i -text $label -command [list runCommand $command] pack .b$i -in .toolbar -side left incr i } } proc output {type text} { .t configure -state normal .t insert end $text $type "\n" .t see end .t configure -state disabled } proc runCommand {cmd} { output command $cmd set f [open "| $cmd" r] fconfigure $f -blocking false fileevent $f readable [list handleFileEvent $f] } proc closePipe {f} { # turn blocking on so we can catch any errors fconfigure $f -blocking true if {[catch {close $f} err]} { output error $err } } proc handleFileEvent {f} { set status [catch { gets $f line } result] if { $status != 0 } { # unexpected error output error $result closePipe $f } elseif { $result >= 0 } { # we got some output output normal $line } elseif { [eof $f] } { # End of file closePipe $f } elseif { [fblocked $f] } { # Read blocked, so do nothing } } main ```