qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
163,760
|
<p>I have a Form being launched from another form on a different thread. Most of the time it works perfectly, but I get the below error from time to time. Can anyone help?</p>
<pre><code>at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height)
at System.Drawing.Icon.ToBitmap()
at System.Windows.Forms.ThreadExceptionDialog..ctor(Exception t)
at System.Windows.Forms.Application.ThreadContext.OnThreadException(Exception t)
at System.Windows.Forms.Control.WndProcException(Exception e)
at System.Windows.Forms.Control.ControlNativeWindow.OnThreadException(Exception e)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
at System.Windows.Forms.Form.ShowDialog()
</code></pre>
|
[
{
"answer_id": 167171,
"author": "joek1975",
"author_id": 4770,
"author_profile": "https://Stackoverflow.com/users/4770",
"pm_score": 0,
"selected": false,
"text": "Thread = New Thread(AddressOf ShowForm)\nThread.SetApartmentState(ApartmentState.STA)\nThread.IsBackground = True\n"
},
{
"answer_id": 175658,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 2,
"selected": true,
"text": "Dim acctForm As New AccountForm()\nacctForm.Show()\n ShowForm ShowForm()\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4770/"
] |
163,761
|
<p>I have a hidden embedded QuickTime object on my page that I'm trying to control via JavaScript, but it's not working. The object looks like this:</p>
<pre><code><object id="myPlayer" data="" type="audio/mpeg" pluginspage="http://www.apple.com/quicktime/download" width="0" height="0">
<param name="autoPlay" value="false" />
<param name="controller" value="false" />
<param name="enablejavascript" value="true" />
</object>
</code></pre>
<p>There is nothing in the data parameter because at render time, I don't know the URL that's going to be loaded. I set it like this:</p>
<pre><code>var player = document.getElementById("myPlayer");
player.SetURL(url);
</code></pre>
<p>The audio will later be played back with:</p>
<pre><code>player.Play();
</code></pre>
<p>Firefox 3.0.3 produces no error in the JavaScript console, but no playback occurs when <code>Play()</code> is called. Safari 3.0.4 produces the following error in the console:</p>
<pre><code>"Value undefined (result of expression player.SetURL) is not object."
</code></pre>
<p>Internet Explorer 7.0.5730.11 gives the following extremely helpful error message:</p>
<pre><code>"Unspecified error."
</code></pre>
<p>I have QuickTime version 7.4 installed on my machine. <a href="http://developer.apple.com/documentation/QuickTime/Conceptual/QTScripting_JavaScript/bQTScripting_JavaScri_Document/chapter_1000_section_5.html" rel="nofollow noreferrer">Apple's documentation</a> says that <code>SetURL()</code> is correct, so why does it not work?</p>
|
[
{
"answer_id": 429916,
"author": "Kev",
"author_id": 16777,
"author_profile": "https://Stackoverflow.com/users/16777",
"pm_score": 0,
"selected": false,
"text": "player.attributes.getNamedItem('data').value = 'http://yoururlhere';\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4287/"
] |
163,783
|
<p>Here's the problem I'm having, I've got a set of logs that can grow fairly quickly. They're split into individual files every day, and the files can easily grow up to a gig in size. To help keep the size down, entries older than 30 days or so are cleared out.</p>
<p>The problem is when I want to search these files for a certain string. Right now, a Boyer-Moore search is unfeasibly slow. I know that applications like dtSearch can provide a really fast search using indexing, but I'm not really sure how to implement that without taking up twice the space a log already takes up.</p>
<p>Are there any resources I can check out that can help? I'm really looking for a standard algorithm that'll explain what I should do to build an index and use it to search.</p>
<p>Edit:<br>
Grep won't work as this search needs to be integrated into a cross-platform application. There's no way I'll be able to swing including any external program into it.</p>
<p>The way it works is that there's a web front end that has a log browser. This talks to a custom C++ web server backend. This server needs to search the logs in a reasonable amount of time. Currently searching through several gigs of logs takes ages.</p>
<p>Edit 2:
Some of these suggestions are great, but I have to reiterate that I can't integrate another application, it's part of the contract. But to answer some questions, the data in the logs varies from either received messages in a health-care specific format or messages relating to these. I'm looking to rely on an index because while it may take up to a minute to rebuild the index, searching currently takes a very long time (I've seen it take up to 2.5 minutes). Also, a lot of the data IS discarded before even recording it. Unless some debug logging options are turned on, more than half of the log messages are ignored.</p>
<p>The search basically goes like this: A user on the web form is presented with a list of the most recent messages (streamed from disk as they scroll, yay for ajax), usually, they'll want to search for messages with some information in it, maybe a patient id, or some string they've sent, and so they can enter the string into the search. The search gets sent asychronously and the custom web server linearly searches through the logs 1MB at a time for some results. This process can take a very long time when the logs get big. And it's what I'm trying to optimize.</p>
|
[
{
"answer_id": 163806,
"author": "changelog",
"author_id": 5646,
"author_profile": "https://Stackoverflow.com/users/5646",
"pm_score": 3,
"selected": false,
"text": "grep"
},
{
"answer_id": 164317,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 0,
"selected": false,
"text": "grep"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4218/"
] |
163,796
|
<p>I have a lot of XML files and I'd like to generate a report from them. The report should provide information such as:</p>
<pre><code>root 100%
a*1 90%
b*1 80%
c*5 40%
</code></pre>
<p>meaning that all documents have a root element, 90% have one <strong>a</strong> element in the root, 80% have one <strong>b</strong> element in the root, 40% have 5 <strong>c</strong> elements in <strong>b</strong>.</p>
<p>If for example some documents have 4 <strong>c</strong> elements, some 5 and some 6, it should say something like: </p>
<pre><code>c*4.3 4 6 40%
</code></pre>
<p>meaning that 40% have between 4 and 6 <strong>c</strong> elements there, and the average is 4.3.</p>
<p>I am looking for free software, if it doesn't exist I'll write it. I was about to do it, but I thought about checking it. I may not be the first one to have to analyze and get an structural overview of thousand of XML files.</p>
|
[
{
"answer_id": 164830,
"author": "JeniT",
"author_id": 6739,
"author_profile": "https://Stackoverflow.com/users/6739",
"pm_score": 4,
"selected": false,
"text": "$docs <xsl:for-each-group> <xsl:for-each-group select=\"$docs//*\" group-by=\"name()\">\n <xsl:sort select=\"current-group-key()\" />\n <xsl:variable name=\"name\" as=\"xs:string\" select=\"current-grouping-key()\" />\n <xsl:value-of select=\"$name\" />\n ...\n</xsl:for-each-group>\n <xsl:variable name=\"docs-with\" as=\"document-node()+\"\n select=\"$docs[//*[name() = $name]\" />\n <xsl:variable name=\"elem-counts\" as=\"xs:integer+\"\n select=\"$docs-with/count(//*[name() = $name])\" />\n avg() min() max() <xsl:for-each-group select=\"$docs//*\" group-by=\"name()\">\n <xsl:sort select=\"current-group-key()\" />\n <xsl:variable name=\"name\" as=\"xs:string\" select=\"current-grouping-key()\" />\n <xsl:variable name=\"docs-with\" as=\"document-node()+\"\n select=\"$docs[//*[name() = $name]\" />\n <xsl:variable name=\"elem-counts\" as=\"xs:integer+\"\n select=\"$docs-with/count(//*[name() = $name])\" />\n <xsl:value-of select=\"$name\" />\n <xsl:text>* </xsl:text>\n <xsl:value-of select=\"format-number(avg($elem-counts), '#,##0.0')\" />\n <xsl:text> </xsl:text>\n <xsl:value-of select=\"format-number(min($elem-counts), '#,##0')\" />\n <xsl:text> </xsl:text>\n <xsl:value-of select=\"format-number(max($elem-counts), '#,##0')\" />\n <xsl:text> </xsl:text>\n <xsl:value-of select=\"format-number((count($docs-with) div count($docs)) * 100, '#0')\" />\n <xsl:text>%</xsl:text>\n <xsl:text>
</xsl:text>\n</xsl:for-each-group>\n <xsl:stylesheet version=\"2.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n exclude-result-prefixes=\"xs\">\n\n<xsl:param name=\"dir\" as=\"xs:string\"\n select=\"'file:///path/to/default/directory?select=*.xml'\" />\n\n<xsl:output method=\"text\" />\n\n<xsl:variable name=\"docs\" as=\"document-node()*\"\n select=\"collection($dir)\" />\n\n<xsl:template name=\"main\">\n <xsl:for-each-group select=\"$docs//*\" group-by=\"name()\">\n <xsl:sort select=\"current-group-key()\" />\n <xsl:variable name=\"name\" as=\"xs:string\" select=\"current-grouping-key()\" />\n <xsl:variable name=\"docs-with\" as=\"document-node()+\"\n select=\"$docs[//*[name() = $name]\" />\n <xsl:variable name=\"elem-counts\" as=\"xs:integer+\"\n select=\"$docs-with/count(//*[name() = $name])\" />\n <xsl:value-of select=\"$name\" />\n <xsl:text>* </xsl:text>\n <xsl:value-of select=\"format-number(avg($elem-counts), '#,##0.0')\" />\n <xsl:text> </xsl:text>\n <xsl:value-of select=\"format-number(min($elem-counts), '#,##0')\" />\n <xsl:text> </xsl:text>\n <xsl:value-of select=\"format-number(max($elem-counts), '#,##0')\" />\n <xsl:text> </xsl:text>\n <xsl:value-of select=\"format-number((count($docs-with) div count($docs)) * 100, '#0')\" />\n <xsl:text>%</xsl:text>\n <xsl:text>
</xsl:text>\n </xsl:for-each-group>\n</xsl:template> \n\n</xsl:stylesheet>\n main dir file:///path/to/your/directory?select=*.xml report.txt"
},
{
"answer_id": 172142,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "Analyzing plant_catalog.xml: \nAnalyzing note.xml: \nAnalyzing portfolio.xml: \nAnalyzing note_ex_dtd.xml: \nAnalyzing home.xml: \nAnalyzing simple.xml: \nAnalyzing cd_catalog.xml: \nAnalyzing portfolio_xsl.xml: \nAnalyzing note_in_dtd.xml: \nStatistical Elements Analysis of 9 xml documents with 34 elements\nCATALOG*2 22%\n CD*26 50%\n ARTIST*26 100%\n COMPANY*26 100%\n COUNTRY*26 100%\n PRICE*26 100%\n TITLE*26 100%\n YEAR*26 100%\n PLANT*36 50%\n AVAILABILITY*36 100%\n BOTANICAL*36 100%\n COMMON*36 100%\n LIGHT*36 100%\n PRICE*36 100%\n ZONE*36 100%\nbreakfast-menu*1 11%\n food*5 100%\n calories*5 100%\n description*5 100%\n name*5 100%\n price*5 100%\nnote*3 33%\n body*1 100%\n from*1 100%\n heading*1 100%\n to*1 100%\npage*1 11%\n para*1 100%\n title*1 100%\nportfolio*2 22%\n stock*2 100%\n name*2 100%\n price*2 100%\n symbol*2 100%\n"
},
{
"answer_id": 172149,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "require \"rexml/document\"\nrequire \"net/http\"\nrequire \"iconv\"\ninclude REXML\nclass NodeAnalyzer\n @@fullPathToFilesToSubNodesNamesToCardinalities = Hash.new()\n @@fullPathsToFiles = Hash.new() #list of files in which a fullPath node is detected\n @@fullPaths = Array.new # all fullpaths sorted alphabetically\n attr_reader :name, :father, :subNodesAnalyzers, :indent, :file, :subNodesNamesToCardinalities\n def initialize(aName=\"\", aFather=nil, aFile=\"\")\n @name = aName; @father = aFather; @subNodesAnalyzers = []; @file = aFile\n @subNodesNamesToCardinalities = Hash.new(0)\n if aFather && !aFather.name.empty? then @indent = \" \" else @indent = \"\" end\n if aFather\n @indent = @father.indent + self.indent\n @father.subNodesAnalyzers << self\n @father.updateSubNodesNamesToCardinalities(@name)\n end\n end\n @@nodesRootAnalyzer = NodeAnalyzer.new\n def NodeAnalyzer.nodesRootAnalyzer\n return @@nodesRootAnalyzer\n end\n def updateSubNodesNamesToCardinalities(aSubNodeName)\n aSubNodeCardinality = @subNodesNamesToCardinalities[aSubNodeName]\n @subNodesNamesToCardinalities[aSubNodeName] = aSubNodeCardinality + 1\n end\n def NodeAnalyzer.recordNode(aNodeAnalyzer)\n if aNodeAnalyzer.fullNodePath.empty? == false\n if @@fullPaths.include?(aNodeAnalyzer.fullNodePath) == false then @@fullPaths << aNodeAnalyzer.fullNodePath end\n # record a full path in regard to its xml file (records it only one for a given xlm file)\n someFiles = @@fullPathsToFiles[aNodeAnalyzer.fullNodePath]\n if someFiles == nil \n someFiles = Array.new(); @@fullPathsToFiles[aNodeAnalyzer.fullNodePath] = someFiles; \n end\n if !someFiles.include?(aNodeAnalyzer.file) then someFiles << aNodeAnalyzer.file end\n end\n #record cardinalties of sub nodes for a given xml file\n someFilesToSubNodesNamesToCardinalities = @@fullPathToFilesToSubNodesNamesToCardinalities[aNodeAnalyzer.fullNodePath]\n if someFilesToSubNodesNamesToCardinalities == nil \n someFilesToSubNodesNamesToCardinalities = Hash.new(); @@fullPathToFilesToSubNodesNamesToCardinalities[aNodeAnalyzer.fullNodePath] = someFilesToSubNodesNamesToCardinalities ; \n end\n someSubNodesNamesToCardinalities = someFilesToSubNodesNamesToCardinalities[aNodeAnalyzer.file]\n if someSubNodesNamesToCardinalities == nil\n someSubNodesNamesToCardinalities = Hash.new(0); someFilesToSubNodesNamesToCardinalities[aNodeAnalyzer.file] = someSubNodesNamesToCardinalities\n someSubNodesNamesToCardinalities.update(aNodeAnalyzer.subNodesNamesToCardinalities)\n else\n aNodeAnalyzer.subNodesNamesToCardinalities.each() do |aSubNodeName, aCardinality|\n someSubNodesNamesToCardinalities[aSubNodeName] = someSubNodesNamesToCardinalities[aSubNodeName] + aCardinality\n end\n end \n #puts \"someSubNodesNamesToCardinalities for #{aNodeAnalyzer.fullNodePath}: #{someSubNodesNamesToCardinalities}\"\n end\n def file\n #if @file.empty? then @father.file else return @file end\n if @file.empty? then if @father != nil then return @father.file else return '' end else return @file end\n end\n def fullNodePath\n if @father == nil then return '' elsif @father.name.empty? then return @name else return @father.fullNodePath+\"/\"+@name end\n end\n def to_s\n s = \"\"\n if @name.empty? == false\n s = \"#{@indent}#{self.fullNodePath} [#{self.file}]\\n\"\n end\n @subNodesAnalyzers.each() do |aSubNodeAnalyzer|\n s = s + aSubNodeAnalyzer.to_s\n end\n return s\n end\n def NodeAnalyzer.displayStats(aFullPath=\"\")\n s = \"\";\n if aFullPath.empty? then s = \"Statistical Elements Analysis of #{@@nodesRootAnalyzer.subNodesAnalyzers.length} xml documents with #{@@fullPaths.length} elements\\n\" end\n someFullPaths = @@fullPaths.sort\n someFullPaths.each do |aFullPath|\n s = s + getIndentedNameFromFullPath(aFullPath) + \"*\"\n nbFilesWithThatFullPath = getNbFilesWithThatFullPath(aFullPath);\n aParentFullPath = getParentFullPath(aFullPath)\n nbFilesWithParentFullPath = getNbFilesWithThatFullPath(aParentFullPath);\n aNameFromFullPath = getNameFromFullPath(aFullPath)\n someFilesToSubNodesNamesToCardinalities = @@fullPathToFilesToSubNodesNamesToCardinalities[aParentFullPath]\n someCardinalities = Array.new()\n someFilesToSubNodesNamesToCardinalities.each() do |aFile, someSubNodesNamesToCardinalities|\n aCardinality = someSubNodesNamesToCardinalities[aNameFromFullPath]\n if aCardinality > 0 && someCardinalities.include?(aCardinality) == false then someCardinalities << aCardinality end\n end\n if someCardinalities.length == 1\n s = s + someCardinalities.to_s + \" \"\n else\n anAvg = someCardinalities.inject(0) {|sum,value| Float(sum) + Float(value) } / Float(someCardinalities.length)\n s = s + sprintf('%.1f', anAvg) + \" \" + someCardinalities.min.to_s + \"...\" + someCardinalities.max.to_s + \" \"\n end\n s = s + sprintf('%d', Float(nbFilesWithThatFullPath) / Float(nbFilesWithParentFullPath) * 100) + '%'\n s = s + \"\\n\"\n end\n return s\n end\n def NodeAnalyzer.getNameFromFullPath(aFullPath)\n if aFullPath.include?(\"/\") == false then return aFullPath end\n aNameFromFullPath = aFullPath.dup\n aNameFromFullPath[/^(?:[^\\/]+\\/)+/] = \"\"\n return aNameFromFullPath\n end\n def NodeAnalyzer.getIndentedNameFromFullPath(aFullPath)\n if aFullPath.include?(\"/\") == false then return aFullPath end\n anIndentedNameFromFullPath = aFullPath.dup\n anIndentedNameFromFullPath = anIndentedNameFromFullPath.gsub(/[^\\/]+\\//, \" \")\n return anIndentedNameFromFullPath\n end\n def NodeAnalyzer.getParentFullPath(aFullPath)\n if aFullPath.include?(\"/\") == false then return \"\" end\n aParentFullPath = aFullPath.dup\n aParentFullPath[/\\/[^\\/]+$/] = \"\"\n return aParentFullPath\n end\n def NodeAnalyzer.getNbFilesWithThatFullPath(aFullPath)\n if aFullPath.empty? \n return @@nodesRootAnalyzer.subNodesAnalyzers.length\n else\n return @@fullPathsToFiles[aFullPath].length;\n end\n end\nend\nclass REXML::Document\n def analyze(node, aFatherNodeAnalyzer, aFile=\"\")\n anNodeAnalyzer = NodeAnalyzer.new(node.name, aFatherNodeAnalyzer, aFile)\n node.elements.each() do |aSubNode| analyze(aSubNode, anNodeAnalyzer) end\n NodeAnalyzer.recordNode(anNodeAnalyzer)\n end\nend\n\nbegin\n anXmlFilesDirectory = \"xmlfiles.com/examples/\"\n anXmlFilesRegExp = Regexp.new(\"http:\\/\\/\" + anXmlFilesDirectory + \"([^\\\"]*)\")\n a = Net::HTTP.get(URI(\"http://www.google.fr/search?q=site:\"+anXmlFilesDirectory+\"+filetype:xml&num=100&as_qdr=all&filter=0\"))\n someXmlFiles = a.scan(anXmlFilesRegExp)\n someXmlFiles.each() do |anXmlFile|\n anXmlFileContent = Net::HTTP.get(URI(\"http://\" + anXmlFilesDirectory + anXmlFile.to_s))\n anUTF8XmlFileContent = Iconv.conv(\"ISO-8859-1//ignore\", 'UTF-8', anXmlFileContent).gsub(/\\s+encoding\\s*=\\s*\\\"[^\\\"]+\\\"\\s*\\?/,\"?\")\n anXmlDocument = Document.new(anUTF8XmlFileContent)\n puts \"Analyzing #{anXmlFile}: #{NodeAnalyzer.nodesRootAnalyzer.name}\"\n anXmlDocument.analyze(anXmlDocument.root,NodeAnalyzer.nodesRootAnalyzer, anXmlFile.to_s)\n end\n NodeAnalyzer.recordNode(NodeAnalyzer.nodesRootAnalyzer)\n puts NodeAnalyzer.displayStats\nend\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
163,803
|
<p>I would like to override the use of the standard app.config by passing a command line parameter. How do I change the default application configuration file so that when I access ConfigurationManager.AppSettings I am accessing the config file specified on the command line?</p>
<p>Edit:</p>
<p>It turns out that the correct way to load a config file that is different than the name of the EXE plus .config is to use OpenMappedExeConfiguration. E.g. </p>
<pre><code>ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, "Shell2.exe.config");
currentConfiguration = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None);
</code></pre>
<p>This partially works. I can see all of the keys in the appSettings section but all the values are null.</p>
|
[
{
"answer_id": 163829,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 1,
"selected": false,
"text": "ConfigurationManager OpenExeConfiguration ConfigurationManager FileConfigurationSource FileConfigurationSource Microsoft.Practices.EnterpriseLibrary.Common.dll static void Main(string[] args)\n{\n //read from current app.config as default\n AppSettingsSection ass = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings;\n\n //if args[0] is a valid file path assume it's a config for this example and attempt to load\n if (args.Length > 0 && File.Exists(args[0]))\n {\n //using FileConfigurationSource from Enterprise Library\n FileConfigurationSource fcs = new FileConfigurationSource(args[0]);\n ass = (AppSettingsSection) fcs.GetSection(\"appSettings\");\n }\n\n //print value from configuration\n Console.WriteLine(ass.Settings[\"test\"].Value);\n Console.ReadLine(); //pause\n}\n"
},
{
"answer_id": 164221,
"author": "Darrel Miller",
"author_id": 6819,
"author_profile": "https://Stackoverflow.com/users/6819",
"pm_score": 5,
"selected": true,
"text": "ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();\nconfigFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, \"Alternate.config\");\nConfiguration config = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None);\n\nAppSettingsSection section = (AppSettingsSection)config.GetSection(\"appSettings\");\nstring MySetting = section.Settings[\"MySetting\"].Value;\n"
},
{
"answer_id": 1091909,
"author": "majkinetor",
"author_id": 82660,
"author_profile": "https://Stackoverflow.com/users/82660",
"pm_score": 1,
"selected": false,
"text": "Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\nstring defCfgName = Environment.GetCommandLineArgs()[0] + \".config\";\n\nif (arg.Length != 0)\n{\n string ConfigFileName = arg[0];\n if (!File.Exists(ConfigFileName))\n Fatal(\"File doesn't exist: \" + ConfigFileName, -1); \n config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = ConfigFileName }, ConfigurationUserLevel.None);\n}\nelse if (!File.Exists(defCfgName)) Fatal(\"Default configuration file doesn't exist and no override is set.\" , -1);\n AppSettingsSection s = (AppSettingsSection)config.GetSection(\"appSettings\");\nKeyValueConfigurationCollection a = s.Settings;\nConnectionString = a[\"ConnectionString\"].Value;\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6819/"
] |
163,809
|
<p>I'm looking for an example algorithm of smart pagination. By smart, what I mean is that I only want to show, for example, 2 adjacent pages to the current page, so instead of ending up with a ridiculously long page list, I truncate it.</p>
<p>Here's a quick example to make it clearer... this is what I have now:</p>
<pre><code>Pages: 1 2 3 4 [5] 6 7 8 9 10 11
</code></pre>
<p>This is what I want to end up with:</p>
<pre><code>Pages: ... 3 4 [5] 6 7 ...
</code></pre>
<p>(In this example, I'm only showing 2 adjacent pages to the current page)</p>
<p>I'm implementing it in PHP/Mysql, and the "basic" pagination (no trucating) is already coded, I'm just looking for an example to optimize it... It can be an example in any language, as long as it gives me an idea as to how to implement it...</p>
|
[
{
"answer_id": 163825,
"author": "changelog",
"author_id": 5646,
"author_profile": "https://Stackoverflow.com/users/5646",
"pm_score": 6,
"selected": true,
"text": "[1] 2 3 4 5 6 ... 100\n1 [2] 3 4 5 6 ... 100\n...\n1 2 ... 14 15 [16] 17 18 ... 100\n...\n1 2 ... 97 [98] 99 100\n <?php\n\n// How many adjacent pages should be shown on each side?\n$adjacents = 3;\n\n//how many items to show per page\n$limit = 5;\n\n// if no page var is given, default to 1.\n$page = (int)$_GET[\"page\"] ?? 1;\n\n//first item to display on this page\n$start = ($page - 1) * $limit;\n\n/* Get data. */\n$data = $db\n ->query(\"SELECT * FROM mytable LIMIT $start, $limit\")\n ->fetchAll();\n\n$total_pages = count($data);\n\n/* Setup page vars for display. */\n$prev = $page - 1;\n$next = $page + 1;\n$lastpage = ceil($total_pages / $limit);\n//last page minus 1\n$lpm1 = $lastpage - 1;\n\n$first_pages = \"<li class='page-item'><a class='page-link' href='?page=1'>1</a></li>\" .\n \"<li class='page-item'><a class='page-link' href='?page=2'>2</a>\";\n\n$ellipsis = \"<li class='page-item disabled'><span class='page-link'>...</span></li>\";\n\n$last_pages = \"<li class='page-item'><a class='page-link' href='?page=$lpm1'>$lpm1</a></li>\" .\n \"<li class='page-item'><a class='page-link' href='?page=$lastpage'>$lastpage</a>\";\n\n$pagination = \"<nav aria-label='page navigation'>\";\n$pagincation .= \"<ul class='pagination'>\";\n\n//previous button\n\n$disabled = ($page === 1) ? \"disabled\" : \"\";\n$pagination.= \"<li class='page-item $disabled'><a class='page-link' href='?page=$prev'>« previous</a></li>\";\n\n//pages \n//not enough pages to bother breaking it up\nif ($lastpage < 7 + ($adjacents * 2)) { \n for ($i = 1; $i <= $lastpage; $i++) {\n $active = $i === $page ? \"active\" : \"\";\n $pagination .= \"<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>\";\n }\n} elseif($lastpage > 5 + ($adjacents * 2)) {\n //enough pages to hide some\n //close to beginning; only hide later pages\n if($page < 1 + ($adjacents * 2)) {\n for ($i = 1; $i < 4 + ($adjacents * 2); $i++) {\n $active = $i === $page ? \"active\" : \"\";\n $pagination .= \"<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>\";\n }\n $pagination .= $ellipsis;\n $pagination .= $last_pages;\n } elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) {\n //in middle; hide some front and some back\n $pagination .= $first_pages;\n $pagination .= $ellipsis\n for ($i = $page - $adjacents; $i <= $page + $adjacents; $i++) {\n $active = $i === $page ? \"active\" : \"\";\n $pagination .= \"<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>\";\n }\n $pagination .= $ellipsis;\n $pagination .= $last_pages;\n } else {\n //close to end; only hide early pages\n $pagination .= $first_pages;\n $pagination .= $ellipsis;\n $pagination .= \"<li class='page-item disabled'><span class='page-link'>...</span></li>\";\n for ($i = $lastpage - (2 + ($adjacents * 2)); $i <= $lastpage; $i++) {\n $active = $i === $page ? \"active\" : \"\";\n $pagination .= \"<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>\";\n }\n }\n}\n\n//next button\n$disabled = ($page === $last) ? \"disabled\" : \"\";\n$pagination.= \"<li class='page-item $disabled'><a class='page-link' href='?page=$next'>next »</a></li>\";\n\n$pagination .= \"</ul></nav>\";\n\nif($lastpage <= 1) {\n $pagination = \"\";\n}\n\n\necho $pagination;\n\nforeach ($data as $row) {\n // display your data\n}\n\necho $pagination;\n\n"
},
{
"answer_id": 163845,
"author": "Fernando Barrocal",
"author_id": 2274,
"author_profile": "https://Stackoverflow.com/users/2274",
"pm_score": 0,
"selected": false,
"text": "if (\n $page_number == 1 || $page_number == $last_page ||\n $page_number == $actual_page ||\n $page_number == $actual_page+1 || $page_number == $actual_page+2 ||\n $page_number == $actual_page-1 || $page_number == $actual_page-2\n ) echo $page_number;\n %"
},
{
"answer_id": 164592,
"author": "Jacob",
"author_id": 8119,
"author_profile": "https://Stackoverflow.com/users/8119",
"pm_score": 2,
"selected": false,
"text": "$paging = new Pagination();\n$paging->set('urlscheme','class.pagination.php?page=%page%');\n$paging->set('perpage',10);\n$paging->set('page',15);\n$paging->set('total',3000);\n$paging->set('nexttext','Next Page');\n$paging->set('prevtext','Previous Page');\n$paging->set('focusedclass','selected');\n$paging->set('delimiter','');\n$paging->set('numlinks',9);\n$paging->display();\n"
},
{
"answer_id": 2759696,
"author": "lazaro",
"author_id": 331613,
"author_profile": "https://Stackoverflow.com/users/331613",
"pm_score": 2,
"selected": false,
"text": "List<int> pages = new List<int>();\nint pn = 2; //example of actual pagenumber\nint total = 8;\n\nfor(int i = pn - 9; i <= pn + 9; i++)\n{\n if(i < 1) continue;\n if(i > total) break;\n pages.Add(i);\n}\n\nreturn pages;\n"
},
{
"answer_id": 7562895,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 4,
"selected": false,
"text": "function Pagination($data, $limit = null, $current = null, $adjacents = null)\n{\n $result = array();\n\n if (isset($data, $limit) === true)\n {\n $result = range(1, ceil($data / $limit));\n\n if (isset($current, $adjacents) === true)\n {\n if (($adjacents = floor($adjacents / 2) * 2 + 1) >= 1)\n {\n $result = array_slice($result, max(0, min(count($result) - $adjacents, intval($current) - ceil($adjacents / 2))), $adjacents);\n }\n }\n }\n\n return $result;\n}\n $total = 1024;\n$per_page = 10;\n$current_page = 2;\n$adjacent_links = 4;\n\nprint_r(Pagination($total, $per_page, $current_page, $adjacent_links));\n Array\n(\n [0] => 1\n [1] => 2\n [2] => 3\n [3] => 4\n [4] => 5\n)\n $total = 1024;\n$per_page = 10;\n$current_page = 42;\n$adjacent_links = 4;\n\nprint_r(Pagination($total, $per_page, $current_page, $adjacent_links));\n Array\n(\n [0] => 40\n [1] => 41\n [2] => 42\n [3] => 43\n [4] => 44\n)\n"
},
{
"answer_id": 7824252,
"author": "Robert Eisele",
"author_id": 1003538,
"author_profile": "https://Stackoverflow.com/users/1003538",
"pm_score": 0,
"selected": false,
"text": "$(\"#pagination\").paging(1000, { // Your number of elements\n format: '. - nncnn - ', // Format to get Pages: ... 3 4 [5] 6 7 ...\n onSelect: function (page) {\n // add code which gets executed when user selects a page\n },\n onFormat: function (type) {\n switch (type) {\n case 'block': // n and c\n return '<a>' + this.value + '</a>';\n case 'fill': // -\n return '...';\n case 'leap': // .\n return 'Pages:';\n }\n }\n});\n"
},
{
"answer_id": 7833191,
"author": "Natrium",
"author_id": 59119,
"author_profile": "https://Stackoverflow.com/users/59119",
"pm_score": 0,
"selected": false,
"text": "$config['num_links'] = 2;\n"
},
{
"answer_id": 8608998,
"author": "Edwin",
"author_id": 1079096,
"author_profile": "https://Stackoverflow.com/users/1079096",
"pm_score": 3,
"selected": false,
"text": "var totalPages = 50, buttons = 5;\nvar currentPage = lowerLimit = upperLimit = Math.min(9, totalPages);\n\n//Search boundaries\nfor (var b = 1; b < buttons && b < totalPages;) {\n if (lowerLimit > 1 ) { lowerLimit--; b++; }\n if (b < buttons && upperLimit < totalPages) { upperLimit++; b++; }\n}\n\n//Do output to a html element\nfor (var i = lowerLimit; i <= upperLimit; i++) {\n if (i == currentPage) $('#pager').append('<li>' + i + '</li> ');\n else $('#pager').append('<a href=\"#\"><li><em>' + i + '</em></li></a> ');\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14981/"
] |
163,823
|
<p>I have a <code>Person</code> model that has a foreign key relationship to <code>Book</code>, which has a number of fields, but I'm most concerned about <code>author</code> (a standard CharField).</p>
<p>With that being said, in my <code>PersonAdmin</code> model, I'd like to display <code>book.author</code> using <code>list_display</code>:</p>
<pre><code>class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
</code></pre>
<p>I've tried all of the obvious methods for doing so, but nothing seems to work.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 163968,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 5,
"selected": false,
"text": "__unicode__ 'book__author'"
},
{
"answer_id": 164631,
"author": "imjoevasquez",
"author_id": 24630,
"author_profile": "https://Stackoverflow.com/users/24630",
"pm_score": 10,
"selected": true,
"text": "class UserAdmin(admin.ModelAdmin):\n list_display = (..., 'get_author')\n \n def get_author(self, obj):\n return obj.book.author\n get_author.short_description = 'Author'\n get_author.admin_order_field = 'book__author'\n display() class UserAdmin(admin.ModelAdmin):\n list_display = (..., 'get_author')\n \n @admin.display(ordering='book__author', description='Author')\n def get_author(self, obj):\n return obj.book.author\n"
},
{
"answer_id": 475086,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "ForeignKey __unicode__ class Category(models.Model):\n name = models.CharField(max_length=50)\n\n def __unicode__(self):\n return self.name\n"
},
{
"answer_id": 679791,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "def book_author(self):\n return self.book.author\n"
},
{
"answer_id": 3351431,
"author": "Arjen",
"author_id": 390441,
"author_profile": "https://Stackoverflow.com/users/390441",
"pm_score": 6,
"selected": false,
"text": "def author(self, obj):\n return obj.book.author\nauthor.admin_order_field = 'book__author'\n def author(self):\n return self.book.author\nauthor.admin_order_field = 'book__author'\n"
},
{
"answer_id": 14677451,
"author": "Jack Cushman",
"author_id": 307769,
"author_profile": "https://Stackoverflow.com/users/307769",
"pm_score": 4,
"selected": false,
"text": "class PersonAdmin(RelatedFieldAdmin):\n list_display = ['book__author',]\n"
},
{
"answer_id": 21456615,
"author": "Eyal Ch",
"author_id": 3218482,
"author_profile": "https://Stackoverflow.com/users/3218482",
"pm_score": 2,
"selected": false,
"text": "class AddInline(admin.TabularInline):\n readonly_fields = ['localname',]\n model = MyModel\n fields = ('localname',)\n class MyModel(models.Model):\n localization = models.ForeignKey(Localizations)\n\n def localname(self):\n return self.localization.name\n"
},
{
"answer_id": 23747842,
"author": "Will",
"author_id": 464923,
"author_profile": "https://Stackoverflow.com/users/464923",
"pm_score": 8,
"selected": false,
"text": "class Author(models.Model):\n name = models.CharField(max_length=255)\n\nclass Book(models.Model):\n author = models.ForeignKey(Author)\n title = models.CharField(max_length=255)\n class BookAdmin(admin.ModelAdmin):\n model = Book\n list_display = ['title', 'author__name', ]\n\nadmin.site.register(Book, BookAdmin)\n class BookAdmin(admin.ModelAdmin):\n model = Book\n list_display = ['title', 'get_name', ]\n\n def get_name(self, obj):\n return obj.author.name\n get_name.admin_order_field = 'author' #Allows column order sorting\n get_name.short_description = 'Author Name' #Renames column head\n\n #Filtering on side - for some reason, this works\n #list_filter = ['title', 'author__name']\n\nadmin.site.register(Book, BookAdmin)\n"
},
{
"answer_id": 28190954,
"author": "Hunger",
"author_id": 2251785,
"author_profile": "https://Stackoverflow.com/users/2251785",
"pm_score": 6,
"selected": false,
"text": "get_author get_queryset def get_queryset(self, request):\n return super(PersonAdmin,self).get_queryset(request).select_related('book')\n"
},
{
"answer_id": 34735225,
"author": "Cauê Thenório",
"author_id": 780262,
"author_profile": "https://Stackoverflow.com/users/780262",
"pm_score": 3,
"selected": false,
"text": "list_display ModelAdmin __getattr__ class DynamicLookupMixin(object):\n '''\n a mixin to add dynamic callable attributes like 'book__author' which\n return a function that return the instance.book.author value\n '''\n\n def __getattr__(self, attr):\n if ('__' in attr\n and not attr.startswith('_')\n and not attr.endswith('_boolean')\n and not attr.endswith('_short_description')):\n\n def dyn_lookup(instance):\n # traverse all __ lookups\n return reduce(lambda parent, child: getattr(parent, child),\n attr.split('__'),\n instance)\n\n # get admin_order_field, boolean and short_description\n dyn_lookup.admin_order_field = attr\n dyn_lookup.boolean = getattr(self, '{}_boolean'.format(attr), False)\n dyn_lookup.short_description = getattr(\n self, '{}_short_description'.format(attr),\n attr.replace('_', ' ').capitalize())\n\n return dyn_lookup\n\n # not dynamic lookup, default behaviour\n return self.__getattribute__(attr)\n\n\n# use examples \n\n@admin.register(models.Person)\nclass PersonAdmin(admin.ModelAdmin, DynamicLookupMixin):\n list_display = ['book__author', 'book__publisher__name',\n 'book__publisher__country']\n\n # custom short description\n book__publisher__country_short_description = 'Publisher Country'\n\n\n@admin.register(models.Product)\nclass ProductAdmin(admin.ModelAdmin, DynamicLookupMixin):\n list_display = ('name', 'category__is_new')\n\n # to show as boolean field\n category__is_new_boolean = True\n boolean short_description ModelAdmin book__author_verbose_name = 'Author name' category__is_new_boolean = True admin_order_field ModelAdmin"
},
{
"answer_id": 37497913,
"author": "Vlad Schnakovszki",
"author_id": 1195527,
"author_profile": "https://Stackoverflow.com/users/1195527",
"pm_score": 4,
"selected": false,
"text": "class PersonAdmin(RelatedFieldAdmin):\n list_display = ['book__author',]\n model.Admin SimpleHistoryAdmin class MyAdmin(SimpleHistoryAdmin, RelatedFieldAdmin)"
},
{
"answer_id": 39642294,
"author": "wieczorek1990",
"author_id": 761200,
"author_profile": "https://Stackoverflow.com/users/761200",
"pm_score": -1,
"selected": false,
"text": "class CoolAdmin(admin.ModelAdmin):\n list_display = ('pk', 'submodel__field')\n\n @staticmethod\n def submodel__field(obj):\n return obj.submodel.field\n"
},
{
"answer_id": 67746847,
"author": "Cesar Canassa",
"author_id": 360829,
"author_profile": "https://Stackoverflow.com/users/360829",
"pm_score": 5,
"selected": false,
"text": "class BookAdmin(admin.ModelAdmin):\n model = Book\n list_display = ['title', 'get_author_name']\n\n @admin.display(description='Author Name', ordering='author__name')\n def get_author_name(self, obj):\n return obj.author.name\n"
},
{
"answer_id": 69360403,
"author": "Eyong Kevin Enowanyo",
"author_id": 8665639,
"author_profile": "https://Stackoverflow.com/users/8665639",
"pm_score": 2,
"selected": false,
"text": "list_display class Person(models.Model):\n book = models.ForeignKey(Book, on_delete=models.CASCADE)\n\n def get_book_author(self):\n return self.book.author\n class PersonAdmin(admin.ModelAdmin):\n list_display = ('get_book_author',)\n get_queryset from django.db.models.expressions import F\n\n@admin.register(models.Person)\nclass PersonAdmin(admin.ModelAdmin):\n list_display = ('get_author',)\n def get_queryset(self, request):\n queryset = super().get_queryset(request)\n queryset = queryset.annotate(\n _author = F('book__author')\n )\n return queryset\n\n @admin.display(ordering='_author', description='Author')\n def get_author(self, obj):\n return obj._author\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10040/"
] |
163,834
|
<p>What's the most elegant templating (preferably in pure PHP!) solution you've seen?</p>
<p>Specifically i'm interested in handling:</p>
<ol>
<li>Detecting in a repeating block whether it's the first or last element</li>
<li>Easy handling of odd/even cases, like a zebra striped table, or similar</li>
<li>Other modulos logic, where you'd do something every n'th time.</li>
</ol>
<p>I'm looking for something that makes this less of a pain:</p>
<pre><code><?php
$persons = array('John', 'Jack', 'Jill', 'Jason');
?>
<?php $i = 0; ?>
<?php if (isset($persons)): ?>
<ul>
<?php foreach ($persons as $name): ?>
<li class="<?= ($i++ % 2 === 0) ? 'odd' : 'even' ?>"><?= $name ?></li>
<?php endforeach ?>
</ul>
<?php endif ?>
</code></pre>
<p>Does it really take the mess above to create something like this below?</p>
<pre><code><ul>
<li class="odd">John</li>
<li class="even">Jack</li>
<li class="odd">Jill</li>
<li class="even">Jason</li>
</ul>
</code></pre>
<p>Is it only me that find the above near hideous? </p>
<p>All those starting and closing of php-tags makes me cringe.</p>
|
[
{
"answer_id": 163860,
"author": "Cruachan",
"author_id": 7315,
"author_profile": "https://Stackoverflow.com/users/7315",
"pm_score": 3,
"selected": false,
"text": "$TBS->MergeBlock('blk1',$sqlconnect, \"SELECT name from people \");\n <ul>\n <li class=\"odd\">[blk.name;block=ul]</li>\n <li class=\"even\">[blk.name;block=ul]</li>\n</ul>\n <ul>\n <li class=\"linestyle1\">[blk.name;block=ul]</li>\n <li class=\"linestyle2\">[blk.name;block=ul]</li>\n <li class=\"linestyle3\">[blk.name;block=ul]</li>\n</ul>\n"
},
{
"answer_id": 163894,
"author": "fijter",
"author_id": 3215,
"author_profile": "https://Stackoverflow.com/users/3215",
"pm_score": 2,
"selected": false,
"text": "\n<ul>\n{foreach from=$var name=loop item=test}\n {if $smarty.foreach.loop.first}<li>This is the first item</li>{/if}\n <li class=\"{cycle values=\"odd,even\"}\">{$var.name}</li>\n {if $smarty.foreach.loop.last}<li>This was the last item</li>{/if}\n{/foreach}\n</ul>\n"
},
{
"answer_id": 164172,
"author": "Randy",
"author_id": 9361,
"author_profile": "https://Stackoverflow.com/users/9361",
"pm_score": 4,
"selected": false,
"text": "<?php\nfunction makeul($items, $classes) {\n $c = count($classes);\n $out = \"\";\n\n if (isset($items) && count($items) > 0) {\n $out = \"<ul>\\n\";\n foreach ($items as $item) {\n $out .= \"\\t<li class=\\\"\" . $classes[$i++%$c] . \"\\\">$item</li>\\n\";\n }\n $out .= \"</ul>\\n\";\n }\n return $out;\n}\n?>\n\nother page content\n\n<?php\n$persons = array('John', 'Jack', 'Jill', 'Jason');\n$classes = array('odd', 'even');\nprint makeul($persons, $classes);\n?>\n $(\"tr:odd\").addClass(\"odd\");\n$(\"tr:even\").addClass(\"even\");\n"
},
{
"answer_id": 1004554,
"author": "gahooa",
"author_id": 64004,
"author_profile": "https://Stackoverflow.com/users/64004",
"pm_score": 3,
"selected": false,
"text": "<? $b=false; foreach($MyList as $name) { ?>\n <li class=\"row<?= $b=!$b ?>\"><?= htmlspecialchars($name); ?></li>\n<? } ?>\n $b=!$b row row1 :first-child"
},
{
"answer_id": 1053303,
"author": "Erik",
"author_id": 129877,
"author_profile": "https://Stackoverflow.com/users/129877",
"pm_score": 0,
"selected": false,
"text": "<?= ($i++ % 2 === 0) ? 'odd' : 'even' ?>\n"
},
{
"answer_id": 1826238,
"author": "Meep3D",
"author_id": 130417,
"author_profile": "https://Stackoverflow.com/users/130417",
"pm_score": 0,
"selected": false,
"text": "<p>Main Menu</p>\n<ul>\n{block:menu_items}\n <li><a href=\"{var:link}\">{var:name}</a></li>\n{/block:menu_items}\n</ul>\n array (\n 'menu_items' => array (\n array (\n 'link' => 'home.htm',\n 'name' => 'Home'\n ),\n array (\n 'link' => 'about.htm',\n 'name' => 'About Us'\n ),\n array (\n 'link' => 'portfolio.htm',\n 'name' => 'Portfolio'\n ),\n array (\n 'link' => 'contact.htm',\n 'name' => 'Contact Us'\n )\n )\n);\n <p>Main Menu</p>\n<ul>\n <li><a href=\"home.htm\">Home</a></li>\n <li><a href=\"about.htm\">About Us</a></li>\n <li><a href=\"portfolio.htm\">Portfolio</a></li>\n <li><a href=\"contact.htm\">Contact Us</a></li>\n</ul>\n"
},
{
"answer_id": 16573170,
"author": "Angie Rabelero",
"author_id": 1306041,
"author_profile": "https://Stackoverflow.com/users/1306041",
"pm_score": 1,
"selected": false,
"text": "enter code here"
},
{
"answer_id": 18478585,
"author": "Dave C",
"author_id": 1664439,
"author_profile": "https://Stackoverflow.com/users/1664439",
"pm_score": 0,
"selected": false,
"text": "<?php\n define ('CRLF', \"\\r\\n\");\n $persons = array('John', 'Jack', 'Jill', 'Jason');\n\n $color = 'white'; // Init $color for striped list\n $ho = '<UL>' . CRLF; // Start HTML Output variable\n foreach ($persons as $name)\n {\n $ho .= ' <li class=\"' . $color . '\">' . $name . '</li>' . CRLF;\n $color = ($color == 'white') ? 'grey' : 'white'; // if white, make it grey else white\n }\n $ho .= '</ul>' . CRLF;\n echo $ho;\n?>\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20538/"
] |
163,837
|
<p>I'm involved in building a donation form for non-profits. We recently got hit by a fast round of low dollar submissions. Many were invalid cards, but a few went through. Obviously someone wrote a script to check a bunch of card numbers for validity, possibly so they can sell them later.</p>
<p>Any ideas on how to prevent or limit the impact of this in the future?</p>
<p>We have control over all aspects of the system (code, webserver, etc). Yes the form runs over https.</p>
|
[
{
"answer_id": 1160012,
"author": "tomjen",
"author_id": 21133,
"author_profile": "https://Stackoverflow.com/users/21133",
"pm_score": 2,
"selected": false,
"text": "<noscript>"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3756/"
] |
163,887
|
<p>Suppose I have a "tags" table with two columns: <strong>tagid</strong> and <strong>contentid</strong>. Each row represents a tag assigned to a piece of content. I want a query that will give me the contentid of every piece of content which is tagged with tagids 334, 338, and 342.</p>
<p>The "easy" way to do this would be (<em>pseudocode</em>):</p>
<pre><code>select contentid from tags where tagid = 334 and contentid in (
select contentid from tags where tagid = 338 and contentid in (
select contentid from tags where tagid = 342
)
)
</code></pre>
<p>However, my gut tells me that there's a better, faster, more extensible way to do this. For example, what if I needed to find the intersection of 12 tags? This could quickly get horrendous. Any ideas?</p>
<p><strong>EDIT</strong>: Turns out that this is also covered in <a href="http://weblogs.sqlteam.com/jeffs/jeffs/archive/2007/06/12/60230.aspx" rel="noreferrer">this excellent blog post</a>.</p>
|
[
{
"answer_id": 163902,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 1,
"selected": false,
"text": "select a.contentid from tags a\ninner join tags b on a.contentid = b.contentid and b.tagid=334\ninner join tags c on a.contentid = c.contentid and c.tagid=342\nwhere a.tagid=338\n"
},
{
"answer_id": 163907,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 6,
"selected": true,
"text": "SELECT contentID\nFROM tags\nWHERE tagID in (334, 338, 342)\nGROUP BY contentID\nHAVING COUNT(DISTINCT tagID) = 3\n\n\n--In general\nSELECT contentID\nFROM tags\nWHERE tagID in (...) --taglist\nGROUP BY contentID\nHAVING COUNT(DISTINCT tagID) = ... --tagcount\n"
},
{
"answer_id": 163910,
"author": "Meff",
"author_id": 9647,
"author_profile": "https://Stackoverflow.com/users/9647",
"pm_score": -1,
"selected": false,
"text": "select contentid from tags where tagid IN (334,338,342)\n"
},
{
"answer_id": 163927,
"author": "Bob Probst",
"author_id": 12424,
"author_profile": "https://Stackoverflow.com/users/12424",
"pm_score": 0,
"selected": false,
"text": "select contentid from tags where tagid = 334\nintersect\nselect contentid from tags where tagid = 338\nintersect\nselect contentid from tags where tagid = 342\n"
},
{
"answer_id": 304314,
"author": "adrian",
"author_id": 39182,
"author_profile": "https://Stackoverflow.com/users/39182",
"pm_score": 2,
"selected": false,
"text": "objtags WHERE SELECT w0.objid\n\nFROM objtags t0\nINNER JOIN objtags t1 ON t1.objid=t0.objid\nINNER JOIN objtags t2 ON t2.objid=t1.objid\n\nWHERE t0.tagid=512\n AND t1.tagid=256\n AND t2.tagid=128\n HAVING COUNT(...)"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16034/"
] |
163,900
|
<p>I'm putting together a little tool that some business people can run on their local filesystems, since we don't want to setup a host for it.</p>
<p>Basically, its just HTML + Javascript (using jQuery) to pull some reports using REST from a 3rd party.</p>
<p>The problem is, FF3 and IE don't allow the ajax call, I get:</p>
<pre><code>Access to restricted URI denied" code: "1012
</code></pre>
<p>Obviously its an XSS issue...how do I work around it? The data returned is in XML format.</p>
<p>I was trying to do it this way:</p>
<pre><code>$.get(productUrl, function (data){
alert (data);
});
</code></pre>
<p><strong>EDIT</strong>: To be clear...I'm not setting up an internal host for this(Way to much red tape), and we CANNOT host this externally due to the data being retrieved.</p>
<p><strong>EDIT #2</strong>: A little testing shows that I can use an IFRAME to make the request. Does anyone know if there any downsides to using a hidden IFRAME?</p>
|
[
{
"answer_id": 163950,
"author": "Greg",
"author_id": 13009,
"author_profile": "https://Stackoverflow.com/users/13009",
"pm_score": -1,
"selected": false,
"text": "python -c “import SimpleHTTPServer;SimpleHTTPServer.test()”\n"
},
{
"answer_id": 166502,
"author": "Morgan ARR Allen",
"author_id": 22474,
"author_profile": "https://Stackoverflow.com/users/22474",
"pm_score": -1,
"selected": false,
"text": "<script>\n function callback(str) {\n alert(str);\n }\n function makeRequest(param) {\n var s = document.createElement('script');\n s.src = 'http://serveranywhere/script.bla?' + params;\n document.getElementsByTagName[0].appendChild(s);\n }\n</script>\n callback('<xml><that><does><something></something></does></that></xml>');\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
163,917
|
<p>I have never clearly understood the usage of <code>MAXDOP</code>. I do know that it makes the query faster and that it is the last item that I can use for Query Optimization.</p>
<p>However, my question is, when and where it is best suited to use in a query?</p>
|
[
{
"answer_id": 167435,
"author": "Jeremiah Peschka",
"author_id": 11780,
"author_profile": "https://Stackoverflow.com/users/11780",
"pm_score": 5,
"selected": false,
"text": "MAXDOP(n) OPTION (FORCE ORDER) OPTION (FORCE PLAN) MAXDOP MAXDOP MAXDOP(8) MAXDOP"
},
{
"answer_id": 36506677,
"author": "LCJ",
"author_id": 696627,
"author_profile": "https://Stackoverflow.com/users/696627",
"pm_score": 0,
"selected": false,
"text": "CTFP max server memory CTFP"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21968/"
] |
163,938
|
<p>How many bytes would an int contain and how many would a long contain?</p>
<p>Context:</p>
<ul>
<li>C++</li>
<li>32 bit computer</li>
<li>Any difference on a 64-bit computer?</li>
</ul>
|
[
{
"answer_id": 163976,
"author": "Dave Turvey",
"author_id": 18966,
"author_profile": "https://Stackoverflow.com/users/18966",
"pm_score": 1,
"selected": false,
"text": "int intBytes;\nlong longBytes;\nintBytes= sizeof(int);\nlongBytes = sizeof(long);\n"
},
{
"answer_id": 164013,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 2,
"selected": false,
"text": "MUST sizeof(int) != sizeof(void*)\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
163,957
|
<p>I know that you can do this in SQL Server 2005, but I'm at a loss for 2000.</p>
|
[
{
"answer_id": 166421,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 0,
"selected": false,
"text": "SELECT crdate\nFROM sysobjects \nWHERE name = 'proc name here' \nAND type = 'P' \n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24602/"
] |
163,962
|
<p>Up until now I have been using std::string in my C++ applications for embedded system (routers, switches, telco gear, etc.).</p>
<p>For the next project, I am considering to switch from std::string to std::wstring for Unicode support. This would, for example, allow end-users to use Chinese characters in the command line interface (CLI).</p>
<p>What complications / headaches / surprises should I expect? What, for example, if I use a third-party library which still uses std::string?</p>
<p>Since support for international strings isn't that strong of a requirement for the type of embedded systems that I work on, I would only do it if it isn't going to cause major headaches.</p>
|
[
{
"answer_id": 166421,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 0,
"selected": false,
"text": "SELECT crdate\nFROM sysobjects \nWHERE name = 'proc name here' \nAND type = 'P' \n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21435/"
] |
163,994
|
<p>I have a very large table (8gb) with information about files, and i need to run a report against it that would would look something like this:</p>
<pre><code>(select * from fs_walk_scan where file_path like '\\\\server1\\groot$\\%' order by file_size desc limit 0,30)
UNION ALL
(select * from fs_walk_scan where file_path like '\\\\server1\\hroot$\\%' order by file_size desc limit 0,30)
UNION ALL
(select * from fs_walk_scan where file_path like '\\\\server1\\iroot$\\%' order by file_size desc limit 0,30)
UNION ALL
(select * from fs_walk_scan where file_path like '\\\\server2\\froot$\\%' order by file_size desc limit 0,30)
UNION ALL
(select * from fs_walk_scan where file_path like '\\\\server2\\groot$\\%' order by file_size desc limit 0,30)
UNION ALL
(select * from fs_walk_scan where file_path like '\\\\server3\\hroot$\\%' order by file_size desc limit 0,30)
UNION ALL
(select * from fs_walk_scan where file_path like '\\\\server4\\iroot$\\%' order by file_size desc limit 0,30)
UNION ALL
(select * from fs_walk_scan where file_path like '\\\\server5\\iroot$\\%' order by file_size desc limit 0,30)
[...]
order by substring_index(file_path,'\\',4), file_size desc
</code></pre>
<p>This method accomplishes what I need to do: Get a list of the 30 biggest files for each volume. However, this is deathly slow, and the 'like' searches are hardcoded even though they are sitting in another table and can be gotten that way.</p>
<p>What I'm looking for is a way to do this without going through the huge table several times. Anyone have any ideas?</p>
<p>Thanks.</p>
<p>P.S. I cant change the structure of the huge source table in any way.</p>
<p>Update: There are indexes on file_path and file_size, but each one of those sub(?)queries still takes about 10 mins, and I have to do 22 minimum.</p>
|
[
{
"answer_id": 164009,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "select * from fs_walk_scan where file_path like '\\\\\\\\server' and file_path like 'root$\\\\%' order by file_size desc \n"
},
{
"answer_id": 164322,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 2,
"selected": false,
"text": "select * from fs_walk_scan\n where file_path regexp '^\\\\\\\\server(1\\\\[ghi]|2\\\\[fg]|3\\\\h|[45]\\\\i)root$\\\\'\n select * from fs_walk_scan\n where server = 'server1' and base_path in ('groot$', 'hroot$', 'iroot$')\n or server = 'server2' and base_path in ('froot$', 'groot$')\n"
},
{
"answer_id": 164910,
"author": "bobwienholt",
"author_id": 24257,
"author_profile": "https://Stackoverflow.com/users/24257",
"pm_score": 1,
"selected": false,
"text": "DELIMITER $$\n\nDROP PROCEDURE IF EXISTS `test`.`proc_fs_search` $$\nCREATE PROCEDURE `test`.`proc_fs_search` ()\nBEGIN\n\nDECLARE cur_path VARCHAR(255);\nDECLARE done INT DEFAULT 0;\n\n\nDECLARE list_cursor CURSOR FOR select file_path from fs_list;\n\nDECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;\n\nSET @sql_query = '';\n\nOPEN list_cursor;\n\nREPEAT\n FETCH list_cursor INTO cur_path;\n\n IF NOT done THEN\n IF @sql_query <> '' THEN\n SET @sql_query = CONCAT(@sql_query, ' UNION ALL ');\n END IF;\n\n SET @sql_query = CONCAT(@sql_query, ' (select * from fs_walk_scan where file_path like ''', cur_path , ''' order by file_size desc limit 0,30)');\n END IF;\n\nUNTIL done END REPEAT;\n\nSET @sql_query = CONCAT(@sql_query, ' order by file_path, file_size desc');\n\nPREPARE stmt FROM @sql_query;\nEXECUTE stmt;\nDEALLOCATE PREPARE stmt;\n\nEND $$\n\nDELIMITER ;\n"
},
{
"answer_id": 166408,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 1,
"selected": false,
"text": "SELECT * \nFROM fs_walk_scan a\nWHERE ( SELECT COUNT(*) \n FROM fs_walk_scan b \n WHERE b.file_size > a.file_size \n AND b.file_path = a.file_path\n ) < 30\n SELECT DISTINCT file_path\nINTO tmp1\nFROM fs_walk_scan a\n\nDECLARE path VARCHAR(255);\n\nSELECT MIN(file_path)\nINTO path\nFROM tmp1 \n\nWHILE path IS NOT NULL DO\n SELECT * \n FROM fs_walk_scan\n WHERE file_path = path\n ORDER BY file_size DESC\n LIMIT 0,30\n\n SELECT MIN(file_path)\n INTO path\n FROM tmp1\n WHERE file_path > path \nEND WHILE\n"
},
{
"answer_id": 7134821,
"author": "Lambs",
"author_id": 837416,
"author_profile": "https://Stackoverflow.com/users/837416",
"pm_score": 0,
"selected": false,
"text": "SELECT substring_index(file_path, '\\\\', 4), file_path\nfrom fs_walk_scan as ws1\nWHERE 30<= (\nselect count(*) from fs_Walk_scan as ws2\nwhere substring_index(ws2.file_path, '\\\\', 4) = substring_index(ws1.file_path, '\\\\', 4)\nand ws2.file_size > ws1.file_size\nand ws2.file_path <> ws1.file_path)\ngroup by substring_index(file_path, '\\\\', 4)\n set @idx=0; set @cur_vol=0; \nSELECT file_volume, file_path, file_size FROM (\n SELECT file_volume, file_path, file_size,\n IF(@cur_vol != a.file_volume, @idx:=1, @idx:=@idx+1) AS row_index,\n IF(@cur_vol != a.file_volume, @cur_vol:=a.file_volume, 0) AS discard\n FROM (SELECT substring_index(file_path, '\\\\', 4) as file_volume, file_path, file_size \n FROM fs_walk_scan\n ORDER BY substring_index(file_path,'\\\\',4), file_size DESC) AS a\n HAVING row_index <= 30) AS b;\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17785/"
] |
163,998
|
<p>Is there any built-in functionality for classical set operations on the java.util.Collection class? My specific implementation would be for ArrayList, but this sounds like something that should apply for all subclasses of Collection. I'm looking for something like:</p>
<pre><code>ArrayList<Integer> setA ...
ArrayList<Integer> setB ...
ArrayList<Integer> setAintersectionB = setA.intersection(setB);
ArrayList<Integer> setAminusB = setA.subtract(setB);
</code></pre>
<p>After some searching, I was only able to find home-grown solutions. Also, I realize I may be confusing the idea of a "Set" with the idea of a "Collection", not allowing and allowing duplicates respectively. Perhaps this is really just functionality for the Set interface?</p>
<p>In the event that nobody knows of any built-in functionality, perhaps we could use this as a repository for standard practice Java set operation code? I imagine this wheel has been reinvented numerous times.</p>
|
[
{
"answer_id": 164145,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 8,
"selected": true,
"text": "Collection.retainAll Collection.removeAll Collection.addAll Set List"
},
{
"answer_id": 34439881,
"author": "mhstnsc",
"author_id": 736533,
"author_profile": "https://Stackoverflow.com/users/736533",
"pm_score": 3,
"selected": false,
"text": "set1\n .stream()\n .filter(item-> !set2.contains(item))\n .collect(Collectors.toSet())\n set1\n .stream()\n .filter(item-> set2.contains(item))\n .collect(Collectors.toSet())\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/163998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19147/"
] |
164,002
|
<p>I am writing a C library that reads a file into memory. It skips the first 54 bytes of the file (header) and then reads the remainder as data. I use fseek to determine the length of the file, and then use fread to read in the file.</p>
<p>The loop runs once and then ends because the EOF is reached (no errors). At the end, bytesRead = 10624, ftell(stream) = 28726, and the buffer contains 28726 values. I expect fread to read 30,000 bytes and the file position to be 30054 when EOF is reached.</p>
<p>C is not my native language so I suspect I've got a dumb beginner mistake somewhere.</p>
<p>Code is as follows:</p>
<pre><code>const size_t headerLen = 54;
FILE * stream;
errno_t ferrno = fopen_s( &stream, filename.c_str(), "r" );
if(ferrno!=0) {
return -1;
}
fseek( stream, 0L, SEEK_END );
size_t bytesTotal = (size_t)(ftell( stream )) - headerLen; //number of data bytes to read
size_t bytesRead = 0;
BYTE* localBuffer = new BYTE[bytesTotal];
fseek(stream,headerLen,SEEK_SET);
while(!feof(stream) && !ferror(stream)) {
size_t result = fread(localBuffer+bytesRead,sizeof(BYTE),bytesTotal-bytesRead,stream);
bytesRead+=result;
}
</code></pre>
<hr>
<p>Depending on the reference you use, it's quite apparent that adding a "b" to the mode flag is the answer. Seeking nominations for the bonehead-badge. :-)</p>
<p><a href="http://www.cplusplus.com/reference/clibrary/cstdio/fopen.html" rel="noreferrer">This reference</a> talks about it in the second paragraph, second sentence (though not in their table).</p>
<p><a href="http://msdn.microsoft.com/en-us/library/z5hh6ee9(VS.80).aspx" rel="noreferrer">MSDN</a> doesn't discuss the binary flag until halfway down the page.</p>
<p><a href="http://www.opengroup.org/onlinepubs/009695399/functions/fopen.html" rel="noreferrer">OpenGroup</a> mentions the existance of the "b" tag, but states that it "shall have no effect".</p>
|
[
{
"answer_id": 164012,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 7,
"selected": true,
"text": "\"r+b\" \"rb\" \"r+b\" \"rb\""
},
{
"answer_id": 24431357,
"author": "Kumar Pushkar",
"author_id": 3779460,
"author_profile": "https://Stackoverflow.com/users/3779460",
"pm_score": -1,
"selected": false,
"text": " size_t bytesRead = 0;\n BYTE* localBuffer = new BYTE[bytesTotal];\n fseek(stream,headerLen,SEEK_SET);\n while(!feof(stream) && !ferror(stream)) {\n size_t result = fread(localBuffer+bytesRead,sizeof(BYTE),bytesTotal-\n bytesRead,stream);\n bytesRead+=result;\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17871/"
] |
164,008
|
<p>Is there a connection limit on Sql Server 2005 Developers Edition. We have many threads grabbing connections, and I know ADO.NET does connection pooling, but I get OutOfMemory exceptions. We take out the db connections and it works fine. </p>
|
[
{
"answer_id": 164016,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 2,
"selected": false,
"text": "using (SqlConnection conn = new SqlConnection(\"connectionstring\"))\n{\n conn.Open();\n\n // database access code goes here\n}\n"
},
{
"answer_id": 164123,
"author": "6eorge Jetson",
"author_id": 23422,
"author_profile": "https://Stackoverflow.com/users/23422",
"pm_score": 2,
"selected": false,
"text": "-- Declare the return variable here\nDECLARE @ResultVar xml\n\n-- Add the T-SQL statements to compute the return value here\nSET @ResultVar =\n (\n SELECT \n @@SPID as SPID,\n @@ProcID as ProcId,\n @@DBTS as DBTS,\n getdate() as DateTimeStamp,\n System_User as SystemUser,\n Current_User as CurrentUser,\n Session_User as SessionUser,\n User_Name() as UserName,\n Permissions() as UserSessionPermissionsBitmap,\n Host_Id() as HostId,\n Host_Name() as HostName,\n App_Name() as AppName,\n\n ServerProperty('ProcessId') as ServerProcessId,\n ServerProperty('MachineName') as ServerMachineName,\n ServerProperty('ServerName') as ServerServerName,\n ServerProperty('ComputerNamePhysicalNetBIOS') as ServerComputerNamePhysicalNetBIOS,\n ServerProperty('InstanceName') as ServerInstanceName,\n ServerProperty('ProductVersion') as ServerProductVersion,\n ServerProperty('ProductLevel') as ServerProductLevel,\n\n @@CONNECTIONS as CumulativeSqlConnectionsSinceStartup,\n @@TOTAL_ERRORS as CumulativeDiskWriteErrorsSinceStartup,\n @@PACKET_ERRORS as CumulativeNetworkPacketErrorsSinceStartup,\n\n --Note: \n --If the time returned in @@CPU_BUSY, or @@IO_BUSY exceeds approximately 49 days of cumulative CPU time, \n --you receive an arithmetic overflow warning. In that case, \n --the value of @@CPU_BUSY, @@IO_BUSY and @@IDLE variables are not accurate. \n -- @@CPU_BUSY * @@TIMETICKS as CumulativeMicroSecondsServerCpuBusyTimeSinceStartup,\n -- @@IO_BUSY * @@TIMETICKS as CumulativeMicroSecondsServerIoBusyTimeSinceStartup,\n -- @@IDLE * @@TIMETICKS as CumulativeMicroSecondsServerIdleTimeSinceStartup,\n\n ServerProperty('BuildClrVersion') as ServerBuildClrVersion,\n ServerProperty('Collation') as ServerCollation,\n ServerProperty('CollationID') as ServerCollationId,\n ServerProperty('ComparisonStyle') as ServerComparisonStyle,\n ServerProperty('Edition') as ServerEdition,\n ServerProperty('EditionID') as ServerEditionID,\n ServerProperty('EngineEdition') as ServerEngineEdition,\n ServerProperty('IsClustered') as ServerIsClustered,\n ServerProperty('IsFullTextInstalled') as ServerIsFullTextInstalled,\n ServerProperty('IsIntegratedSecurityOnly') as ServerIsIntegratedSecurityOnly,\n ServerProperty('IsSingleUser') as ServerIsSingleUser,\n ServerProperty('LCID') as ServerLCID,\n ServerProperty('LicenseType') as ServerLicenseType,\n ServerProperty('NumLicenses') as ServerNumLicenses,\n ServerProperty('ResourceLastUpdateDateTime') as ServerResourceLastUpdateDateTime,\n ServerProperty('ResourceVersion') as ServerResourceVersion,\n ServerProperty('SqlCharSet') as ServerSqlCharSet,\n ServerProperty('SqlCharSetName') as ServerSqlCharSetName,\n ServerProperty('SqlSortOrder') as ServerSqlSortOrder,\n ServerProperty('SqlSortOrderName') as ServerSqlSortOrderName,\n\n @@MAX_CONNECTIONS as MaxAllowedConcurrentSqlConnections,\n\n SessionProperty('ANSI_NULLS') as SessionANSI_NULLS,\n SessionProperty('ANSI_PADDING') as SessionANSI_PADDING,\n SessionProperty('ANSI_WARNINGS') as SessionANSI_WARNINGS,\n SessionProperty('ARITHABORT') as SessionARITHABORT,\n SessionProperty('CONCAT_NULL_YIELDS_NULL') as SessionCONCAT_NULL_YIELDS_NULL,\n SessionProperty('NUMERIC_ROUNDABORT') as SessionNUMERIC_ROUNDABORT,\n SessionProperty('QUOTED_IDENTIFIER') as SessionQUOTED_IDENTIFIER\n FOR XML PATH('SequenceIdEnvironment')\n ) \n-- Return the result of the function\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11907/"
] |
164,026
|
<p>I'd like to make sure that a thread is moved to a specific CPU core and can never be moved from it by the scheduler.</p>
<p>There's a <code>SetThreadAffinityMask()</code> call but there's no <code>GetThreadAffinityMask()</code>.</p>
<p>The reason I need this is because high resolution timers will get messed up if the scheduler moves that thread to another CPU.</p>
|
[
{
"answer_id": 165641,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 2,
"selected": false,
"text": "SetThreadAffinityMask() RDTSC RDTSC QueryPerformanceCounter() QueryPerformanceCounter() QueryPerformanceCounter() RDTSC RDTSC QueryPerformanceCounter()"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841/"
] |
164,039
|
<p>How can I dock a CControlBar derived window to the middle of a splitter window (CSplitterWnd)? I would like the bar to be repositioned whenever the splitter is moved.</p>
<p>To make it a little clearer as to what I'm after, imagine the vertical ruler in the Dialog Editor in Visual Studio (MFC only). It gets repositioned whenever the tree view is resized.</p>
|
[
{
"answer_id": 169239,
"author": "Alf Zimmerman",
"author_id": 24612,
"author_profile": "https://Stackoverflow.com/users/24612",
"pm_score": 0,
"selected": false,
"text": "m_wndSplitter.CreateStatic(this, 1, 3);\n\nm_wndLeftPane.Create(&m_wndSplitter,WS_CHILD|WS_VISIBLE,m_wndSplitter.IdFromRowCol(0, 0));\nm_ruler.Create(&m_wndSplitter,WS_CHILD|WS_VISIBLE,m_wndSplitter.IdFromRowCol(0, 1));\n\nm_wndSplitter.CreateView(0, 2, pContext->m_pNewViewClass, CSize(300, 0), pContext);\nSetActiveView((CScrollView*)m_wndSplitter.GetDlgItem(m_wndSplitter.IdFromRowCol(0, 2)));\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24612/"
] |
164,048
|
<p>I'm about to start (with fellow programmers) a programming & algorithms club in my high school. The language of choice is C++ - sorry about that, I can't change this. We can assume students have little to no experience in the aforementioned topics.</p>
<p>What do you think are the most basic concepts I should focus on?</p>
<p>I know that teaching something that's already obvious to me isn't an easy task. I realize that the very first meeting should be given an extreme attention - to not scare students away - hence I ask you.</p>
<p><strong>Edit:</strong> I noticed that probably the main difference between programmers and beginners is "programmer's way of thinking" - I mean, conceptualizing problems as, you know, algorithms. I know it's just a matter of practice, but do you know any kind of exercises/concepts/things that could stimulate development in this area?</p>
|
[
{
"answer_id": 164470,
"author": "m_pGladiator",
"author_id": 446104,
"author_profile": "https://Stackoverflow.com/users/446104",
"pm_score": 1,
"selected": false,
"text": "1) Go to the Fridge \n2) Open the fridge door \n3) Search for eggs \n4) If there are no eggs - go to the shop to buy eggs ( this is another function ;) ) \n5) If there are eggs - calculate how many do you need to fry \n6) Close the fridge door \n7) e.t.c. :)\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19082/"
] |
164,053
|
<p>Should log classes open/close a log file stream on each write to the log file or should it keep the log file stream open throughout the application's lifetime until all logging is complete? </p>
<p>I'm asking in context of a desktop application. I have seen people do it both ways and was wondering which approach yields the best all-around results for a logger.</p>
|
[
{
"answer_id": 164770,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 4,
"selected": false,
"text": "fstat() st_nlink stat() open() fstat() O_SYNC O_DSYNC open() fflush() write() flockfile() dprintf() dprintf() write() writev() int fd = open(\"/some/file\", O_WRITE|O_CREATE|O_TRUNC, 0444);\nlseek(fd, 1024L * 1024L * 1024L, 0);\nwrite(fd, \"hi\", 2);\nclose(fd);\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20133/"
] |
164,073
|
<p>I've been thinking about this problem for a while and have yet to come up with any stable/elegant ideas.</p>
<p>I know with MyISAM tables, you can get the table def update time but thats not so true with InnoDB and I've found its not even reliable to look at the .frm file for an idea of when the definition might have been modified.... nevermind if the dataset has been changed.</p>
<p>I had an idea of every 30 minutes mysqldumping the contents of a schema, breaking that apart with an AWK script, then diffing that to the last version... but that seems a little excessive and could be a problem if the dataset involved is large.</p>
|
[
{
"answer_id": 164318,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 2,
"selected": false,
"text": "mysqldump -d [gary.richardson@server ~]$ mysqldump -d -u root mysql user\n-- MySQL dump 10.11\n--\n-- Host: localhost Database: mysql\n-- ------------------------------------------------------\n-- Server version 5.0.45\n\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n/*!40101 SET NAMES utf8 */;\n/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;\n/*!40103 SET TIME_ZONE='+00:00' */;\n/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;\n/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;\n/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;\n/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;\n\n--\n-- Table structure for table `user`\n--\n\nDROP TABLE IF EXISTS `user`;\nCREATE TABLE `user` (\n `Host` char(60) collate utf8_bin NOT NULL default '',\n `User` char(16) collate utf8_bin NOT NULL default '',\n `Password` char(41) character set latin1 collate latin1_bin NOT NULL default '',\n `Select_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Insert_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Update_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Delete_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Create_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Drop_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Reload_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Shutdown_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Process_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `File_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Grant_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `References_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Index_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Alter_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Show_db_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Super_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Create_tmp_table_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Lock_tables_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Execute_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Repl_slave_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Repl_client_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Create_view_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Show_view_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Create_routine_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Alter_routine_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `Create_user_priv` enum('N','Y') character set utf8 NOT NULL default 'N',\n `ssl_type` enum('','ANY','X509','SPECIFIED') character set utf8 NOT NULL default '',\n `ssl_cipher` blob NOT NULL,\n `x509_issuer` blob NOT NULL,\n `x509_subject` blob NOT NULL,\n `max_questions` int(11) unsigned NOT NULL default '0',\n `max_updates` int(11) unsigned NOT NULL default '0',\n `max_connections` int(11) unsigned NOT NULL default '0',\n `max_user_connections` int(11) unsigned NOT NULL default '0',\n PRIMARY KEY (`Host`,`User`)\n) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Users and global privileges';\n/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;\n\n/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;\n/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;\n/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;\n\n-- Dump completed on 2008-10-02 20:06:38\n CREATE TABLE example (\n name varchar(32) COMMENT='Name of a person'\n) COMMENT='example table';\n CREATE TABLE example (\n name varchar(32) COMMENT='Name of a person'\n) COMMENT='VERSION=1.2.3 example table';\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9908/"
] |
164,085
|
<p>I need to execute a callback when an IFRAME has finished loading. I have no control over the content in the IFRAME, so I can't fire the callback from there.</p>
<p>This IFRAME is programmaticly created, and I need to pass its data as a variable in the callback, as well as destroy the iframe.</p>
<p>Any ideas?</p>
<p><strong>EDIT:</strong></p>
<p>Here is what I have now:</p>
<pre><code>function xssRequest(url, callback)
{
var iFrameObj = document.createElement('IFRAME');
iFrameObj.src = url;
document.body.appendChild(iFrameObj);
$(iFrameObj).load(function()
{
document.body.removeChild(iFrameObj);
callback(iFrameObj.innerHTML);
});
}
</code></pre>
<p>This callsback before the iFrame has loaded, so the callback has no data returned.</p>
|
[
{
"answer_id": 204781,
"author": "Pier Luigi",
"author_id": 27789,
"author_profile": "https://Stackoverflow.com/users/27789",
"pm_score": 1,
"selected": false,
"text": "function xssRequest(url, callback)\n{\n var iFrameObj = document.createElement('IFRAME');\n iFrameObj.id = 'myUniqueID';\n document.body.appendChild(iFrameObj); \n iFrameObj.src = url; \n\n $(iFrameObj).load(function() \n {\n callback(window['myUniqueID'].document.body.innerHTML);\n document.body.removeChild(iFrameObj);\n });\n}\n"
},
{
"answer_id": 209723,
"author": "Remy Sharp",
"author_id": 22617,
"author_profile": "https://Stackoverflow.com/users/22617",
"pm_score": 6,
"selected": false,
"text": "// possibly excessive use of jQuery - but I've got a live working example in production\n$('#myUniqueID').load(function () {\n if (typeof callback == 'function') {\n callback($('body', this.contentWindow.document).html());\n }\n setTimeout(function () {$('#frameId').remove();}, 50);\n});\n"
},
{
"answer_id": 342991,
"author": "Ryan Cook",
"author_id": 43029,
"author_profile": "https://Stackoverflow.com/users/43029",
"pm_score": 3,
"selected": false,
"text": "onreadystatechanged document.getElementById('myIframe').onreadystatechange = MyIframeReadyStateChanged;\n function MyIframeReadyStateChanged()\n{\n if(document.getElementById('myIframe').readyState == 'complete')\n {\n // Do your complete stuff here.\n }\n}\n"
},
{
"answer_id": 1328303,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "iFrameObj.contentDocument $(childDom).html() $(childDom).find('some selector') ..."
},
{
"answer_id": 2251109,
"author": "allyourcode",
"author_id": 62163,
"author_profile": "https://Stackoverflow.com/users/62163",
"pm_score": 3,
"selected": false,
"text": "<script src=\"http://prototypejs.org/assets/2009/8/31/prototype.js\" type=\"text/javascript\"></script>\n\n<h1>Parent</h1>\n\n<script type=\"text/javascript\">\nfunction on_load(iframe) {\n try {\n // Displays the first 50 chars in the innerHTML of the\n // body of the page that the iframe is showing.\n // EDIT 2012-04-17: for wider support, fallback to contentWindow.document\n var doc = iframe.contentDocument || iframe.contentWindow.document;\n alert(doc.body.innerHTML.substring(0, 50));\n } catch (e) {\n // This can happen if the src of the iframe is\n // on another domain\n alert('exception: ' + e);\n }\n}\n</script>\n<iframe id=\"child\" src=\"iframe_content.html\" onload=\"on_load(this)\"></iframe>\n <h1>Child</h1>\n\n<a href=\"http://www.google.com/\">Google</a>\n\n<p>Use the preceeding link to change the src of the iframe\nto see what happens when the src domain is different from\nthat of the parent page</p>\n"
},
{
"answer_id": 7370519,
"author": "Automatico",
"author_id": 741850,
"author_profile": "https://Stackoverflow.com/users/741850",
"pm_score": 2,
"selected": false,
"text": "$(function(){ //this is regular jQuery code. It waits for the dom to load fully the first time you open the page.\n\n $(\"#myIframeId\").load(function(){\n callback($(\"#myIframeId\").html());\n $(\"#myIframeId\").remove();\n\n });\n\n});\n"
},
{
"answer_id": 16363322,
"author": "Neo",
"author_id": 405238,
"author_profile": "https://Stackoverflow.com/users/405238",
"pm_score": 5,
"selected": false,
"text": "$('#the_iframe').load(function(){\n alert('loaded!');\n});\n"
},
{
"answer_id": 27396147,
"author": "Nada N. Hantouli",
"author_id": 2513046,
"author_profile": "https://Stackoverflow.com/users/2513046",
"pm_score": 3,
"selected": false,
"text": " $(window).load(function () {\n //alert(\"Done window ready \");\n var lblWait = document.getElementById(\"lblWait\");\n if (lblWait != null ) {\n lblWait.style.visibility = \"false\";\n document.getElementById(\"divWait\").style.display = \"none\";\n }\n });\n"
},
{
"answer_id": 49486714,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "onload function a() {\nalert(\"Your iframe has been loaded\");\n} <iframe src=\"https://stackoverflow.com\" onload=\"a()\"></iframe>"
},
{
"answer_id": 69694808,
"author": "arafatgazi",
"author_id": 15757382,
"author_profile": "https://Stackoverflow.com/users/15757382",
"pm_score": 2,
"selected": false,
"text": "about:blank readyState == \"complete\" DOMContentLoaded load load readyState == \"complete\" <iframe> function iframeReady(callback, iframeElement) {\n const iframeWindow = iframeElement.contentWindow;\n if ((iframeElement.src == \"about:blank\" || (iframeElement.src != \"about:blank\" && iframeWindow.location.href != \"about:blank\")) && iframeWindow.document.readyState == \"complete\") {\n callback();\n } else {\n iframeWindow.addEventListener(\"load\", callback);\n }\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
164,088
|
<p>When designing a collection class, is there any reason not to implement locking privately to make it thread safe? Or should I leave that responsibility up to the consumer of the collection?</p>
|
[
{
"answer_id": 3798398,
"author": "Ohad Schneider",
"author_id": 67824,
"author_profile": "https://Stackoverflow.com/users/67824",
"pm_score": 3,
"selected": false,
"text": "static int GetFirstOrDefault(ThreadSafeList<int> list) {\n if (list.Count > 0) {\n return list[0];\n }\n return 0; }\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11574/"
] |
164,093
|
<p>in a C program I have an long* that I want to serialize (thus converting to chars). A long doesn't fit in a single char, and the size varies depending of the processor (can be 4 bytes or 8 bytes).</p>
<p>Theres a good way to make the serialization and de-serialization? </p>
|
[
{
"answer_id": 164115,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "long list[MAX];\nchar *serial = list;\nint chunk = sizeof(long);\nint k;\nfor(k=0; k<(MAX*chunk); k++){\n // do something with the \"char\"\n}\n"
},
{
"answer_id": 164116,
"author": "Lev",
"author_id": 7224,
"author_profile": "https://Stackoverflow.com/users/7224",
"pm_score": 2,
"selected": true,
"text": "long * longs;\n\n// ...\n\nint numChars = numLongs * sizeof(long);\nchar* longsAsChars = (char*) longs;\nchar* chars = malloc(numChars);\nmemcpy(chars, longsAsChars, numChars);\n"
},
{
"answer_id": 164125,
"author": "Georg Schölly",
"author_id": 24587,
"author_profile": "https://Stackoverflow.com/users/24587",
"pm_score": 1,
"selected": false,
"text": "sizeof(long)\n"
},
{
"answer_id": 164242,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 2,
"selected": false,
"text": "char *p = &long_array[0];\n #include <stdio.h>\n\nmain()\n{\n int aaa[10];\n int i;\n char *p;\n\n for(i=0;i<sizeof(aaa)/sizeof(aaa[0]);i++)\n {\n aaa[i] = i;\n printf (\"setting aaa[%d] = %8x\\n\",i,aaa[i]);\n }\n\n aaa[9] = 0xaabbccdd;\n\n printf (\"sizeof aaa (bytes) :%d\\n\",sizeof(aaa));\n printf (\"each element of aaa bytes :%d\\n\",sizeof(aaa[0]));\n\n p = (char*) aaa;\n for(i=0;i<sizeof(aaa);i++)\n printf (\"%d: %8x\\n\",i,(unsigned char)p[i]);\n}\n"
},
{
"answer_id": 180698,
"author": "PhirePhly",
"author_id": 20082,
"author_profile": "https://Stackoverflow.com/users/20082",
"pm_score": 2,
"selected": false,
"text": "void longtochar(char *buffer, unsigned long number) {\n int i;\n for (i=0; i<sizeof(long); i++) {\n buffer[i] = number & 0xFF; // place bottom 8 bits in char\n number = number >> 8; // shift down remaining bits\n }\n return; // the long is now stored in the first few (2,4,or 8) bytes of buffer\n}\n long chartolong(char *buffer) {\n long number = 0;\n int i;\n for (i=sizeof(long)-1; i>=0; i--) {\n number = number << 8; // left shift bits in long already\n number += buffer[i]; // add in bottom 8 bits\n }\n return number;\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18403/"
] |
164,095
|
<p>I'm writing a DSL in Ruby to control an Arduino project I'm working on; Bardino. It's a bar monkey that will be software controlled to serve drinks. The Arduino takes commands via the serial port to tell the Arduino what pumps to turn on and for how long.</p>
<p>It currently reads a recipe (see below) and prints it back out. The code for serial communications still need to be worked in as well as some other ideas that I have mentioned below.</p>
<p>This is my first DSL and I'm working off of a previous example so it's very rough around the edges. Any critiques, code improvements (are there any good references for Ruby DSL best practices or idioms?) or any general comments.</p>
<p>I currently have a rough draft of the DSL so a drink recipe looks like the following (<a href="http://github.com/mwilliams/barduino-tender/tree/571fb9128c02ce72b1f891d841930bf526f1432c/examples/water.rb" rel="nofollow noreferrer">Github link</a>):</p>
<pre><code>desc "Simple glass of water"
recipe "water" do
ingredients(
"Water" => 2.ounces
)
end
</code></pre>
<p>This in turn is interpreted and currently results with the following (<a href="http://github.com/mwilliams/barduino-tender/tree/571fb9128c02ce72b1f891d841930bf526f1432c/barduino-tender.rb" rel="nofollow noreferrer">Github link</a>):</p>
<pre><code>[mwilliams@Danzig barduino-tender]$ ruby barduino-tender.rb examples/water.rb
Preparing: Simple glass of water
Ingredients:
Water: 2 ounces
</code></pre>
<p>This is a good start for the DSL, however, I do think it could be implemented a little bit better. Some ideas I had below:</p>
<ol>
<li>Defining what "ingredients" are available using the name of the ingredient and the number pump that it's connected to. Maybe using a hash? ingredients = {"water" => 1, "vodka" => 2}. This way, when an ingredient is interpreted it can either a) send the pump number over the serial port followed by the number of ounces for the Arduino to dispense b) tell the user that ingredient does not exist and abort so nothing is dispensed c) easily have the capability to change or add new ingredients if they're changed.</li>
<li>Making the recipe look less code like, which is the main purpose of a DSL, maybe build a recipe builder? Using the available ingredients to prompt the user for a drink name, ingredients involved and how much?</li>
</ol>
<p>The Github project is <a href="http://github.com/mwilliams/barduino-tender/tree/master" rel="nofollow noreferrer">here</a>, feel free to fork and make pull requests, or post your code suggestions and examples here for other users to see. And if you're at all curious, the Arduino code, using the Ruby Arduino Development framework is <a href="http://github.com/mwilliams/barduino/tree/master" rel="nofollow noreferrer">here</a>.</p>
<p><strong>Update</strong></p>
<p>I modified and cleaned things up a bit to reflect Orion Edwards suggestion for a recipe. It now looks like the following.</p>
<pre><code>description 'Screwdriver' do
serve_in 'Highball Glass'
ingredients do
2.ounces :vodka
5.ounces :orange_juice
end
end
</code></pre>
<p>I also added a hash (key being the ingredient and the value the pump number it's hooked up to). I think this provided much progress. I'll leave the question open for any further suggestions for now, but will ultimately select Orion's answer. The updated DSL code is <a href="http://github.com/mwilliams/barduino-tender/tree/master/barduino-tender.rb" rel="nofollow noreferrer">here</a>.</p>
|
[
{
"answer_id": 164358,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": true,
"text": "describe \"Long Island Iced Tea\" do\n serve_in 'Highball Glass'\n\n ingredients do\n half.ounce.of :vodka\n half.ounce.of :tequila\n half.ounce.of :light_rum\n half.ounce.of :gin\n 1.dash.of :coca_cola\n #ignoring lemon peel as how can a robot peel a lemon?\n end\n\n steps do\n add :vodka, :tequila, :light_rum, :gin\n stir :gently\n add :coca_cola\n end\nend\n"
},
{
"answer_id": 165827,
"author": "user24631",
"author_id": 24631,
"author_profile": "https://Stackoverflow.com/users/24631",
"pm_score": 1,
"selected": false,
"text": "description recipe vodka = :vodka"
},
{
"answer_id": 365747,
"author": "Christian Lescuyer",
"author_id": 341,
"author_profile": "https://Stackoverflow.com/users/341",
"pm_score": 2,
"selected": false,
"text": "Recipe for Long Island Iced Tea #1\nIngredients:\n 1/2 oz Vodka\n 1/2 oz Tequila\n 1/2 oz Light Rum\n 1/2 oz Gin\n 1 Dash Coca-Cola\n # ignored Twist of Lemon Peel (or Lime)\n grammar Cocktail\n rule cocktail\n title ingredients\n end\n\n rule title\n 'Recipe for' S text:(.*) EOF\n end\n\n rule ingredients\n ingredient+\n end\n\n rule ingredient\n qty S liquid\n end\n# ...\nend\n parser = CocktailParser.new\nr = parser.parse(recipe)\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23909/"
] |
164,102
|
<p>For example, suppose I have a class:</p>
<pre><code>class Foo
{
public:
std::string& Name()
{
m_maybe_modified = true;
return m_name;
}
const std::string& Name() const
{
return m_name;
}
protected:
std::string m_name;
bool m_maybe_modified;
};
</code></pre>
<p>And somewhere else in the code, I have something like this:</p>
<pre><code>Foo *a;
// Do stuff...
std::string name = a->Name(); // <-- chooses the non-const version
</code></pre>
<p>Does anyone know why the compiler would choose the non-const version in this case?</p>
<p>This is a somewhat contrived example, but the actual problem we are trying to solve is periodically auto-saving an object if it has changed, and the pointer must be non-const because it might be changed at some point. </p>
|
[
{
"answer_id": 164130,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "a const Foo *"
},
{
"answer_id": 164139,
"author": "Lev",
"author_id": 7224,
"author_profile": "https://Stackoverflow.com/users/7224",
"pm_score": 4,
"selected": false,
"text": "const Foo* b = a;\nstd::string name = b->Name();\n"
},
{
"answer_id": 164208,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 3,
"selected": false,
"text": "std::string name = b->Name();\n b->Name() = \"me\";\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9876/"
] |
164,105
|
<p>I'm trying to write a Selenium test for a web page that uses an onbeforeunload event to prompt the user before leaving. Selenium doesn't seem to recognize the confirmation dialog that comes up, or to provide a way to hit OK or Cancel. Is there any way to do this? I'm using the Java Selenium driver, if that's relevant.</p>
|
[
{
"answer_id": 26787603,
"author": "Louis",
"author_id": 1906307,
"author_profile": "https://Stackoverflow.com/users/1906307",
"pm_score": 1,
"selected": false,
"text": "onbeforeunload driver.switch_to.alert.accept()\n driver.switchTo().alert().accept();\n NoAlertPresentException window.onbeforeunload null"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13210/"
] |
164,144
|
<p>I have two DataTables, <code>A</code> and <code>B</code>, produced from CSV files. I need to be able to check which rows exist in <code>B</code> that do not exist in <code>A</code>.</p>
<p>Is there a way to do some sort of query to show the different rows or would I have to iterate through each row on each DataTable to check if they are the same? The latter option seems to be very intensive if the tables become large.</p>
|
[
{
"answer_id": 164200,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 3,
"selected": false,
"text": "A.Merge(B); // this will add to A any records that are in B but not A\nreturn A.GetChanges(); // returns records originally only in B\n"
},
{
"answer_id": 164213,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 1,
"selected": false,
"text": "other_item= A.first()\nonly_in_B= empty_list()\nfor item in B:\n while other_item > item:\n other_item= A.next()\n if A.eof():\n only_in_B.add( all the remaining B items)\n return only_in_B\n if item < other_item:\n empty_list.append(item)\nreturn only_in_B\n"
},
{
"answer_id": 164370,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "IEnumerable<string> idsInA = tableA.AsEnumerable().Select(row => (string)row[\"ID\"]);\nIEnumerable<string> idsInB = tableB.AsEnumerable().Select(row => (string)row[\"ID\"]);\nIEnumerable<string> bNotA = idsInB.Except(idsInA);\n"
},
{
"answer_id": 164421,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 2,
"selected": false,
"text": "Dictionary<int, DataRow> Dictionary<int, List<DataRow>>"
},
{
"answer_id": 657024,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "public DataTable compareDataTables(DataTable First, DataTable Second)\n{\n First.TableName = \"FirstTable\";\n Second.TableName = \"SecondTable\";\n\n //Create Empty Table\n DataTable table = new DataTable(\"Difference\");\n DataTable table1 = new DataTable();\n try\n {\n //Must use a Dataset to make use of a DataRelation object\n using (DataSet ds4 = new DataSet())\n {\n //Add tables\n ds4.Tables.AddRange(new DataTable[] { First.Copy(), Second.Copy() });\n\n //Get Columns for DataRelation\n DataColumn[] firstcolumns = new DataColumn[ds4.Tables[0].Columns.Count];\n for (int i = 0; i < firstcolumns.Length; i++)\n {\n firstcolumns[i] = ds4.Tables[0].Columns[i];\n }\n DataColumn[] secondcolumns = new DataColumn[ds4.Tables[1].Columns.Count];\n for (int i = 0; i < secondcolumns.Length; i++)\n {\n secondcolumns[i] = ds4.Tables[1].Columns[i];\n }\n //Create DataRelation\n DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);\n ds4.Relations.Add(r);\n //Create columns for return table\n for (int i = 0; i < First.Columns.Count; i++)\n {\n table.Columns.Add(First.Columns[i].ColumnName, First.Columns[i].DataType);\n }\n //If First Row not in Second, Add to return table.\n table.BeginLoadData();\n foreach (DataRow parentrow in ds4.Tables[0].Rows)\n { \n DataRow[] childrows = parentrow.GetChildRows(r);\n\n if (childrows == null || childrows.Length == 0)\n table.LoadDataRow(parentrow.ItemArray, true);\n table1.LoadDataRow(childrows, false);\n\n }\n table.EndLoadData();\n }\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.Message);\n }\n return table;\n}\n"
},
{
"answer_id": 657027,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " try\n {\n if (ds.Tables[0].Columns.Count == ds1.Tables[0].Columns.Count)\n {\n for (int i = 0; i < ds.Tables[0].Rows.Count; i++)\n {\n for (int j = 0; j < ds.Tables[0].Columns.Count; j++)\n {\n if (ds.Tables[0].Rows[i][j].ToString() == ds1.Tables[0].Rows[i][j].ToString())\n {\n\n\n }\n else\n {\n\n MessageBox.Show(i.ToString() + \",\" + j.ToString());\n\n\n }\n\n }\n\n }\n\n }\n else\n {\n MessageBox.Show(\"Table has different columns \");\n }\n }\n catch (Exception)\n {\n MessageBox.Show(\"Please select The Table\");\n }\n"
},
{
"answer_id": 9055626,
"author": "Ying",
"author_id": 1150401,
"author_profile": "https://Stackoverflow.com/users/1150401",
"pm_score": 0,
"selected": false,
"text": "List<string> diffList = new List<string>(sortedListA.Except(sortedListB));\n"
},
{
"answer_id": 17559586,
"author": "NewCsharper",
"author_id": 1700836,
"author_profile": "https://Stackoverflow.com/users/1700836",
"pm_score": 1,
"selected": false,
"text": "//Pass in your two datatables into your method\n\n //build the queries based on id.\n var qry1 = datatable1.AsEnumerable().Select(a => new { ID = a[\"ID\"].ToString() });\n var qry2 = datatable2.AsEnumerable().Select(b => new { ID = b[\"ID\"].ToString() });\n\n\n //detect row deletes - a row is in datatable1 except missing from datatable2\n var exceptAB = qry1.Except(qry2);\n\n //detect row inserts - a row is in datatable2 except missing from datatable1\n var exceptAB2 = qry2.Except(qry1);\n if (exceptAB.Any())\n {\n foreach (var id in exceptAB)\n {\n //execute code here\n }\n\n\n }\n if (exceptAB2.Any())\n {\n foreach (var id in exceptAB2)\n {\n//execute code here\n }\n\n\n\n }\n"
},
{
"answer_id": 31984030,
"author": "Pedro M Duarte",
"author_id": 1476240,
"author_profile": "https://Stackoverflow.com/users/1476240",
"pm_score": 0,
"selected": false,
"text": "DataTable DataRows DataTable DataRowState Original DataRowVersion Merge Unchanged GetChanges() DataTables DataTables Unchanged GetDelta() using System;\nusing System.Data;\nusing System.Xml;\nusing System.Linq;\nusing System.Collections.Generic;\nusing System.Data.DataSetExtensions;\n\npublic class Program\n{\n private static DataTable GetDelta(DataTable table1, DataTable table2)\n {\n // Modified2 : row1 keys match rowOther keys AND row1 does not match row2:\n IEnumerable<DataRow> modified2 = (\n from row1 in table1.AsEnumerable()\n from row2 in table2.AsEnumerable()\n where table1.PrimaryKey.Aggregate(true, (boolAggregate, keycol) => boolAggregate & row1[keycol].Equals(row2[keycol.Ordinal]))\n && !row1.ItemArray.SequenceEqual(row2.ItemArray)\n select row2);\n\n // Modified1 :\n IEnumerable<DataRow> modified1 = (\n from row1 in table1.AsEnumerable()\n from row2 in table2.AsEnumerable()\n where table1.PrimaryKey.Aggregate(true, (boolAggregate, keycol) => boolAggregate & row1[keycol].Equals(row2[keycol.Ordinal]))\n && !row1.ItemArray.SequenceEqual(row2.ItemArray)\n select row1);\n\n // Added : row2 not in table1 AND row2 not in modified2\n IEnumerable<DataRow> added = table2.AsEnumerable().Except(modified2, DataRowComparer.Default).Except(table1.AsEnumerable(), DataRowComparer.Default);\n\n // Deleted : row1 not in row2 AND row1 not in modified1\n IEnumerable<DataRow> deleted = table1.AsEnumerable().Except(modified1, DataRowComparer.Default).Except(table2.AsEnumerable(), DataRowComparer.Default);\n\n\n Console.WriteLine();\n Console.WriteLine(\"modified count =\" + modified1.Count());\n Console.WriteLine(\"added count =\" + added.Count());\n Console.WriteLine(\"deleted count =\" + deleted.Count());\n\n DataTable deltas = table1.Clone();\n\n foreach (DataRow row in modified2)\n {\n // Match the unmodified version of the row via the PrimaryKey\n DataRow matchIn1 = modified1.Where(row1 => table1.PrimaryKey.Aggregate(true, (boolAggregate, keycol) => boolAggregate & row1[keycol].Equals(row[keycol.Ordinal]))).First();\n DataRow newRow = deltas.NewRow();\n\n // Set the row with the original values\n foreach(DataColumn dc in deltas.Columns)\n newRow[dc.ColumnName] = matchIn1[dc.ColumnName];\n deltas.Rows.Add(newRow);\n newRow.AcceptChanges();\n\n // Set the modified values\n foreach (DataColumn dc in deltas.Columns)\n newRow[dc.ColumnName] = row[dc.ColumnName];\n // At this point newRow.DataRowState should be : Modified\n }\n\n foreach (DataRow row in added)\n {\n DataRow newRow = deltas.NewRow();\n foreach (DataColumn dc in deltas.Columns)\n newRow[dc.ColumnName] = row[dc.ColumnName];\n deltas.Rows.Add(newRow);\n // At this point newRow.DataRowState should be : Added\n }\n\n\n foreach (DataRow row in deleted)\n {\n DataRow newRow = deltas.NewRow();\n foreach (DataColumn dc in deltas.Columns)\n newRow[dc.ColumnName] = row[dc.ColumnName];\n deltas.Rows.Add(newRow);\n newRow.AcceptChanges();\n newRow.Delete();\n // At this point newRow.DataRowState should be : Deleted\n }\n\n return deltas;\n }\n\n private static void DemonstrateGetDelta()\n {\n DataTable table1 = new DataTable(\"Items\");\n\n // Add columns\n DataColumn column1 = new DataColumn(\"id1\", typeof(System.Int32));\n DataColumn column2 = new DataColumn(\"id2\", typeof(System.Int32));\n DataColumn column3 = new DataColumn(\"item\", typeof(System.Int32));\n table1.Columns.Add(column1);\n table1.Columns.Add(column2);\n table1.Columns.Add(column3);\n\n // Set the primary key column.\n table1.PrimaryKey = new DataColumn[] { column1, column2 };\n\n\n // Add some rows.\n DataRow row;\n for (int i = 0; i <= 4; i++)\n {\n row = table1.NewRow();\n row[\"id1\"] = i;\n row[\"id2\"] = i*i;\n row[\"item\"] = i;\n table1.Rows.Add(row);\n }\n\n // Accept changes.\n table1.AcceptChanges();\n PrintValues(table1, \"table1:\");\n\n // Create a second DataTable identical to the first.\n DataTable table2 = table1.Clone();\n\n // Add a row that exists in table1:\n row = table2.NewRow();\n row[\"id1\"] = 0;\n row[\"id2\"] = 0; \n row[\"item\"] = 0;\n table2.Rows.Add(row);\n\n // Modify the values of a row that exists in table1:\n row = table2.NewRow();\n row[\"id1\"] = 1;\n row[\"id2\"] = 1;\n row[\"item\"] = 455;\n table2.Rows.Add(row);\n\n // Modify the values of a row that exists in table1:\n row = table2.NewRow();\n row[\"id1\"] = 2;\n row[\"id2\"] = 4;\n row[\"item\"] = 555;\n table2.Rows.Add(row);\n\n // Add a row that does not exist in table1:\n row = table2.NewRow();\n row[\"id1\"] = 13;\n row[\"id2\"] = 169;\n row[\"item\"] = 655;\n table2.Rows.Add(row);\n\n table2.AcceptChanges();\n\n Console.WriteLine();\n PrintValues(table2, \"table2:\");\n\n DataTable delta = GetDelta(table1,table2);\n\n Console.WriteLine();\n PrintValues(delta,\"delta:\");\n\n // Verify that the deltas DataTable contains the adequate Original DataRowVersions:\n DataTable originals = table1.Clone();\n foreach (DataRow drow in delta.Rows)\n {\n if (drow.RowState != DataRowState.Added)\n {\n DataRow originalRow = originals.NewRow();\n foreach (DataColumn dc in originals.Columns)\n originalRow[dc.ColumnName] = drow[dc.ColumnName, DataRowVersion.Original];\n originals.Rows.Add(originalRow);\n }\n }\n originals.AcceptChanges();\n\n Console.WriteLine();\n PrintValues(originals,\"delta original values:\");\n }\n\n private static void Row_Changed(object sender, \n DataRowChangeEventArgs e)\n {\n Console.WriteLine(\"Row changed {0}\\t{1}\", \n e.Action, e.Row.ItemArray[0]);\n }\n\n private static void PrintValues(DataTable table, string label)\n {\n // Display the values in the supplied DataTable:\n Console.WriteLine(label);\n foreach (DataRow row in table.Rows)\n {\n foreach (DataColumn col in table.Columns)\n {\n Console.Write(\"\\t \" + row[col, row.RowState == DataRowState.Deleted ? DataRowVersion.Original : DataRowVersion.Current].ToString());\n }\n Console.Write(\"\\t DataRowState =\" + row.RowState);\n Console.WriteLine();\n }\n }\n\n public static void Main()\n {\n DemonstrateGetDelta();\n }\n}\n table1:\n 0 0 0 DataRowState =Unchanged\n 1 1 1 DataRowState =Unchanged\n 2 4 2 DataRowState =Unchanged\n 3 9 3 DataRowState =Unchanged\n 4 16 4 DataRowState =Unchanged\n\ntable2:\n 0 0 0 DataRowState =Unchanged\n 1 1 455 DataRowState =Unchanged\n 2 4 555 DataRowState =Unchanged\n 13 169 655 DataRowState =Unchanged\n\nmodified count =2\nadded count =1\ndeleted count =2\n\ndelta:\n 1 1 455 DataRowState =Modified\n 2 4 555 DataRowState =Modified\n 13 169 655 DataRowState =Added\n 3 9 3 DataRowState =Deleted\n 4 16 4 DataRowState =Deleted\n\ndelta original values:\n 1 1 1 DataRowState =Unchanged\n 2 4 2 DataRowState =Unchanged\n 3 9 3 DataRowState =Unchanged\n 4 16 4 DataRowState =Unchanged\n PrimaryKey where"
},
{
"answer_id": 37455967,
"author": "Ruban J",
"author_id": 2607791,
"author_profile": "https://Stackoverflow.com/users/2607791",
"pm_score": 0,
"selected": false,
"text": "private DataTable CompareDT(DataTable TableA, DataTable TableB)\n {\n DataTable TableC = new DataTable();\n try\n {\n\n var idsNotInB = TableA.AsEnumerable().Select(r => r.Field<string>(Keyfield))\n .Except(TableB.AsEnumerable().Select(r => r.Field<string>(Keyfield)));\n TableC = (from row in TableA.AsEnumerable()\n join id in idsNotInB\n on row.Field<string>(ddlColumn.SelectedItem.ToString()) equals id\n select row).CopyToDataTable();\n }\n catch (Exception ex)\n {\n lblresult.Text = ex.Message;\n ex = null;\n }\n return TableC;\n\n }\n"
},
{
"answer_id": 38130720,
"author": "withakay",
"author_id": 151160,
"author_profile": "https://Stackoverflow.com/users/151160",
"pm_score": 1,
"selected": false,
"text": "string[] a = System.IO.File.ReadAllLines(@\"cvs_a.txt\");\nstring[] b = System.IO.File.ReadAllLines(@\"csv_b.txt\");\n\n// get the lines from b that are not in a\nIEnumerable<string> diff = b.Except(a);\n\n//... parse b into DataTable ...\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6486/"
] |
164,147
|
<p>As far as I can tell there's no simple way of retrieving a character offset from a TextRange object in Internet Explorer. The W3C Range object has a node, and the offset into the text within that node. IE seems to just have pixel offsets. There are methods to create, extend and compare ranges, so it would be possible to write an algorithm to calculate the character offset, but I feel I must be missing something.</p>
<p>So, what's the easiest way to calculate the character offset of the start of an Internet Explorer TextRange?</p>
|
[
{
"answer_id": 164347,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "TextRange.text String.substring() function charOffset(textRange, parentTextRange)\n { var parentTxt = parentTextRange.text;\n var txt = textRange.text;\n var parentLen = parentTxt.length;\n\n for(int i=0; i < parentLen ; ++i) \n { if (parentTxt.substring(i, txt.length+i) == txt) \n { var originalPosition = textRange.getBookmark();\n\n //moves back one and searches backwards for same text\n textRange.moveStart(\"character\",-1);\n var foundOther = textRange.findText(textRange.text,-parentLen,1);\n\n //if no others were found return offset\n if (!foundOther) return i;\n\n //returns to original position to try next offset\n else textRange.moveToBookmark(originalPosition);\n }\n }\n\n return -1;\n }\n findText()"
},
{
"answer_id": 198456,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 3,
"selected": false,
"text": "// Assume r is a range:\nvar offsetFromBody = Math.abs( r.moveEnd('character', -1000000) );\n // where paramter r is a range:\nfunction getRangeOffsetIE( r ) {\n var end = Math.abs( r.duplicate().moveEnd('character', -1000000) );\n // find the anchor element's offset\n var range = r.duplicate();\n r.collapse( false );\n var parentElm = range.parentElement();\n var children = parentElm.getElementsByTagName('*');\n for (var i = children.length - 1; i >= 0; i--) {\n range.moveToElementText( children[i] );\n if ( range.inRange(r) ) {\n parentElm = children[i];\n break;\n }\n }\n range.moveToElementText( parentElm );\n return end - Math.abs( range.moveStart('character', -1000000) );\n}\n"
},
{
"answer_id": 790081,
"author": "Tim Down",
"author_id": 96100,
"author_profile": "https://Stackoverflow.com/users/96100",
"pm_score": 4,
"selected": true,
"text": "TextRange DOM Range"
},
{
"answer_id": 2515627,
"author": "Tom Berthon",
"author_id": 175239,
"author_profile": "https://Stackoverflow.com/users/175239",
"pm_score": 2,
"selected": false,
"text": "function getIECharOffset() {\n var offset = 0;\n\n // get the users selection - this handles empty selections\n var userSelection = document.selection.createRange();\n\n // get a selection from the contents of the parent element\n var parentSelection = userSelection.parentElement().createTextRange();\n\n // loop - moving the parent selection on a character at a time until the offsets match\n while (!offsetEqual(parentSelection, userSelection)) {\n parentSelection.move('character');\n offset++;\n }\n\n // return the number of char you have moved through\n return offset;\n}\n\nfunction offsetEqual(arg1, arg2) {\n if (arg1.offsetLeft == arg2.offsetLeft && arg1.offsetTop == arg2.offsetTop) {\n return true;\n }\n return false;\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24618/"
] |
164,154
|
<p>I want to tune a production SQL server. After making adjustments (such as changing the degree of parallelism) I want to know if it helped or hurt query execution times.</p>
<p>This seems like an obvious performance counter, but for the last half hour I've been searching Google and the counter list in perfmon, and I have not been able to find a performance counter for SQL server to give me the average execution time for all queries hitting a server. The SQL Server equivalent of the ASP.NET Request Execution Time.</p>
<p>Does one exist that I'm missing? Is there another effective way of monitoring the average query times for a server?</p>
|
[
{
"answer_id": 6338261,
"author": "Jason Jong",
"author_id": 209254,
"author_profile": "https://Stackoverflow.com/users/209254",
"pm_score": 1,
"selected": false,
"text": "File Save As Trace Table select avg(duration) from dbo.[YourTableImportName] \n"
},
{
"answer_id": 60148054,
"author": "Joscelyn Gainié",
"author_id": 4015058,
"author_profile": "https://Stackoverflow.com/users/4015058",
"pm_score": 1,
"selected": false,
"text": "DO $proc$\nDECLARE\n StartTime timestamptz;\n EndTime timestamptz;\n Delta double precision;\nBEGIN\n StartTime := clock_timestamp();\n FOR i IN 1..100 LOOP\n PERFORM * FROM table_name;\n END LOOP;\n EndTime := clock_timestamp();\n Delta := 1000 * (extract(epoch FROM EndTime) - extract(epoch FROM StartTime)) / 100;\n RAISE NOTICE 'Average duration in ms = %', Delta;\nEND;\n$proc$;\n PERFORM * FROM table_name;\n SELECT PERFORM"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15118/"
] |
164,163
|
<p>When implementing Quicksort, one of the things you have to do is to choose a pivot. But when I look at pseudocode like the one below, it is not clear how I should choose the pivot. First element of list? Something else?</p>
<pre><code> function quicksort(array)
var list less, greater
if length(array) ≤ 1
return array
select and remove a pivot value pivot from array
for each x in array
if x ≤ pivot then append x to less
else append x to greater
return concatenate(quicksort(less), pivot, quicksort(greater))
</code></pre>
<p>Can someone help me grasp the concept of choosing a pivot and whether or not different scenarios call for different strategies.</p>
|
[
{
"answer_id": 237070,
"author": "mindvirus",
"author_id": 31455,
"author_profile": "https://Stackoverflow.com/users/31455",
"pm_score": 4,
"selected": false,
"text": "T(n) = O(n) (find the median) + O(n) (partition) + 2T(n/2) (recurse left and right)\n"
},
{
"answer_id": 5254733,
"author": "Uglybb",
"author_id": 652759,
"author_profile": "https://Stackoverflow.com/users/652759",
"pm_score": 2,
"selected": false,
"text": "/* This selects what the data type in the array to be sorted is */\n\n#define DATATYPE long\n\n/* This is the swap function .. your job is to swap data in x & y .. how depends on\ndata type .. the example works for normal numerical data types .. like long I chose\nabove */\n\nvoid swap (DATATYPE *x, DATATYPE *y){ \n DATATYPE Temp;\n\n Temp = *x; // Hold current x value\n *x = *y; // Transfer y to x\n *y = Temp; // Set y to the held old x value\n};\n\n\n/* This is the partition code */\n\nint partition (DATATYPE list[], int l, int h){\n\n int i;\n int p; // pivot element index\n int firsthigh; // divider position for pivot element\n\n // Random pivot example shown for median p = (l+h)/2 would be used\n p = l + (short)(rand() % (int)(h - l + 1)); // Random partition point\n\n swap(&list[p], &list[h]); // Swap the values\n firsthigh = l; // Hold first high value\n for (i = l; i < h; i++)\n if(list[i] < list[h]) { // Value at i is less than h\n swap(&list[i], &list[firsthigh]); // So swap the value\n firsthigh++; // Incement first high\n }\n swap(&list[h], &list[firsthigh]); // Swap h and first high values\n return(firsthigh); // Return first high\n};\n\n\n\n/* Finally the body sort */\n\nvoid quicksort(DATATYPE list[], int l, int h){\n\n int p; // index of partition \n if ((h - l) > 0) {\n p = partition(list, l, h); // Partition list \n quicksort(list, l, p - 1); // Sort lower partion\n quicksort(list, p + 1, h); // Sort upper partition\n };\n};\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20032/"
] |
164,167
|
<p>Warning: this is the actual code generated from my system:</p>
<pre><code>;WITH RESULTS AS (
SELECT 1174 AS BatchRunID, 'STATINV' AS Program, m.APPL_CD, m.ALBASE, 'CountFocusRecords' AS Measure, COUNT(*) AS Value
FROM [MISWork].[SX_FOCUS_NATIVE_200806] AS m WITH(NOLOCK)
INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK)
ON cat.APPL_CD = m.APPL_CD
AND cat.ALBASE = m.ALBASE
AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV'
GROUP BY m.APPL_CD, m.ALBASE
UNION
SELECT 1174 AS BatchRunID, 'STATINV' AS Program, c.APPL_CD, c.ALBASE, 'CountBiminiRecords' AS Measure, COUNT(*) AS Value
FROM [MISWork].[SX_STATINV] AS c WITH(NOLOCK)
INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK)
ON cat.APPL_CD = c.APPL_CD
AND cat.ALBASE = c.ALBASE
AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV'
GROUP BY c.APPL_CD, c.ALBASE
UNION
SELECT 1174 AS BatchRunID, 'STATINV' AS Program, m.APPL_CD, m.ALBASE, 'RecordsInFocusMissingInBimini' AS Measure, COUNT(*) AS Value
FROM [MISWork].[SX_FOCUS_NATIVE_200806] AS m WITH(NOLOCK)
LEFT JOIN [MISWork].[SX_STATINV] AS c WITH(NOLOCK)
ON m.[YEAR] = c.[YEAR]
AND m.[MONTH] = c.[MONTH]
AND m.[BANK_NO] = c.[BANK_NO]
AND m.[COST_CENTER] = c.[COST_CENTER]
AND m.[GLACCOUNT_NO] = c.[GLACCOUNT_NO]
AND m.[CUSTACCOUNT] = c.[CUSTACCOUNT]
AND m.[APPL_CD] = c.[APPL_CD]
AND m.[ALBASE] = c.[ALBASE]
INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK)
ON cat.APPL_CD = m.APPL_CD
AND cat.ALBASE = m.ALBASE
AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV'
WHERE c.[YEAR] IS NULL
GROUP BY m.APPL_CD, m.ALBASE
UNION
SELECT 1174 AS BatchRunID, 'STATINV' AS Program, c.APPL_CD, c.ALBASE, 'RecordsInBiminiMissingInFocus' AS Measure, COUNT(*) AS Value
FROM [MISWork].[SX_FOCUS_NATIVE_200806] AS m WITH(NOLOCK)
RIGHT JOIN [MISWork].[SX_STATINV] AS c WITH(NOLOCK)
ON m.[YEAR] = c.[YEAR]
AND m.[MONTH] = c.[MONTH]
AND m.[BANK_NO] = c.[BANK_NO]
AND m.[COST_CENTER] = c.[COST_CENTER]
AND m.[GLACCOUNT_NO] = c.[GLACCOUNT_NO]
AND m.[CUSTACCOUNT] = c.[CUSTACCOUNT]
AND m.[APPL_CD] = c.[APPL_CD]
AND m.[ALBASE] = c.[ALBASE]
INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK)
ON cat.APPL_CD = c.APPL_CD
AND cat.ALBASE = c.ALBASE
AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV'
WHERE m.[YEAR] IS NULL
GROUP BY c.APPL_CD, c.ALBASE
) SELECT * FROM RESULTS ORDER BY Program, APPL_CD, ALBASE, Measure
</code></pre>
<p>The code just sits there, no locking or blocking.</p>
<p>The individual components of the UNION return in a few seconds each. The code works in general for checking the output results of all the other programs in the STAT group, but just halts for this one.</p>
<p>Remove the CTE, no effect, sits there for 30 minutes/an hour, however long you care to wait before cancelling.</p>
<p>Remove the UNION, and the 4 result sets return in 11 seconds, total of 19 records accross all 4 result sets.</p>
<p>Run just the first two together - works fine, run just the last 2 together, also fine. First 3 together, fine, too.</p>
<p>I've already modified the code to output these to a #temp table, for other requirements, so I'm just going to change it to output each to the #temp table in sequence, but I have never seen SQL just stop like that with no evidence of blocking or anything.</p>
|
[
{
"answer_id": 219012,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "<?xml version=\"1.0\"?>\n<ShowPlanXML xmlns=\"http://schemas.microsoft.com/sqlserver/2004/07/showplan\" Version=\"1.0\" Build=\"9.00.3239.00\">\n <BatchSequence>\n <Batch>\n <Statements>\n <StmtSimple StatementText=\" ;WITH RESULTS AS ( SELECT 1251 AS BatchRunID, 'STATINV' AS Program, m.APPL_CD, m.ALBASE, 'CountFocusRecords' AS Measure, COUNT(*) AS Value FROM [MISWork].[SX_FOCUS_NATIVE_200808] AS m WITH(NOLOCK) INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK) ON cat.APPL_CD = m.APPL_CD AND cat.ALBASE = m.ALBASE AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV' GROUP BY m.APPL_CD, m.ALBASE UNION SELECT 1251 AS BatchRunID, 'STATINV' AS Program, c.APPL_CD, c.ALBASE, 'CountBiminiRecords' AS Measure, COUNT(*) AS Value FROM [MISWork].[SX_STATINV] AS c WITH(NOLOCK) INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK) ON cat.APPL_CD = c.APPL_CD AND cat.ALBASE = c.ALBASE AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV' GROUP BY c.APPL_CD, c.ALBASE UNION SELECT 1251 AS BatchRunID, 'STATINV' AS Program, m.APPL_CD, m.ALBASE, 'RecordsInFocusMissingInBimini' AS Measure, COUNT(*) AS Value FROM [MISWork].[SX_FOCUS_NATIVE_200808] AS m WITH(NOLOCK) LEFT JOIN [MISWork].[SX_STATINV] AS c WITH(NOLOCK) ON m.[YEAR] = c.[YEAR] AND m.[MONTH] = c.[MONTH] AND m.[BANK_NO] = c.[BANK_NO] AND m.[COST_CENTER] = c.[COST_CENTER] AND m.[GLACCOUNT_NO] = c.[GLACCOUNT_NO] AND m.[CUSTACCOUNT] = c.[CUSTACCOUNT] AND m.[APPL_CD] = c.[APPL_CD] AND m.[ALBASE] = c.[ALBASE] INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK) ON cat.APPL_CD = m.APPL_CD AND cat.ALBASE = m.ALBASE AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV' WHERE c.[YEAR] IS NULL GROUP BY m.APPL_CD, m.ALBASE UNION SELECT 1251 AS BatchRunID, 'STATINV' AS Program, c.APPL_CD, c.ALBASE, 'RecordsInBiminiMissingInFocus' AS Measure, COUNT(*) AS Value FROM [MISWork].[SX_FOCUS_NATIVE_200808] AS m WITH(NOLOCK) RIGHT JOIN [MISWork].[SX_STATINV] AS c WITH(NOLOCK) ON m.[YEAR] = c.[YEAR] AND m.[MONTH] = c.[MONTH] AND m.[BANK_NO] = c.[BANK_NO] AND m.[COST_CENTER] = c.[COST_CENTER] AND m.[GLACCOUNT_NO] = c.[GLACCOUNT_NO] AND m.[CUSTACCOUNT] = c.[CUSTACCOUNT] AND m.[APPL_CD] = c.[APPL_CD] AND m.[ALBASE] = c.[ALBASE] INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK) ON cat.APPL_CD = c.APPL_CD AND cat.ALBASE = c.ALBASE AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV' WHERE m.[YEAR] IS NULL GROUP BY c.APPL_CD, c.ALBASE ) SELECT * FROM RESULTS ORDER BY Program, APPL_CD, ALBASE, Measure \" StatementId=\"1\" StatementCompId=\"1\" StatementType=\"SELECT\" StatementSubTreeCost=\"1209.5\" StatementEstRows=\"13965.1\" StatementOptmLevel=\"FULL\">\n <StatementSetOptions QUOTED_IDENTIFIER=\"false\" ARITHABORT=\"true\" CONCAT_NULL_YIELDS_NULL=\"false\" ANSI_NULLS=\"false\" ANSI_PADDING=\"false\" ANSI_WARNINGS=\"false\" NUMERIC_ROUNDABORT=\"false\"/>\n <QueryPlan CachedPlanSize=\"504\" CompileTime=\"1244\" CompileCPU=\"1099\" CompileMemory=\"5016\">\n <MissingIndexes>\n <MissingIndexGroup Impact=\"29.2539\">\n <MissingIndex Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\">\n <ColumnGroup Usage=\"EQUALITY\">\n <Column Name=\"[APPL_CD]\" ColumnId=\"7\"/>\n <Column Name=\"[ALBASE]\" ColumnId=\"8\"/>\n </ColumnGroup>\n <ColumnGroup Usage=\"INCLUDE\">\n <Column Name=\"[YEAR]\" ColumnId=\"1\"/>\n <Column Name=\"[MONTH]\" ColumnId=\"2\"/>\n <Column Name=\"[BANK_NO]\" ColumnId=\"3\"/>\n <Column Name=\"[COST_CENTER]\" ColumnId=\"4\"/>\n <Column Name=\"[GLACCOUNT_NO]\" ColumnId=\"5\"/>\n <Column Name=\"[CUSTACCOUNT]\" ColumnId=\"6\"/>\n </ColumnGroup>\n </MissingIndex>\n </MissingIndexGroup>\n <MissingIndexGroup Impact=\"29.6796\">\n <MissingIndex Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\">\n <ColumnGroup Usage=\"EQUALITY\">\n <Column Name=\"[APPL_CD]\" ColumnId=\"7\"/>\n <Column Name=\"[ALBASE]\" ColumnId=\"8\"/>\n </ColumnGroup>\n </MissingIndex>\n </MissingIndexGroup>\n </MissingIndexes>\n <RelOp NodeId=\"0\" PhysicalOp=\"Parallelism\" LogicalOp=\"Gather Streams\" EstimateRows=\"13965.1\" EstimateIO=\"0\" EstimateCPU=\"0.121489\" AvgRowSize=\"45\" EstimatedTotalSubtreeCost=\"1209.5\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\">\n <OutputList>\n <ColumnReference Column=\"Union1039\"/>\n <ColumnReference Column=\"Union1040\"/>\n <ColumnReference Column=\"Union1041\"/>\n <ColumnReference Column=\"Union1042\"/>\n <ColumnReference Column=\"Union1043\"/>\n <ColumnReference Column=\"Union1044\"/>\n </OutputList>\n <Parallelism>\n <OrderBy>\n <OrderByColumn Ascending=\"1\">\n <ColumnReference Column=\"Union1041\"/>\n </OrderByColumn>\n <OrderByColumn Ascending=\"1\">\n <ColumnReference Column=\"Union1042\"/>\n </OrderByColumn>\n <OrderByColumn Ascending=\"1\">\n <ColumnReference Column=\"Union1043\"/>\n </OrderByColumn>\n </OrderBy>\n <RelOp NodeId=\"1\" PhysicalOp=\"Sort\" LogicalOp=\"Sort\" EstimateRows=\"13965.1\" EstimateIO=\"0.00281532\" EstimateCPU=\"0.220682\" AvgRowSize=\"45\" EstimatedTotalSubtreeCost=\"1209.37\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\">\n <OutputList>\n <ColumnReference Column=\"Union1039\"/>\n <ColumnReference Column=\"Union1040\"/>\n <ColumnReference Column=\"Union1041\"/>\n <ColumnReference Column=\"Union1042\"/>\n <ColumnReference Column=\"Union1043\"/>\n <ColumnReference Column=\"Union1044\"/>\n </OutputList>\n <MemoryFractions Input=\"0.0191727\" Output=\"1\"/>\n <Sort Distinct=\"0\">\n <OrderBy>\n <OrderByColumn Ascending=\"1\">\n <ColumnReference Column=\"Union1041\"/>\n </OrderByColumn>\n <OrderByColumn Ascending=\"1\">\n <ColumnReference Column=\"Union1042\"/>\n </OrderByColumn>\n <OrderByColumn Ascending=\"1\">\n <ColumnReference Column=\"Union1043\"/>\n </OrderByColumn>\n </OrderBy>\n <RelOp NodeId=\"2\" PhysicalOp=\"Concatenation\" LogicalOp=\"Concatenation\" EstimateRows=\"13965.1\" EstimateIO=\"0\" EstimateCPU=\"0.000349132\" AvgRowSize=\"45\" EstimatedTotalSubtreeCost=\"1209.15\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\">\n <OutputList>\n <ColumnReference Column=\"Union1039\"/>\n <ColumnReference Column=\"Union1040\"/>\n <ColumnReference Column=\"Union1041\"/>\n <ColumnReference Column=\"Union1042\"/>\n <ColumnReference Column=\"Union1043\"/>\n <ColumnReference Column=\"Union1044\"/>\n </OutputList>\n <Concat>\n <DefinedValues>\n <DefinedValue>\n <ColumnReference Column=\"Union1039\"/>\n <ColumnReference Column=\"Expr1006\"/>\n <ColumnReference Column=\"Expr1014\"/>\n <ColumnReference Column=\"Expr1025\"/>\n <ColumnReference Column=\"Expr1036\"/>\n </DefinedValue>\n <DefinedValue>\n <ColumnReference Column=\"Union1040\"/>\n <ColumnReference Column=\"Expr1007\"/>\n <ColumnReference Column=\"Expr1015\"/>\n <ColumnReference Column=\"Expr1026\"/>\n <ColumnReference Column=\"Expr1037\"/>\n </DefinedValue>\n <DefinedValue>\n <ColumnReference Column=\"Union1041\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_STATINV]\" Alias=\"[c]\" Column=\"APPL_CD\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_STATINV]\" Alias=\"[c]\" Column=\"APPL_CD\"/>\n </DefinedValue>\n <DefinedValue>\n <ColumnReference Column=\"Union1042\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_STATINV]\" Alias=\"[c]\" Column=\"ALBASE\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_STATINV]\" Alias=\"[c]\" Column=\"ALBASE\"/>\n </DefinedValue>\n <DefinedValue>\n <ColumnReference Column=\"Union1043\"/>\n <ColumnReference Column=\"Expr1008\"/>\n <ColumnReference Column=\"Expr1016\"/>\n <ColumnReference Column=\"Expr1027\"/>\n <ColumnReference Column=\"Expr1038\"/>\n </DefinedValue>\n <DefinedValue>\n <ColumnReference Column=\"Union1044\"/>\n <ColumnReference Column=\"Expr1005\"/>\n <ColumnReference Column=\"Expr1013\"/>\n <ColumnReference Column=\"Expr1024\"/>\n <ColumnReference Column=\"Expr1035\"/>\n </DefinedValue>\n </DefinedValues>\n <RelOp NodeId=\"4\" PhysicalOp=\"Compute Scalar\" LogicalOp=\"Compute Scalar\" EstimateRows=\"7140\" EstimateIO=\"0\" EstimateCPU=\"0.0001785\" AvgRowSize=\"42\" EstimatedTotalSubtreeCost=\"362.728\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\">\n <OutputList>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n <ColumnReference Column=\"Expr1005\"/>\n <ColumnReference Column=\"Expr1006\"/>\n <ColumnReference Column=\"Expr1007\"/>\n <ColumnReference Column=\"Expr1008\"/>\n </OutputList>\n <ComputeScalar>\n <DefinedValues>\n <DefinedValue>\n <ColumnReference Column=\"Expr1006\"/>\n <ScalarOperator ScalarString=\"(1251)\">\n <Const ConstValue=\"(1251)\"/>\n </ScalarOperator>\n </DefinedValue>\n <DefinedValue>\n <ColumnReference Column=\"Expr1007\"/>\n <ScalarOperator ScalarString=\"'STATINV'\">\n <Const ConstValue=\"'STATINV'\"/>\n </ScalarOperator>\n </DefinedValue>\n <DefinedValue>\n <ColumnReference Column=\"Expr1008\"/>\n <ScalarOperator ScalarString=\"'CountFocusRecords'\">\n <Const ConstValue=\"'CountFocusRecords'\"/>\n </ScalarOperator>\n </DefinedValue>\n </DefinedValues>\n <RelOp NodeId=\"6\" PhysicalOp=\"Compute Scalar\" LogicalOp=\"Compute Scalar\" EstimateRows=\"7140\" EstimateIO=\"0\" EstimateCPU=\"0.0001785\" AvgRowSize=\"23\" EstimatedTotalSubtreeCost=\"362.728\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\">\n <OutputList>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n <ColumnReference Column=\"Expr1005\"/>\n </OutputList>\n <ComputeScalar>\n <DefinedValues>\n <DefinedValue>\n <ColumnReference Column=\"Expr1005\"/>\n <ScalarOperator ScalarString=\"CONVERT_IMPLICIT(int,[globalagg1083],0)\">\n <Convert DataType=\"int\" Style=\"0\" Implicit=\"1\">\n <ScalarOperator>\n <Identifier>\n <ColumnReference Column=\"globalagg1083\"/>\n </Identifier>\n </ScalarOperator>\n </Convert>\n </ScalarOperator>\n </DefinedValue>\n </DefinedValues>\n <RelOp NodeId=\"7\" PhysicalOp=\"Hash Match\" LogicalOp=\"Aggregate\" EstimateRows=\"7140\" EstimateIO=\"0\" EstimateCPU=\"0.114864\" AvgRowSize=\"27\" EstimatedTotalSubtreeCost=\"362.728\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\">\n <OutputList>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n <ColumnReference Column=\"globalagg1083\"/>\n </OutputList>\n <MemoryFractions Input=\"0.5\" Output=\"0.980827\"/>\n <Hash>\n <DefinedValues>\n <DefinedValue>\n <ColumnReference Column=\"globalagg1083\"/>\n <ScalarOperator ScalarString=\"SUM([partialagg1082])\">\n <Aggregate Distinct=\"0\" AggType=\"SUM\">\n <ScalarOperator>\n <Identifier>\n <ColumnReference Column=\"partialagg1082\"/>\n </Identifier>\n </ScalarOperator>\n </Aggregate>\n </ScalarOperator>\n </DefinedValue>\n </DefinedValues>\n <HashKeysBuild>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n </HashKeysBuild>\n <BuildResidual>\n <ScalarOperator ScalarString=\"[DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[APPL_CD] as [m].[APPL_CD] = [DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[APPL_CD] as [m].[APPL_CD] AND [DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[ALBASE] as [m].[ALBASE] = [DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[ALBASE] as [m].[ALBASE]\">\n <Logical Operation=\"AND\">\n <ScalarOperator>\n <Compare CompareOp=\"IS\">\n <ScalarOperator>\n <Identifier>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n </Identifier>\n </ScalarOperator>\n <ScalarOperator>\n <Identifier>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n </Identifier>\n </ScalarOperator>\n </Compare>\n </ScalarOperator>\n <ScalarOperator>\n <Compare CompareOp=\"IS\">\n <ScalarOperator>\n <Identifier>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n </Identifier>\n </ScalarOperator>\n <ScalarOperator>\n <Identifier>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n </Identifier>\n </ScalarOperator>\n </Compare>\n </ScalarOperator>\n </Logical>\n </ScalarOperator>\n </BuildResidual>\n <RelOp NodeId=\"8\" PhysicalOp=\"Parallelism\" LogicalOp=\"Repartition Streams\" EstimateRows=\"28560\" EstimateIO=\"0\" EstimateCPU=\"0.0614707\" AvgRowSize=\"27\" EstimatedTotalSubtreeCost=\"362.613\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\">\n <OutputList>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n <ColumnReference Column=\"partialagg1082\"/>\n </OutputList>\n <Parallelism PartitioningType=\"Hash\">\n <PartitionColumns>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n </PartitionColumns>\n <RelOp NodeId=\"9\" PhysicalOp=\"Hash Match\" LogicalOp=\"Partial Aggregate\" EstimateRows=\"28560\" EstimateIO=\"0\" EstimateCPU=\"1.7277\" AvgRowSize=\"27\" EstimatedTotalSubtreeCost=\"362.551\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\">\n <OutputList>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n <ColumnReference Column=\"partialagg1082\"/>\n </OutputList>\n <MemoryFractions Input=\"0\" Output=\"0\"/>\n <Hash>\n <DefinedValues>\n <DefinedValue>\n <ColumnReference Column=\"partialagg1082\"/>\n <ScalarOperator ScalarString=\"COUNT(*)\">\n <Aggregate Distinct=\"0\" AggType=\"COUNT*\"/>\n </ScalarOperator>\n </DefinedValue>\n </DefinedValues>\n <HashKeysBuild>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n </HashKeysBuild>\n <BuildResidual>\n <ScalarOperator ScalarString=\"[DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[APPL_CD] as [m].[APPL_CD] = [DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[APPL_CD] as [m].[APPL_CD] AND [DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[ALBASE] as [m].[ALBASE] = [DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[ALBASE] as [m].[ALBASE]\">\n <Logical Operation=\"AND\">\n <ScalarOperator>\n <Compare CompareOp=\"IS\">\n <ScalarOperator>\n <Identifier>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n </Identifier>\n </ScalarOperator>\n <ScalarOperator>\n <Identifier>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n </Identifier>\n </ScalarOperator>\n </Compare>\n </ScalarOperator>\n <ScalarOperator>\n <Compare CompareOp=\"IS\">\n <ScalarOperator>\n <Identifier>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n </Identifier>\n </ScalarOperator>\n <ScalarOperator>\n <Identifier>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n </Identifier>\n </ScalarOperator>\n </Compare>\n </ScalarOperator>\n </Logical>\n </ScalarOperator>\n </BuildResidual>\n <RelOp NodeId=\"10\" PhysicalOp=\"Hash Match\" LogicalOp=\"Inner Join\" EstimateRows=\"879583\" EstimateIO=\"0\" EstimateCPU=\"62.0602\" AvgRowSize=\"19\" EstimatedTotalSubtreeCost=\"360.824\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\">\n <OutputList>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n </OutputList>\n <MemoryFractions Input=\"1\" Output=\"0.5\"/>\n <Hash>\n <DefinedValues/>\n <HashKeysBuild>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISProcess]\" Table=\"[SXProcessCatalog]\" Alias=\"[cat]\" Column=\"APPL_CD\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISProcess]\" Table=\"[SXProcessCatalog]\" Alias=\"[cat]\" Column=\"ALBASE\"/>\n </HashKeysBuild>\n <HashKeysProbe>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/>\n <ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/>\n </HashKeysProbe>\n <ProbeResidual>\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18255/"
] |
164,168
|
<p>If I want to construct a std::string with a line like:</p>
<pre><code>std::string my_string("a\0b");
</code></pre>
<p>Where i want to have three characters in the resulting string (a, null, b), I only get one. What is the proper syntax?</p>
|
[
{
"answer_id": 164185,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 4,
"selected": false,
"text": "std::string my_string(\"a\\0b\", 3);\n"
},
{
"answer_id": 164211,
"author": "Jurney",
"author_id": 2642,
"author_profile": "https://Stackoverflow.com/users/2642",
"pm_score": -1,
"selected": false,
"text": "std::string s(\"aab\");\ns.at(1) = '\\0';\n"
},
{
"answer_id": 164220,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": 3,
"selected": false,
"text": "std::string s;\ns.push_back('a');\ns.push_back('\\0');\ns.push_back('b');\n"
},
{
"answer_id": 164257,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 5,
"selected": false,
"text": "std::vector<char>\n std::vector<char> vec(100)\nstrncpy(&vec[0], \"blah blah blah\", 100);\nstd::string vecAsStr( vec.begin(), vec.end());\n printf(\"%s\" &vec[0])\nvec[10] = '\\0';\nvec[11] = 'b';\n"
},
{
"answer_id": 164274,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 8,
"selected": true,
"text": "std::string #include <iostream>\n#include <string>\n\nint main()\n{\n using namespace std::string_literals;\n\n std::string s = \"pl-\\0-op\"s; // <- Notice the \"s\" at the end\n // This is a std::string literal not\n // a C-String literal.\n std::cout << s << \"\\n\";\n}\n std::string const char* \\0 \\0 std::string x(\"pq\\0rs\"); // Two characters because input assumed to be C-String\nstd::string x(\"pq\\0rs\",5); // 5 Characters as the input is now a char array with 5 characters.\n std::string \\0 c_str() vector<char>"
},
{
"answer_id": 2175911,
"author": "Dil09",
"author_id": 263408,
"author_profile": "https://Stackoverflow.com/users/263408",
"pm_score": -1,
"selected": false,
"text": "CComBSTR(20,\"mystring1\\0mystring2\\0\")\n"
},
{
"answer_id": 12738351,
"author": "anonym",
"author_id": 1721734,
"author_profile": "https://Stackoverflow.com/users/1721734",
"pm_score": 4,
"selected": false,
"text": "std::string operator \"\" _s(const char* str, size_t n) \n{ \n return std::string(str, n); \n}\n std::string my_string(\"a\\0b\"_s);\n auto my_string = \"a\\0b\"_s;\n #define S(s) s, sizeof s - 1 // trailing NUL does not belong to the string\n std::string my_string(S(\"a\\0b\"));\n"
},
{
"answer_id": 12884464,
"author": "David Stone",
"author_id": 852254,
"author_profile": "https://Stackoverflow.com/users/852254",
"pm_score": 3,
"selected": false,
"text": "// Create '\\0' followed by '0' 40 times ;)\nstd::string str(\"\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\", 80);\nstd::cerr << \"Entering loop.\\n\";\nfor (char & c : str) {\n std::cerr << c;\n // 'Q' is way cooler than '\\0' or '0'\n c = 'Q';\n}\nstd::cerr << \"\\n\";\nfor (char & c : str) {\n std::cerr << c;\n}\nstd::cerr << \"\\n\";\n Entering loop.\nEntering loop.\n\nvector::_M_emplace_ba\nQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ\n std::string(\"0\", 100); std::string str({'a', '\\0', 'b'}) char"
},
{
"answer_id": 34723611,
"author": "RiaD",
"author_id": 768110,
"author_profile": "https://Stackoverflow.com/users/768110",
"pm_score": 2,
"selected": false,
"text": "using namespace std::literals::string_literals;\nstd::string s = \"a\\0b\"s;\nstd::cout << s.size(); // 3\n"
},
{
"answer_id": 40514043,
"author": "Kyle Strand",
"author_id": 1858225,
"author_profile": "https://Stackoverflow.com/users/1858225",
"pm_score": 1,
"selected": false,
"text": "template <size_t N>\nstd::string RawString(const char (&ch)[N])\n{\n return std::string(ch, N-1); // Again, exclude trailing `null`\n}\n RawString(/* literal */) S(/* literal */) std::string my_string_t(RawString(\"a\\0b\"));\nstd::string my_string_m(S(\"a\\0b\"));\nstd::cout << \"Using template: \" << my_string_t << std::endl;\nstd::cout << \"Using macro: \" << my_string_m << std::endl;\n std::string std::string s = S(\"a\\0b\"); // ERROR!\n #define std::string(s, sizeof s - 1)\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17958/"
] |
164,181
|
<p>How can I fetch images from a server?</p>
<p>I've got this bit of code which allows me to draw some images on a canvas.</p>
<pre><code><html>
<head>
<script type="text/javascript">
function draw(){
var canvas = document.getElementById('canv');
var ctx = canvas.getContext('2d');
for (i=0;i<document.images.length;i++){
ctx.drawImage(document.images[i],i*150,i*130);
}
}
</script>
</head>
<body onload="draw();">
<canvas id="canv" width="1024" height="1024"></canvas>
<img src="http://www.google.com/intl/en_ALL/images/logo.gif">
<img src="http://l.yimg.com/a/i/ww/beta/y3.gif">
<img src="http://static.ak.fbcdn.net/images/welcome/welcome_page_map.png">
</body>
</html>
</code></pre>
<p>Instead of looping over document.images, i would like to continually fetch images from a server.</p>
<pre><code>for (;;) {
/* how to fetch myimage??? */
myimage = fetch???('http://myserver/nextimage.cgi');
ctx.drawImage(myimage, x, y);
}
</code></pre>
|
[
{
"answer_id": 164191,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 6,
"selected": true,
"text": "myimage = new Image();\nmyimage.src = 'http://myserver/nextimage.cgi';\n myimage = new Image();\nmyimage.onload = function() {\n ctx.drawImage(myimage, x, y);\n }\nmyimage.src = 'http://myserver/nextimage.cgi';\n"
},
{
"answer_id": 164210,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 2,
"selected": false,
"text": "myimage = new Image()\nmyimage.src='http://....'\n"
},
{
"answer_id": 164262,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": -1,
"selected": false,
"text": "$.('<img src=\"http://myserver/nextimage.cgi\" />').appendTo('#canv');\n"
},
{
"answer_id": 165387,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 3,
"selected": false,
"text": "myimage = new Image();\nmyimage.onload = function() {\n context.drawImage(myimage, ...);\n}\nmyimage.src = 'http://myserver/nextimage.cgi';\n"
},
{
"answer_id": 9636983,
"author": "TheCrzyMan",
"author_id": 1259665,
"author_profile": "https://Stackoverflow.com/users/1259665",
"pm_score": 1,
"selected": false,
"text": "Image.prototype.position = {\n x: 0,\n y: 0\n}\n\nImage.prototype.onload = function(){\n context.drawImage(this, this.position.x, this.position.y);\n}\n var myImg = new Image();\nmyImg.position.x = 20;\nmyImg.position.y = 200;\nmyImg.src = \"http://www.google.com/intl/en_ALL/images/logo.gif\";\n Array.prototype.sum = function(){\n var _sum = 0.0;\n for (var i=0; i<this.length; i++){\n _sum += parseFloat(this[i]);\n }\n return _sum;\n}\n var Bob;\nBob.Prototype.sayHi = function(){\n alert(\"Hello there.\");\n}\n var Bob = function(){\n this.sayHi = function(){\n alert(\"Hello there.\");\n }\n}\n"
},
{
"answer_id": 70388230,
"author": "Ray Foss",
"author_id": 370238,
"author_profile": "https://Stackoverflow.com/users/370238",
"pm_score": 0,
"selected": false,
"text": "class App {\n imageUrl = 'https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE4HZBo'\n\n constructor(dom) {\n this.start(dom)\n }\n\n async start(dom) {\n const appEl = dom.createElement('div')\n dom.body.append(appEl)\n \n const imageEl = await this.loadImage(this.imageUrl)\n \n const canvas = dom.createElement('canvas')\n canvas.width = imageEl.width\n canvas.height = imageEl.height\n const ctx = canvas.getContext('2d')\n ctx.drawImage(imageEl, 0, 0)\n \n appEl.append(canvas)\n }\n \n loadImage = async (url) => \n new Promise((resolve) => {\n const imageEl = new Image()\n imageEl.src = url\n imageEl.onload = () => resolve(imageEl)\n })\n}\n\nnew App(document)"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
164,194
|
<p>The following code receives seg fault on line 2:</p>
<pre><code>char *str = "string";
str[0] = 'z'; // could be also written as *str = 'z'
printf("%s\n", str);
</code></pre>
<p>While this works perfectly well:</p>
<pre><code>char str[] = "string";
str[0] = 'z';
printf("%s\n", str);
</code></pre>
<p>Tested with MSVC and GCC.</p>
|
[
{
"answer_id": 164227,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "\"whatever\" const char *"
},
{
"answer_id": 164229,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 7,
"selected": false,
"text": "\"string\" *str 'z' \"string\" str[] printf(\"%p\", str);\n str printf(\"%d\", sizeof(str));\n"
},
{
"answer_id": 164233,
"author": "DougN",
"author_id": 7442,
"author_profile": "https://Stackoverflow.com/users/7442",
"pm_score": 3,
"selected": false,
"text": "char *str = \"string\"; \n str \"string\" str[0]="
},
{
"answer_id": 164235,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 4,
"selected": false,
"text": "char str[7] = { 's', 't', 'r', 'i', 'n', 'g', '\\0' };\n"
},
{
"answer_id": 164239,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 3,
"selected": false,
"text": "char *str = \"string\";\n char str[] = \"string\";\n"
},
{
"answer_id": 164256,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": " char *str = \"string\";\n str[0] = 'z';\n char str[] = \"string\";\n"
},
{
"answer_id": 164258,
"author": "matli",
"author_id": 23896,
"author_profile": "https://Stackoverflow.com/users/23896",
"pm_score": 9,
"selected": true,
"text": "char a[] = \"string literal\"; char *p = \"string literal\"; p[i] char a[]"
},
{
"answer_id": 164265,
"author": "David Thornley",
"author_id": 14148,
"author_profile": "https://Stackoverflow.com/users/14148",
"pm_score": 1,
"selected": false,
"text": "str \"string\" const char * char * \"string\" char[7]"
},
{
"answer_id": 8934638,
"author": "jokeysmurf",
"author_id": 1024343,
"author_profile": "https://Stackoverflow.com/users/1024343",
"pm_score": 2,
"selected": false,
"text": "// create a string constant like this - will be read only\nchar *str_p;\nstr_p = \"String constant\";\n\n// create an array of characters like this \nchar *arr_p;\nchar arr[] = \"String in an array\";\narr_p = &arr[0];\n\n// now we try to change a character in the array first, this will work\n*arr_p = 'E';\n\n// lets try to change the first character of the string contant\n*str_p = 'G'; // this will result in a segmentation fault. Comment it out to work.\n\n\n/*-----------------------------------------------------------------------------\n * String constants can't be modified. A segmentation fault is the result,\n * because most operating systems will not allow a write\n * operation on read only memory.\n *-----------------------------------------------------------------------------*/\n\n//print both strings to see if they have changed\nprintf(\"%s\\n\", str_p); //print the string without a variable\nprintf(\"%s\\n\", arr_p); //print the string, which is in an array. \n"
},
{
"answer_id": 14145422,
"author": "Raghu Srikanth Reddy",
"author_id": 589026,
"author_profile": "https://Stackoverflow.com/users/589026",
"pm_score": -1,
"selected": false,
"text": "char *str char str[]"
},
{
"answer_id": 20441961,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": " char strarray[] = \"hello\";\n [h][e][l][l][o][\\0] =>[] strarray \"hello\" `strarray[0]='m'` it access character at index 0 which is 'h'in strarray\n 'm' \"mello\" strarray=\"new string\" char *ptr = \"hello\";\n \"hello\" \"hello\" \"hello\" ptr=\"new string\"; is valid\n"
},
{
"answer_id": 30662213,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 5,
"selected": false,
"text": "char[] char c[] = \"abc\"; \n char c[] = {'a', 'b', 'c', '\\0'};\n c char *c = \"abc\";\n /* __unnamed is magic because modifying it gives UB. */\nstatic char __unnamed[] = \"abc\";\nchar *c = __unnamed;\n char[] char * c[0] __unnamed char s[] = \"abc\", t[3] = \"abc\";\n s t char s[] = { 'a', 'b', 'c', '\\0' },\nt[] = { 'a', 'b', 'c' };\n char *p = \"abc\";\n p p #include <stdio.h>\n\nint main(void) {\n char *s = \"abc\";\n printf(\"%s\\n\", s);\n return 0;\n}\n gcc -ggdb -std=c99 -c main.c\nobjdump -Sr main.o\n char *s = \"abc\";\n8: 48 c7 45 f8 00 00 00 movq $0x0,-0x8(%rbp)\nf: 00 \n c: R_X86_64_32S .rodata\n char* .rodata .text char[] char s[] = \"abc\";\n 17: c7 45 f0 61 62 63 00 movl $0x636261,-0x10(%rbp)\n %rbp .rodata .text readelf -l a.out\n Section to Segment mapping:\n Segment Sections...\n 02 .text .rodata\n"
},
{
"answer_id": 54517972,
"author": "Venki",
"author_id": 751865,
"author_profile": "https://Stackoverflow.com/users/751865",
"pm_score": 1,
"selected": false,
"text": "char a[] = \"string literal copied to stack\";\nchar *p = \"string literal referenced by p\";\n"
},
{
"answer_id": 68607670,
"author": "Hari",
"author_id": 1047213,
"author_profile": "https://Stackoverflow.com/users/1047213",
"pm_score": 1,
"selected": false,
"text": "Section 5.5 Character Pointers and Functions K&R char amessage[] = \"now is the time\"; /* an array */ char *pmessage = \"now is the time\"; /* a pointer */ amessage '\\0' amessage pmessage"
},
{
"answer_id": 69005668,
"author": "Tim Skov Jacobsen",
"author_id": 5993892,
"author_profile": "https://Stackoverflow.com/users/5993892",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n\nint main(void) {\n char *s = \"hello\";\n printf(\"%p\\n\", &s); // Prints a read-only address, e.g. 0x7ffc8e224620\n return 0;\n}\n s s[0] = 'H';\n Segmentation fault (core dumped) 0x7ffc8e224620 \"Hello\" 0x7ffc8e224620 #include <stdio.h>\n\nint main(void) {\n // We create an array from a string literal with address 0x7ffc8e224620.\n // C initializes an array variable in the stack, let's give it address\n // 0x7ffc7a9a9db2.\n // C then copies the read-only value from 0x7ffc8e224620 into \n // 0x7ffc7a9a9db2 to give us a local copy we can mutate.\n char a[] = \"hello\";\n\n // We can now mutate the local copy\n a[0] = 'H';\n\n printf(\"%p\\n\", &a); // Prints the Stack address, e.g. 0x7ffc7a9a9db2\n printf(\"%s\\n\", a); // Prints \"Hello\"\n\n return 0;\n}\n const const *s = \"hello\" error: assignment of read-only location ‘*s’"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24622/"
] |
164,197
|
<p>I am working on an ASP.Net web application that must print dynamically created labels on standard Avery-style label sheets (one particular size, so only one overall layout). The labels have a variable number of lines (3-6) and may contain either lines of text or a graphic barcode image.</p>
<p>Our first cut, that I inherited, used monospaced fonts to reduce the formatting issues, but that did not allow enough text to the fit on the labels and the customer was dissatisfied. Basically it was formatted text.</p>
<p>My next version used TABLEs, DIVs, CSS, and a bit of JavaScript calculations to format the labels using proportional fonts. It still required a bit of tweaking (the user had to set their print margins correctly and turn off the print headers and footers), but it seemed to work. </p>
<p>However, it seems that there are some variations on how different printers render the text (WYS ain't WYG), so even though we tested on different browsers using at least two different printers (an inkjet and a laser printer), some user's labels don't line up. Slight margin variations can be adjusted by adjusting the margins on the page setup dialog, but the harder problem is that the inter-label spacing can be off by a tiny fraction of an inch, so that if the first label is pretty well centered, by the end of the page the label text and images have crawled off the top or bottom of the labels.</p>
<p>We are about to the point of switching to generating Word, Excel, or PDF output which is going to take quite a bit of development time and possible add extra steps in the printing process.</p>
<p>So, does anyone have any suggestions on how to do an HTML/CSS layout that will precisely render on different types of printers? I don't really care if the line/word breaks are a bit different, but I need to be able to predictably position the upper left corners of each label area.</p>
<p>Right now the labels flow down the page in a table and we have been tweaking the box model of the cells and internal DIVs to make them a uniform height. I suspect that using absolute positioning of each element may be the best answer, but that is going to be tricky as well due to the ASP.Net generation of the label elements. If I knew for sure that would work, I would rather try it than throw away everything we have to go to a different generation method.</p>
<p>Slight Update:
Right now I'm doing some tests with absolute positioning - setting only the top and left coordinate of a containing block element. So far there are minor variations on the offset onto the page (margins, paper alignment, etc.), but all browsers and printers tested put the elements in <strong><em>exactly</em></strong> the right spots relative to each other. I appreciate the PDF tips, but does anyone know of additional "gotchas" on using absolute positioning this way?</p>
<p><strong>Update:</strong>
For the record, I rewrote the label printing portion using iTextSharp and it works perfectly - definitely the way to do this in the future...</p>
|
[
{
"answer_id": 33681423,
"author": "Bill Rawlinson",
"author_id": 7329,
"author_profile": "https://Stackoverflow.com/users/7329",
"pm_score": 2,
"selected": false,
"text": "LabelDefinition"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14894/"
] |
164,282
|
<p>Specifically, we've got some external JavaScript tracking code on our sites that throws itself into an infinite loop each time an anchor is clicked on.</p>
<p>We don't maintain the tracking code, so we don't know exactly how it works. Since the code causes the browser to lock up almost immediately, I was wondering if there's anyway to log the results of Firebug's 'profile' functionality to an external file for review?</p>
|
[
{
"answer_id": 33681423,
"author": "Bill Rawlinson",
"author_id": 7329,
"author_profile": "https://Stackoverflow.com/users/7329",
"pm_score": 2,
"selected": false,
"text": "LabelDefinition"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22468/"
] |
164,284
|
<p>I would like to transfer a text file to a webserver using wininet as if the file was being transferred using a web form that posts the file to the server.</p>
<p>Based on answers I've received I've tried the following code:</p>
<pre><code> static TCHAR hdrs[] = "Content-Type: multipart/form-data\nContent-Length: 25";
static TCHAR frmdata[] = "file=filename.txt\ncontent";
HINTERNET hSession = InternetOpen("MyAgent",
INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
HINTERNET hConnect = InternetConnect(hSession, "example.com",
INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
HINTERNET hRequest = HttpOpenRequest(hConnect, "POST", "test.php", NULL, NULL, NULL, 0, 1);
HttpSendRequest(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata));");
</code></pre>
<p>The test.php script is being run, but it doesn't appear to be getting the correct data.</p>
<p>Could anyone give me any additional help or somewhere to look? Thanks.</p>
|
[
{
"answer_id": 164502,
"author": "Gustavo Carreno",
"author_id": 8167,
"author_profile": "https://Stackoverflow.com/users/8167",
"pm_score": 2,
"selected": false,
"text": "POST /file_upload.php HTTP/1.0\nContent-type: multipart/form-data\nContent-length: <calculated string's length: integer>\n\nfile=filename.txt\n...File Content...\n <?php\n// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead\n// of $_FILES.\n\n$uploaddir = '/var/www/uploads/';\n$uploadfile = $uploaddir . basename($_FILES['file']['name']);\n\necho '<pre>';\nif (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {\n echo \"File is valid, and was successfully uploaded.\\n\";\n} else {\n echo \"Possible file upload attack!\\n\";\n}\n\necho 'Here is some more debugging info:';\nprint_r($_FILES);\n\nprint \"</pre>\";\n\n?>\n"
},
{
"answer_id": 167269,
"author": "Rob",
"author_id": 24628,
"author_profile": "https://Stackoverflow.com/users/24628",
"pm_score": 2,
"selected": true,
"text": " static TCHAR frmdata[] = \"-----------------------------7d82751e2bc0858\\nContent-Disposition: form-data; name=\\\"uploadedfile\\\"; filename=\\\"file.txt\\\"\\nContent-Type: text/plain\\n\\nfile contents here\\n-----------------------------7d82751e2bc0858--\";\n static TCHAR hdrs[] = \"Content-Type: multipart/form-data; boundary=---------------------------7d82751e2bc0858\";\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24628/"
] |
164,305
|
<p>I'm using CodeSynthesis XSD C++/Tree Mapping utility to convert an existing xsd into c++ code we can populate the values in. This was we always make sure we follow the schema.</p>
<p>After doing the conversion, I'm trying to get it to work so I can test it. Problem is, I'm not used to doing this in c++ and it's my first time with this tool.</p>
<p>I start with a class called ABSTRACTNETWORKMODEL with types <code>versno_type</code> and <code>fromtime_type</code>
typedef'd inside. Here is the constructor I am trying to use as well as the typedefs</p>
<pre><code>ABSTRACTNETWORKMODEL(const versno_type&, const fromtime_type&);
typedef ::xml_schema::double_ versno_type;
typedef ::xml_schema::time fromtime_type;
</code></pre>
<p>all these are in the ABSTRACTNETWORKMODEL class and the definitions for double_ and time are:</p>
<pre><code>typedef ::xsd::cxx::tree::time<char, simple_type> time;
typedef double double_;
</code></pre>
<p>where the definition for time is a class with multiple constructors:</p>
<pre><code>template<typename C, typename B>
class time: public B, public time_zone
{
public:
time(unsigned short hours, unsigned short minutes, double seconds);
...
}
</code></pre>
<p>I know I'm not correctly creating a new ABSTRACTNETWORKMODEL but I don't know what I need to do this. Here is all I'm trying to do at this point:</p>
<pre><code> ::xml_schema::time t();
ABSTRACTNETWORKMODEL anm(1234, t);
</code></pre>
<p>This, of course, throws an error about converting the second parameter, but can somebody tell me what it is that is incorrect? Or at least point me down the right path, as one of the things I'm trying to do right now is learn more c++.</p>
|
[
{
"answer_id": 168157,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 3,
"selected": true,
"text": "::xml_schema::time t();\n ::xml_schema::time t;\n ::xml_schema::time ABSTRACTNETWORKMODEL ::xml_schema::time t();\nABSTRACTNETWORKMODEL anm(1234, t()); // calls t(), gets a temporary of type ::xml_schema::time, and passes the temporary to the constructor\n int hours = time().get_hours(); // assuming that there is now a default constructor\n int hours = time.set_time(\"12:00:00am\"); // error: there is a time class, but no object named \"time\"\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23553/"
] |
164,307
|
<p>With the MacPorts version of ImageMagick 6.4.4 installed, I'm getting an error installing the RMagick gem.</p>
<pre><code>/opt/local/bin/ruby extconf.rb update rmagick
checking for Ruby version >= 1.8.2... yes
checking for /usr/bin/gcc-4.0... yes
checking for Magick-config... no
Can't install RMagick 2.7.0. Can't find Magick-config in
/System/Library/Frameworks/JavaVM.framework/Versions/1.5/Commands:
/Users/jason/.bin:/opt/local/bin:/usr/local/bin:/usr/local/mysql/bin:
/usr/local/ec2-api-tools/bin:/opt/local/bin:/usr/bin:
/usr/local/bin:/bin:/usr/sbin:/sbin:/usr/X11/bin
</code></pre>
<p>I've installed older versions of rmagick successfully. I've seen references to a dev package of ImageMagick, but it doesn't seem to be available from MacPorts.</p>
<p>How can I install RMagick 2.7 on Mac OS X with ImageMagick 6.4.4 from MacPorts?</p>
|
[
{
"answer_id": 165656,
"author": "user6325",
"author_id": 6325,
"author_profile": "https://Stackoverflow.com/users/6325",
"pm_score": 3,
"selected": false,
"text": "sudo port install tiff -macosx imagemagick +q8 +gs +wmf\n"
},
{
"answer_id": 1476485,
"author": "ehaselwanter",
"author_id": 97734,
"author_profile": "https://Stackoverflow.com/users/97734",
"pm_score": 1,
"selected": false,
"text": "/Library/Ruby/Gems/1.8/gems/rmagick-2.11.1/lib/RMagick2.bundle RMagick2.so"
},
{
"answer_id": 4328661,
"author": "balexand",
"author_id": 239965,
"author_profile": "https://Stackoverflow.com/users/239965",
"pm_score": 5,
"selected": false,
"text": "brew install imagemagick\ngem install rmagick\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11078/"
] |
164,319
|
<p>I learned something simple about SQL the other day:</p>
<pre><code>SELECT c FROM myTbl GROUP BY C
</code></pre>
<p>Has the same result as:</p>
<pre><code>SELECT DISTINCT C FROM myTbl
</code></pre>
<p>What I am curious of, is there anything different in the way an SQL engine processes the command, or are they truly the same thing? </p>
<p>I personally prefer the distinct syntax, but I am sure it's more out of habit than anything else.</p>
<p>EDIT: This is not a question about aggregates. The use of <code>GROUP BY</code> with aggregate functions is understood.</p>
|
[
{
"answer_id": 164329,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 8,
"selected": false,
"text": "GROUP BY AVG MAX MIN SUM COUNT DISTINCT SELECT department, SUM(amount) FROM purchases GROUP BY department\n amount"
},
{
"answer_id": 164331,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 5,
"selected": false,
"text": "DISTINCT GROUPY BY MAX SUM GROUP_CONCAT HAVING"
},
{
"answer_id": 164332,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": false,
"text": "SELECT C FROM myTbl GROUP BY C, D\n"
},
{
"answer_id": 164352,
"author": "Danimal",
"author_id": 2757,
"author_profile": "https://Stackoverflow.com/users/2757",
"pm_score": 2,
"selected": false,
"text": "select C, count(B) from myTbl group by C\n"
},
{
"answer_id": 164357,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 2,
"selected": false,
"text": "SELECT name, SUM(transaction) FROM myTbl GROUP BY name\n"
},
{
"answer_id": 164376,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 3,
"selected": false,
"text": "name\n------\nbarry\ndave\nbill\ndave\ndave\nbarry\njohn\n SELECT name, count(*) AS count FROM table GROUP BY name;\n name count\n-------------\nbarry 2\ndave 3\nbill 1\njohn 1\n"
},
{
"answer_id": 164533,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 5,
"selected": false,
"text": "core> select sta from zip group by sta;\n\n---------------------------------------------------------------------------\n| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |\n---------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 58 | 174 | 44 (19)| 00:00:01 |\n| 1 | HASH GROUP BY | | 58 | 174 | 44 (19)| 00:00:01 |\n| 2 | TABLE ACCESS FULL| ZIP | 42303 | 123K| 38 (6)| 00:00:01 |\n---------------------------------------------------------------------------\n\ncore> select distinct sta from zip;\n\n---------------------------------------------------------------------------\n| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |\n---------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 58 | 174 | 44 (19)| 00:00:01 |\n| 1 | HASH UNIQUE | | 58 | 174 | 44 (19)| 00:00:01 |\n| 2 | TABLE ACCESS FULL| ZIP | 42303 | 123K| 38 (6)| 00:00:01 |\n---------------------------------------------------------------------------\n"
},
{
"answer_id": 164544,
"author": "Skeolan",
"author_id": 9640,
"author_profile": "https://Stackoverflow.com/users/9640",
"pm_score": 9,
"selected": true,
"text": "Hammer : Screwdriver :: GroupBy : Distinct screw => get list of unique values in a table column"
},
{
"answer_id": 164605,
"author": "Zenshai",
"author_id": 17785,
"author_profile": "https://Stackoverflow.com/users/17785",
"pm_score": 0,
"selected": false,
"text": "select distinct a, b, c from table;\n select a, b, c from table group by a, b, c\n"
},
{
"answer_id": 166194,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 2,
"selected": false,
"text": "SELECT COUNT(DISTINCT C) FROM myTbl;\n\nSELECT DISTINCT COUNT(C) FROM myTbl;\n"
},
{
"answer_id": 10639305,
"author": "The Light",
"author_id": 133212,
"author_profile": "https://Stackoverflow.com/users/133212",
"pm_score": 4,
"selected": false,
"text": "SELECT distinct ROW_NUMBER() OVER (ORDER BY Name), Name FROM NamesTable\n\n SELECT ROW_NUMBER() OVER (ORDER BY Name), Name FROM NamesTable\nGROUP BY Name\n"
},
{
"answer_id": 28437372,
"author": "Vinod Narwal",
"author_id": 3285874,
"author_profile": "https://Stackoverflow.com/users/3285874",
"pm_score": -1,
"selected": false,
"text": "Declare @tmpresult table\n(\n Id tinyint\n)\n\nInsert into @tmpresult\nSelect 5\nUnion all\nSelect 2\nUnion all\nSelect 3\nUnion all\nSelect 4\n\n\nSelect distinct \nId\nFrom @tmpresult\n"
},
{
"answer_id": 45833583,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 6,
"selected": false,
"text": "DISTINCT GROUP BY SELECT FROM JOIN APPLY WHERE GROUP BY HAVING SELECT DISTINCT UNION INTERSECT EXCEPT ORDER BY OFFSET LIMIT GROUP BY SELECT SELECT rating, row_number() OVER (ORDER BY rating) AS rn\nFROM film\nGROUP BY rating\n rating rn\n-----------\nG 1\nNC-17 2\nPG 3\nPG-13 4\nR 5\n DISTINCT SELECT DISTINCT rating, row_number() OVER (ORDER BY rating) AS rn\nFROM film\n rating rn\n------------\nG 1\nG 2\nG 3\n...\nG 178\nNC-17 179\nNC-17 180\n...\n DISTINCT DISTINCT DISTINCT SELECT rating, row_number() OVER (ORDER BY rating) AS rn\nFROM (\n SELECT DISTINCT rating FROM film\n) f\n DENSE_RANK() SELECT DISTINCT rating, dense_rank() OVER (ORDER BY rating) AS rn\nFROM film\n SELECT first_name || ' ' || last_name AS name\nFROM customer\nGROUP BY name\n SELECT first_name || ' ' || last_name AS name\nFROM customer\nGROUP BY first_name || ' ' || last_name\n SELECT name\nFROM (\n SELECT first_name || ' ' || last_name AS name\n FROM customer\n) c\nGROUP BY name\n"
},
{
"answer_id": 51126218,
"author": "John Jiang",
"author_id": 437441,
"author_profile": "https://Stackoverflow.com/users/437441",
"pm_score": 1,
"selected": false,
"text": "GROUP BY DISTINCT"
},
{
"answer_id": 57084722,
"author": "SkyRar",
"author_id": 4753716,
"author_profile": "https://Stackoverflow.com/users/4753716",
"pm_score": 2,
"selected": false,
"text": "DISTINCT DISTINCT GROUP BY Branch SELECT * FROM student; \n+------+--------+------+\n| Id | Branch | CGPA |\n+------+--------+------+\n| 3 | civil | 7.2 |\n| 2 | mech | 6.3 |\n| 6 | cs | 9.1 |\n| 4 | eee | 8.2 |\n| 1 | cs | 5.5 |\n+------+--------+------+\n5 rows in set (0.001 sec)\n\nSELECT DISTINCT * FROM student; \n+------+--------+------+\n| Id | Branch | CGPA |\n+------+--------+------+\n| 3 | civil | 7.2 |\n| 2 | mech | 6.3 |\n| 6 | cs | 9.1 |\n| 4 | eee | 8.2 |\n| 1 | cs | 5.5 |\n+------+--------+------+\n5 rows in set (0.001 sec)\n\nSELECT * FROM student GROUP BY Branch;\n+------+--------+------+\n| Id | Branch | CGPA |\n+------+--------+------+\n| 3 | civil | 7.2 |\n| 6 | cs | 9.1 |\n| 4 | eee | 8.2 |\n| 2 | mech | 6.3 |\n+------+--------+------+\n4 rows in set (0.001 sec)\n GROUP BY DISTINCT DISTINCT GROUP BY GROUP BY SELECT * FROM student GROUP BY Id, Branch, CGPA;\n+------+--------+------+\n| Id | Branch | CGPA |\n+------+--------+------+\n| 1 | cs | 5.5 |\n| 2 | mech | 6.3 |\n| 3 | civil | 7.2 |\n| 4 | eee | 8.2 |\n| 6 | cs | 9.1 |\n+------+--------+------+\n GROUP BY DISTINCT"
},
{
"answer_id": 57729375,
"author": "Lova Chittumuri",
"author_id": 5256337,
"author_profile": "https://Stackoverflow.com/users/5256337",
"pm_score": 0,
"selected": false,
"text": "DISTINCT AVG MAX MIN SUM COUNT select specialColumn,sum(specialColumn) from yourTableName group by specialColumn;\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5836/"
] |
164,324
|
<p>I need to get the Folder size and display the info on a report (SSRS). I need to do this for a number of Databases (loop!). These DB's are websites' backends.</p>
<p>Are any samples available for this? Does xp_filesize and the like the right solution?</p>
|
[
{
"answer_id": 179648,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "System.IO.Directory"
},
{
"answer_id": 186836,
"author": "Meff",
"author_id": 9647,
"author_profile": "https://Stackoverflow.com/users/9647",
"pm_score": 3,
"selected": true,
"text": "Public Shared Function GetFolderSize(ByVal DirPath As String, _\n Optional IncludeSubFolders as Boolean = True) As Long\n\n Dim lngDirSize As Long\n Dim objFileInfo As FileInfo\n Dim objDir As DirectoryInfo = New DirectoryInfo(DirPath)\n Dim objSubFolder As DirectoryInfo\n\nTry\n\n'add length of each file\n For Each objFileInfo In objDir.GetFiles()\n lngDirSize += objFileInfo.Length\n Next\n\n 'call recursively to get sub folders\n 'if you don't want this set optional\n 'parameter to false \nIf IncludeSubFolders then\n For Each objSubFolder In objDir.GetDirectories()\n lngDirSize += GetFolderSize(objSubFolder.FullName)\n Next\nEnd if\n\nCatch Ex As Exception\n\n\nEnd Try\n\n Return lngDirSize\nEnd Function\n =Code.GetFolderSize(Fields!FolderPath.Value)\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10385/"
] |
164,335
|
<p>Any XPath like /NodeName/position() would give you the position of the Node w.r.t it's parent node.</p>
<p>There is no method on the XElement (Linq to XML) object that can get the position of the Element. Is there?</p>
|
[
{
"answer_id": 164444,
"author": "Michael Damatov",
"author_id": 23372,
"author_profile": "https://Stackoverflow.com/users/23372",
"pm_score": 0,
"selected": false,
"text": "static int Position(this XNode node) {\n var position = 0;\n foreach(var n in node.Parent.Nodes()) {\n if(n == node) {\n return position;\n }\n position++;\n }\n return -1;\n}\n"
},
{
"answer_id": 164462,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 3,
"selected": false,
"text": " XElement root = new XElement(\"root\",\n new XElement(\"one\", \n new XElement(\"oneA\"),\n new XElement(\"oneB\")\n ),\n new XElement(\"two\"),\n new XElement(\"three\")\n );\n\n foreach (XElement x in root.Elements())\n {\n Console.WriteLine(x.Name);\n Console.WriteLine(x.NodesBeforeSelf().Count()); \n }\n public static class ExMethods\n{\n public static int Position(this XNode node)\n {\n return node.NodesBeforeSelf().Count(); \n }\n}\n"
},
{
"answer_id": 165013,
"author": "Vin",
"author_id": 1747,
"author_profile": "https://Stackoverflow.com/users/1747",
"pm_score": 5,
"selected": true,
"text": "int position = obj.ElementsBeforeSelf().Count();\n"
},
{
"answer_id": 165068,
"author": "Tim Jarvis",
"author_id": 10387,
"author_profile": "https://Stackoverflow.com/users/10387",
"pm_score": 1,
"selected": false,
"text": "var list = from xe in xmldoc.Descendants(\"SomeElem\")\n let info = (IXmlLineInfo)xe\n select new \n {\n LineNum = info.LineNumber,\n Element = xe\n }\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1747/"
] |
164,342
|
<p>I'm considering one of two IRepository interfaces, one that is a descendant of IQueryable and one that contains IQueryable. </p>
<p>Like this:</p>
<pre><code>public interface IRepository<T> : IQueryable<T>
{
T Save(T entity);
void Delete(T entity);
}
</code></pre>
<p>Or this:</p>
<pre><code>public interface IRepository<T>
{
T Save(T entity);
void Delete(T entity);
IQueryable<T> Query();
}
</code></pre>
<p>LINQ usage would be:</p>
<pre><code>from dos
in ServiceLocator.Current.GetInstance<IRepository<DomainObject>>()
where dos.Id == id
select dos
</code></pre>
<p>Or...</p>
<pre><code>from dos
in ServiceLocator.Current.GetInstance<IRepository<DomainObject>>().Query
where dos.Id == id
select dos
</code></pre>
<p>I kinda like the first one, but it's problematic to mock. How have other people implemented LINQable, mockable repositories?</p>
|
[
{
"answer_id": 5319662,
"author": "Pure.Krome",
"author_id": 30674,
"author_profile": "https://Stackoverflow.com/users/30674",
"pm_score": 3,
"selected": false,
"text": "Repository Pattern IQueryable public interface IRepository<T>\n{\n IQueryable<T> Find();\n void Save(T entity);\n void Delete(T entity);\n}\n public class UserRepository : IRepository<User>\n{\n public IQueryable<User> Find()\n {\n // Context is some Entity Framework context or \n // Linq-to-Sql or NHib or an Xml file, etc...\n // I didn't bother adding this, to this example code.\n return context.Users().AsQueryable();\n }\n\n // ... etc\n}\n public void UserServices : IUserServices\n{\n private readonly IRepository<User> _userRepository;\n\n public UserServices(IRepository<User> userRepository)\n {\n _userRepository = userRepository;\n }\n\n public User FindById(int userId)\n {\n return _userRepository.Find()\n .WithUserId(userId)\n .SingleOrDefault(); // <-- This will be null, if the \n // user doesn't exist\n // in the repository.\n }\n\n // Note: some people might not want the FindBySingle method because this\n // uber method can do that, also. But i wanted to show u the power\n // of having the Repository return an IQuerable.\n public User FindSingle(Expression<Func<User, bool>> predicate)\n {\n return _userRepository\n .Find()\n .SingleOrDefault(predicate);\n }\n}\n WithUserId(userId) FindById public static User WithId(this IQueryable<User> source, int userId)\n{\n return source.Where(u => u.UserId == userId).SingleOrDefault();\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3759/"
] |
164,343
|
<p>I'm playing around with BCEL. I'm not using it to generate bytecode, but instead I'm trying to inspect the structure of existing compiled classes.</p>
<p>I need to be able to point to an arbitrary .class file anywhere on my hard drive and load a <a href="http://jakarta.apache.org/bcel/apidocs/org/apache/bcel/classfile/JavaClass.html" rel="noreferrer">JavaClass</a> object based on that. Ideally I'd like to avoid having to add the given class to my classpath.</p>
|
[
{
"answer_id": 10858280,
"author": "ILOVEPIE",
"author_id": 1164259,
"author_profile": "https://Stackoverflow.com/users/1164259",
"pm_score": 2,
"selected": false,
"text": "new ClassParser(classfilebytearrayhere).parse()\n"
},
{
"answer_id": 32984765,
"author": "JITHIN_PATHROSE",
"author_id": 4229716,
"author_profile": "https://Stackoverflow.com/users/4229716",
"pm_score": 2,
"selected": false,
"text": "Class<?> javaClass1 = null;\njavaClass1 = ucl.loadClass(\"com.sample.Customer\");\norg.apache.bcel.classfile.JavaClass javaClazz1=org.apache.bcel.Repository.lookupClass(javaClass1);\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1247/"
] |
164,344
|
<p>How can I make my <code>std::fstream</code> object start reading a text file from the second line?</p>
|
[
{
"answer_id": 164353,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 5,
"selected": false,
"text": "ifstream stream(\"filename.txt\");\nstring dummyLine;\ngetline(stream, dummyLine);\n// Begin reading your stream here\nwhile (stream)\n ...\n"
},
{
"answer_id": 164367,
"author": "Adam",
"author_id": 1366,
"author_profile": "https://Stackoverflow.com/users/1366",
"pm_score": 1,
"selected": false,
"text": "#include <fstream>\n#include <iostream>\nusing namespace std;\n\nint main () \n{\n // Open your file\n ifstream someStream( \"textFile.txt\" );\n\n // Set up a place to store our data read from the file\n string line;\n\n // Read and throw away the first line simply by doing\n // nothing with it and reading again\n getline( someStream, line );\n\n // Now begin your useful code\n while( !someStream.eof() ) {\n // This will just over write the first line read\n getline( someStream, line );\n cout << line << endl;\n }\n\n return 0;\n}\n"
},
{
"answer_id": 164374,
"author": "m_pGladiator",
"author_id": 446104,
"author_profile": "https://Stackoverflow.com/users/446104",
"pm_score": -1,
"selected": false,
"text": "#include <fstream>\n#include <iostream>\nusing namespace std;\n\nint main () \n{\n char buffer[256];\n ifstream myfile (\"test.txt\");\n\n // first line\n myfile.getline (buffer,100);\n\n // the rest\n while (! myfile.eof() )\n {\n myfile.getline (buffer,100);\n cout << buffer << endl;\n }\n return 0;\n}\n"
},
{
"answer_id": 164694,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 5,
"selected": false,
"text": "ifstream stream(\"filename.txt\");\n\n// Get and drop a line\nstream.ignore ( std::numeric_limits<std::streamsize>::max(), '\\n' );\n\n// Get and store a line for processing.\n// std::getline() has a third parameter the defaults to '\\n' as the line\n// delimiter.\nstd::string line;\nstd::getline(stream,line);\n\nstd::string word;\nstream >> word; // Reads one space separated word from the stream.\n while( someStream.good() ) // !someStream.eof()\n{\n getline( someStream, line );\n cout << line << endl;\n}\n while( someStream ) // Same as someStream.good()\n{\n getline( someStream, line );\n if (someStream) // streams when used in a boolean context are converted to a type that is usable in that context. If the stream is in a good state the object returned can be used as true\n {\n // Only write to cout if the getline did not fail.\n cout << line << endl;\n }\n}\n while(getline( someStream, line ))\n{\n // Loop only entered if reading a line from somestream is OK.\n // Note: getline() returns a stream reference. This is automatically cast\n // to boolean for the test. streams have a cast to bool operator that checks\n // good()\n cout << line << endl;\n}\n"
},
{
"answer_id": 16623167,
"author": "Aaron Sterling",
"author_id": 2396572,
"author_profile": "https://Stackoverflow.com/users/2396572",
"pm_score": -1,
"selected": false,
"text": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\nstring textString;\nstring anotherString;\nifstream textFile;\ntextFile.open(\"TextFile.txt\");\nif (textFile.is_open()) {\n while (getline(textFile, textString)){\n anotherString = anotherString + textString;\n }\n}\n\nstd::cout << anotherString;\n\ntextFile.close();\nreturn 0;\n}\n"
},
{
"answer_id": 25012489,
"author": "Arthur P. Golubev",
"author_id": 1790694,
"author_profile": "https://Stackoverflow.com/users/1790694",
"pm_score": 2,
"selected": false,
"text": "for (int currLineNumber = 0; currLineNumber < startLineNumber; ++currLineNumber){\n if (addressesFile.ignore(numeric_limits<streamsize>::max(), addressesFile.widen('\\n'))){ \n //just skipping the line\n } else \n return HandleReadingLineError(addressesFile, currLineNumber);\n}\n"
},
{
"answer_id": 61342527,
"author": "Sina Raoufi",
"author_id": 12541646,
"author_profile": "https://Stackoverflow.com/users/12541646",
"pm_score": -1,
"selected": false,
"text": "fstream dataFile(\"file.txt\");\ndataFile.ignore(1, '\\n'); // ignore one line\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
164,356
|
<p>For example, I'm writing a multi-threaded time-critical application that processes and streams audio in real-time. Interruptions in the audio are totally unacceptable. Does this mean I cannot use the STL because of the potential slow down when an exception is thrown? </p>
|
[
{
"answer_id": 164423,
"author": "Henk",
"author_id": 4613,
"author_profile": "https://Stackoverflow.com/users/4613",
"pm_score": 1,
"selected": false,
"text": "std::vector::at() Project Properties -> C/C++ -> Code Generation -> Enable C++ Exceptions"
},
{
"answer_id": 1281627,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 4,
"selected": true,
"text": "void doSomething()\n{\n MyString str ;\n doSomethingElse() ;\n}\n typedef std::vector<std::string> Vector ;\n\nvoid outputAllData(const Vector & aString)\n{\n for(Vector::size_type i = 0, iMax = aString.size() ; i != iMax ; ++i)\n {\n std::cout << i << \" : \" << aString[i] << std::endl ;\n }\n}\n typedef std::vector<std::string> Vector ;\n\nvoid outputSomeData(const Vector & aString, Vector::size_type iIndex)\n{\n std::cout << iIndex << \" : \" << aString.at(iIndex) << std::endl ;\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13760/"
] |
164,369
|
<p>While I'm googling/reading for this answer I thought I would also ask here. </p>
<p>I have a class that is a wrapper for a SDK. The class accepts an ILoader object and uses the ILoader object to create an ISBAObject which is cast into an ISmallBusinessInstance object. I am simply trying to mock this behavior using Moq.</p>
<pre><code> [TestMethod]
public void Test_Customer_GetByID()
{
var mock = new Mock<ILoader>();
var sbainst = new Mock<ISbaObjects>();
mock.Expect(x => x.GetSbaObjects("")).Returns(sbainst);
}
</code></pre>
<p>The compiler error reads: Error 1 The best overloaded method match for 'Moq.Language.IReturns.Returns(Microsoft.BusinessSolutions.SmallBusinessAccounting.Loader.ISbaObjects)' has some invalid arguments</p>
<p>What is going on here? I expected the Mock of ISbaObjects to be able to be returned without a problem.</p>
|
[
{
"answer_id": 169182,
"author": "Trevor Abell",
"author_id": 2916,
"author_profile": "https://Stackoverflow.com/users/2916",
"pm_score": 2,
"selected": false,
"text": "[TestMethod]\npublic void Test_Customer_GetByID()\n{\n var mock = new Mock<ILoader>();\n\n var sbainst = new Mock<ISbaObjects>();\n\n mock.Expect(x => x.GetSbaObjects(\"\")).Returns(sbainst.Object);\n\n\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2916/"
] |
164,382
|
<p>We've been creating banners using the getURL linking method (in a blank window). For many people, it works just fine. You click the banner and are taken to our site. For others (me included), clicking the flash object triggers a pop-up warning in FireFox (both 2 and 3, default settings). The weird thing is that it doesn't happen for everyone. It happens on my main machine (vista 64, FF3) but not on my secondary machine (XP 64, FF3). I have other people running Vista/FF3 just like me, and it's working fine for them...but not me. </p>
<p>An example is the 300x250 banner on the left side of this page:
<a href="http://www.jguitar.com/" rel="nofollow noreferrer">http://www.jguitar.com/</a></p>
<p>We're pretty stumped and have no idea why this is happening. Any feedback would be greatly appreicated.</p>
|
[
{
"answer_id": 615018,
"author": "Pascal Immerzeel",
"author_id": 1729,
"author_profile": "https://Stackoverflow.com/users/1729",
"pm_score": 0,
"selected": false,
"text": "private function click(event : MouseEvent) : void {\n getURL(LoaderInfo(root.loaderInfo).parameters.clic kTag);\n}\n\nprivate function getURL(url : String, window : String = \"_blank\") : void { \n var browser : String = ExternalInterface.call(\"function getBrowser(){return \n navigator.userAgent}\") as String; \n\n if (browser.indexOf(\"Firefox\") != -1 || browser.indexOf(\"MSIE 7.0\") != -1) { \n ExternalInterface.call('window.open(\"' + url + '\",\"' + window + '\")'); \n } else { \n navigateToURL(new URLRequest(url), window); \n }\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24632/"
] |
164,393
|
<p>In the quest for localization I need to find all the string literals littered amongst our source code. I was looking for a way to script this into a post-modification source repository check. (I.E. after some one checks something in have a box setup to check this stat) I'll probably use NAnt and CruiseControl or something to handle the management of the CVS (Well StarTeam in my case :( ) But do you know of any scriptable (or command line) utility to accurately cycle through source code looking for string literals? I realize I could do simple string look up based on regular expressions but want a little more bang for my buck. (Maybe analyze the string or put it into categories) Because a lot of times the string may not necessarily require translation. Any ideas?</p>
|
[
{
"answer_id": 164439,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 6,
"selected": true,
"text": ":q ((\\\".+?\\\")|('.+?'))"
},
{
"answer_id": 29919882,
"author": "gleichdanke",
"author_id": 715724,
"author_profile": "https://Stackoverflow.com/users/715724",
"pm_score": 1,
"selected": false,
"text": "Text=\"textonly\" (Text=)(\")([a-z])\n Text=\"*\" Text=\"<%$ Resources:LocalizedText, KeyNameFromResourceFile%>\"\n (>)([a-z]) <h1>HeaderText</h1>\n"
},
{
"answer_id": 58603637,
"author": "Edward Koetsjarjan",
"author_id": 2804973,
"author_profile": "https://Stackoverflow.com/users/2804973",
"pm_score": 0,
"selected": false,
"text": "([\",`,'])([\\w,\\s]*)([\",`,'])\n"
},
{
"answer_id": 60285561,
"author": "Kleberson Leite",
"author_id": 6025266,
"author_profile": "https://Stackoverflow.com/users/6025266",
"pm_score": 1,
"selected": false,
"text": "Use Regular Expressions \"+.*(MYSPECIFICTEXT)+.*\"+ \"+.*\"+"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13688/"
] |
164,395
|
<p>I'm wondering if its possible to add new class data members at run-time in PHP?</p>
|
[
{
"answer_id": 164418,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 5,
"selected": true,
"text": "$prop = 'newname';\n$obj->$prop = 42;\n $obj->newname = 42;\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
] |
164,397
|
<p>How can I print a message to the error console, preferably including a variable? </p>
<p>For example, something like:</p>
<pre><code>print('x=%d', x);
</code></pre>
|
[
{
"answer_id": 164408,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 10,
"selected": true,
"text": "console.log(...) console.debug(...)"
},
{
"answer_id": 3060267,
"author": "Ivo Danihelka",
"author_id": 101097,
"author_profile": "https://Stackoverflow.com/users/101097",
"pm_score": 6,
"selected": false,
"text": "function log(msg) {\n setTimeout(function() {\n throw new Error(msg);\n }, 0);\n}\n log('Hello World');\nlog('another message');\n"
},
{
"answer_id": 4823263,
"author": "dlaliberte",
"author_id": 311389,
"author_profile": "https://Stackoverflow.com/users/311389",
"pm_score": 4,
"selected": false,
"text": "var startTime = (new Date()).getTime();\nfunction logError(msg)\n{\n var milliseconds = (new Date()).getTime() - startTime;\n window.setTimeout(function () {\n throw( new Error(milliseconds + ': ' + msg, \"\") );\n });\n}\nlogError('testing');\n"
},
{
"answer_id": 5367944,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 3,
"selected": false,
"text": "console.log() function log()\n{\n if (arguments.length > 0)\n {\n // Join for graceful degregation\n var args = (arguments.length > 1) ? Array.prototype.join.call(arguments, \" \") : arguments[0];\n\n // This is the standard; Firebug and newer WebKit browsers support this.\n try {\n console.log(args);\n return true;\n } catch(e) {\n // Newer Opera browsers support posting erros to their consoles.\n try {\n opera.postError(args);\n return true;\n } \n catch(e) \n {\n }\n }\n\n // Catch all; a good old alert box.\n alert(args);\n return false;\n }\n}\n"
},
{
"answer_id": 9664336,
"author": "Lukas",
"author_id": 1263715,
"author_profile": "https://Stackoverflow.com/users/1263715",
"pm_score": 4,
"selected": false,
"text": "console.log(\"your message here\");\n"
},
{
"answer_id": 12516572,
"author": "Nicholas",
"author_id": 1163414,
"author_profile": "https://Stackoverflow.com/users/1163414",
"pm_score": 8,
"selected": false,
"text": "console.error(message); // Outputs an error message to the Web Console\nconsole.log(message); // Outputs a message to the Web Console\nconsole.warn(message); // Outputs a warning message to the Web Console\nconsole.info(message); // Outputs an informational message to the Web Console. In some browsers it shows a small \"i\" in front of the message.\n console.log('%c My message here', \"background: blue; color: white; padding-left:10px;\");\n"
},
{
"answer_id": 19544487,
"author": "mmm",
"author_id": 1549834,
"author_profile": "https://Stackoverflow.com/users/1549834",
"pm_score": 0,
"selected": false,
"text": "alert(\"message\");\n"
},
{
"answer_id": 21497693,
"author": "D.K",
"author_id": 3239530,
"author_profile": "https://Stackoverflow.com/users/3239530",
"pm_score": 1,
"selected": false,
"text": "console.log(\"your message here\");\n $('document').ready(function() {\nconsole.log('all images are loaded');\n});\n"
},
{
"answer_id": 22663170,
"author": "Yster",
"author_id": 1317559,
"author_profile": "https://Stackoverflow.com/users/1317559",
"pm_score": 3,
"selected": false,
"text": "console.error('An error occurred!');\nconsole.error('An error occurred! ', 'My variable = ', myVar);\nconsole.error('An error occurred! ' + 'My variable = ' + myVar);\n"
},
{
"answer_id": 30376939,
"author": "devSouth555",
"author_id": 2464921,
"author_profile": "https://Stackoverflow.com/users/2464921",
"pm_score": 2,
"selected": false,
"text": " console.error(object[Obj,....])\\\n"
},
{
"answer_id": 32392602,
"author": "Kenneth John Falbous",
"author_id": 1042251,
"author_profile": "https://Stackoverflow.com/users/1042251",
"pm_score": 1,
"selected": false,
"text": "console.warn(\"Text to print on console\");\n"
},
{
"answer_id": 40428915,
"author": "Parth Raval",
"author_id": 5734387,
"author_profile": "https://Stackoverflow.com/users/5734387",
"pm_score": 2,
"selected": false,
"text": "function foo() {\n function bar() {\n console.trace(\"Tracing is Done here\");\n }\n bar();\n}\n\nfoo(); console.log(console); //to print console object\nconsole.clear('console.clear'); //to clear console\nconsole.log('console.log'); //to print log message\nconsole.info('console.info'); //to print log message \nconsole.debug('console.debug'); //to debug message\nconsole.warn('console.warn'); //to print Warning\nconsole.error('console.error'); //to print Error\nconsole.table([\"car\", \"fruits\", \"color\"]);//to print data in table structure\nconsole.assert('console.assert'); //to print Error\nconsole.dir({\"name\":\"test\"});//to print object\nconsole.dirxml({\"name\":\"test\"});//to print object as xml formate To Print Error:- console.error('x=%d', x);\n console.log(\"This is the outer level\");\nconsole.group();\nconsole.log(\"Level 2\");\nconsole.group();\nconsole.log(\"Level 3\");\nconsole.warn(\"More of level 3\");\nconsole.groupEnd();\nconsole.log(\"Back to level 2\");\nconsole.groupEnd();\nconsole.log(\"Back to the outer level\");"
},
{
"answer_id": 47903642,
"author": "jkordas",
"author_id": 6034325,
"author_profile": "https://Stackoverflow.com/users/6034325",
"pm_score": 0,
"selected": false,
"text": "console.log(`x = ${x}`);\n"
},
{
"answer_id": 50818375,
"author": "Aniket Kulkarni",
"author_id": 2183868,
"author_profile": "https://Stackoverflow.com/users/2183868",
"pm_score": 1,
"selected": false,
"text": "var var=10;\nconsole.log(`var=${var}`);\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
164,414
|
<p>I'm processing a file, line-by-line, and I'd like to do an inverse match. For instance, I want to match lines where there is a string of six letters, but only if these six letters are not '<em>Andrea</em>'. How should I do that?</p>
<p>I'm using <a href="https://en.wikipedia.org/wiki/RegexBuddy" rel="noreferrer">RegexBuddy</a>, but still having trouble.</p>
|
[
{
"answer_id": 164419,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 8,
"selected": true,
"text": "(?!Andrea).{6}\n [A-Za-z]{6} .{6}"
},
{
"answer_id": 164440,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "(?!Andrea)\n"
},
{
"answer_id": 164486,
"author": "Hamish Downer",
"author_id": 3189,
"author_profile": "https://Stackoverflow.com/users/3189",
"pm_score": 4,
"selected": false,
"text": "import re\n\nnot_andrea = re.compile('(?!Andrea)\\w{6}', re.IGNORECASE)\n"
},
{
"answer_id": 164561,
"author": "phreakre",
"author_id": 12051,
"author_profile": "https://Stackoverflow.com/users/12051",
"pm_score": -1,
"selected": false,
"text": "process($line) if ($line =~ !/Andrea/);\n"
},
{
"answer_id": 1909960,
"author": "Dmytro",
"author_id": 232398,
"author_profile": "https://Stackoverflow.com/users/232398",
"pm_score": 6,
"selected": false,
"text": "^(.(?!(some text)))*$\n"
},
{
"answer_id": 27192482,
"author": "weakish",
"author_id": 222893,
"author_profile": "https://Stackoverflow.com/users/222893",
"pm_score": 3,
"selected": false,
"text": "(?!"
},
{
"answer_id": 38846455,
"author": "Zenexer",
"author_id": 1188377,
"author_profile": "https://Stackoverflow.com/users/1188377",
"pm_score": 5,
"selected": false,
"text": "^(?:(?!Andrea).)*$\n"
},
{
"answer_id": 44287287,
"author": "Matthias Herrmann",
"author_id": 5111904,
"author_profile": "https://Stackoverflow.com/users/5111904",
"pm_score": 3,
"selected": false,
"text": "notMatched = re.sub(regex, \"\", string)"
},
{
"answer_id": 72182648,
"author": "Dodo",
"author_id": 8567437,
"author_profile": "https://Stackoverflow.com/users/8567437",
"pm_score": 2,
"selected": false,
"text": "^((?!yourRegex).)* (?<=yourRegex).*"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21384/"
] |
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": 164455,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "if ((currentWeather.Type & _badWeatherTypes) == _badWeatherTypes)\n if ((currentWeather.Type & _badWeatherTypes) != 0)\n FlagsAttribute [Flags] ToString() WeatherTypes"
},
{
"answer_id": 164466,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 0,
"selected": false,
"text": "(currentWeather.Type & WeatherType.Thunderstorm == WeatherType.Thunderstorm)\n"
},
{
"answer_id": 164591,
"author": "Ken Wootton",
"author_id": 7357,
"author_profile": "https://Stackoverflow.com/users/7357",
"pm_score": 0,
"selected": false,
"text": " WeatherType[] badWeatherTypes = new WeatherType[]\n { \n WeatherType.Thunderstorm, \n WeatherType.Raining\n };\n\n if (Array.IndexOf(badWeatherTypes, currentWeather.Type) >= 0)\n {\n return false;\n }\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18821/"
] |
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": 3487254,
"author": "Aneil Mallavarapu",
"author_id": 305149,
"author_profile": "https://Stackoverflow.com/users/305149",
"pm_score": 4,
"selected": false,
"text": "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 MIDDLEWARE_CLASSES= [...\n 'yourproj.middleware.MobileMiddleware',\n...]\n urlpatterns=patterns('',('r'/?$', 'mobile.index'), ...)\n"
},
{
"answer_id": 4152279,
"author": "Thomas",
"author_id": 234254,
"author_profile": "https://Stackoverflow.com/users/234254",
"pm_score": 1,
"selected": false,
"text": "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 <html>\n <head>\n {% block head %}\n <title>blah</title>\n {% if request.mobile %}\n <link rel=\"stylesheet\" href=\"{{ MEDIA_URL }}/styles/base-mobile.css\">\n {% else %}\n <link rel=\"stylesheet\" href=\"{{ MEDIA_URL }}/styles/base-desktop.css\">\n {% endif %}\n </head>\n <body>\n <div id=\"navigation\">\n {% include \"_navigation.html\" %}\n </div>\n {% if not request.mobile %}\n <div id=\"sidebar\">\n <p> sidebar content not fit for mobile </p>\n </div>\n {% endif %>\n <div id=\"content\">\n <article>\n {% if not request.mobile %}\n <aside>\n <p> aside content </p>\n </aside>\n {% endif %}\n <p> article content </p>\n </aricle>\n </div>\n </body>\n</html>\n"
},
{
"answer_id": 14510830,
"author": "Samora Dake",
"author_id": 1068519,
"author_profile": "https://Stackoverflow.com/users/1068519",
"pm_score": 0,
"selected": false,
"text": "django.shortcuts.render utils utils.shortcuts 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 view from utils.shortcuts import my_render\n\ndef home(request): return my_render(request, 'home.html')\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24630/"
] |
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 & sleep 3 && ~/xsendkey -window "Adobe Flash Player 10" Control+F
</code></pre>
|
[
{
"answer_id": 277865,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "nspluginplayer --fullscreen src=path/to/flashfile.swf\n"
},
{
"answer_id": 3994891,
"author": "Daniel",
"author_id": 483952,
"author_profile": "https://Stackoverflow.com/users/483952",
"pm_score": 0,
"selected": false,
"text": "stage.displayState = StageDisplayState.FULL_SCREEN;\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11176/"
] |
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": 164530,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 0,
"selected": false,
"text": "try..catch y ArgumentOutOfRangeException"
},
{
"answer_id": 164565,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 3,
"selected": false,
"text": "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"
},
{
"answer_id": 164665,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 1,
"selected": false,
"text": "Session[\"UserID\"] = SomeProprietarySessionManagementLookup();\n"
},
{
"answer_id": 164750,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 2,
"selected": false,
"text": "SomeProprietarySessionManagementLookup() Session[\"UserID\"] = SomeProprietarySessionManagementLookup();\n public void SomeProprietarySessionManagementLookup()\n{\n // do some async lookup\n Action<object> 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 Action<object> 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 Action<object> 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"
},
{
"answer_id": 166928,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 0,
"selected": false,
"text": "SomeProprietarySessionManagementLookup(Session[\"UserID\"]);\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12260/"
] |
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<> will remove the volatile qualifier. Thanks again to Josh.</p>
|
[
{
"answer_id": 164534,
"author": "Matthew Murdoch",
"author_id": 4023,
"author_profile": "https://Stackoverflow.com/users/4023",
"pm_score": 4,
"selected": false,
"text": "// 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(&InstanceLock);\n }\n\n ~Singleton() {\n DeleteCriticalSection(&InstanceLock);\n }\n\n public:\n // Not thread-safe - to be called from the main application thread\n static void Create() {\n InitializeCriticalSection(&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(&InitLock);\n }\n\n // Thread-safe lazy initializer\n static Singleton* GetInstance() {\n Guard(&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(&InstanceLock);\n\n // Perform thread-safe operation\n }\n};\n"
},
{
"answer_id": 164588,
"author": "Eric",
"author_id": 6367,
"author_profile": "https://Stackoverflow.com/users/6367",
"pm_score": 0,
"selected": false,
"text": "MySingleton::getInstance()->doWork();\n MySingleton::getInstance()->initSingleton();\n"
},
{
"answer_id": 164640,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 5,
"selected": true,
"text": "Singleton* GetSingleton()\n{\n volatile static Singleton* pSingleton = 0;\n\n if (pSingleton == NULL)\n {\n EnterCriticalSection(&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(&cs);\n }\n\n return const_cast<Singleton*>(pSingleton);\n}\n"
},
{
"answer_id": 11131957,
"author": "zhaorufei",
"author_id": 64469,
"author_profile": "https://Stackoverflow.com/users/64469",
"pm_score": 0,
"selected": false,
"text": "struct X { };\n\nX * get_X_Instance()\n{\n static X x;\n return &x;\n}\nextern int X_singleton_helper = (get_X_instance(), 1);\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
] |
164,520
|
<p><strong>Premise:</strong>
Usually during preparation of a new Ruby on Rails App, I draw out models and relations regarding user navigations. Usually I hit a place where I need to ask myself, whether or not I should go beyond the usual "rule of thumb" of nesting no more 1 level deep. Sometimes I feel the need to nest, rather than creating another namespace route and duplicating work.
<br/>Here's an example:<br/></p>
<p><strong>Models:</strong> User, Company, Location <br/>
User has and belongs to many Companies (many to many) <br/>
User has and belongs to many Locations (many to many) <br/>
Company has and belongs to many Locations (many to many) <br/></p>
<p><strong>Routes:</strong><br/>
<strong><em>1 level nesting</em></strong> <br/>
users/:user_id/companies/ - list all companies related to a user<br/>
users/:user_id/locations/ - list all locations related to a user<br/>
<strong><em>more than 1 level nesting</em></strong><br/>
users/:user_id/companies/:company_id/locations/ - list all company-locations of a user</p>
<p><strong>So, my question is whether or not it is appropriate to nest more than 1 level deep in RoR? Yes or no? And why?</strong></p>
|
[
{
"answer_id": 164875,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "users/:user_id/companies/:company_id/locations/\n user_company_location_path( user_id, company_id, location_id )\n"
},
{
"answer_id": 165537,
"author": "Dave Smylie",
"author_id": 1505600,
"author_profile": "https://Stackoverflow.com/users/1505600",
"pm_score": 1,
"selected": false,
"text": " user/x/blog/y/profile/z, and\n user/x/profile/a\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24393/"
] |
164,527
|
<p>In .NET, if a class contains a member that is a class object, should that member be exposed as a property or with a method?</p>
|
[
{
"answer_id": 164553,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 5,
"selected": false,
"text": "public string Name\nget \n{\n return name;\n}\nset \n{\n name = value;\n}\n Type type = // Get a type.\nfor (int i = 0; i < type.Methods.Length; i++)\n{\n if (type.Methods[i].Name.Equals (\"text\"))\n {\n // Perform some operation.\n }\n}\n class Connection\n {\n // The following three members should be properties\n // because they can be set in any order.\n string DNSName {get{};set{};}\n string UserName {get{};set{};}\n string Password {get{};set{};}\n\n // The following member should be a method\n // because the order of execution is important.\n // This method cannot be executed until after the \n // properties have been set.\n bool Execute ();\n }\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19065/"
] |
164,564
|
<p>Edit: Ryan raised a good point. I specifically want to be able to map to and from while still storing human-readable values in the database. That is, I don't want a bunch of enumeration integers in my database.</p>
|
[
{
"answer_id": 214276,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 0,
"selected": false,
"text": "<property name=\"EnumProperty\" Type=\"string\" Length=\"50\" NotNull=\"true\" />\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] |
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": 164662,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 3,
"selected": true,
"text": "#include <msxml2.h>\n\nbool FormatDOMDocument (IXMLDOMDocument *pDoc, IStream *pStream)\n{\n\n // Create the writer\n\n CComPtr <IMXWriter> pMXWriter;\n if (FAILED (pMXWriter.CoCreateInstance(__uuidof (MXXMLWriter), NULL, CLSCTX_ALL)))\n {\n return false;\n }\n CComPtr <ISAXContentHandler> pISAXContentHandler;\n if (FAILED (pMXWriter.QueryInterface(&pISAXContentHandler)))\n {\n return false;\n }\n CComPtr <ISAXErrorHandler> pISAXErrorHandler;\n if (FAILED (pMXWriter.QueryInterface (&pISAXErrorHandler)))\n {\n return false;\n }\n CComPtr <ISAXDTDHandler> pISAXDTDHandler;\n if (FAILED (pMXWriter.QueryInterface (&pISAXDTDHandler)))\n {\n return false;\n }\n\n if (FAILED (pMXWriter ->put_omitXMLDeclaration (VARIANT_FALSE)) ||\n FAILED (pMXWriter ->put_standalone (VARIANT_TRUE)) ||\n FAILED (pMXWriter ->put_indent (VARIANT_TRUE)) ||\n FAILED (pMXWriter ->put_encoding (L\"UTF-8\")))\n {\n return false;\n }\n\n // Create the SAX reader\n\n CComPtr <ISAXXMLReader> pSAXReader;\n if (FAILED (pSAXReader.CoCreateInstance (__uuidof (SAXXMLReader), NULL, CLSCTX_ALL)))\n {\n return false;\n }\n\n if (FAILED (pSAXReader ->putContentHandler (pISAXContentHandler)) ||\n FAILED (pSAXReader ->putDTDHandler (pISAXDTDHandler)) ||\n FAILED (pSAXReader ->putErrorHandler (pISAXErrorHandler)) ||\n FAILED (pSAXReader ->putProperty (\n L\"http://xml.org/sax/properties/lexical-handler\", CComVariant (pMXWriter))) ||\n FAILED (pSAXReader ->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 ->put_output (CComVariant (pStream))) &&\n SUCCEEDED (pSAXReader ->parse (CComVariant (pDoc)));\n}\n"
},
{
"answer_id": 164747,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 2,
"selected": false,
"text": "bool CXml::FormatDOMDocument(IXMLDOMDocument *pDoc)\n{\n // Create the writer\n CComPtr <IMXWriter> pMXWriter;\n if (FAILED (pMXWriter.CoCreateInstance(__uuidof (MXXMLWriter), NULL, CLSCTX_ALL))) {\n return false;\n }\n CComPtr <ISAXContentHandler> pISAXContentHandler;\n if (FAILED (pMXWriter.QueryInterface(&pISAXContentHandler))) {\n return false;\n }\n CComPtr <ISAXErrorHandler> pISAXErrorHandler;\n if (FAILED (pMXWriter.QueryInterface (&pISAXErrorHandler))) {\n return false;\n }\n CComPtr <ISAXDTDHandler> pISAXDTDHandler;\n if (FAILED (pMXWriter.QueryInterface (&pISAXDTDHandler))) {\n return false;\n }\n\n if (FAILED (pMXWriter->put_omitXMLDeclaration (VARIANT_FALSE)) ||\n FAILED (pMXWriter->put_standalone (VARIANT_TRUE)) ||\n FAILED (pMXWriter->put_indent (VARIANT_TRUE)) ||\n FAILED (pMXWriter->put_encoding (L\"UTF-8\")))\n {\n return false;\n }\n\n // Create the SAX reader\n CComPtr <ISAXXMLReader> pSAXReader;\n if (FAILED(pSAXReader.CoCreateInstance(__uuidof (SAXXMLReader), NULL, CLSCTX_ALL))) {\n return false;\n }\n\n if (FAILED(pSAXReader->putContentHandler (pISAXContentHandler)) ||\n FAILED(pSAXReader->putDTDHandler (pISAXDTDHandler)) ||\n FAILED(pSAXReader->putErrorHandler (pISAXErrorHandler)) ||\n FAILED(pSAXReader->putProperty (L\"http://xml.org/sax/properties/lexical-handler\", CComVariant (pMXWriter))) ||\n FAILED(pSAXReader->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->put_output(CComVariant(pDoc.GetInterfacePtr())));\n bool success2 = SUCCEEDED(pSAXReader->parse(CComVariant(pDoc.GetInterfacePtr())));\n\n return success1 && success2;\n}\n"
},
{
"answer_id": 164749,
"author": "mitchnull",
"author_id": 18645,
"author_profile": "https://Stackoverflow.com/users/18645",
"pm_score": 0,
"selected": false,
"text": ":a\n/>/!N;s/\\n/ /;ta\ns/ / /g;s/^ *//;s/ */ /g\n/^<!--/{\n:e\n/-->/!N;s/\\n//;te\ns/-->/\\n/;D;\n}\n/^<[?!][^>]*>/{\nH;x;s/\\n//;s/>.*$/>/;p;bb\n}\n/^<\\/[^>]*>/{\nH;x;s/\\n//;s/>.*$/>/;s/^ //;p;bb\n}\n/^<[^>]*\\/>/{\nH;x;s/\\n//;s/>.*$/>/;p;bb\n}\n/^<[^>]*[^\\/]>/{\nH;x;s/\\n//;s/>.*$/>/;p;s/^/ /;bb\n}\n/</!ba\n{\nH;x;s/\\n//;s/ *<.*$//;p;s/[^ ].*$//;x;s/^[^<]*//;ba\n}\n:b\n{\ns/[^ ].*$//;x;s/^<[^>]*>//;ba\n}\n"
},
{
"answer_id": 36982487,
"author": "klaus triendl",
"author_id": 279251,
"author_profile": "https://Stackoverflow.com/users/279251",
"pm_score": 2,
"selected": false,
"text": "#import CXml msxml6 void PrettyWriteXmlDocument(MSXML2::IXMLDOMDocument* xmlDoc, IStream* stream)\n{\n MSXML2::IMXWriterPtr writer(__uuidof(MSXML2::MXXMLWriter60));\n writer->encoding = L\"utf-8\";\n writer->indent = _variant_t(true);\n writer->standalone = _variant_t(true);\n writer->output = stream;\n\n MSXML2::ISAXXMLReaderPtr saxReader(__uuidof(MSXML2::SAXXMLReader60));\n saxReader->putContentHandler(MSXML2::ISAXContentHandlerPtr(writer));\n saxReader->putProperty(PUSHORT(L\"http://xml.org/sax/properties/lexical-handler\"), writer.GetInterfacePtr());\n saxReader->parse(xmlDoc);\n}\n IStream void PrettySaveXmlDocument(MSXML2::IXMLDOMDocument* xmlDoc, const wchar_t* filePath)\n{\n ADODB::_StreamPtr stream(__uuidof(ADODB::Stream));\n stream->Type = ADODB::adTypeBinary;\n stream->Open(vtMissing, ADODB::adModeUnknown, ADODB::adOpenStreamUnspecified, _bstr_t(), _bstr_t());\n PrettyWriteXmlDocument(xmlDoc, IStreamPtr(stream));\n stream->SaveToFile(filePath, ADODB::adSaveCreateOverWrite);\n}\n main #include <stdlib.h>\n#include <objbase.h>\n#include <comutil.h>\n#include <comdef.h>\n#include <comdefsp.h>\n#import <msxml6.dll>\n#import <msado60.tlb> 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->appendChild(xmlDoc->createElement(L\"root\"));\n\n PrettySaveXmlDocument(xmlDoc, L\"xmldoc.xml\");\n }\n catch (const _com_error&)\n {\n }\n\n CoUninitialize();\n\n return EXIT_SUCCESS;\n}\n\n\n// assume definitions of PrettyWriteXmlDocument and PrettySaveXmlDocument go here\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11449/"
] |
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><?xml version="1.0" encoding="utf-16" ?>
<MyObject>
<Property1>Data</Property1>
<Property2>More Data</Property2>
</MyObject>
</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><MyObject>
<Property1>Data</Property1>
<Property2>More Data</Property2>
</MyObject>
</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": 164604,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 0,
"selected": false,
"text": "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"
},
{
"answer_id": 164608,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 3,
"selected": true,
"text": "// 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"
},
{
"answer_id": 322091,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "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"
},
{
"answer_id": 590036,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 0,
"selected": false,
"text": " 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"
},
{
"answer_id": 625915,
"author": "NetSide",
"author_id": 66018,
"author_profile": "https://Stackoverflow.com/users/66018",
"pm_score": 1,
"selected": false,
"text": "XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();\n namespaces.Add(\"\", \"\");\n <message xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:xsd=\\\"http://www.w3.org/2001/XMLSchema\\\">\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24222/"
] |
164,594
|
<p>I have a c# application that interfaces with the database only through stored procedures. I have tried various techniques for calling stored procedures. At the root is the SqlCommand class, however I would like to achieve several things:</p>
<ul>
<li>make the interface between c# and sql smoother, so that procedure calls look more like c# function calls</li>
<li>have an easy way to determine whether a given stored procedure is called anywhere in code.</li>
<li>make the creation of a procedure call quick and easy.</li>
</ul>
<p>I have explored various avenues. In one, I had a project that with its namespace structure mirrored the name structure of stored procedures, that way I could generate the name of the stored procedure from the name of the class, and I could tell whether a given stored procedure was in use by fining it in the namespace tree. What are some other experiences?</p>
|
[
{
"answer_id": 164637,
"author": "Micky McQuade",
"author_id": 12908,
"author_profile": "https://Stackoverflow.com/users/12908",
"pm_score": 2,
"selected": false,
"text": "Public Shared Function GetOrg(ByVal OrgID As Integer) As System.Data.DataSet\n Return db.ExecuteDataSet(\"dbo.cp_GetOrg\", OrgID)\nEnd Function\n Dim db As Microsoft.Practices.EnterpriseLibrary.Data.Database = DatabaseFactory.CreateDatabase()\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13855/"
] |
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": "svnserve svn:// svn update /server/staging"
},
{
"answer_id": 164654,
"author": "zappan",
"author_id": 4723,
"author_profile": "https://Stackoverflow.com/users/4723",
"pm_score": 0,
"selected": false,
"text": "[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 cat passwd\n"
},
{
"answer_id": 164670,
"author": "Adam",
"author_id": 13320,
"author_profile": "https://Stackoverflow.com/users/13320",
"pm_score": 4,
"selected": true,
"text": "chmod g+s spcprjdir\n drwxrwsr-x 2 kathy spcprj 1674 Sep 17 1999 spcprjdir\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/326176/"
] |
164,613
|
<p>I've heard the advice that you should avoid try catch blocks if possible since they're expensive.</p>
<p>My question is specifically about the .NET platform: Why are try blocks expensive?</p>
<p><strong>Summary of Responses:</strong></p>
<p>There are clearly two camps on this issue: those that say that try blocks are expensive, and those that say "maybe a tiny little bit".</p>
<p>Those that say try blocks are expensive normally mention the "high cost" of unwinding the call stack. Personally, I'm not convinced by that argument - specially after reading about how exceptions handlers are stored <a href="http://www.yoda.arachsys.com/csharp/exceptions2.html" rel="nofollow noreferrer">here</a>.</p>
<p>Jon Skeet sits on the "maybe a tiny little bit" camp, and has written two articles on exceptions and performance which you can find <a href="https://jonskeet.uk/csharp/exceptions2.html" rel="nofollow noreferrer">here</a>.</p>
<p>There was one article that I found extremely interesting: it talked about "other" performance implications of try blocks (not necessarily memory or cpu consumption). Peter Ritchie mentions that he found that code inside try blocks is not optimized as it'd otherwise be by the compiler. You can read about his findings <a href="http://msmvps.com/blogs/peterritchie/archive/2007/06/22/performance-implications-of-try-catch-finally.aspx" rel="nofollow noreferrer">here</a>.</p>
<p>Finally, there's a blog entry about the issue from the man that implemented exceptions in the CLR. Go take a look at Chris Brumme's article <a href="https://cbrumme.dev/the-exception-model" rel="nofollow noreferrer">here</a>.</p>
|
[
{
"answer_id": 165352,
"author": "Michael Petrotta",
"author_id": 23897,
"author_profile": "https://Stackoverflow.com/users/23897",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Diagnostics;\n\nnamespace Test\n{\n class Program\n {\n static void Main(string[] args)\n {\n Stopwatch sw = Stopwatch.StartNew();\n for (int i = 0; i < 1000000; i++)\n {\n try\n {\n throw new Exception();\n }\n catch {}\n }\n Console.WriteLine(sw.ElapsedMilliseconds);\n Console.Read();\n }\n }\n}\n"
},
{
"answer_id": 170175,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 2,
"selected": false,
"text": "using System;\npublic class Program\n{\n static void Main(string[] args)\n {\n Console.WriteLine(\"abc\");\n }\n}\n .method private hidebysig static void Main(string[] args) cil managed\n{\n .entrypoint\n // Code size 13 (0xd)\n .maxstack 8\n IL_0000: nop\n IL_0001: ldstr \"abc\"\n IL_0006: call void [mscorlib]System.Console::WriteLine(string)\n IL_000b: nop\n IL_000c: ret\n} // end of method Program::Main\n using System;\npublic class Program\n{\n static void Main(string[] args)\n {\n try { Console.WriteLine(\"abc\"); }\n catch { }\n }\n}\n .method private hidebysig static void Main(string[] args) cil managed\n{\n .entrypoint\n // Code size 23 (0x17)\n .maxstack 1\n IL_0000: nop\n .try\n {\n IL_0001: nop\n IL_0002: ldstr \"abc\"\n IL_0007: call void [mscorlib]System.Console::WriteLine(string)\n IL_000c: nop\n IL_000d: nop\n IL_000e: leave.s IL_0015\n } // end .try\n catch [mscorlib]System.Object \n {\n IL_0010: pop\n IL_0011: nop\n IL_0012: nop\n IL_0013: leave.s IL_0015\n } // end handler\n IL_0015: nop\n IL_0016: ret\n} // end of method Program::Main\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] |
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": 165003,
"author": "SeaDrive",
"author_id": 19267,
"author_profile": "https://Stackoverflow.com/users/19267",
"pm_score": 1,
"selected": false,
"text": "AcctStatement oRpt = new AcctStatement() ;\noRpt.Database.Tables[0].SetDataSource(dsRpt.Tables[0]);\noRpt.SetParameterValue(\"plan_title\",sPlanName) ;\ncrViewer.ReportSource = oRpt ;\n"
},
{
"answer_id": 278916,
"author": "Piku",
"author_id": 18854,
"author_profile": "https://Stackoverflow.com/users/18854",
"pm_score": 3,
"selected": true,
"text": "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 ((CPickingNoteData)rptData[0]).header_date = DateTime.Now;\n((CPickingNoteData)rptData[rptData.Count-1]).footer_serial = GenerateSerialNumber();\n ReportDocument reportDoc = new ReportDocument();\nreportDoc.Load(reportPath);\nreportDoc.SetDataSource(rptData);\ncrystalReportViewer.ReportSource = reportDoc;\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18854/"
] |
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": "string parentPath = Directory.GetParent(rafFilePath);\nstring imagePath = Path.Combine(parentPath, imageFileNameFromRaf);\n"
},
{
"answer_id": 1747737,
"author": "Siarhei Kuchuk",
"author_id": 212746,
"author_profile": "https://Stackoverflow.com/users/212746",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.IO;\n\nnamespace ZipSolution\n{\n internal static class RelativePathDiscovery\n {\n /// <summary>\n /// Produces relative path when possible to go from baseLocation to targetLocation\n /// </summary>\n /// <param name=\"baseLocation\">The root folder</param>\n /// <param name=\"targetLocation\">The target folder</param>\n /// <returns>The relative path relative to baseLocation</returns>\n /// <exception cref=\"ArgumentNullException\">base or target locations are null or empty</exception>\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 /// <summary>\n /// Resolves the relative pathes\n /// </summary>\n /// <param name=\"relativePath\">Relative path</param>\n /// <param name=\"basePath\">base path for discovering</param>\n /// <returns>Resolved path</returns>\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"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
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": "grails war foo.war\n"
},
{
"answer_id": 223603,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 3,
"selected": false,
"text": "grails war /opt/java/tomcat-5.5.24/foobar.war\n grails.war.destFile = \"foobar-prod.war\"\n"
},
{
"answer_id": 855659,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "grails war foo.war app.version foo.war grails.war.destFile"
},
{
"answer_id": 4892530,
"author": "Phuong LeCong",
"author_id": 1243628,
"author_profile": "https://Stackoverflow.com/users/1243628",
"pm_score": 5,
"selected": false,
"text": "grails.war.destFile Config.groovy grails.project.war.file BuildConfig.groovy \ngrails.project.war.file = \"target/${appName}.war\"\n"
},
{
"answer_id": 39277804,
"author": "Jay Prall",
"author_id": 56083,
"author_profile": "https://Stackoverflow.com/users/56083",
"pm_score": 2,
"selected": false,
"text": "build.gradle war {\n archiveName 'foo.war'\n}\n"
},
{
"answer_id": 56781213,
"author": "Glushiator",
"author_id": 1284183,
"author_profile": "https://Stackoverflow.com/users/1284183",
"pm_score": 0,
"selected": false,
"text": "grails.project.war.file = \"target/${appName}##${appVersion}.war\"\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
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": "int System.Int32"
},
{
"answer_id": 164692,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "int System.Int32 long System.Int64"
},
{
"answer_id": 3249355,
"author": "BlueRaja - Danny Pflughoeft",
"author_id": 238419,
"author_profile": "https://Stackoverflow.com/users/238419",
"pm_score": 4,
"selected": false,
"text": "int Int32 int"
},
{
"answer_id": 3249357,
"author": "Tomas Petricek",
"author_id": 33518,
"author_profile": "https://Stackoverflow.com/users/33518",
"pm_score": 5,
"selected": false,
"text": "int System.Int32 System.Int32 int System.Int32 int"
},
{
"answer_id": 3249393,
"author": "Jess",
"author_id": 151495,
"author_profile": "https://Stackoverflow.com/users/151495",
"pm_score": 2,
"selected": false,
"text": "int System.Int32"
},
{
"answer_id": 3249501,
"author": "Brian Gideon",
"author_id": 158779,
"author_profile": "https://Stackoverflow.com/users/158779",
"pm_score": 3,
"selected": false,
"text": "int Int32 IntPtr"
},
{
"answer_id": 3250411,
"author": "Eric Lippert",
"author_id": 88656,
"author_profile": "https://Stackoverflow.com/users/88656",
"pm_score": 4,
"selected": false,
"text": "sizeof(int) sizeof(int)"
},
{
"answer_id": 38176696,
"author": "PreventRage",
"author_id": 6543067,
"author_profile": "https://Stackoverflow.com/users/6543067",
"pm_score": 2,
"selected": false,
"text": "314159 -314159 -((int)314159) -2147483648 -((uint)2147483648)"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
164,645
|
<p>Is there any way that I can change how a Literal of a code snippet renders when it is used in the code that the snippet generates?</p>
<p>Specifically I'd like to know if I can have a literal called say, $PropertyName$ and then get the snippet engine to render "_$PropertyName$ where the first character is made lowercase.</p>
<p>I can't afford R#. Please help :)</p>
|
[
{
"answer_id": 18289183,
"author": "fred",
"author_id": 2692059,
"author_profile": "https://Stackoverflow.com/users/2692059",
"pm_score": 3,
"selected": false,
"text": "string m_$name$;\nstring $name$\n{\n get{return m_$name$;}\n set{m_$name$=value;}\n};\n"
},
{
"answer_id": 47789765,
"author": "Nikolay Makhonin",
"author_id": 5221762,
"author_profile": "https://Stackoverflow.com/users/5221762",
"pm_score": 3,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<CodeSnippet Format=\"1.0.0\" xmlns=\"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\">\n <Header>\n <Title>Notifiable Property</Title>\n <Author>Nikolay Makhonin</Author>\n <Shortcut>propn</Shortcut>\n <Description>Property With in Built Property Changed method implementation.</Description>\n <SnippetTypes>\n <SnippetType>SurroundsWith</SnippetType>\n <SnippetType>Expansion</SnippetType>\n </SnippetTypes>\n </Header>\n <Snippet>\n <Declarations>\n <Literal>\n <ID>Type</ID>\n <Default>Type</Default>\n </Literal>\n <Literal>\n <ID>P</ID>\n <Default>P</Default>\n </Literal>\n <Literal>\n <ID>roperty</ID>\n <Default>ropertyName</Default>\n </Literal>\n <Literal>\n <ID>p</ID>\n <Default>p</Default>\n </Literal>\n <Literal>\n <ID>Ownerclass</ID>\n <ToolTip>The owning class of this Property.</ToolTip>\n <Function>ClassName()</Function>\n <Default>Ownerclass</Default>\n </Literal>\n </Declarations>\n <Code Language=\"CSharp\">\n <![CDATA[#region $P$$roperty$\n\n private Field<$Type$> _$p$$roperty$;\n public static readonly string $P$$roperty$PropertyName = GetPropertyName(() => (($Ownerclass$)null).$P$$roperty$);\n public $Type$ $P$$roperty$\n {\n get { return _$p$$roperty$; }\n set { Set(ref _$p$$roperty$, value); }\n }\n\n #endregion\n\n]]>\n </Code>\n </Snippet>\n</CodeSnippet>\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19452/"
] |
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": "Dim i as Nullable(Of Integer) = Nothing '.NET 2.0/3.0'\nDim j as Integer? = Nothing '.NET 3.5'\n"
},
{
"answer_id": 164709,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 0,
"selected": false,
"text": "int? a = null;\n"
},
{
"answer_id": 164728,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 2,
"selected": false,
"text": "if IsNothing(foo) OrElse IsDbNull(foo) Then\n ' Do Something Because foo Is Either Nothing or DBNull.Value\nEnd If\n"
},
{
"answer_id": 164757,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 1,
"selected": false,
"text": "static public bool IsNull(this object obj)\n{\n return obj != null && obj != DbNull.Value;\n}\n\n...\n\nif(dataTable[0][\"MyColumn\"].IsNull())\n{\n //do something\n}\n"
},
{
"answer_id": 164763,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 0,
"selected": false,
"text": "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"
},
{
"answer_id": 165172,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 3,
"selected": true,
"text": "Nullable<T> Nullable<int> Nullable<double> Nullable<T> int? x = null;\n x.HasValue() int y = x ?? 2; // y becomes 2 if x is null.\nint z = x.GetValueOrDefault(2); // same as y\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17235/"
] |
164,714
|
<p>I just want to know the best way to emulate a C# style enumeration in Ruby.</p>
|
[
{
"answer_id": 164810,
"author": "Ris Adams",
"author_id": 15683,
"author_profile": "https://Stackoverflow.com/users/15683",
"pm_score": 2,
"selected": false,
"text": "class WindowState\n Open = 1\n Closed = 2\n Max = 3\n Min = 4\nend\n"
},
{
"answer_id": 164833,
"author": "Nate",
"author_id": 12779,
"author_profile": "https://Stackoverflow.com/users/12779",
"pm_score": 3,
"selected": false,
"text": "STATES = {:open => 1, :closed => 2, :max => 3, :min => 4}.freeze()\n STATES = Hash.new { |hash, key| raise NameError, \"#{key} is not allowed\" }\nSTATES.merge!({:open => 1, :closed => 2, :max => 3, :min => 4}).freeze()\n\nSTATES[:other] # raises NameError\n"
},
{
"answer_id": 164852,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 1,
"selected": false,
"text": "greetingtype = :hello\n"
},
{
"answer_id": 164891,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": true,
"text": "WINDOW_STATES = { :minimized => 0, :maximized => 100 }.freeze\n WINDOW_STATES.keys.include?(window_state)\n WINDOW_STATES = [:minimized, :maximized].freeze\n WINDOW_STATES.include?(window_state)\n WINDOW_STATES = %w(minimized maximized open closed).freeze\n validates_inclusion_of 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 && args.first.respond_to?(:include?) && !self.kind_of?(Array) ?\n args.first.include?( self ) :\n args.include?( self )\n end\n end\nend\n window_state.in? WINDOW_STATES\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20714/"
] |
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": "w_my_parent_window_name.istr_my_structure = lstr_my_structure\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4466/"
] |
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": 2268137,
"author": "Jader Dias",
"author_id": 48465,
"author_profile": "https://Stackoverflow.com/users/48465",
"pm_score": 4,
"selected": false,
"text": "private void Redirect(StreamReader input, TextBox output)\n{\n new Thread(a =>\n {\n var buffer = new char[1];\n while (input.Read(buffer, 0, 1) > 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"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1508/"
] |
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->BitBlt(0, 0, rect.Width(), rect.Height(), &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": "CLIPCHILDREN"
},
{
"answer_id": 164977,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 3,
"selected": false,
"text": " ModifyStyle(0, WS_CLIPCHILDREN, 0);\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7442/"
] |
164,767
|
<pre><code>$array = explode(".", $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": "$index = count($array) - 1;\n$a = $array[$index];\n"
},
{
"answer_id": 164785,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 3,
"selected": false,
"text": "$array = explode(\".\", $row[copy]);\n$a = count($array) - 1;\n$array[$a]; // last element\n"
},
{
"answer_id": 164788,
"author": "Rick",
"author_id": 14138,
"author_profile": "https://Stackoverflow.com/users/14138",
"pm_score": -1,
"selected": false,
"text": "$array = explode(\".\", $row[$copy]);\n$a = $array[count($array)];\n"
},
{
"answer_id": 164796,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 0,
"selected": false,
"text": "$array = explode(\".\", $row[copy]);\n$a = count($array) - 1;\n$value = $array[$a];\n"
},
{
"answer_id": 164841,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "$array = explode(\".\", $row[copy]);\n$a = array_pop($array);\n"
},
{
"answer_id": 165078,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 1,
"selected": false,
"text": "$pos = strrpos($row['copy'], '.');\n$str=($pos!==false) ? substr($row['copy'],$pos+1) : '';\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
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 <-------> CheckInMediator : ICheckInMediator
----------------------------------------------------------------------------------------
CheckInForm.Show() <--------
--------> AttemptCheckIn(CheckInInfo)
CheckInForm.DisplayCheckInInfo(DisplayInfo) <--------
--------> CompleteCheckIn(AdditionalCheckInInfo)
PleaseWaitDialog.Show() <--------
PleaseWaitDialog.Close() <--------
CheckInForm.Close() <--------
</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": 166782,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 0,
"selected": false,
"text": "Control.Invoke() Forms.Timer"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
164,792
|
<p>From the documentation, I would expect adModeShareDenyWrite to be the way, but it's not working right.</p>
<p>I'm using an Access database via ADO. My connection string says Mode=8, which is adModeShareDenyWrite. But when I try to delete a row from a table, I get:</p>
<p>Unspecified error, Description:Could not delete from specified tables., Source:Microsoft JET Database Engine</p>
<p>In other words, the setting is preventing ME from updating the database using my OWN connection.</p>
<p>I found a couple other posts on the web reporting the same thing, the adModeShareDenyWrite setting used with Access not working as documented.</p>
<p>I am looking for a solution that doesn't involve an administrator changing permissions. It needs to be something that my program can control. </p>
<p>My motivation here is to minimize the chances of database corruption. One of the causes of mdb file corruption documented by Microsoft is two apps writing to the same db. So, I want to make sure that only one app can have a write connection to the db. Others can read, but should fail when they try to write. Whoever makes a connection first wins.</p>
|
[
{
"answer_id": 164900,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 0,
"selected": false,
"text": "(where you have a user object with a '.role' property, or anything equivalent ...)\nif activeUser.role = \"admin\" then\n m_connectionMode = adModeWrite\nelse\n m_connectionMode = adModeShareDenyWrite\nendif\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9328/"
] |
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": "192.168.100.5 othermachine othermachine.mydomain.local\n"
},
{
"answer_id": 1207527,
"author": "Jason Musgrove",
"author_id": 94838,
"author_profile": "https://Stackoverflow.com/users/94838",
"pm_score": 2,
"selected": false,
"text": "ipconfig /flushdns telnet 192.168.0.1 80\n 192.168.0.1 GET / HTTP/1.1\nHost: fqdn.mywebserver.com\n fqdn.mywebserver.com ServerAlias"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19159/"
] |
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": "devenv.exe /SafeMode\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21745/"
] |
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 p"
},
{
"answer_id": 164867,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 6,
"selected": false,
"text": "set backup\nset backupdir=~/.vim/backup\nset directory=~/.vim/tmp\n"
},
{
"answer_id": 164884,
"author": "Trenton",
"author_id": 2601671,
"author_profile": "https://Stackoverflow.com/users/2601671",
"pm_score": 2,
"selected": false,
"text": "syntax on\nset tabstop=4\nset expandtab\nset shiftwidth=4\n"
},
{
"answer_id": 164889,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 2,
"selected": false,
"text": "\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"
},
{
"answer_id": 164935,
"author": "Aleksandar Dimitrov",
"author_id": 11797,
"author_profile": "https://Stackoverflow.com/users/11797",
"pm_score": 2,
"selected": false,
"text": " highlight flicker cterm=bold ctermfg=white\n au CursorMoved <buffer> exe 'match flicker /\\V\\<'.escape(expand('<cword>'), '/').'\\>/'\n cterm termfg gvim gvim gui guifg"
},
{
"answer_id": 164961,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 2,
"selected": false,
"text": "map = }{!}fmt^M}\nmap + }{!}fmt -p '> '^M}\nset showmatch\n"
},
{
"answer_id": 165002,
"author": "pixelbeat",
"author_id": 4421,
"author_profile": "https://Stackoverflow.com/users/4421",
"pm_score": 2,
"selected": false,
"text": "au BufNewFile,BufReadPre *.gpg :set secure vimi= noswap noback nowriteback hist=0 binary\nau BufReadPost *.gpg :%!gpg -d 2>/dev/null\nau BufWritePre *.gpg :%!gpg -e -r 'name@email.com' 2>/dev/null\nau BufWritePost *.gpg u\n"
},
{
"answer_id": 165247,
"author": "shank",
"author_id": 24697,
"author_profile": "https://Stackoverflow.com/users/24697",
"pm_score": 2,
"selected": false,
"text": "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 <C-R>=expand(\"<cword>\")<CR><CR>\nmap ^Kd :cs find 1 <C-R>=expand(\"<cword>\")<CR><CR>\nmap ^Kg :cs find 2 <C-R>=expand(\"<cword>\")<CR><CR>\nmap ^Kc :cs find 3 <C-R>=expand(\"<cword>\")<CR><CR>\nmap ^Kt :cs find 4 <C-R>=expand(\"<cword>\")<CR><CR>\nmap ^Ke :cs find 6 <C-R>=expand(\"<cword>\")<CR><CR>\nmap ^Kf :cs find 7 <C-R>=expand(\"<cfile>\")<CR><CR>\nmap ^Ki :cs find 8 <C-R>=expand(\"%\")<CR><CR>\n"
},
{
"answer_id": 165257,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 2,
"selected": false,
"text": ":set tags=tags;/\n map <right> <ESC>:bn<RETURN>\nmap <left> <ESC>:bp<RETURN>\n map - :nohls<cr>\n"
},
{
"answer_id": 165267,
"author": "Alex B",
"author_id": 23643,
"author_profile": "https://Stackoverflow.com/users/23643",
"pm_score": 4,
"selected": false,
"text": "set noerrorbells\nset visualbell\nset t_vb=\n inoremap <Down> <C-o>gj\ninoremap <Up> <C-o>gk\n ctags set tags=tags;/\n autocmd BufReadPre,BufNewFile SConstruct set filetype=python\nautocmd BufReadPre,BufNewFile SConscript set filetype=python\n"
},
{
"answer_id": 166562,
"author": "Kris Kumler",
"author_id": 4281,
"author_profile": "https://Stackoverflow.com/users/4281",
"pm_score": 2,
"selected": false,
"text": "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 \" <space> switches to the next window (give it a second)\n\" <space>n switches to the next window\n\" <space><space> switches to the next window and maximizes it\n\" <space>= 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 <space> <c-W>w\n:map <space>n <c-W>w\n:map <space><space> <c-W>w<c-W>_\n:map <space>= <c-W>=\nif bufwinnr(1)\n map + <c-W>+\n map - <c-W>-\nendif\n"
},
{
"answer_id": 166636,
"author": "Dominic Dos Santos",
"author_id": 5379,
"author_profile": "https://Stackoverflow.com/users/5379",
"pm_score": 3,
"selected": false,
"text": ":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"
},
{
"answer_id": 167261,
"author": "rampion",
"author_id": 9859,
"author_profile": "https://Stackoverflow.com/users/9859",
"pm_score": 0,
"selected": false,
"text": "~/.vimrc $VIMRUNTIME/vimrc_example.vim ~/.vim ~/.vim/ftplugin ~/.vim/syntax"
},
{
"answer_id": 171558,
"author": "Frew Schmidt",
"author_id": 12448,
"author_profile": "https://Stackoverflow.com/users/12448",
"pm_score": 7,
"selected": false,
"text": "\"{{{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 ! &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(\"<afile>:p:h\") !=? $TEMP |\n \\ if line(\"'\\\"\") > 1 && line(\"'\\\"\") <= line(\"$\") |\n \\ let JumpCursorOnEdit_foo = line(\"'\\\"\") |\n \\ let b:doopenfold = 1 |\n \\ if (foldlevel(JumpCursorOnEdit_foo) > 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 > 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 >= 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 <Esc>\n\nnnoremap JJJJ <Nop>\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\\ (%{&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 <Leader>w :call Browser ()<CR>\n\n\" Open the Project Plugin <F2>\nnnoremap <silent> <F2> :Project<CR>\n\n\" Open the Project Plugin\nnnoremap <silent> <Leader>pal :Project .vimproject<CR>\n\n\" TODO Mode\nnnoremap <silent> <Leader>todo :execute TodoListMode()<CR>\n\n\" Open the TagList Plugin <F3>\nnnoremap <silent> <F3> :Tlist<CR>\n\n\" Next Tab\nnnoremap <silent> <C-Right> :tabnext<CR>\n\n\" Previous Tab\nnnoremap <silent> <C-Left> :tabprevious<CR>\n\n\" New Tab\nnnoremap <silent> <C-t> :tabnew<CR>\n\n\" Rotate Color Scheme <F8>\nnnoremap <silent> <F8> :execute RotateColorTheme()<CR>\n\n\" DOS is for fools.\nnnoremap <silent> <F9> :%s/$//g<CR>:%s// /g<CR>\n\n\" Paste Mode! Dang! <F10>\nnnoremap <silent> <F10> :call Paste_on_off()<CR>\nset pastetoggle=<F10>\n\n\" Edit vimrc \\ev\nnnoremap <silent> <Leader>ev :tabnew<CR>:e ~/.vimrc<CR>\n\n\" Edit gvimrc \\gv\nnnoremap <silent> <Leader>gv :tabnew<CR>:e ~/.gvimrc<CR>\n\n\" Up and down are more logical with g..\nnnoremap <silent> k gk\nnnoremap <silent> j gj\ninoremap <silent> <Up> <Esc>gka\ninoremap <silent> <Down> <Esc>gja\n\n\" Good call Benjie (r for i)\nnnoremap <silent> <Home> i <Esc>r\nnnoremap <silent> <End> a <Esc>r\n\n\" Create Blank Newlines and stay in Normal mode\nnnoremap <silent> zj o<Esc>\nnnoremap <silent> zk O<Esc>\n\n\" Space will toggle folds!\nnnoremap <space> 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 <expr> <cr> pumvisible() ? \"\\<c-y>\" : \"\\<c-g>u\\<cr>\"\ninoremap <expr> <c-n> pumvisible() ? \"\\<lt>c-n>\" : \"\\<lt>c-n>\\<lt>c-r>=pumvisible() ? \\\"\\\\<lt>down>\\\" : \\\"\\\"\\<lt>cr>\"\ninoremap <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>\"\n\n\" Swap ; and : Convenient.\nnnoremap ; :\nnnoremap : ;\n\n\" Fix email paragraphs\nnnoremap <leader>par :%s/^>$//<CR>\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"
},
{
"answer_id": 219617,
"author": "Julien Nephtali",
"author_id": 5060,
"author_profile": "https://Stackoverflow.com/users/5060",
"pm_score": 1,
"selected": false,
"text": "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 <C-S-tab> :tabprevious<cr>\n:nmap <C-tab> :tabnext<cr>\n:imap <C-S-tab> <ESC>:tabprevious<cr>i\n:imap <C-tab> <ESC>:tabnext<cr>i\n:nmap <C-t> :tabnew<cr>\n:imap <C-t> <ESC>:tabnew<cr>i\n:map <C-w> :tabclose<cr>\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"
},
{
"answer_id": 219693,
"author": "rshdev",
"author_id": 19961,
"author_profile": "https://Stackoverflow.com/users/19961",
"pm_score": 3,
"selected": false,
"text": "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 ,<Tab> :set hls<CR>/\\\\n.*\\\\n/<CR>\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<CR>\n\" Read\nnmap ;r :r ~/.vimxfer<CR>\n\" Append \nnmap ;a :. w! >>~/.vimxfer<CR>\n"
},
{
"answer_id": 257356,
"author": "ngn",
"author_id": 23109,
"author_profile": "https://Stackoverflow.com/users/23109",
"pm_score": 1,
"selected": false,
"text": ".vimrc ngn@macavity:~$ cat .vimrc\n\" This file intentionally left blank\n ~/.vim/ :) vim.org"
},
{
"answer_id": 257444,
"author": "Whaledawg",
"author_id": 23829,
"author_profile": "https://Stackoverflow.com/users/23829",
"pm_score": 3,
"selected": false,
"text": "function! Mosh_Tab_Or_Complete()\n if col('.')>1 && strpart( getline('.'), col('.')-2, 3 ) =~ '^\\w'\n return \"\\<C-N>\"\n else\n return \"\\<Tab>\"\nendfunction\n\ninoremap <Tab> <C-R>=Mosh_Tab_Or_Complete()<CR>\n map cc :.,$s/^ *//<CR>\n set nu! \nset nobackup\n imap ii <C-[>\n"
},
{
"answer_id": 257445,
"author": "Terminus",
"author_id": 7053,
"author_profile": "https://Stackoverflow.com/users/7053",
"pm_score": 0,
"selected": false,
"text": "\" **************************\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 <F1> prompt for a help topic, rather than displaying the introduction\n\" page, and have it do this from any mode:\nnnoremap <F1> :help<Space>\nvmap <F1> <C-C><F1>\nomap <F1> <C-C><F1>\nmap! <F1> <C-C><F1>\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 & 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 <Tab> <C-x><C-o>\ninoremap <tab> <c-r>=InsertTabWrapper()<cr>\n\n\" ***************************\n\" * keyboard mapping ********\n\" ***************************\nimap <A-1> <Esc>:tabn 1<CR>i\nimap <A-2> <Esc>:tabn 2<CR>i\nimap <A-3> <Esc>:tabn 3<CR>i\nimap <A-4> <Esc>:tabn 4<CR>i\nimap <A-5> <Esc>:tabn 5<CR>i\nimap <A-6> <Esc>:tabn 6<CR>i\nimap <A-7> <Esc>:tabn 7<CR>i\nimap <A-8> <Esc>:tabn 8<CR>i\nimap <A-9> <Esc>:tabn 9<CR>i\n\nmap <A-1> :tabn 1<CR>\nmap <A-2> :tabn 2<CR>\nmap <A-3> :tabn 3<CR>\nmap <A-4> :tabn 4<CR>\nmap <A-5> :tabn 5<CR>\nmap <A-6> :tabn 6<CR>\nmap <A-7> :tabn 7<CR>\nmap <A-8> :tabn 8<CR>\nmap <A-9> :tabn 9<CR>\n\n\" ***************************\n\" * Utilities Needed ********\n\" ***************************\nfunction InsertTabWrapper()\n let col = col('.') - 1\n if !col || getline('.')[col - 1] !~ '\\k'\n return \"\\<tab>\"\n else\n return \"\\<c-p>\"\n endif\nendfunction\n\n\" end of .vimrc\n"
},
{
"answer_id": 342511,
"author": "Jon DellOro",
"author_id": 36456,
"author_profile": "https://Stackoverflow.com/users/36456",
"pm_score": 0,
"selected": false,
"text": "\"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"
},
{
"answer_id": 369302,
"author": "Ronny Brendel",
"author_id": 14114,
"author_profile": "https://Stackoverflow.com/users/14114",
"pm_score": 0,
"selected": false,
"text": "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 << 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(\\'<cword>\\')\")\n if wordUnderCursor is None :\n wordUnderCursor = \"\"\n\n # escape the word\n wordUnderCursor = vim.eval(\"RonnyEscapeString(\\\"\" + wordUnderCursor + \"\\\")\")\n wordUnderCursor = \"\\<\" + wordUnderCursor + \"\\>\"\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 << 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"
},
{
"answer_id": 475904,
"author": "Martin",
"author_id": 52986,
"author_profile": "https://Stackoverflow.com/users/52986",
"pm_score": 5,
"selected": false,
"text": "set cul # highlight current line\nhi CursorLine term=none cterm=none ctermbg=3 # adjust color\n"
},
{
"answer_id": 652532,
"author": "Adam Gibbins",
"author_id": 20528,
"author_profile": "https://Stackoverflow.com/users/20528",
"pm_score": 4,
"selected": false,
"text": "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 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 >= 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 <LocalLeader>tl :set list!<cr>\n\" toggle paste mode\nnmap <LocalLeader>pp :set paste!<cr>\n"
},
{
"answer_id": 652632,
"author": "Herbert Sitz",
"author_id": 76434,
"author_profile": "https://Stackoverflow.com/users/76434",
"pm_score": 5,
"selected": false,
"text": "autocmd BufEnter * execute \"chdir \".escape(expand(\"%:p:h\"), ' ')\n set autochdir\n"
},
{
"answer_id": 701319,
"author": "Fire Crow",
"author_id": 80479,
"author_profile": "https://Stackoverflow.com/users/80479",
"pm_score": 0,
"selected": false,
"text": "au BufNewFile,BufRead *.txtap,*.txtcd setf fc_comdoc\n"
},
{
"answer_id": 702644,
"author": "Nick Bolton",
"author_id": 47775,
"author_profile": "https://Stackoverflow.com/users/47775",
"pm_score": 1,
"selected": false,
"text": "set number\nsyntax on\n"
},
{
"answer_id": 789272,
"author": "Don Reba",
"author_id": 49329,
"author_profile": "https://Stackoverflow.com/users/49329",
"pm_score": 0,
"selected": false,
"text": "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 >= 0\n \" we are in a fold\n let numLines = foldEnd - foldStart + 1\n if (numLines > 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) >= 0\n return FoldBalloon()\n else\n return SyntaxBallon()\nendfunction\n\nset balloonexpr=Balloon()\nset ballooneval\n"
},
{
"answer_id": 789284,
"author": "Nick Presta",
"author_id": 40906,
"author_profile": "https://Stackoverflow.com/users/40906",
"pm_score": 0,
"selected": false,
"text": "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 {<CR>} while ();<C-O>3h<C-O>\n \" iabbr for for (;;) {<CR>}<C-O>k<C-O>3l<C-O>\n \" iabbr switch switch () {<CR>}<C-O>k<C-O>6l<C-O>\n \" iabbr while while () {<CR>}<C-O>k<C-O>5l<C-O>\n \" iabbr if if () {<CR>}<C-O>k<C-O>2l<C-O>\n iabbr #d #define\n iabbr #i #include\nendfunc\nau FileType c,cpp call LoadCAbbrevs()\n\nau BufReadPost * if line(\"'\\\"\") > 0 && line(\"'\\\"\") <= line(\"$\") |\n \\ exe \"normal g'\\\"\" | endif\n\nautocmd FileType python set nocindent shiftwidth=4 ts=4 foldmethod=indent\n"
},
{
"answer_id": 1219104,
"author": "Gavin Gilmour",
"author_id": 126893,
"author_profile": "https://Stackoverflow.com/users/126893",
"pm_score": 5,
"selected": false,
"text": "\"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 !&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 '[&et]' if &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 !&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('^ \\{' . &ts . ',}[^\\t]', 'nw') != 0\n\n if tabs && spaces\n let b:statusline_tab_warning = '[mixed-indenting]'\n elseif (spaces && !&et) || (tabs && &et)\n let b:statusline_tab_warning = '[&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 &textwidth or 80 (if\n\"no &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 !&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) > 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 = (&tw ? &tw : 80)\n let spaces = repeat(\" \", &ts)\n\n let long_line_lens = []\n\n let i = 1\n while i <= line(\"$\")\n let len = strlen(substitute(getline(i), '\\t', spaces, 'g'))\n if len > 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+=%{&ff!='unix'?'['.&ff.']':''}\nset statusline+=%*\n\n\"display a warning if file encoding isnt utf-8\nset statusline+=%#warningmsg#\nset statusline+=%{(&fenc!='utf-8'&&&fenc!='')?'['.&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 &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 &paste is set\nset statusline+=%#error#\nset statusline+=%{&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"
},
{
"answer_id": 1219114,
"author": "Tadeusz A. Kadłubowski",
"author_id": 122460,
"author_profile": "https://Stackoverflow.com/users/122460",
"pm_score": 2,
"selected": false,
"text": "set statusline=%2*%n\\|%<%*%-.40F%2*\\|\\ %2*%M\\ %3*%=%1*\\ %1*%2.6l%2*x%1*%1.9(%c%V%)%2*[%1*%P%2*]%1*%2B\n"
},
{
"answer_id": 1330572,
"author": "Mosh",
"author_id": 161609,
"author_profile": "https://Stackoverflow.com/users/161609",
"pm_score": 0,
"selected": false,
"text": ":nnoremap <esc> :noh<return><esc>\n"
},
{
"answer_id": 1330577,
"author": "chaos",
"author_id": 47529,
"author_profile": "https://Stackoverflow.com/users/47529",
"pm_score": 0,
"selected": false,
"text": "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 ( &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() <Bar> q!\n"
},
{
"answer_id": 1606206,
"author": "DaedalusFall",
"author_id": 74013,
"author_profile": "https://Stackoverflow.com/users/74013",
"pm_score": 0,
"selected": false,
"text": "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 .>\" . 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 . \">\" . tempfile\n execute \":sf \".tempfile\n return\nendfunction\n\nfunction! SvnStatus()\n let tempfile = system(\"tempfile\")\n silent execute \":!svn status .>\" . 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"
},
{
"answer_id": 1636961,
"author": "Maxim Sloyko",
"author_id": 141906,
"author_profile": "https://Stackoverflow.com/users/141906",
"pm_score": 3,
"selected": false,
"text": "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 <F2> <Esc>:w<CR>\nmap! <F2> <Esc>:w<CR>\n\nmap <F10> <Esc>:qa<CR>\nmap! <F10> <Esc>:qa<CR>\n\nmap <F9> <Esc>:wqa<CR>\nmap! <F9> <Esc>:wqa<CR>\n\ninoremap <s-up> <Esc><c-w>W<Ins>\ninoremap <s-down> <Esc><c-w>w<Ins>\n\nnnoremap <s-up> <c-w>W\nnnoremap <s-down> <c-w>w\n\n\" Fancy middle-line <CR>\ninoremap <C-CR> <Esc>o\nnnoremap <C-CR> o\n\n\" This is the way I like my quotation marks and various braces\ninoremap '' ''<Left>\ninoremap \"\" \"\"<Left>\ninoremap () ()<Left>\ninoremap <> <><Left>\ninoremap {} {}<Left>\ninoremap [] []<Left>\ninoremap () ()<Left>\n\n\" Quickly set comma or semicolon at the end of the string\ninoremap ,, <End>,\ninoremap ;; <End>;\nau FileType python inoremap :: <End>:\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 &\n inoremap 8 *\n inoremap 9 (\n inoremap 0 )\n inoremap - _\n inoremap 90 ()<Left>\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 & 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 &\n iunmap *\n iunmap (\n iunmap )\n iunmap _\n inoremap () ()<Left>\nendfunction\n\n\"call ToggleNumberRow()\nnnoremap <M-n> :call ToggleNumberRow()<CR>\n\n\" Add use <CWORD> 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 > 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(\"<cword>\"))\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(\"<cword>\")] = 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 <F7> :call UseCWord()<CR>\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 <M-d> <Esc>:call MarkDebug()<CR><Ins>\nau FileType perl,python inoremap <F6> <Esc>:call RemoveDebug()<CR><Ins>\nau FileType perl,python nnoremap <F6> :call RemoveDebug()<CR>\n\n\" end Perl settings\n\nnnoremap <silent> <F8> :TlistToggle<CR>\ninoremap <silent> <F8> <Esc>:TlistToggle<CR><Esc>\n\nfunction! AlwaysCD()\n if bufname(\"\") !~ \"^scp://\" && bufname(\"\") !~ \"^sftp://\" && 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 <c-j> j<c-e>\nnoremap <c-k> k<c-y>\n\n\" Better Marks\nnnoremap ' `\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": "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"
},
{
"answer_id": 1637004,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 2,
"selected": false,
"text": "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 <C-j> <Esc>\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 <c-j> <c-w>j\nmap <c-k> <c-w>k\nmap <c-l> <c-w>l\nmap <c-h> <c-w>h\n\n\" Nerd tree stuff\nlet NERDTreeIgnore = ['\\.pyc$', '\\.pyo$']\nnoremap gn :NERDTree<Cr>\n\n\" cd to the current file's directory\nnoremap gc :lcd %:h<Cr>\n"
},
{
"answer_id": 1637544,
"author": "Benj",
"author_id": 193128,
"author_profile": "https://Stackoverflow.com/users/193128",
"pm_score": 0,
"selected": false,
"text": "\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"
},
{
"answer_id": 1639333,
"author": "Mosh",
"author_id": 161609,
"author_profile": "https://Stackoverflow.com/users/161609",
"pm_score": 1,
"selected": false,
"text": "\" =====Key mapping\n\" Insert empty line.\nnmap <A-o> o<ESC>k\nnmap <A-O> O<ESC>j\n\" Insert one character.\nnmap <A-i> i <Esc>r\nnmap <A-a> a <Esc>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 <esc>\nnnoremap <esc> :noh<return><esc>\n\" Center screen on next/previous selection.\nmap n nzz\nmap N Nzz\n\" <Esc> with jj.\ninoremap jj <Esc>\n\" Switch jump to mark.\nnnoremap ' `\nnnoremap ` '\n\" Last and next jump should center too.\nnnoremap <C-o> <C-o>zz\nnnoremap <C-i> <C-i>zz\n\" Paste on new line.\nnnoremap <A-p> :pu<CR>\nnnoremap <A-S-p> :pu!<CR>\n\" Quick paste on insert mode.\ninoremap <C-F> <C-R>\"\n\" Indent cursor on empty line.\nnnoremap <A-c> ddO\nnnoremap <leader>c ddO\n\" Save and quit quickly.\nnnoremap <leader>s :w<CR>\nnnoremap <leader>q :q<CR>\nnnoremap <leader>Q :q!<CR>\n\" The way it should have been.\nnoremap Y y$\n\" Moving in buffers.\nnnoremap <C-S-tab> :bprev<CR>\nnnoremap <C-tab> :bnext<CR>\n\" Using bufkill plugin.\nnnoremap <leader>b :BD<CR>\nnnoremap <leader>B :BD!<CR>\nnnoremap <leader>ZZ :w<CR>:BD<CR>\n\" Moving and resizing in windows.\nnnoremap + <C-W>+\nnnoremap _ <C-W>-\nnnoremap <C-h> <C-w>h\nnnoremap <C-j> <C-w>j\nnnoremap <C-k> <C-w>k\nnnoremap <C-l> <C-w>l\nnnoremap <leader>w <C-w>c\n\" Moving in tabs\nnoremap <c-right> gt\nnoremap <c-left> gT\nnnoremap <leader>t :tabc<CR>\n\" Moving around in insert mode.\ninoremap <A-j> <C-O>gj\ninoremap <A-k> <C-O>gk\ninoremap <A-h> <Left>\ninoremap <A-l> <Right>\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=%<%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 <leader>ob :call BufWipeout()<CR>\n\" ===SuperTab\n\" Map SuperTab to space key.\nlet g:SuperTabMappingForward = '<c-space>'\nlet g:SuperTabMappingBackward = '<s-c-space>'\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 <leader>n :NERDTreeToggle<CR>\n\" ===delimitMate\nlet delimitMate = \"(:),[:],{:}\"\n"
},
{
"answer_id": 1639391,
"author": "guns",
"author_id": 76288,
"author_profile": "https://Stackoverflow.com/users/76288",
"pm_score": 3,
"selected": false,
"text": "if version >= 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 & 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:>·,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 <Tab>\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 &term == 'rxvt-unicode'\n set t_Co=256\n endif\n\n if &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 <Ctrl>-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 <Enter>\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 <Tab>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 <M-\". c .\">=\\e\". c\n exec \"map \\e\". c .\" <M-\". c .\">\"\n exec \"map! \\e\". c .\" <M-\". c .\">\"\nendfor\n\n\"\"\" Emacs keybindings\n\" first move the window command because we'll be taking it over\nnoremap <C-x> <C-w>\n\" Movement left/right\nnoremap! <C-b> <Left>\nnoremap! <C-f> <Right>\n\" word left/right\nnoremap <M-b> b\nnoremap! <M-b> <C-o>b\nnoremap <M-f> w\nnoremap! <M-f> <C-o>w\n\" line start/end\nnoremap <C-a> ^\nnoremap! <C-a> <Esc>I\nnoremap <C-e> $\nnoremap! <C-e> <Esc>A\n\" Rubout word / line and enter insert mode\nnoremap <C-w> i<C-w>\nnoremap <C-u> i<C-u>\n\" Forward delete char / word / line and enter insert mode\nnoremap! <C-d> <C-o>x\nnoremap <M-d> dw\nnoremap! <M-d> <C-o>dw\nnoremap <C-k> Da\nnoremap! <C-k> <C-o>D\n\" Undo / Redo and enter normal mode\nnoremap <C-_> u\nnoremap! <C-_> <C-o>u<Esc><Right>\nnoremap! <C-r> <C-o><C-r><Esc>\n\n\" Remap <C-space> to word completion\nnoremap! <Nul> <C-n>\n\n\" OS X paste (pretty poor implementation)\nif has('mac')\n noremap √ :r!pbpaste<CR>\n noremap! √ <Esc>√\nendif\n\n\"\"\" screen.vim REPL: http://github.com/ervandew/vimfiles\n\" send paragraph to parallel process\nvmap <C-c><C-c> :ScreenSend<CR>\nnmap <C-c><C-c> mCvip<C-c><C-c>`C\nimap <C-c><C-c> <Esc><C-c><C-c><Right>\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 & 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 >= 500\n"
},
{
"answer_id": 1639762,
"author": "Jan Christoph",
"author_id": 198414,
"author_profile": "https://Stackoverflow.com/users/198414",
"pm_score": 0,
"selected": false,
"text": "\" 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=<,> \" 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=<C-Z>\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('#')})%=[%{&fileformat}:%{&fileencoding}:%{&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:<,extends:> \" 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 &term == '' || &term == 'builtin_gui' || &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 <BS>, <Del>, 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=<F11> \" 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+=<:>\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\" ---------- Special Configuration ----------\n\"\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n\" ########## determine terminal encoding ##########\n\"if has(\"multi_byte\") && &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 &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 \"%\" ] && 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(\"'\\\"\") > 0 && line(\"'\\\"\") <= line(\"$\") && &filetype != \"mail\" | exe \"normal g`\\\"\" | endif\n \" jump to last position every time a buffer is entered\n \"au BufEnter * if line(\"'x\") > 0 && line(\"'x\") <= line(\"$\") && line(\"'y\") > 0 && line(\"'y\") <= line(\"$\") && &filetype != \"mail\" | exe \"normal g'yztg`x\" | endif\n \"au BufLeave * if &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 &textwidth > 0 | let m='\\|\\%' . &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 && 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 > 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, <f-args>)\ncom! -nargs=* -complete=file Vsp call Sp(1, <f-args>)\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(\"$\") > 20\n let l = 20\n else\n let l = line(\"$\")\n endif\n \" replace only if the buffer was modified\n if &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') && 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! /^> --[\\t ]*$/,/^-- $/-2d\n \" fix quotation\n silent! /^\\(On\\|In\\) .*$/,/^-- $/-1:s/>>/> >/g\n silent! /^\\(On\\|In\\) .*$/,/^-- $/-1:s/>\\([^\\ \\t]\\)/> \\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/&#\\([0-9]*\\);/\\=nr2char(submatch(1))/g\n \" break undo sequence\n normal iu\n exec 'silent! /\\(^\\(On\\|In\\) .*$\\|\\(schrieb\\|wrote\\):$\\)/,/^-- $/-1!par '.&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\\<Esc>\"\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 > lineB || lineA <= lineB && columnA > 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! <SID>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! <SID>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! <SID>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 < 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 >= 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 > 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 = &selection\n let &selection = \"inclusive\"\n let reg_save = @@\n\n if a:0 \" Invoked from Visual mode, use '< and '> marks.\n silent exe \"normal! `<\" . a:type . \"`>y\"\n elseif a:type == 'line'\n silent exe \"normal! '[V']y\"\n elseif a:type == 'block'\n silent exe \"normal! `[\\<C-V>`]y\"\n else\n silent exe \"normal! `[v`]y\"\n endif\n\n silent exe \"normal! `[gu`]~`]\"\n\n let &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 < 1\n echo \"'\".a:1.\"' not found\"\n return\n endif\n if l:num != 1\n let tmpfile = tempname()\n exe \"redir! > \" . tmpfile\n silent echon l:list\n redir END\n let old_efm = &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 &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 <silent> <buffer> <tab> :call eclim#util#FillTemplate(\"${\", \"}\")<CR>\n\" nnoremap <silent> <buffer> <leader>i :JavaImport<CR>\n\" nnoremap <silent> <buffer> <leader>d :JavaDocSearch -x declarations<CR>\n\" nnoremap <silent> <buffer> <CR> :JavaSearchContext<CR>\n\" nnoremap <silent> <buffer> <CR> :AntDoc<CR>\n\n\" quickfix notes plugin\nmap <Leader>n <Plug>QuickFixNote\nnnoremap <F6> :QFNSave ~/.vimquickfix/\nnnoremap <S-F6> :e ~/.vimquickfix/\nnnoremap <F7> :cgetfile ~/.vimquickfix/\nnnoremap <S-F7> :caddfile ~/.vimquickfix/\nnnoremap <S-F8> :!rm ~/.vimquickfix/\n\n\" EnhancedCommentify updated keybindings\nvmap <Leader><Space> <Plug>VisualTraditional\nnmap <Leader><Space> <Plug>Traditional\nlet g:EnhCommentifyTraditionalMode = 'No'\nlet g:EnhCommentifyPretty = 'No'\nlet g:EnhCommentifyRespectIndent = 'Yes'\n\n\" FuzzyFinder keybinding\nnnoremap <leader>fb :FufBuffer<CR>\nnnoremap <leader>fd :FufDir<CR>\nnnoremap <leader>fD :FufDir <C-r>=expand('%:~:.:h').'/'<CR><CR>\nnmap <leader>Fd <leader>fD\nnmap <leader>FD <leader>fD\nnnoremap <leader>ff :FufFile<CR>\nnnoremap <leader>fF :FufFile <C-r>=expand('%:~:.:h').'/'<CR><CR>\nnmap <leader>FF <leader>fF\nnnoremap <leader>ft :FufTextMate<CR>\nnnoremap <leader>fr :FufRenewCache<CR>\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 <silent> <F8> :YRShow<CR>\nlet g:yankring_history_file = '.yankring_history_file'\nlet g:yankring_replace_n_pkey = '<c-\\>'\nlet g:yankring_replace_n_nkey = '<c-m>'\n\n\" supertab\nlet g:SuperTabDefaultCompletionType = \"<c-n>\"\n\n\" TagList\nlet Tlist_Show_One_File = 1\n\n\" UltiSnips\n\"let g:UltiSnipsJumpForwardTrigger = \"<tab>\"\n\"let g:UltiSnipsJumpBackwardTrigger = \"<S-tab>\"\n\n\" NERD Commenter\nnmap <leader><space> <plug>NERDCommenterToggle\nvmap <leader><space> <plug>NERDCommenterToggle\nimap <C-c> <ESC>:call NERDComment(0, \"insert\")<CR>\n\n\" disable unused Mark mappings\nnmap <leader>_r <plug>MarkRegex\nvmap <leader>_r <plug>MarkRegex\nnmap <leader>_n <plug>MarkClear\nvmap <leader>_n <plug>MarkClear\nnmap <leader>_* <plug>MarkSearchCurrentNext\nnmap <leader>_# <plug>MarkSearchCurrentPrev\nnmap <leader>_/ <plug>MarkSearchAnyNext\nnmap <leader>_# <plug>MarkSearchAnyPrev\nnmap <leader>__* <plug>MarkSearchNext\nnmap <leader>__# <plug>MarkSearchPrev\n\n\" Nerd Tree explorer mapping\nnmap <leader>e :NERDTree<CR>\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<CR>\nnnoremap gcl :source $HOME/.vimrc<CR>:echo \"Configuration reloaded\"<CR>\n\n\" un/hightlight current line\nnnoremap <silent> <Leader>H :match<CR>\nnnoremap <silent> <Leader>h mk:exe 'match Search /<Bslash>%'.line(\".\").'l/'<CR>\n\n\" spellcheck off, german, englisch\nnnoremap gsg :setlocal invspell spelllang=de<CR>\nnnoremap gse :setlocal invspell spelllang=en<CR>\n\n\" switch to previous/next buffer\nnnoremap <silent> <c-p> :bprevious<CR>\nnnoremap <silent> <c-n> :bnext<CR>\n\n\" kill/delete trailing spaces and tabs\nnnoremap <Leader>kt msHmt:silent! %s/[\\t \\x0d]\\+$//g<CR>:let @/ = \"\"<CR>:echo \"Deleted trailing spaces\"<CR>'tzt`s\nvnoremap <Leader>kt :s/[\\t \\x0d]\\+$//g<CR>:let @/ = \"\"<CR>:echo \"Deleted trailing, spaces\"<CR>\n\n\" kill/reduce inner spaces and tabs to a single space/tab\nnnoremap <Leader>ki msHmt:silent! %s/\\([^\\xa0\\x0d\\t ]\\)[\\xa0\\x0d\\t ]\\+\\([^\\xa0\\x0d\\t ]\\)/\\1 \\2/g<CR>:let @/ = \"\"<CR>:echo \"Deleted inner spaces\"<CR>'tzt`s\nvnoremap <Leader>ki :s/\\([^\\xa0\\x0d\\t ]\\)[\\xa0\\x0d\\t ]\\+\\([^\\xa0\\x0d\\t ]\\)/\\1 \\2/g<CR>:let @/ = \"\"<CR>:echo \"Deleted inner spaces\"<CR>\n\n\" start new undo sequences when using certain commands in insert mode\ninoremap <C-U> <C-G>u<C-U>\ninoremap <C-W> <C-G>u<C-W>\ninoremap <BS> <C-G>u<BS>\ninoremap <C-H> <C-G>u<C-H>\ninoremap <Del> <C-G>u<Del>\n\n\" swap two words\n\" http://www.vim.org/tips/tip.php?tip_id=329\nnmap <silent> gw \"_yiw:s/\\(\\%#[ÄÖÜäöüßa-zA-Z0-9]\\+\\)\\(\\_W\\+\\)\\([ÄÖÜäöüßa-zA-Z0-9]\\+\\)/\\3\\2\\1/<CR><C-o><C-l>:let @/ = \"\"<CR>\nnmap <silent> gW \"_yiW:s/\\(\\%#[ÄÖÜäöüßa-zA-Z0-9-+*_]\\+\\)\\(\\_W\\+\\)\\([ÄÖÜäöüßa-zA-Z0-9-+*_]\\+\\)/\\3\\2\\1/<CR><C-o><C-l>:let @/ = \"\"<CR>\n\n\" Capitalize movement\nnnoremap <silent> gC :set opfunc=Capitalize<CR>g@\nvnoremap <silent> gC :<C-U>call Capitalize(visualmode(), 1)<CR>\n\n\" delete search-register\nnnoremap <silent> <leader>/ :let @/ = \"\"<CR>\n\n\" browse current buffer/selection in www-browser\nnnoremap <Leader>b :!x-www-browser %:p<CR>:echo \"WWW-Browser started\"<CR>\nvnoremap <Leader>b y:!x-www-browser <C-R>\"<CR>:echo \"WWW-Browser started\"<CR>\n\n\" lookup/translate inner/selected word in dictionary\n\" recode is only needed for non-utf-8-text\n\" nnoremap <Leader>T mayiw`a:exe \"!dict -P - -- $(echo \" . @\" . \"\\| recode latin1..utf-8)\"<CR>\n\"nnoremap <Leader>t mayiw`a:exe \"!dict -P - -- \" . @\"<CR>\n\" vnoremap <Leader>T may`a:exe \"!dict -P - -- $(echo \" . @\" . \"\\| recode latin1..utf-8)\"<CR>\n\"vnoremap <Leader>t may`a:exe \"!dict -P - -- \" . @\"<CR>\n\n\" delete words in insert mode like expected - doesn't work properly at\n\" the end of the line\ninoremap <C-BS> <C-w>\n\n\" Switch buffers\nnnoremap <silent> [b :ls<Bar>let nr = input(\"Buffer: \")<Bar>if nr != ''<Bar>exe \":b \" . nr<Bar>endif<CR>\n\" Search for the occurence of the word under the cursor\nnnoremap <silent> [I [I:le\n"
},
{
"answer_id": 1647401,
"author": "Richard",
"author_id": 110772,
"author_profile": "https://Stackoverflow.com/users/110772",
"pm_score": 0,
"selected": false,
"text": "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<CR>\nnoremap \\2 I\"<Esc>A\"<Esc>\nnoremap \\3 bi'<Esc>ea'<Esc>\nnoremap \\\" i\"<Esc>ea\"<Esc>\nnoremap ?2 Bi\"<Esc>Ea\"<Esc>\nset matchpairs+=<:>\nnnoremap <C-N> :next<CR>\nnnoremap <C-P> :prev<CR>\nnnoremap <Tab> :bnext<CR>\nnnoremap <S-Tab> :bprevious<CR>\nnnoremap \\w :let @/=expand(\"<cword>\")<Bar>split<Bar>normal n<CR>\nnnoremap \\W :let @/='\\<'.expand(\"<cword>\").'\\>'<Bar>split<Bar>normal n<CR>\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.\"?\\<CR>\"\n exec 'nnoremap '.a:key.' '.cmd\n exec 'inoremap '.a:key.\" \\<C-O>\".cmd\nendfunction\ncommand -nargs=+ MapToggle call MapToggle(<f-args>)\n\nmap <F6> :if exists(\"syntax_on\") <Bar> syntax off <Bar> else <Bar> syntax enable <Bar> endif <CR>\n\n\" Display-altering option toggles\nMapToggle <F7> hlsearch\nMapToggle <F8> wrap\nMapToggle <F9> list\n\n\" Behavior-altering option toggles\nMapToggle <F10> scrollbind\nMapToggle <F11> ignorecase\nMapToggle <F12> paste\nset pastetoggle=<F12>\n"
},
{
"answer_id": 1656156,
"author": "Pierre-Antoine LaFayette",
"author_id": 135360,
"author_profile": "https://Stackoverflow.com/users/135360",
"pm_score": 1,
"selected": false,
"text": "\n\" .vimrc \n\"\n\" $Author$\n\" $Date$\n\" $Revision$ \n\n\" * Initial Configuration * {{{1 \"\n\" change directory on open file, buffer switch etc. {{{2\nset autochdir\n\n\" turn on filetype detection and indentation {{{2\nfiletype indent plugin on\n\n\" set tags file to search in parent directories with tags; {{{2\nset tags=tags;\n\n\" reload vimrc on update {{{2\nautocmd BufWritePost .vimrc source %\n\n\" set folds to look for markers {{{2\n:set foldmethod=marker\n\n\" automatically save view and reload folds {{{2\n\"au BufWinLeave * mkview\n\"au BufWinEnter * silent loadview\n\n\" behave like windows {{{2\n\"source $VIMRUNTIME/mswin.vim \" can't use if on (use with gvim only)\n\"behave mswin\n\n\" load dictionary files for complete suggestion with Ctrl-n {{{2\nset complete+=k\nautocmd FileType * exec('set dictionary+=~/.vim/dict/' . &filetype)\n\n\" * User Interface * {{{1 \"\n\" turn on coloring {{{2\nif has('syntax')\n syntax on\nendif\n\n\" gvim color scheme of choice {{{2\nif has('gui')\n so $VIMRUNTIME/colors/desert.vim\nendif\n\n\" turn off annoying bell {{{2\nset vb\n\n\" set the directory for swp files {{{2\nif(isdirectory(expand(\"$VIMRUNTIME/swp\")))\n set dir=$VIMRUNTIME/swp\nendif\n\n\" have fifty lines of cmdline (etc) history {{{2\nset history=50\n\n\" 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\n\n\" use \"[RO]\" for \"[readonly]\" to save space in the message line: {{{2\nset shortmess+=r\n\n\" display current mode and partially typed commands in status line {{{2\nset showmode\nset showcmd\n\n\" 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]\\ %<%.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\n\n\" * Macros * {{{1 \"\n\" Function keys {{{2\n\" Don't you always find yourself hitting instead of ? {{{3\ninoremap \nnoremap \n\n\" turn off syntax highlighting {{{3\nnnoremap :nohlsearch\ninoremap :nohlsearcha\n\n\" NERD Tree Explorer {{{3\nnnoremap :NERDTreeToggle \n\n\" open tag list {{{3\nnnoremap :TlistToggle\n\n\" Spell check {{{3\nnnoremap :set spell\n\n\" No spell check {{{3\nnnoremap :set nospell\n\n\" refactor curly braces on keyword line {{{3\nmap :%s/) \\?\\n^\\s*{/) {/g\n\n\" useful mappings to paste and reformat/reindent {{{2\nnnoremap P P'[v']=\nnnoremap p P'[v']=\n\n\" * Scripts * {{{1 \"\n:au Filetype html,xml,xsl source ~/.vim/scripts/closetag.vim\n\n\" Modeline {{{1\n\" vim:set fdm=marker sw=4 ts=4:\n"
},
{
"answer_id": 1656158,
"author": "John Kugelman",
"author_id": 68587,
"author_profile": "https://Stackoverflow.com/users/68587",
"pm_score": 0,
"selected": false,
"text": "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 <TAB> 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 <C-N> :confirm next<Enter>\nnnoremap <C-P> :confirm prev<Enter>\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=<F5>\n\n\" Don't exit visual mode when shifting.\nvnoremap < <gv\nvnoremap > >gv\n\n\" Move up and down by visual lines not buffer lines.\nnnoremap <Up> gk\nvnoremap <Up> gk\nnnoremap <Down> gj\nvnoremap <Down> gj\n"
},
{
"answer_id": 1773289,
"author": "Yada",
"author_id": 45066,
"author_profile": "https://Stackoverflow.com/users/45066",
"pm_score": 0,
"selected": false,
"text": "\" Intelligent tab completion\ninoremap <silent> <Tab> <C-r>=<SID>InsertTabWrapper(1)<CR>\ninoremap <silent> <S-Tab> <C-r>=<SID>InsertTabWrapper(-1)<CR>\n\nfunction! <SID>InsertTabWrapper(direction)\n let idx = col('.') - 1\n let str = getline('.')\n\n if a:direction > 0 && idx >= 2 && str[idx - 1] == ' '\n \\&& str[idx - 2] =~? '[a-z]'\n if &softtabstop && idx % &softtabstop == 0\n return \"\\<BS>\\<Tab>\\<Tab>\"\n else\n return \"\\<BS>\\<Tab>\"\n endif\n elseif idx == 0 || str[idx - 1] !~? '[a-z]'\n return \"\\<Tab>\"\n elseif a:direction > 0\n return \"\\<C-p>\"\n else\n return \"\\<C-n>\"\n endif\nendfunction\n"
},
{
"answer_id": 1817199,
"author": "Roberto Bonvallet",
"author_id": 13169,
"author_profile": "https://Stackoverflow.com/users/13169",
"pm_score": 1,
"selected": false,
"text": "\" Page down, page up, scroll down, scroll up\nnoremap <Space> <C-f>\nnoremap - <C-b>\nnoremap <Backspace> <C-y>\nnoremap <Return> <C-e>\n"
},
{
"answer_id": 2079364,
"author": "fferen",
"author_id": 243503,
"author_profile": "https://Stackoverflow.com/users/243503",
"pm_score": 0,
"selected": false,
"text": "let g:pfx='' \" prefix for private pastebin.\n\nfunction PBSubmit()\npython << 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 <Leader>pb :call PBSubmit()<CR>\n"
},
{
"answer_id": 2648674,
"author": "ravett",
"author_id": 317931,
"author_profile": "https://Stackoverflow.com/users/317931",
"pm_score": 0,
"selected": false,
"text": "nnoremap <Leader>qa mqGo<Esc>\"ap\nnnoremap <Leader>qb mqGo<Esc>\"bp\nnnoremap <Leader>qc mqGo<Esc>\"cp\n<SNIP>\nnnoremap <Leader>qz mqGo<Esc>\"zp\n\nnnoremap <Leader>Qa G0\"ad$dd'q\nnnoremap <Leader>Qb G0\"bd$dd'q\nnnoremap <Leader>Qc G0\"cd$dd'q\n<SNIP>\nnnoremap <Leader>Qz G0\"zd$dd'q\n"
},
{
"answer_id": 2746150,
"author": "Siddhartha Reddy",
"author_id": 130535,
"author_profile": "https://Stackoverflow.com/users/130535",
"pm_score": 0,
"selected": false,
"text": "\" 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 <S-Enter> O<ESC> \" Insert above current line\"\nmap <Enter> o<ESC> \" Insert below current line\"\n\n\" After selecting something in visual mode and shifting, I still want that\"\n\" selection intact ************************************************************\"\nvmap > >gv\nvmap < <gv\n"
},
{
"answer_id": 2841066,
"author": "sixtyfootersdude",
"author_id": 251589,
"author_profile": "https://Stackoverflow.com/users/251589",
"pm_score": 0,
"selected": false,
"text": "~/.vim/after/syntax/vim.vim highlight JakeRedKeywords cterm=bold term=bold ctermbg=black ctermfg=Red\n 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"
},
{
"answer_id": 2989503,
"author": "Alexis Métaireau",
"author_id": 147077,
"author_profile": "https://Stackoverflow.com/users/147077",
"pm_score": 0,
"selected": false,
"text": "\" 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\" <alt-left/right> to navigate trough tabs\n\" <ctrl-e> to display the explorator\n\" <ctrl-p> for the code explorator\n\" <ctrl-space> to autocomplete\n\" <ctrl-n> enter tabnew to open a new file\n\" <alt-h> highlight the lines of more than 80 columns\n\" <ctrl-h> set textwith to 80 cols\n\" <maj-k> 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 <c-n> :tabnew \nmap <silent><c-e> :NERDTreeToggle <cr>\nmap <silent><c-p> :TlistToggle <cr>\nnnoremap <a-right> gt\nnnoremap <a-left> gT\ncommand W w !sudo tee % > /dev/null\nmap <buffer> K :execute \"!pydoc \" . expand(\"<cword>\")<CR>\nmap <F2> :set textwidth=80 <cr>\n\" Replace trailing slashes\nmap <F3> :%s/\\s\\+$//<CR>:exe \":echo'trailing slashes removes'\"<CR>\nmap <silent><F6> :QFix<CR>\n\n\" edit vim quickly\nmap ,v :sp ~/.vimrc<CR><C-W>_\nmap <silent> ,V :source ~/.vimrc<CR>:filetype detect<CR>:exe \":echo'vimrc reloaded'\"<CR> \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 <Nul> <C-n>\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 <silent><F1>\n\\ :if exists('w:long_line_match') <Bar>\n\\ silent! call matchdelete(w:long_line_match) <Bar>\n\\ unlet w:long_line_match <Bar>\n\\ elseif &textwidth > 0 <Bar>\n\\ let w:long_line_match = matchadd('ErrorMsg', '\\%>'.&tw.'v.\\+', -1) <Bar>\n\\ else <Bar>\n\\ let w:long_line_match = matchadd('ErrorMsg', '\\%>80v.\\+', -1) <Bar>\n\\ endif<CR>\n\ncommand -bang -nargs=? QFix call QFixToggle(<bang>0)\nfunction! QFixToggle(forced)\n if exists(\"g:qfix_win\") && 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"
},
{
"answer_id": 2989673,
"author": "ZyX",
"author_id": 273566,
"author_profile": "https://Stackoverflow.com/users/273566",
"pm_score": 0,
"selected": false,
"text": "\"{{{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:>-,trail:-,nbsp:_\nset magic\nset pastetoggle=<F1>\nset foldmethod=marker\nset wildmenu\nset wildcharm=<Tab>\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\") &&\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 <\".tmp[0].\">=\".\n \\substitute(tmp[1], \"\\\\^\\\\[\", \"\\<ESC>\", \"g\")\n endif\n endfor\nendif\n\" function g:DefineKeys()\n \"{{{4 screen\n if 0 && $_SECONDLAUNCH\n set <F1>=[11~\n set <F2>=[12~\n set <F3>=[13~\n set <F4>=[14~\n set <F5>=[15~\n set <F6>=[17~\n set <F7>=[18~\n set <F8>=[19~\n set <F9>=[20~\n set <F10>=[21~\n set <F11>=[23~\n set <F12>=[24~\n set <S-F1>=[23~\n set <S-F2>=[24~\n set <S-F3>=[25~\n set <S-F4>=[26~\n set <S-F5>=[28~\n set <S-F6>=[29~\n set <S-F7>=[31~\n set <S-F8>=[32~\n set <S-F9>=[33~\n set <S-F10>=[34~\n set <S-F11>=[23$\n set <S-F12>=[24$\n set <HOME>=[7~\n set <END>=[8~\n \"{{{4 xterm \n elseif $TERM==\"xterm\"\n set <M-a>=a\n set <M-b>=b\n set <M-c>=c\n set <M-d>=d\n set <M-e>=e\n set <M-f>=f\n set <M-g>=g\n set <M-h>=h\n set <M-i>=i\n set <M-j>=j\n set <M-k>=k\n set <M-l>=l\n set <M-m>=m\n set <M-n>=n\n set <M-o>=o\n set <M-p>=p\n set <M-q>=q\n set <M-r>=r\n set <M-s>=s\n set <M-t>=t\n set <M-u>=u\n set <M-v>=v\n set <M-w>=w\n set <M-x>=x\n set <M-y>=y\n set <M-z>=z\n \"set <M-SPACE>= \n \"set <Left>=OD\n \"set <S-Left>=O2D\n \"set <C-Left>=O5D\n \"set <Right>=OC\n \"set <S-Right>=O2C\n \"set <C-Right>=O5C\n \"set <Up>=OA\n \"set <S-Up>=O2A\n \"set <C-Up>=O5A\n \"set <Down>=OB\n \"set <S-Down>=O2B\n \"set <C-Down>=O5B\n set <F1>=[11~\n set <F2>=[12~\n set <F3>=[13~\n set <F4>=[14~\n set <F5>=[15~\n set <F6>=[17~\n set <F7>=[18~\n set <F8>=[19~\n set <F9>=[20~\n set <F10>=[21~\n set <F11>=[23~\n set <F12>=[24~\n \"set <C-F1>=\n \"set <C-F2>=\n \"set <C-F3>=\n \"set <C-F4>=\n \"set <C-F5>=[15;5~\n \"set <C-F6>=[17;5~\n \"\n \"set <C-F7>=[18;5~\n \"set <C-F8>=[19;5~\n \"set <C-F9>=[20;5~\n \"set <C-F10>=[21;5~\n \"set <C-F11>=[23;5~\n \"set <C-F12>=[24;5~\n set <S-F1>=[11;2~\n set <S-F2>=[12;2~\n set <S-F3>=[13;2~\n set <S-F4>=[14;2~\n set <S-F5>=[15;2~\n set <S-F6>=[17;2~\n set <S-F7>=[18;2~\n set <S-F8>=[19;2~\n set <S-F9>=[20;2~\n set <S-F10>=[21;2~\n set <S-F11>=[23;2~\n set <S-F12>=[24;2~\n set <END>=OF\n set <S-END>=O2F\n set <S-HOME>=O2H\n set <HOME>=OH\n set <DEL>=\n \" set <PageUp>=[5~\n \" set <PageDown>=[6~\n \" noremap <DEL>\n \" inoremap <DEL>\n \" cnoremap <DEL>\n set <S-Del>=[3;2~\n \" set <C-Del>=[3;5~\n \" set <M-Del>=[3;3~\n \"{{{4 rxvt --- aterm\n elseif $TERM==\"rxvt\"\n set <M-a>=a\n set <M-b>=b\n set <M-c>=c\n set <M-d>=d\n set <M-e>=e\n set <M-f>=f\n set <M-g>=g\n set <M-h>=h\n set <M-i>=i\n set <M-j>=j\n set <M-k>=k\n set <M-l>=l\n set <M-m>=m\n set <M-n>=n\n set <M-o>=o\n set <M-p>=p\n set <M-q>=q\n set <M-r>=r\n set <M-s>=s\n set <M-t>=t\n set <M-u>=u\n set <M-v>=v\n set <M-w>=w\n set <M-x>=x\n set <M-y>=y\n set <M-z>=z\n set <F1>=OP\n set <F2>=OQ\n set <F3>=OR\n set <F4>=OS\n set <F5>=[15~\n set <F6>=[17~\n set <F7>=[18~\n set <F8>=[19~\n set <F9>=[20~\n set <F10>=[21~\n set <F11>=[23~\n set <F12>=[24~\n set <S-F1>=[23~\n set <S-F2>=[24~\n set <S-F3>=[25~\n set <S-F4>=[26~\n set <S-F5>=[28~\n set <S-F6>=[29~\n set <S-F7>=[31~\n set <S-F8>=[32~\n set <S-F9>=[33~\n set <S-F10>=[34~\n set <S-F11>=[23$\n set <S-F12>=[24$\n \" set <C-S-F2>=[24^\n \" set <C-S-F3>=[25^\n \" set <C-S-F4>=[26^\n \" set <C-S-F5>=[28^\n \" set <C-S-F6>=[29^\n \" set <C-S-F7>=[31^\n \" set <C-S-F8>=[32^\n \" set <C-S-F9>=[33^\n \" set <C-S-F10>=[34^\n \" set <C-S-F11>=[23@\n \" set <C-S-F12>=[24@\n \" set <M-F5>=<F5>\n \" set <M-F6>=<F6>\n \" set <M-F7>=<F7>\n \" set <M-F8>=<F8>\n \" set <M-F9>=<F9>\n \" set <M-F10>=<F10>\n \" set <M-F11>=<F11>\n \" set <M-F12>=<F12>\n \" set <M-S-F5>=<S-F5>\n \" set <M-S-F6>=<S-F6>\n \" set <M-S-F7>=<S-F7>\n \" set <M-S-F8>=<S-F8>\n \" set <M-S-F9>=<S-F9>\n \" set <M-S-F10>=<S-F10>\n \" set <M-S-F11>=<S-F11>\n \" set <M-S-F12>=<S-F12>\n \"{{{4 rxvt-unicode --- urxvt\n elseif $TERM==\"rxvt-unicode\"\n set <M-a>=a\n set <M-b>=b\n set <M-c>=c\n set <M-d>=d\n set <M-e>=e\n set <M-f>=f\n set <M-g>=g\n set <M-h>=h\n set <M-i>=i\n set <M-j>=j\n set <M-k>=k\n set <M-l>=l\n set <M-m>=m\n set <M-n>=n\n set <M-o>=o\n set <M-p>=p\n set <M-q>=q\n set <M-r>=r\n set <M-s>=s\n set <M-t>=t\n set <M-u>=u\n set <M-v>=v\n set <M-w>=w\n set <M-x>=x\n set <M-y>=y\n set <M-z>=z\n set <F1>=[11~\n set <F2>=[12~\n set <F3>=[13~\n set <F4>=[14~\n set <F5>=[15~\n set <F6>=[17~\n set <F7>=[18~\n set <F8>=[19~\n set <F9>=[20~\n set <F10>=[21~\n set <F11>=[23~\n set <F12>=[24~\n \" fluxbox!<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n set <S-F1>=[23~\n set <S-F2>=[24~\n set <S-F3>=[25~\n set <S-F4>=[26~\n set <S-F5>=[28~\n set <S-F6>=[29~\n set <S-F7>=[31~\n set <S-F8>=[32~\n set <S-F9>=[33~\n set <S-F10>=[34~\n set <S-F11>=[23$\n set <S-F12>=[24$\n \" set <C-F1>=[11^\n \" set <C-F2>=[12^\n \" set <C-F3>=[13^\n \" set <C-F4>=[14^\n \" set <C-F5>=[15^\n \" set <C-F6>=[17^\n \" set <C-F7>=[18^\n \" set <C-F8>=[19^\n \" set <C-F9>=[20^\n \" set <C-F10>=[21^\n \" set <C-F11>=[23^\n \" set <C-F12>=[24^\n \" openbox!<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n \" set <S-F1>=[23~\n \" set <S-F2>=[24~\n \" set <S-F3>=[25~\n \" set <S-F4>=[26~\n \" set <S-F5>=[28~\n \" set <S-F6>=[29~\n \" set <S-F7>=[31~\n \" set <S-F8>=[32~\n \" set <S-F9>=[33~\n \" set <S-F10>=[34~\n \" set <S-F11>=[23$\n \" set <S-F12>=[24$\n \" set <C-S-F2>=[24^\n \" set <C-S-F3>=[25^\n \" set <C-S-F4>=[26^\n \" set <C-S-F5>=[28^\n \" set <C-S-F6>=[29^\n \" set <C-S-F7>=[31^\n \" set <C-S-F8>=[32^\n \" set <C-S-F9>=[33^\n \" set <C-S-F10>=[34^\n \" set <C-S-F11>=[23@\n \" set <C-S-F12>=[24@\n \" set <M-F5>=<F5>\n \" set <M-F6>=<F6>\n \" set <M-F7>=<F7>\n \" set <M-F8>=<F8>\n \" set <M-F9>=<F9>\n \" set <M-F10>=<F10>\n \" set <M-F11>=<F11>\n \" set <M-F12>=<F12>\n \" set <M-S-F5>=<S-F5>\n \" set <M-S-F6>=<S-F6>\n \" set <M-S-F7>=<S-F7>\n \" set <M-S-F8>=<S-F8>\n \" set <M-S-F9>=<S-F9>\n \" set <M-S-F10>=<S-F10>\n \" set <M-S-F11>=<S-F11>\n \" set <M-S-F12>=<S-F12>\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!<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n \" let g:C_F1=\"\\<ESC>[11^\"\n \" let g:C_F2=\"\\<ESC>[12^\"\n \" let g:C_F3=\"\\<ESC>[13^\"\n \" let g:C_F4=\"\\<ESC>[14^\"\n \" let g:C_F5=\"\\<ESC>[15^\"\n \" let g:C_F6=\"\\<ESC>[17^\"\n \" let g:C_F7=\"\\<ESC>[18^\"\n \" let g:C_F8=\"\\<ESC>[19^\"\n \" let g:C_F9=\"\\<ESC>[20^\"\n \" let g:C_F10=\"\\<ESC>[21^\"\n \" let g:C_F11=\"\\<ESC>[23^\"\n \" let g:C_F12=\"\\<ESC>[24^\"\n \" let g:M_S_F1=\"\\<ESC>\\<ESC>[23$\"\n \" let g:M_S_F2=\"\\<ESC>\\<ESC>[24$\"\n \" let g:M_S_F3=\"\\<ESC>\\<ESC>[25$\"\n \" let g:M_S_F4=\"\\<ESC>\\<ESC>[26$\"\n \" let g:M_S_F5=\"\\<ESC>\\<ESC>[28$\"\n \" let g:M_S_F6=\"\\<ESC>\\<ESC>[29$\"\n \" let g:M_S_F7=\"\\<ESC>\\<ESC>[31$\"\n \" let g:M_S_F8=\"\\<ESC>\\<ESC>[32$\"\n \" let g:M_S_F9=\"\\<ESC>\\<ESC>[33$\"\n \" let g:M_S_F10=\"\\<ESC>\\<ESC>[34$\"\n \" let g:M_S_F11=\"\\<ESC>\\<ESC>[23$\"\n \" let g:M_S_F12=\"\\<ESC>\\<ESC>[24$\"\n \" let g:M_C_F1=\"\\<ESC>\\<ESC>[11^\"\n \" let g:M_C_F2=\"\\<ESC>\\<ESC>[12^\"\n \" let g:M_C_F3=\"\\<ESC>\\<ESC>[13^\"\n \" let g:M_C_F4=\"\\<ESC>\\<ESC>[14^\"\n \" let g:M_C_F5=\"\\<ESC>\\<ESC>[15^\"\n \" let g:M_C_F6=\"\\<ESC>\\<ESC>[17^\"\n \" let g:M_C_F7=\"\\<ESC>\\<ESC>[18^\"\n \" let g:M_C_F8=\"\\<ESC>\\<ESC>[19^\"\n \" let g:M_C_F9=\"\\<ESC>\\<ESC>[20^\"\n \" let g:M_C_F10=\"\\<ESC>\\<ESC>[21^\"\n \" let g:M_C_F11=\"\\<ESC>\\<ESC>[23^\"\n \" let g:M_C_F12=\"\\<ESC>\\<ESC>[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\\%>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 &l:modifiable=(!(&ro && !&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<CR>\n\" menu Encoding.windows-1251 :e ++enc=8bit-cp1251<CR>\n\" menu Encoding.ibm-866 :e ++enc=8bit-ibm866<CR>\n\" menu Encoding.utf-8 :e ++enc=2byte-utf-8<CR>\n\" menu Encoding.ucs-2le :e ++enc=ucs-2le<CR>\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>/dev/null\"\nendfunction\ncommand -range=% -nargs=+ S call s:Substitute(<q-args>, <line1>, <line2>)\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 \"\\<C-n>\"\n else\n return \"\\<Tab>\"\n endif\nendfunction\ninoremap <Tab> <C-R>=CleverTab()<CR>\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, &keymap)\n echo s:ki\n if s:ki==-1\n let &keymap=s:kmapvals[0]\n return\n elseif s:ki>=len(a:kmaps)-1\n let &keymap=s:kmapvals[0]\n return\n endif\n let &keymap=s:kmapvals[s:ki+1]\n return\n elseif has_key(a:kmaps, a:knum)\n let &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 &keymap=val\n return\n endif\n let s:ki+=1\n endfor\n let &keymap=s:kmapvals[0]\nendfunction\n\" inoremap <S-Tab> <C-\\><C-o>:call<SPACE>SwitchKeymap(g:kmaps,<SPACE>\"+\")<C-m>\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 <F4>sv :call<SPACE>ToggleVerbose()\ninoremap <F4>sv <C-o>:call<SPACE>ToggleVerbose()\n\n\"{{{2 Other mappings \n\"{{{3 <.*F12> mappings - for some browsing \n noremap <F12> :TlistToggle<CR>\ninoremap <F12> <C-O>:TlistToggle<CR>\ninoremap <S-F12> <C-O>:BufExplorer<CR>\n noremap <S-F12> :BufExplorer<CR>\ninoremap <M-F12> <C-O>:NERDTreeToggle<CR>\n noremap <M-F12> :NERDTreeToggle<CR>\n\"{{{3 yank/paste \nvnoremap <C-Insert> \"+y\nnnoremap <S-Insert> \"+p\ninoremap <S-Insert> <C-o><S-Insert>\nvnoremap p \"_da<C-r><C-r>\"<CR><ESC>\n\"{{{3 Motions \n\"{{{4 Left/Right replace \ncnoremap <C-b> <Left>\ncnoremap <C-f> <Right>\ninoremap <C-b> <C-\\><C-o>h\ninoremap <C-f> <C-o>a\n\ncnoremap <M-b> <C-Right>\ninoremap <M-b> <C-o>w\ninoremap <M-f> <C-o>b\ncnoremap <M-f> <C-Left>\n\"{{{4 Page Up/Down \nnnoremap <C-b> <C-U><C-U>\ninoremap <PageUp> <C-O><C-U><C-O><C-U>\nnnoremap <C-f> <C-D><C-D>\ninoremap <PageDown> <C-O><C-D><C-O><C-D>\n\"{{{4 Up/Down \ninoremap <C-G> <C-\\><C-o>gk\ninoremap <Up> <C-\\><C-o>gk\ninoremap <Down> <C-\\><C-o>gj\ninoremap <C-l> <C-\\><C-o>gj\nnnoremap <Down> gj\nvnoremap <Down> 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 <Up> gk\nvnoremap <Up> gk\n\"{{{4 Smart <HOME> and <END> \n\n \" imap <HOME> <C-o>g^\n \" imap <C-O>g^<HOME> <C-o>^\n\" inoremap <C-o>^<HOME> <C-o>0\n \" imap <END> <C-o>g$\n\" inoremap <C-o>g$<END> <C-o>$\n \" nmap <HOME> <C-o>g^\n \" nmap <C-O>g^<HOME> ^\n\" nnoremap <C-o>^<HOME> 0\n \" nmap <END> g$\n\" nnoremap <C-o>g$<END> $\n\"{{{3 <F3> and searching \n noremap <F3> :nohl<CR>\ninoremap <S-F3> <C-o>:nohl<CR>\ninoremap <F3> <C-o>n\n\"{{{3 <F2> for saving, <F10> for exiting \n noremap <F2> :up<CR>\ninoremap <F2> <C-o>:up<CR>\ninoremap <F10> <ESC>ZZ\n noremap <F10> <ESC>ZZ\ninoremap <S-F10> <ESC>:q!<CR>\n noremap <S-F10> :q!<CR>\ninoremap <C-F10> <ESC>:silent<SPACE>mksession<SPACE>session.vim<CR>:wq!\n noremap <C-F10> :silent<SPACE>mksession<SPACE>session.vim<CR>:wq!\n\"{{{3 Something \ninoremap <C-z> <C-o>u\n noremap <F1> :set paste!<C-m>\ninoremap <C-^> <C-O><C-^>\ninoremap <C-d> <Del>\ncnoremap <C-d> <Del>\n\"{{{3 <C-j> \ninoremap <C-j>j <C-o>:bn<CR>\ninoremap <C-j>J <C-o>:bN<CR>\n noremap <C-j>j :bn<CR>\n noremap <C-j>J :bN<CR>\n\"{{{3 for visual \ninoremap <S-Left> <C-o>vge\ninoremap <S-Up> <C-o>vk\ninoremap <S-Down> <C-o>vj\ninoremap <S-Right> <C-o>ve\ninoremap <S-End> <C-o>v$\ninoremap <S-Home> <C-o>v$o^\nvnoremap A <C-c>i\n\"{{{3 <F4> \n\"{{{4 <F4> folds \n noremap <F4>{ a{{{<ESC>\ninoremap <F4>{ {{{\n noremap <F4>} a}}}<ESC>\ninoremap <F4>} }}}\ninoremap <F4>[ <C-o>o{{{<C-o>:call NERDComment(0,\"norm\")<C-m>\n noremap <F4>[ o{{{<C-o>:call NERDComment(0,\"norm\")<C-m>\ninoremap <F4>] <C-o>o}}}<C-o>:call NERDComment(0,\"norm\")<C-m>\n noremap <F4>] o}}}<C-o>:call NERDComment(0,\"norm\")<C-m>\n\"{{{4 <F4> folds \ninoremap <F4>f <C-o>za<C-o>j<C-o>^\n noremap <F4>f zaj\n\"{{{4 <F4> yank/paste/delete \ninoremap <F4>p <C-o>p\ninoremap <F4>gp <C-o>\"+p\ninoremap <F4>y( <C-o>ya)\ninoremap <F4>yl <C-o>yy\ninoremap <F4>gy( <C-o>\"+ya)\ninoremap <F4>gyl <C-o>\"+yy\ninoremap <F4>P <C-o>P\ninoremap <F4>d( <C-o>da)\ninoremap <F4>dl <C-o>dd\n\"{{{4 <F4> frequently used expressions \ninoremap <F4>c \\033[m<C-/><C-o>h\n\"{{{4 <F4> alternate \n imap <F4>a <C-o>:A<C-m>\n map <F4>a :A<C-m>\n\"}}}\n\"}}}\n\"{{{3 «,» \n\"\n\" &lower\n\" &upper\n\" &1st\n\" &2nd\n\" &both lower and upper (or both 1st and 2nd)\n\" prefixed with &e\n\" prefixed with &E\n\" is &Prefix for smth\n\" &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\" < > | | +b | | +b+eb | +1 |\n\" - _ | | +1 | | +b | |\n\" @ / | b | | | | |\n\" = | | | | | |\n\"\n\"{{{4 insert \ninoremap ,<SPACE> ,<SPACE>\ninoremap ,<Esc> ,\ninoremap ,<BS> <Nop>\ninoremap ,ef <C-o>I{<C-m><C-o>o}<C-o>O\ninoremap ,eF <C-m>{<C-m><C-o>o}<C-o>O\ninoremap ,F {<C-o>o}<C-o>O\ninoremap ,f {}<C-\\><C-o>h\ninoremap ,h []<C-\\><C-o>h\ninoremap ,s ()<C-\\><C-o>h\ninoremap ,u <LT>><C-\\><C-o>h\ninoremap ,es (<C-\\><C-o>E<C-o>a)<C-\\><C-o>h\ninoremap ,H [[::]]<C-o>F:\ninoremap ,eh [::]<C-o>F:\ninoremap ,, \\\ninoremap ,. <C-o>==\ninoremap ,w <C-o>w\ninoremap ,W <C-o>W\ninoremap ,b <C-o>b\ninoremap ,B <C-o>B\ninoremap ,a <C-o>A\ninoremap ,i <C-o>I\ninoremap ,l <C-o>o\ninoremap ,o <C-o>O\ninoremap ,dw <C-o>\"zdaw\ninoremap ,p <C-o>\"zp\ninoremap ,P <C-o>\"zP\ninoremap ,yw <C-o>\"zyaw\ninoremap ,y <C-o>\"zy\ninoremap ,d <C-o>\"zd\ninoremap ,D <C-o>\"_d\ninoremap ,c <C-o>:call<SPACE>NERDComment(0,\"toggle\")<C-m>\ninoremap ,ec <C-o>:call<SPACE>NERDComment(0,\"toEOL\")<C-m>\ninoremap ,t <C-r>=Tr3transliterate(input(\"Translit: \"))<C-m>\ninoremap ,T <C-o>b<C-o>\"tdiw<C-r><C-r>=Tr3transliterate(@t)<C-m>\ninoremap ,et <C-o>B<C-o>\"tdiW<C-r><C-r>=Tr3transliterate(@t)<C-m>\ninoremap ,/ <C-x><C-f>\ninoremap ,@ <C-o>:w!<C-m>\ninoremap ,; <C-o>%\ninoremap ,m <C-\\><C-o>:call system(\"make &\")<C-m>\ninoremap ,n \\<C-m>\ninoremap ,q «»<C-\\><C-o>h\ninoremap ,Q „“<C-\\><C-o>h\ninoremap ,eq “”<C-\\><C-o>h\ninoremap ,eQ ‘’<C-\\><C-o>h\ninoremap ,\" \"\"<C-\\><C-o>h\ninoremap ,' ''<C-\\><C-o>h\n\n\"{{{4 visual \nvnoremap ,y \"zy\nvnoremap ,d \"zd\nvnoremap ,D \"_d\nvnoremap ,p \"zp\n\n\"{{{4 command \ncnoremap ,s ()<Left>\ncnoremap ,S \\(\\)<Left><Left>\ncnoremap ,U \\<LT>\\><Left><Left>\ncnoremap ,u <LT>><Left>\ncnoremap ,F \\{}<Left>\ncnoremap ,f {}<Left>\ncnoremap ,h []<Left>\ncnoremap ,H [[::]]<Left><Left><Left>\ncnoremap ,eh [::]<Left><Left>\ncnoremap ,i <Home>\ncnoremap ,a <End>\ncnoremap ,, \\\ncnoremap ,. <C-r>:\ncnoremap ,p <C-r>\"\ncnoremap ,P <C-r>+\ncnoremap ,z <C-r>z\ncnoremap ,t <C-r>=Tr3transliterate(input(\"Translit: \"))<C-m>\ncnoremap ,b <C-Left>\ncnoremap ,w <C-Right>\ncnoremap ,B <C-Left>\ncnoremap ,W <C-Right>\n\n\"{{{4 normal \nnnoremap ,C :!\nnnoremap ,c :call<SPACE>NERDComment(0,\"toggle\")<C-m>\nnnoremap ,d \"_\nnnoremap ,D \"_d\nnnoremap ,m :call system(\"make &\")<C-m>\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"
},
{
"answer_id": 3688637,
"author": "dash-tom-bang",
"author_id": 65845,
"author_profile": "https://Stackoverflow.com/users/65845",
"pm_score": 1,
"selected": false,
"text": ":find if argc() == 0\n cd $PROJECT_DIR\nendif\n :find src scripts c:\\work PROJECT_DIR set path+=src/**;c:/work,scripts/**;c:/work\n 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(\"\\<C-\\>\\<C-N>\")\naugroup END\n :e augroup MiscellaneousTomStuff\n autocmd!\n \" make up for the deficiencies in 'autochdir'\n autocmd BufEnter * silent! lcd %:p:h:gs/ /\\\\ /\naugroup END\n"
},
{
"answer_id": 3791030,
"author": "mike3996",
"author_id": 308668,
"author_profile": "https://Stackoverflow.com/users/308668",
"pm_score": 3,
"selected": false,
"text": ".vimrc map <C-j> :bprev<CR>\nmap <C-k> :bnext<CR>\nset hidden \" this will go along\n map <C-n> :cn<CR>\nmap <C-m> :cp<CR>\n"
},
{
"answer_id": 3871787,
"author": "Dummy00001",
"author_id": 360695,
"author_profile": "https://Stackoverflow.com/users/360695",
"pm_score": 1,
"selected": false,
"text": ".vimrc \" prevent switch to Replece mode if <Insert> pressed in insert mode\nimap <Insert> <Nop>\n map <silent> <PageUp> 1000<C-U>\nmap <silent> <PageDown> 1000<C-D>\nimap <silent> <PageUp> <C-O>1000<C-U>\nimap <silent> <PageDown> <C-O>1000<C-D>\nset nostartofline\n set noshowmatch\nlet loaded_matchparen = 1\n au BufReadPost * if getfsize(bufname(\"%\")) > 4*1024*1024 |\n\\ set syntax= |\n\\ endif\n 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 <silent> <F11> :call CalcX(\".\")<CR>\n"
},
{
"answer_id": 3977974,
"author": "SergioAraujo",
"author_id": 2571881,
"author_profile": "https://Stackoverflow.com/users/2571881",
"pm_score": 1,
"selected": false,
"text": "\" place holders snippets\n\" File Templates\n\" --------------\n\" <leader>j jumps to the next marker\n\" iabbr <buffer> for for <+i+> in <+intervalo+>:<cr><tab><+i+>\nfunction! LoadFileTemplate()\n \"silent! 0r ~/.vim/templates/%:e.tmpl\n syn match vimTemplateMarker \"<+.\\++>\" containedin=ALL\n hi vimTemplateMarker guifg=#67a42c guibg=#112300 gui=bold\nendfunction\nfunction! JumpToNextPlaceholder()\n let old_query = getreg('/')\n echo search(\"<+.\\\\++>\")\n exec \"norm! c/+>/e\\<CR>\"\n call setreg('/', old_query)\nendfunction\nautocmd BufNewFile * :call LoadFileTemplate()\nnnoremap <leader>j :call JumpToNextPlaceholder()<CR>a\ninoremap <leader>j <ESC>:call JumpToNextPlaceholder()<CR>a\n\n\nfun! InsertChangeLog()\n normal(1G)\n call append(0, \"Arquivo: <+Description+>\")\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: <+digite seu nome+>\")\n call append(4, \"site: <+digite o endereço de seu site+>\")\n call append(5, \"twitter: <+your twitter here+>\")\n normal gg\nendfun\n"
},
{
"answer_id": 4177516,
"author": "Benoit",
"author_id": 457352,
"author_profile": "https://Stackoverflow.com/users/457352",
"pm_score": 0,
"selected": false,
"text": "\" F10 inverts 'wrap'\nxnoremap <F10> :<C-U>set wrap! <Bar> set wrap? <CR>gv\nnnoremap <F10> :set wrap! <Bar> set wrap? <CR>\ninoremap <F10> <C-O>:set wrap! <Bar> set wrap? <CR>\n\" Shift-F10 inverts 'virtualedit'\nxnoremap <S-F10> :<C-U>set ve=<C-R>=(&ve == 'all') ? '' : 'all'<return> ve?<CR>gv\nnnoremap <S-F10> :set ve=<C-R>=(&ve == 'all') ? '' : 'all'<return> ve?<CR>\ninoremap <S-F10> <C-O>:set ve=<C-R>=(&ve == 'all') ? '' : 'all'<return> ve?<CR>\n\" Ctrl-F10 inverts 'hidden'\nxnoremap <C-F10> :<C-U>set hidden! <Bar> set hidden? <CR>gv\nnnoremap <C-F10> :set hidden! <Bar> set hidden? <CR>\ninoremap <C-F10> <C-O>:set hidden! <Bar> set hidden? <CR>\n \" F11 and F12 to go to resp. previous and next item in quickfix entries\nnnoremap <F11> :silent! cc<CR>:silent! cp <CR>:call ErrBlink()<CR>\nnnoremap <F12> :silent! cc<CR>:silent! cn <CR>:call ErrBlink()<CR>\n\" Shift-F11 and Shift-F12 to go to resp prev. and next file in quickfix list\nnnoremap <S-F11> :silent! cc<CR>:silent! cpf<CR>:call ErrBlink()<CR>\nnnoremap <S-F12> :silent! cc<CR>:silent! cnf<CR>:call ErrBlink()<CR>\n\" Ctrl-F11 and Ctrl-F1 to recall older and newer quickfix lists\nnnoremap <C-F11> :silent! col <CR>:call ErrBlink()<CR>\nnnoremap <C-F12> :silent! cnew<CR>:call ErrBlink()<CR>\n xnoremap <silent> _* :<C-U>\n \\let old_reg=getreg('\"')<Bar>let old_regtype=getregtype('\"')<CR>\n \\gvy/<C-R><C-R>/\\|<C-R><C-R>=substitute(\n \\substitute(escape(@\", '/\\.*$^~['), '\\s\\+', '\\\\s\\\\+', 'g'), '\\_s\\+', '\\\\_s*', 'g')<CR><CR>\n \\gV:call setreg('\"', old_reg, old_regtype)<CR>\n\nxnoremap <silent> _# :<C-U>\n \\let old_reg=getreg('\"')<Bar>let old_regtype=getregtype('\"')<CR>\n \\gvy?<C-R><C-R>/\\|<C-R><C-R>=substitute(\n \\substitute(escape(@\", '?\\.*$^~['), '\\s\\+', '\\\\s\\\\+', 'g'), '\\_s\\+', '\\\\_s*', 'g')<CR><CR>\n \\gV:call setreg('\"', old_reg, old_regtype)<CR>\n\nxnoremap <silent> * :<C-U>\n \\let old_reg=getreg('\"')<Bar>let old_regtype=getregtype('\"')<CR>\n \\gvy/<C-R><C-R>=substitute(\n \\substitute(escape(@\", '/\\.*$^~['), '\\s\\+', '\\\\s\\\\+', 'g'), '\\_s\\+', '\\\\_s*', 'g')<CR><CR>\n \\gV:call setreg('\"', old_reg, old_regtype)<CR>\n\nxnoremap <silent> # :<C-U>\n \\let old_reg=getreg('\"')<Bar>let old_regtype=getregtype('\"')<CR>\n \\gvy?<C-R><C-R>=substitute(\n \\substitute(escape(@\", '?\\.*$^~['), '\\s\\+', '\\\\s\\\\+', 'g'), '\\_s\\+', '\\\\_s*', 'g')<CR><CR>\n \\gV:call setreg('\"', old_reg, old_regtype)<CR>\n set grepprg=ack\n\" F2 uses ack to search a Perl pattern\nnnoremap <F2> :grep<space>\nnnoremap <S-F2> :grepadd<space>\n\" F3 uses vim to search current pattern\nnnoremap <F3> :noautocmd vim // **/*<C-F>Bhhi\nnnoremap <F3><F3> :noautocmd vim /<C-R><C-O>// **/*<Return>\n\" F3 to search the current highlighted pattern\nxnoremap <F3> \"zy:noautocmd vim /\\M<C-R>=escape(@z,'\\/')<CR>/ **/*<CR>\nnnoremap <S-F3> :noautocmd vimgrepadd // **/*<C-F>Bhhi\nnnoremap <S-F3><S-F3> :noautocmd vimgrepadd /<C-R><C-O>// **/*<Return>\nxnoremap <S-F3> \"zy:noautocmd vimgrepadd /\\M<C-R>=escape(@z,'\\/')<CR>/ **/*<CR>\n xnoremap p pgvy\n \" 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 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 < a:i2.lnum ? -1 : 1)\n else\n return bufname(a:i1.bufnr) < 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"
},
{
"answer_id": 4200067,
"author": "SergioAraujo",
"author_id": 2571881,
"author_profile": "https://Stackoverflow.com/users/2571881",
"pm_score": 1,
"selected": false,
"text": " \" 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 >= 5\n normal(1G)\n call append(0, \"File: <+Description+>\")\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: <+your name+>\")\n call append(4, \"site: <+site+>\")\n call append(5, \"twitter: <+your twitter here+>\")\n normal gg\n endif\nendfun\nmap <special> <F4> <esc>:call InsertChangeLog()<cr>\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(\"$\") >= 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(\"<+.\\\\++>\")\n exec \"norm! c/+>/e\\<CR>\"\n call setreg('/', old_query)\nendfunction\nautocmd BufNewFile * :call LoadFileTemplate()\nnnoremap <special> <leader>j :call JumpToNextPlaceholder()<CR>a\ninoremap <special> <leader>j <ESC>:call JumpToNextPlaceholder()<CR>a\n\n\" Cientific calculator\ncommand! -nargs=+ Calc :py print <args>\npy from math import *\nmap ,c :Calc\n\n\nset statusline=%F%m%r%h%w\\\n\\ ft:%{&ft}\\ \\\n\\ff:%{&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"
},
{
"answer_id": 5368078,
"author": "expelledboy",
"author_id": 644945,
"author_profile": "https://Stackoverflow.com/users/644945",
"pm_score": 1,
"selected": false,
"text": "alias :q=exit"
},
{
"answer_id": 7135371,
"author": "dpogg1",
"author_id": 327453,
"author_profile": "https://Stackoverflow.com/users/327453",
"pm_score": 2,
"selected": false,
"text": "imap <C-l> <Space>=><Space>\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7028/"
] |
164,855
|
<p>I have a an HTML form which contains the YAHOO rich text editor on it.</p>
<p>When I display the form I want the YAHOO editor to have focus so that the cursor is ready to accept input without the user having to click on it or tab into it</p>
|
[
{
"answer_id": 174050,
"author": "pmg",
"author_id": 25324,
"author_profile": "https://Stackoverflow.com/users/25324",
"pm_score": 0,
"selected": false,
"text": "window.onload id=\"yahoo_text_editor\" <body onload=\"document.getElementById('yahoo_text_editor').focus()\">\n"
},
{
"answer_id": 227958,
"author": "Benry",
"author_id": 28408,
"author_profile": "https://Stackoverflow.com/users/28408",
"pm_score": 2,
"selected": true,
"text": "var myEditor = new YAHOO.widget.Editor('editor', {focusAtStart:true}); myEditor.render();"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15352/"
] |
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": "i++ i i ++ // 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 Inc(ref i) i i String.Format(...)"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
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 "foo@bar.com|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->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;
</code></pre>
|
[
{
"answer_id": 164892,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 3,
"selected": false,
"text": "#!/ust/bin/perl -w\nuse strict;\n\nwhile (<>) {\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"
},
{
"answer_id": 164893,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 3,
"selected": false,
"text": "while (<STDIN>) {\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"
},
{
"answer_id": 164906,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 5,
"selected": true,
"text": "while(<STDIN>) {\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->prepare(qq{INSERT INTO bademails VALUES(?, ?)});\n $sth->execute($email, $reason); \n $sth->finish(); \n}\n"
},
{
"answer_id": 164909,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "my(@list) = split /\\|/, $line;\n $line =~ m/^([^|]+)\\|(.*)$/;\nmy(@list) = ($1, $2);\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] |
164,879
|
<p>How can I write from Java to the Windows Event Log?</p>
|
[
{
"answer_id": 164898,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 6,
"selected": true,
"text": "NTEventLogAppender"
},
{
"answer_id": 2215876,
"author": "Andrew",
"author_id": 242615,
"author_profile": "https://Stackoverflow.com/users/242615",
"pm_score": 3,
"selected": false,
"text": "String command = \"eventcreate \"\n + \" /l APPLICATION\"\n + \" /so \\\"\" + applicationObjectName + \"\\\"\"\n + \" /t \" + lvl\n + \" /id \" + id\n + \" /d \\\"\" + description + \"\\\"\";\n\nRuntime.getRuntime().exec(command);\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8934/"
] |
164,896
|
<p>In the installation documentation to RoR it mentions that there are many limitations to running Ruby on Rails on Windows, and in some cases, whole libraries do not work.</p>
<p>How bad are these limitations, should I always default to Linux to code / run RoR, and is Iron Ruby expected to fix these limitations or are they core to the OS itself?</p>
<p><strong><em>EDIT</em></strong> Thanks for the answer around installation and running on Linux, but I am really trying to understand the limitations in functionality as referenced in the installation documentation, and non-working libraries - I am trying to find a link to the comment, but it was referenced in an installation read me when I installed the msi package I think</p>
<p><strong><em>EDIT</em></strong>
Thanks for the references to IronRuby lately, it is certainly a project to watch, and as it, obviously, is a .NET language, it will be invaluable if it lives up to the promises. Eventually, however, in my case, I just bit the bullet and installed an Ubuntu server. </p>
<p><bias> I should've done it years ago </bias></p>
|
[
{
"answer_id": 166548,
"author": "Charles Roper",
"author_id": 1944,
"author_profile": "https://Stackoverflow.com/users/1944",
"pm_score": 8,
"selected": true,
"text": "gem install rails"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] |
164,901
|
<p>Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves.</p>
<p>My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound like a good idea as the people I sell it to too could just make copies of them and pass them on.</p>
<p>I think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same (LAMP) setup.</p>
|
[
{
"answer_id": 164987,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 7,
"selected": true,
"text": "#"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] |
164,903
|
<p>How can I capture enter keypresses anywhere on my form and force it to fire the submit button event?</p>
|
[
{
"answer_id": 164917,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 8,
"selected": false,
"text": "Form AcceptButton Button Form KeyPreview true Form KeyDown Enter"
},
{
"answer_id": 16124122,
"author": "sanjeev",
"author_id": 2240266,
"author_profile": "https://Stackoverflow.com/users/2240266",
"pm_score": 3,
"selected": false,
"text": "KeyUp TextBox private void txtInput_KeyUp(object sender, KeyEventArgs e)\n{\n if (e.KeyCode == Keys.Enter)\n DoSomething();\n}\n"
},
{
"answer_id": 17852975,
"author": "ruvi",
"author_id": 2118614,
"author_profile": "https://Stackoverflow.com/users/2118614",
"pm_score": 5,
"selected": false,
"text": "private void textBox_KeyDown(object sender, KeyEventArgs e) \n{\n if (e.KeyCode == Keys.Enter)\n button.PerformClick();\n}\n"
},
{
"answer_id": 30521472,
"author": "BenW",
"author_id": 1833408,
"author_profile": "https://Stackoverflow.com/users/1833408",
"pm_score": 0,
"selected": false,
"text": " if (e.KeyCode.ToString() == \"Return\")\n { \n //do something\n }\n"
},
{
"answer_id": 35773774,
"author": "Bino",
"author_id": 4123776,
"author_profile": "https://Stackoverflow.com/users/4123776",
"pm_score": 1,
"selected": false,
"text": "this.Form.DefaultButton = MyButton.UniqueID; \n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
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": "decimalVar.ToString(\"#.##\"); // returns \".5\" when decimalVar == 0.5m\n decimalVar.ToString(\"0.##\"); // returns \"0.5\" when decimalVar == 0.5m\n decimalVar.ToString(\"0.00\"); // returns \"0.50\" when decimalVar == 0.5m\n"
},
{
"answer_id": 164934,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 7,
"selected": false,
"text": "String.Format(\"{0:0.00}\", 123.4567m); // \"123.46\"\n"
},
{
"answer_id": 164966,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 6,
"selected": false,
"text": "C{Precision specifier} String.Format(\"{0:C2}\", 5.123d)"
},
{
"answer_id": 775089,
"author": "Joel Mueller",
"author_id": 24380,
"author_profile": "https://Stackoverflow.com/users/24380",
"pm_score": 6,
"selected": false,
"text": "decimalVar.ToString(\"n2\");\n"
},
{
"answer_id": 1907832,
"author": "Sofox",
"author_id": 232147,
"author_profile": "https://Stackoverflow.com/users/232147",
"pm_score": 9,
"selected": false,
"text": "decimalVar.ToString(\"F\");\n 23.456 23.46 23 23.00 12.5 12.50"
},
{
"answer_id": 5724542,
"author": "Mike M.",
"author_id": 358637,
"author_profile": "https://Stackoverflow.com/users/358637",
"pm_score": 9,
"selected": false,
"text": "decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero);\n"
},
{
"answer_id": 7155020,
"author": "Smitha Poluri",
"author_id": 906828,
"author_profile": "https://Stackoverflow.com/users/906828",
"pm_score": 3,
"selected": false,
"text": "system.globalization.cultureinfo ci = new system.globalization.cultureinfo(\"en-ca\");\n decimal d = 1.2300000 d.Tostring(\"F2\",ci);"
},
{
"answer_id": 7899828,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 5,
"selected": false,
"text": "Decimal Decimal Decimal.Parse(\"25\").ToString() => \"25\"\nDecimal.Parse(\"25.\").ToString() => \"25\"\nDecimal.Parse(\"25.0\").ToString() => \"25.0\"\nDecimal.Parse(\"25.0000\").ToString() => \"25.0000\"\n\n25m.ToString() => \"25\"\n25.000m.ToString() => \"25.000\"\n Double \"25\" Decimal.Parse(\"25.0\").ToString(\"c\") => \"$25.00\"\n {Binding Price, StringFormat=c} 25.1200 25.12 Decimal.Round(...) // generated code by XSD.exe\n StandardPrice = new OverrideCurrencyAmount()\n {\n TypedValue = Decimal.Round(product.StandardPrice, 2),\n currency = \"USD\"\n }\n TypedValue Decimal ToString(\"N2\") decimal"
},
{
"answer_id": 13070953,
"author": "Kaido",
"author_id": 513778,
"author_profile": "https://Stackoverflow.com/users/513778",
"pm_score": 3,
"selected": false,
"text": "0.005 -> 0.01 Math.Round(exactResult * 1.00m, 2, MidpointRounding.AwayFromZero)\n\n6.665m.ToString() -> \"6.67\"\n\n6.6m.ToString() -> \"6.60\"\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": "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 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"
},
{
"answer_id": 38032451,
"author": "Jeff Jose",
"author_id": 6147480,
"author_profile": "https://Stackoverflow.com/users/6147480",
"pm_score": 3,
"selected": false,
"text": "double whateverYouWantToChange = whateverYouWantToChange.ToString(\"F2\");\n"
},
{
"answer_id": 40051017,
"author": "JsAndDotNet",
"author_id": 852806,
"author_profile": "https://Stackoverflow.com/users/852806",
"pm_score": 4,
"selected": false,
"text": "decimal.Round decimal roundedValue = Math.Round(rawNumber, 2, MidpointRounding.AwayFromZero);\n 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"
},
{
"answer_id": 45427758,
"author": "goamn",
"author_id": 712700,
"author_profile": "https://Stackoverflow.com/users/712700",
"pm_score": 4,
"selected": false,
"text": "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"
},
{
"answer_id": 45865331,
"author": "Alex",
"author_id": 5221030,
"author_profile": "https://Stackoverflow.com/users/5221030",
"pm_score": 3,
"selected": false,
"text": "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 [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"
},
{
"answer_id": 57568126,
"author": "Code",
"author_id": 9787173,
"author_profile": "https://Stackoverflow.com/users/9787173",
"pm_score": 2,
"selected": false,
"text": "Double Amount = 0;\nstring amount;\namount=string.Format(\"{0:F2}\", Decimal.Parse(Amount.ToString()));\n"
},
{
"answer_id": 60669801,
"author": "Aleksei Mialkin",
"author_id": 1833895,
"author_profile": "https://Stackoverflow.com/users/1833895",
"pm_score": 2,
"selected": false,
"text": "decimal val = 3.14789m;\ndecimal result = Math.Floor(val * 100) / 100; // result = 3.14\n decimal val = 3.14789m;\ndecimal result = Math.Floor(val * 1000) / 1000; // result = 3.147\n"
},
{
"answer_id": 71104865,
"author": "ihsan güç",
"author_id": 13056635,
"author_profile": "https://Stackoverflow.com/users/13056635",
"pm_score": 0,
"selected": false,
"text": " var arr = new List<int>() { -4, 3, -9, 0, 4, 1 };\n decimal result1 = arr.Where(p => p > 0).Count();\n var responseResult1 = result1 / arr.Count();\n decimal result2 = arr.Where(p => p < 0).Count();\n var responseResult2 = result2 / arr.Count();\n decimal result3 = arr.Where(p => p == 0).Count();\n var responseResult3 = result3 / arr.Count();\n Console.WriteLine(String.Format(\"{0:#,0.000}\", responseResult1));\n Console.WriteLine(String.Format(\"{0:#,0.0000}\", responseResult2));\n Console.WriteLine(String.Format(\"{0:#,0.00000}\", responseResult3));\n"
},
{
"answer_id": 72628873,
"author": "BanukaKA",
"author_id": 19202848,
"author_profile": "https://Stackoverflow.com/users/19202848",
"pm_score": 2,
"selected": false,
"text": "decimalVar.ToString(\"#.##\");\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1692/"
] |
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": 164950,
"author": "Brian",
"author_id": 700,
"author_profile": "https://Stackoverflow.com/users/700",
"pm_score": 0,
"selected": false,
"text": "Select count(key) into :result from table where key = :theValue\n"
},
{
"answer_id": 164952,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": -1,
"selected": false,
"text": "\nIF EXISTS (SELECT key FROM table WHERE key = 'value')\n PRINT 'Found it!'\nELSE\n PRINT 'Cannot find it!'\n"
},
{
"answer_id": 165024,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 1,
"selected": false,
"text": "SELECT 1 FROM table WHERE id key = 'value'\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740/"
] |
164,931
|
<p>I'm looking at introducing multi-lingual support to a mature CGI application written in Perl. I had originally considered rolling my own solution using a Perl hash (stored on disk) for translation files but then I came across a CPAN module which appears to do just what I want (<a href="http://search.cpan.org/~audreyt/i18n-0.10/lib/i18n.pm" rel="noreferrer" title="i18n">i18n</a>). </p>
<p>Does anyone have any experience with internationalization (specifically the i18n CPAN module) in Perl? Is the i18n module the preferred method for multi-lingual support or should I reconsider a custom solution?</p>
<p>Thanks</p>
|
[
{
"answer_id": 164970,
"author": "pjf",
"author_id": 19422,
"author_profile": "https://Stackoverflow.com/users/19422",
"pm_score": 5,
"selected": true,
"text": "Locale::Maketext"
},
{
"answer_id": 191130,
"author": "EvdB",
"author_id": 5349,
"author_profile": "https://Stackoverflow.com/users/5349",
"pm_score": 2,
"selected": false,
"text": "_ _(\"text to translate\")"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20790/"
] |
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": "result = 1\nwhile b > 0\n if b is odd\n result *= a\n b -= 1\n b /= 2\n a = a * a\n result = 1\nwhile b > 0\n while b is even\n a = a * a\n b = b / 2\n result = result * a\n b = b - 1\n"
},
{
"answer_id": 165181,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": true,
"text": " * 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'|<=0.5.\n * 3. Return x**y = 2**n*exp(y'*log2)\n log2 2**"
},
{
"answer_id": 165348,
"author": "gsarnold",
"author_id": 21961,
"author_profile": "https://Stackoverflow.com/users/21961",
"pm_score": 2,
"selected": false,
"text": " +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"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55/"
] |
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": " 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 = &H80000000\n Const HKEY_CURRENT_USER = &H80000001\n Const HKEY_LOCAL_MACHINE = &H80000002\n Const HKEY_USERS = &H80000003\n\n Const ERROR_SUCCESS = 0&\n\n Const SYNCHRONIZE = &H100000\n Const STANDARD_RIGHTS_READ = &H20000\n Const STANDARD_RIGHTS_WRITE = &H20000\n Const STANDARD_RIGHTS_EXECUTE = &H20000\n Const STANDARD_RIGHTS_REQUIRED = &HF0000\n Const STANDARD_RIGHTS_ALL = &H1F0000\n Const KEY_QUERY_VALUE = &H1\n Const KEY_SET_VALUE = &H2\n Const KEY_CREATE_SUB_KEY = &H4\n Const KEY_ENUMERATE_SUB_KEYS = &H8\n Const KEY_NOTIFY = &H10\n Const KEY_CREATE_LINK = &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&, _\n KEY_READ, _\n lngKeyHandle)\n\n If lngResult <> 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&, _\n REG_DWORD, _\n ByVal lngData, _\n lngDataLen)\n lngCurIdx = lngCurIdx + 1\n\n If lngResult = ERROR_SUCCESS Then\n strResult = strResult & lngCurIdx & \": \" & Left(strValue, lngValueLen) & vbCrLf\n End If\n Loop While lngResult = ERROR_SUCCESS\n Call RegCloseKey(lngKeyHandle)\n\n Call MsgBox(strResult, vbInformation)\n End Sub\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1354/"
] |
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": "^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$\n"
},
{
"answer_id": 164994,
"author": "marcj",
"author_id": 23940,
"author_profile": "https://Stackoverflow.com/users/23940",
"pm_score": 9,
"selected": true,
"text": "([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"
},
{
"answer_id": 4793095,
"author": "minglis",
"author_id": 502087,
"author_profile": "https://Stackoverflow.com/users/502087",
"pm_score": 3,
"selected": false,
"text": "^(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"
},
{
"answer_id": 6276530,
"author": "Will Tomlins",
"author_id": 690904,
"author_profile": "https://Stackoverflow.com/users/690904",
"pm_score": 3,
"selected": false,
"text": "/^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-Z]{2}$/\n /^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-BD-HJLNP-UW-Z]{2}$/\n"
},
{
"answer_id": 7259020,
"author": "Colin",
"author_id": 521518,
"author_profile": "https://Stackoverflow.com/users/521518",
"pm_score": 6,
"selected": false,
"text": "^(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})$ ^((GIR &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]))) &[0-9][ABD-HJLNP-UW-Z]{2}))$\n ^(([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"
},
{
"answer_id": 10600422,
"author": "Vikas Pandey",
"author_id": 1396126,
"author_profile": "https://Stackoverflow.com/users/1396126",
"pm_score": 1,
"selected": false,
"text": "^((([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"
},
{
"answer_id": 11865017,
"author": "paulslater19",
"author_id": 705752,
"author_profile": "https://Stackoverflow.com/users/705752",
"pm_score": 0,
"selected": false,
"text": "/^([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"
},
{
"answer_id": 14257846,
"author": "Dan Solo",
"author_id": 1139823,
"author_profile": "https://Stackoverflow.com/users/1139823",
"pm_score": 3,
"selected": false,
"text": "<?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<br>\";\n\n } else {\n\n echo \"$postcode2check is not a valid postcode<br>\";\n\n }\n\n?>\n"
},
{
"answer_id": 15953188,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 4,
"selected": false,
"text": "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"
},
{
"answer_id": 16485951,
"author": "Jesús Carrera",
"author_id": 2330244,
"author_profile": "https://Stackoverflow.com/users/2330244",
"pm_score": 4,
"selected": false,
"text": "^([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"
},
{
"answer_id": 17024047,
"author": "Ben",
"author_id": 458741,
"author_profile": "https://Stackoverflow.com/users/458741",
"pm_score": 6,
"selected": false,
"text": "W1"
},
{
"answer_id": 17507615,
"author": "RichardTowers",
"author_id": 1344760,
"author_profile": "https://Stackoverflow.com/users/1344760",
"pm_score": 4,
"selected": false,
"text": "grep 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 $pattern '^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$'\n# => 6016 (0.36%)\n '^(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# => 0\n '^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# => 0\n '^.*$'\n# => 0\n"
},
{
"answer_id": 23375983,
"author": "andre",
"author_id": 3108126,
"author_profile": "https://Stackoverflow.com/users/3108126",
"pm_score": 3,
"selected": false,
"text": "[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y] (GIR(?=\\s*0AA)|(?:[BEGLMNSW]|[A-Z]{2})[0-9](?:[0-9]|(?<=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 /^\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 (?<=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"
},
{
"answer_id": 25176865,
"author": "Alex Stephens",
"author_id": 1955203,
"author_profile": "https://Stackoverflow.com/users/1955203",
"pm_score": 2,
"selected": false,
"text": "^([A-Za-z]{1,2}[0-9]{1,2}[A-Za-z]?[ ]?)([0-9]{1}[A-Za-z]{2})$\n"
},
{
"answer_id": 26887154,
"author": "deadcrab",
"author_id": 1071022,
"author_profile": "https://Stackoverflow.com/users/1071022",
"pm_score": 4,
"selected": false,
"text": "^([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 ^(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"
},
{
"answer_id": 28108191,
"author": "Raphos",
"author_id": 4222767,
"author_profile": "https://Stackoverflow.com/users/4222767",
"pm_score": 2,
"selected": false,
"text": "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$\n ^(?:(?:[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"
},
{
"answer_id": 29302162,
"author": "Jackson Pauls",
"author_id": 1777662,
"author_profile": "https://Stackoverflow.com/users/1777662",
"pm_score": 2,
"selected": false,
"text": " |----------------------------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 ? '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"
},
{
"answer_id": 29363535,
"author": "Stieb",
"author_id": 3060634,
"author_profile": "https://Stackoverflow.com/users/3060634",
"pm_score": 0,
"selected": false,
"text": "(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 (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"
},
{
"answer_id": 29820230,
"author": "AntPachon",
"author_id": 763085,
"author_profile": "https://Stackoverflow.com/users/763085",
"pm_score": 4,
"selected": false,
"text": "(?:[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"
},
{
"answer_id": 32735959,
"author": "User1",
"author_id": 2987066,
"author_profile": "https://Stackoverflow.com/users/2987066",
"pm_score": 2,
"selected": false,
"text": "empty string ^$|^(([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"
},
{
"answer_id": 33610889,
"author": "Chisel",
"author_id": 2991563,
"author_profile": "https://Stackoverflow.com/users/2991563",
"pm_score": 2,
"selected": false,
"text": "([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"
},
{
"answer_id": 34593598,
"author": "Matas Vaitkevicius",
"author_id": 1509764,
"author_profile": "https://Stackoverflow.com/users/1509764",
"pm_score": 2,
"selected": false,
"text": "^\\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"
},
{
"answer_id": 43793562,
"author": "user667489",
"author_id": 667489,
"author_profile": "https://Stackoverflow.com/users/667489",
"pm_score": -1,
"selected": false,
"text": "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}$\n /* \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 &$10. Notes &$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"
},
{
"answer_id": 47313542,
"author": "Andrew Schliewe",
"author_id": 6211051,
"author_profile": "https://Stackoverflow.com/users/6211051",
"pm_score": 0,
"selected": false,
"text": "^([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"
},
{
"answer_id": 47589824,
"author": "Henrik N",
"author_id": 6962,
"author_profile": "https://Stackoverflow.com/users/6962",
"pm_score": 3,
"selected": false,
"text": "/^([a-z0-9]\\s*){5,8}$/i\n"
},
{
"answer_id": 51885364,
"author": "ctwheels",
"author_id": 3600709,
"author_profile": "https://Stackoverflow.com/users/3600709",
"pm_score": 8,
"selected": false,
"text": "^([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 ^([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 GIR 0AA ^([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 ^([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 fooA11 1AA ^ ([Gg][Ii][Rr] 0[Aa]{2}) $ GIR 0AAfoo ^([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 ^(([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 ^([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 - ANA NAA A N A Z A1A 1AA Z1A 1AA B1A 1AA - A Z ^([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 ^([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 [0-9] AAA 1AA [0-9] ^([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 GIR 0AA ? ^([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 ^([A-Z][A-HJ-Y]?[0-9][A-Z0-9]? ?[0-9][A-Z]{2}|GIR ?0A{2})$\n [0-9] \\d ^([A-Z][A-HJ-Y]?\\d[A-Z\\d]? ?\\d[A-Z]{2}|GIR ?0A{2})$\n ^([A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}|GIR ?0A{2})$\n GIR 0AA ^[A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}$\n ^(([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 ^(([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 AI-1111 ASCN 1ZZ STHL 1ZZ TDCU 1ZZ BBND 1ZZ BIQQ 1ZZ FIQQ 1ZZ GX11 1ZZ PCRN 1ZZ SIQQ 1ZZ TKCA 1ZZ BFPO 11 ZZ 11 GE CX KY1-1111 VG1111 MSR 1111 ^((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 BF# # BFPO ^BFPO ?\\d{1,4}$\n SAN TA1 ^SAN ?TA1$\n"
},
{
"answer_id": 55083027,
"author": "Aathi",
"author_id": 3008370,
"author_profile": "https://Stackoverflow.com/users/3008370",
"pm_score": 0,
"selected": false,
"text": "const isValidUKPostcode = postcode => {\n try {\n postcode = postcode.replace(/\\s/g, \"\");\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 console.log(isValidUKPostcode('GU348RR'))\n{isValid: true, formattedPostcode: \"GU34 8RR\", error: false, message: \"It is a valid postcode\"}\n console.log(isValidUKPostcode('sdasd4746asd'))\n{error: true, message: \"Invalid postcode!\"}\n valid_postcode('787898523')\nresult => {error: true, message: \"Invalid postcode\"}\n"
},
{
"answer_id": 56134559,
"author": "Ghoti",
"author_id": 80662,
"author_profile": "https://Stackoverflow.com/users/80662",
"pm_score": -1,
"selected": false,
"text": "%r{[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}}i\n"
},
{
"answer_id": 61430132,
"author": "jontsai",
"author_id": 865091,
"author_profile": "https://Stackoverflow.com/users/865091",
"pm_score": 2,
"selected": false,
"text": "UK_POSTCODE_REGEX = r'(?P<postcode_area>[A-Z]{1,2})(?P<district>(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P<sector>[0-9])(?P<postcode>[A-Z]{2})' @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<postcode_area>[A-Z]{1,2})(?P<district>(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P<sector>[0-9])(?P<postcode>[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 @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"
},
{
"answer_id": 69269028,
"author": "Ella Bella",
"author_id": 14713613,
"author_profile": "https://Stackoverflow.com/users/14713613",
"pm_score": -1,
"selected": false,
"text": "^((([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"
},
{
"answer_id": 69806181,
"author": "Mecanik",
"author_id": 6583298,
"author_profile": "https://Stackoverflow.com/users/6583298",
"pm_score": 3,
"selected": false,
"text": "^([a-zA-Z]{1,2}[a-zA-Z\\d]{1,2})\\s(\\d[a-zA-Z]{2})$\n ^ 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 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"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5777/"
] |
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": "^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$\n"
},
{
"answer_id": 164994,
"author": "marcj",
"author_id": 23940,
"author_profile": "https://Stackoverflow.com/users/23940",
"pm_score": 9,
"selected": true,
"text": "([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"
},
{
"answer_id": 4793095,
"author": "minglis",
"author_id": 502087,
"author_profile": "https://Stackoverflow.com/users/502087",
"pm_score": 3,
"selected": false,
"text": "^(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"
},
{
"answer_id": 6276530,
"author": "Will Tomlins",
"author_id": 690904,
"author_profile": "https://Stackoverflow.com/users/690904",
"pm_score": 3,
"selected": false,
"text": "/^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-Z]{2}$/\n /^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-BD-HJLNP-UW-Z]{2}$/\n"
},
{
"answer_id": 7259020,
"author": "Colin",
"author_id": 521518,
"author_profile": "https://Stackoverflow.com/users/521518",
"pm_score": 6,
"selected": false,
"text": "^(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})$ ^((GIR &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]))) &[0-9][ABD-HJLNP-UW-Z]{2}))$\n ^(([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"
},
{
"answer_id": 10600422,
"author": "Vikas Pandey",
"author_id": 1396126,
"author_profile": "https://Stackoverflow.com/users/1396126",
"pm_score": 1,
"selected": false,
"text": "^((([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"
},
{
"answer_id": 11865017,
"author": "paulslater19",
"author_id": 705752,
"author_profile": "https://Stackoverflow.com/users/705752",
"pm_score": 0,
"selected": false,
"text": "/^([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"
},
{
"answer_id": 14257846,
"author": "Dan Solo",
"author_id": 1139823,
"author_profile": "https://Stackoverflow.com/users/1139823",
"pm_score": 3,
"selected": false,
"text": "<?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<br>\";\n\n } else {\n\n echo \"$postcode2check is not a valid postcode<br>\";\n\n }\n\n?>\n"
},
{
"answer_id": 15953188,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 4,
"selected": false,
"text": "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"
},
{
"answer_id": 16485951,
"author": "Jesús Carrera",
"author_id": 2330244,
"author_profile": "https://Stackoverflow.com/users/2330244",
"pm_score": 4,
"selected": false,
"text": "^([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"
},
{
"answer_id": 17024047,
"author": "Ben",
"author_id": 458741,
"author_profile": "https://Stackoverflow.com/users/458741",
"pm_score": 6,
"selected": false,
"text": "W1"
},
{
"answer_id": 17507615,
"author": "RichardTowers",
"author_id": 1344760,
"author_profile": "https://Stackoverflow.com/users/1344760",
"pm_score": 4,
"selected": false,
"text": "grep 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 $pattern '^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$'\n# => 6016 (0.36%)\n '^(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# => 0\n '^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# => 0\n '^.*$'\n# => 0\n"
},
{
"answer_id": 23375983,
"author": "andre",
"author_id": 3108126,
"author_profile": "https://Stackoverflow.com/users/3108126",
"pm_score": 3,
"selected": false,
"text": "[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y] (GIR(?=\\s*0AA)|(?:[BEGLMNSW]|[A-Z]{2})[0-9](?:[0-9]|(?<=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 /^\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 (?<=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"
},
{
"answer_id": 25176865,
"author": "Alex Stephens",
"author_id": 1955203,
"author_profile": "https://Stackoverflow.com/users/1955203",
"pm_score": 2,
"selected": false,
"text": "^([A-Za-z]{1,2}[0-9]{1,2}[A-Za-z]?[ ]?)([0-9]{1}[A-Za-z]{2})$\n"
},
{
"answer_id": 26887154,
"author": "deadcrab",
"author_id": 1071022,
"author_profile": "https://Stackoverflow.com/users/1071022",
"pm_score": 4,
"selected": false,
"text": "^([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 ^(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"
},
{
"answer_id": 28108191,
"author": "Raphos",
"author_id": 4222767,
"author_profile": "https://Stackoverflow.com/users/4222767",
"pm_score": 2,
"selected": false,
"text": "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$\n ^(?:(?:[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"
},
{
"answer_id": 29302162,
"author": "Jackson Pauls",
"author_id": 1777662,
"author_profile": "https://Stackoverflow.com/users/1777662",
"pm_score": 2,
"selected": false,
"text": " |----------------------------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 ? '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"
},
{
"answer_id": 29363535,
"author": "Stieb",
"author_id": 3060634,
"author_profile": "https://Stackoverflow.com/users/3060634",
"pm_score": 0,
"selected": false,
"text": "(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 (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"
},
{
"answer_id": 29820230,
"author": "AntPachon",
"author_id": 763085,
"author_profile": "https://Stackoverflow.com/users/763085",
"pm_score": 4,
"selected": false,
"text": "(?:[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"
},
{
"answer_id": 32735959,
"author": "User1",
"author_id": 2987066,
"author_profile": "https://Stackoverflow.com/users/2987066",
"pm_score": 2,
"selected": false,
"text": "empty string ^$|^(([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"
},
{
"answer_id": 33610889,
"author": "Chisel",
"author_id": 2991563,
"author_profile": "https://Stackoverflow.com/users/2991563",
"pm_score": 2,
"selected": false,
"text": "([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"
},
{
"answer_id": 34593598,
"author": "Matas Vaitkevicius",
"author_id": 1509764,
"author_profile": "https://Stackoverflow.com/users/1509764",
"pm_score": 2,
"selected": false,
"text": "^\\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"
},
{
"answer_id": 43793562,
"author": "user667489",
"author_id": 667489,
"author_profile": "https://Stackoverflow.com/users/667489",
"pm_score": -1,
"selected": false,
"text": "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}$\n /* \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 &$10. Notes &$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"
},
{
"answer_id": 47313542,
"author": "Andrew Schliewe",
"author_id": 6211051,
"author_profile": "https://Stackoverflow.com/users/6211051",
"pm_score": 0,
"selected": false,
"text": "^([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"
},
{
"answer_id": 47589824,
"author": "Henrik N",
"author_id": 6962,
"author_profile": "https://Stackoverflow.com/users/6962",
"pm_score": 3,
"selected": false,
"text": "/^([a-z0-9]\\s*){5,8}$/i\n"
},
{
"answer_id": 51885364,
"author": "ctwheels",
"author_id": 3600709,
"author_profile": "https://Stackoverflow.com/users/3600709",
"pm_score": 8,
"selected": false,
"text": "^([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 ^([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 GIR 0AA ^([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 ^([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 fooA11 1AA ^ ([Gg][Ii][Rr] 0[Aa]{2}) $ GIR 0AAfoo ^([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 ^(([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 ^([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 - ANA NAA A N A Z A1A 1AA Z1A 1AA B1A 1AA - A Z ^([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 ^([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 [0-9] AAA 1AA [0-9] ^([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 GIR 0AA ? ^([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 ^([A-Z][A-HJ-Y]?[0-9][A-Z0-9]? ?[0-9][A-Z]{2}|GIR ?0A{2})$\n [0-9] \\d ^([A-Z][A-HJ-Y]?\\d[A-Z\\d]? ?\\d[A-Z]{2}|GIR ?0A{2})$\n ^([A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}|GIR ?0A{2})$\n GIR 0AA ^[A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}$\n ^(([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 ^(([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 AI-1111 ASCN 1ZZ STHL 1ZZ TDCU 1ZZ BBND 1ZZ BIQQ 1ZZ FIQQ 1ZZ GX11 1ZZ PCRN 1ZZ SIQQ 1ZZ TKCA 1ZZ BFPO 11 ZZ 11 GE CX KY1-1111 VG1111 MSR 1111 ^((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 BF# # BFPO ^BFPO ?\\d{1,4}$\n SAN TA1 ^SAN ?TA1$\n"
},
{
"answer_id": 55083027,
"author": "Aathi",
"author_id": 3008370,
"author_profile": "https://Stackoverflow.com/users/3008370",
"pm_score": 0,
"selected": false,
"text": "const isValidUKPostcode = postcode => {\n try {\n postcode = postcode.replace(/\\s/g, \"\");\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 console.log(isValidUKPostcode('GU348RR'))\n{isValid: true, formattedPostcode: \"GU34 8RR\", error: false, message: \"It is a valid postcode\"}\n console.log(isValidUKPostcode('sdasd4746asd'))\n{error: true, message: \"Invalid postcode!\"}\n valid_postcode('787898523')\nresult => {error: true, message: \"Invalid postcode\"}\n"
},
{
"answer_id": 56134559,
"author": "Ghoti",
"author_id": 80662,
"author_profile": "https://Stackoverflow.com/users/80662",
"pm_score": -1,
"selected": false,
"text": "%r{[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}}i\n"
},
{
"answer_id": 61430132,
"author": "jontsai",
"author_id": 865091,
"author_profile": "https://Stackoverflow.com/users/865091",
"pm_score": 2,
"selected": false,
"text": "UK_POSTCODE_REGEX = r'(?P<postcode_area>[A-Z]{1,2})(?P<district>(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P<sector>[0-9])(?P<postcode>[A-Z]{2})' @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<postcode_area>[A-Z]{1,2})(?P<district>(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P<sector>[0-9])(?P<postcode>[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 @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"
},
{
"answer_id": 69269028,
"author": "Ella Bella",
"author_id": 14713613,
"author_profile": "https://Stackoverflow.com/users/14713613",
"pm_score": -1,
"selected": false,
"text": "^((([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"
},
{
"answer_id": 69806181,
"author": "Mecanik",
"author_id": 6583298,
"author_profile": "https://Stackoverflow.com/users/6583298",
"pm_score": 3,
"selected": false,
"text": "^([a-zA-Z]{1,2}[a-zA-Z\\d]{1,2})\\s(\\d[a-zA-Z]{2})$\n ^ 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 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"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
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": "^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$\n"
},
{
"answer_id": 164994,
"author": "marcj",
"author_id": 23940,
"author_profile": "https://Stackoverflow.com/users/23940",
"pm_score": 9,
"selected": true,
"text": "([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"
},
{
"answer_id": 4793095,
"author": "minglis",
"author_id": 502087,
"author_profile": "https://Stackoverflow.com/users/502087",
"pm_score": 3,
"selected": false,
"text": "^(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"
},
{
"answer_id": 6276530,
"author": "Will Tomlins",
"author_id": 690904,
"author_profile": "https://Stackoverflow.com/users/690904",
"pm_score": 3,
"selected": false,
"text": "/^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-Z]{2}$/\n /^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-BD-HJLNP-UW-Z]{2}$/\n"
},
{
"answer_id": 7259020,
"author": "Colin",
"author_id": 521518,
"author_profile": "https://Stackoverflow.com/users/521518",
"pm_score": 6,
"selected": false,
"text": "^(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})$ ^((GIR &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]))) &[0-9][ABD-HJLNP-UW-Z]{2}))$\n ^(([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"
},
{
"answer_id": 10600422,
"author": "Vikas Pandey",
"author_id": 1396126,
"author_profile": "https://Stackoverflow.com/users/1396126",
"pm_score": 1,
"selected": false,
"text": "^((([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"
},
{
"answer_id": 11865017,
"author": "paulslater19",
"author_id": 705752,
"author_profile": "https://Stackoverflow.com/users/705752",
"pm_score": 0,
"selected": false,
"text": "/^([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"
},
{
"answer_id": 14257846,
"author": "Dan Solo",
"author_id": 1139823,
"author_profile": "https://Stackoverflow.com/users/1139823",
"pm_score": 3,
"selected": false,
"text": "<?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<br>\";\n\n } else {\n\n echo \"$postcode2check is not a valid postcode<br>\";\n\n }\n\n?>\n"
},
{
"answer_id": 15953188,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 4,
"selected": false,
"text": "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"
},
{
"answer_id": 16485951,
"author": "Jesús Carrera",
"author_id": 2330244,
"author_profile": "https://Stackoverflow.com/users/2330244",
"pm_score": 4,
"selected": false,
"text": "^([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"
},
{
"answer_id": 17024047,
"author": "Ben",
"author_id": 458741,
"author_profile": "https://Stackoverflow.com/users/458741",
"pm_score": 6,
"selected": false,
"text": "W1"
},
{
"answer_id": 17507615,
"author": "RichardTowers",
"author_id": 1344760,
"author_profile": "https://Stackoverflow.com/users/1344760",
"pm_score": 4,
"selected": false,
"text": "grep 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 $pattern '^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$'\n# => 6016 (0.36%)\n '^(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# => 0\n '^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# => 0\n '^.*$'\n# => 0\n"
},
{
"answer_id": 23375983,
"author": "andre",
"author_id": 3108126,
"author_profile": "https://Stackoverflow.com/users/3108126",
"pm_score": 3,
"selected": false,
"text": "[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y] (GIR(?=\\s*0AA)|(?:[BEGLMNSW]|[A-Z]{2})[0-9](?:[0-9]|(?<=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 /^\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 (?<=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"
},
{
"answer_id": 25176865,
"author": "Alex Stephens",
"author_id": 1955203,
"author_profile": "https://Stackoverflow.com/users/1955203",
"pm_score": 2,
"selected": false,
"text": "^([A-Za-z]{1,2}[0-9]{1,2}[A-Za-z]?[ ]?)([0-9]{1}[A-Za-z]{2})$\n"
},
{
"answer_id": 26887154,
"author": "deadcrab",
"author_id": 1071022,
"author_profile": "https://Stackoverflow.com/users/1071022",
"pm_score": 4,
"selected": false,
"text": "^([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 ^(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"
},
{
"answer_id": 28108191,
"author": "Raphos",
"author_id": 4222767,
"author_profile": "https://Stackoverflow.com/users/4222767",
"pm_score": 2,
"selected": false,
"text": "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$\n ^(?:(?:[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"
},
{
"answer_id": 29302162,
"author": "Jackson Pauls",
"author_id": 1777662,
"author_profile": "https://Stackoverflow.com/users/1777662",
"pm_score": 2,
"selected": false,
"text": " |----------------------------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 ? '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"
},
{
"answer_id": 29363535,
"author": "Stieb",
"author_id": 3060634,
"author_profile": "https://Stackoverflow.com/users/3060634",
"pm_score": 0,
"selected": false,
"text": "(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 (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"
},
{
"answer_id": 29820230,
"author": "AntPachon",
"author_id": 763085,
"author_profile": "https://Stackoverflow.com/users/763085",
"pm_score": 4,
"selected": false,
"text": "(?:[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"
},
{
"answer_id": 32735959,
"author": "User1",
"author_id": 2987066,
"author_profile": "https://Stackoverflow.com/users/2987066",
"pm_score": 2,
"selected": false,
"text": "empty string ^$|^(([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"
},
{
"answer_id": 33610889,
"author": "Chisel",
"author_id": 2991563,
"author_profile": "https://Stackoverflow.com/users/2991563",
"pm_score": 2,
"selected": false,
"text": "([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"
},
{
"answer_id": 34593598,
"author": "Matas Vaitkevicius",
"author_id": 1509764,
"author_profile": "https://Stackoverflow.com/users/1509764",
"pm_score": 2,
"selected": false,
"text": "^\\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"
},
{
"answer_id": 43793562,
"author": "user667489",
"author_id": 667489,
"author_profile": "https://Stackoverflow.com/users/667489",
"pm_score": -1,
"selected": false,
"text": "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}$\n /* \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 &$10. Notes &$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"
},
{
"answer_id": 47313542,
"author": "Andrew Schliewe",
"author_id": 6211051,
"author_profile": "https://Stackoverflow.com/users/6211051",
"pm_score": 0,
"selected": false,
"text": "^([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"
},
{
"answer_id": 47589824,
"author": "Henrik N",
"author_id": 6962,
"author_profile": "https://Stackoverflow.com/users/6962",
"pm_score": 3,
"selected": false,
"text": "/^([a-z0-9]\\s*){5,8}$/i\n"
},
{
"answer_id": 51885364,
"author": "ctwheels",
"author_id": 3600709,
"author_profile": "https://Stackoverflow.com/users/3600709",
"pm_score": 8,
"selected": false,
"text": "^([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 ^([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 GIR 0AA ^([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 ^([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 fooA11 1AA ^ ([Gg][Ii][Rr] 0[Aa]{2}) $ GIR 0AAfoo ^([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 ^(([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 ^([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 - ANA NAA A N A Z A1A 1AA Z1A 1AA B1A 1AA - A Z ^([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 ^([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 [0-9] AAA 1AA [0-9] ^([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 GIR 0AA ? ^([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 ^([A-Z][A-HJ-Y]?[0-9][A-Z0-9]? ?[0-9][A-Z]{2}|GIR ?0A{2})$\n [0-9] \\d ^([A-Z][A-HJ-Y]?\\d[A-Z\\d]? ?\\d[A-Z]{2}|GIR ?0A{2})$\n ^([A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}|GIR ?0A{2})$\n GIR 0AA ^[A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}$\n ^(([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 ^(([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 AI-1111 ASCN 1ZZ STHL 1ZZ TDCU 1ZZ BBND 1ZZ BIQQ 1ZZ FIQQ 1ZZ GX11 1ZZ PCRN 1ZZ SIQQ 1ZZ TKCA 1ZZ BFPO 11 ZZ 11 GE CX KY1-1111 VG1111 MSR 1111 ^((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 BF# # BFPO ^BFPO ?\\d{1,4}$\n SAN TA1 ^SAN ?TA1$\n"
},
{
"answer_id": 55083027,
"author": "Aathi",
"author_id": 3008370,
"author_profile": "https://Stackoverflow.com/users/3008370",
"pm_score": 0,
"selected": false,
"text": "const isValidUKPostcode = postcode => {\n try {\n postcode = postcode.replace(/\\s/g, \"\");\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 console.log(isValidUKPostcode('GU348RR'))\n{isValid: true, formattedPostcode: \"GU34 8RR\", error: false, message: \"It is a valid postcode\"}\n console.log(isValidUKPostcode('sdasd4746asd'))\n{error: true, message: \"Invalid postcode!\"}\n valid_postcode('787898523')\nresult => {error: true, message: \"Invalid postcode\"}\n"
},
{
"answer_id": 56134559,
"author": "Ghoti",
"author_id": 80662,
"author_profile": "https://Stackoverflow.com/users/80662",
"pm_score": -1,
"selected": false,
"text": "%r{[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}}i\n"
},
{
"answer_id": 61430132,
"author": "jontsai",
"author_id": 865091,
"author_profile": "https://Stackoverflow.com/users/865091",
"pm_score": 2,
"selected": false,
"text": "UK_POSTCODE_REGEX = r'(?P<postcode_area>[A-Z]{1,2})(?P<district>(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P<sector>[0-9])(?P<postcode>[A-Z]{2})' @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<postcode_area>[A-Z]{1,2})(?P<district>(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P<sector>[0-9])(?P<postcode>[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 @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"
},
{
"answer_id": 69269028,
"author": "Ella Bella",
"author_id": 14713613,
"author_profile": "https://Stackoverflow.com/users/14713613",
"pm_score": -1,
"selected": false,
"text": "^((([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"
},
{
"answer_id": 69806181,
"author": "Mecanik",
"author_id": 6583298,
"author_profile": "https://Stackoverflow.com/users/6583298",
"pm_score": 3,
"selected": false,
"text": "^([a-zA-Z]{1,2}[a-zA-Z\\d]{1,2})\\s(\\d[a-zA-Z]{2})$\n ^ 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 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"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/164990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1894/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.