qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
52,794 | <p>How do I create a branch in subversion that is deeper' than just the 'branches' directory?</p>
<p>I have the standard <code>trunk</code>, <code>tags</code> and <code>branches</code> structure and I want to create a branch that is several directories deeper than the 'branches' tag.</p>
<p>Using the standard svn move method, it gives me a <strong>folder not found</strong> error. I also tried copying it into the branches folder, checked it out, and the 'svn move' it into the tree structure I wanted, but also got a 'working copy admin area is missing' error.</p>
<p>What do I need to do to create this?</p>
<p>For the sake of illustration, let us suppose I want to create a branch to go directly into 'branches/version_1/project/subproject' (which does not exist yet)?</p>
| [
{
"answer_id": 52799,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 5,
"selected": true,
"text": "<pre><code>svn copy --parents http://url/to/subproject http://url/to/repository/branches/version_1/project/subproject\n</code></pre>\n\n<p>That should create the directory you want to put the subproject in (<code>--parents</code> means \"create the intermediate directories for me\").</p>\n"
},
{
"answer_id": 52804,
"author": "xanadont",
"author_id": 1886,
"author_profile": "https://Stackoverflow.com/users/1886",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using <code>TortoiseSVN</code>, you can use its <strong>Repository Explorer</strong> to do such things. Makes it all pretty <code>WYSIWYG</code> simple.</p>\n"
},
{
"answer_id": 52807,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 2,
"selected": false,
"text": "<p>Since subversion doesn't actually think of branches as anything special other than more directories, you can always just create the directory tree you want (with svn mkdir) then copy the code you want into the tree location.</p>\n\n<p>Or just use the --parents flag @BlairC mentioned.</p>\n"
},
{
"answer_id": 52818,
"author": "Kit Roed",
"author_id": 1339,
"author_profile": "https://Stackoverflow.com/users/1339",
"pm_score": 2,
"selected": false,
"text": "<p>I second the use of TortoiseSVN, simply right-click on the directory and go to TortoiseSVN->Branch/tag... to quickly create a branch at a specified directory. Be sure to fill out the URL to be what you want it to be on the resulting \"Copy (Branch / Tag)\" dialog window.</p>\n"
},
{
"answer_id": 52878,
"author": "warsze",
"author_id": 4968,
"author_profile": "https://Stackoverflow.com/users/4968",
"pm_score": 1,
"selected": false,
"text": "<p><code>SVN</code> doesn't really manage your branches. It simply does a wholesale copy. It's up to you how you want to manage it.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] | How do I create a branch in subversion that is deeper' than just the 'branches' directory?
I have the standard `trunk`, `tags` and `branches` structure and I want to create a branch that is several directories deeper than the 'branches' tag.
Using the standard svn move method, it gives me a **folder not found** error. I also tried copying it into the branches folder, checked it out, and the 'svn move' it into the tree structure I wanted, but also got a 'working copy admin area is missing' error.
What do I need to do to create this?
For the sake of illustration, let us suppose I want to create a branch to go directly into 'branches/version\_1/project/subproject' (which does not exist yet)? | ```
svn copy --parents http://url/to/subproject http://url/to/repository/branches/version_1/project/subproject
```
That should create the directory you want to put the subproject in (`--parents` means "create the intermediate directories for me"). |
52,797 | <p>Is there a way to get the path for the assembly in which the current code resides? I do not want the path of the calling assembly, just the one containing the code. </p>
<p>Basically my unit test needs to read some xml test files which are located relative to the dll. I want the path to always resolve correctly regardless of whether the testing dll is run from TestDriven.NET, the MbUnit GUI or something else.</p>
<p><strong>Edit</strong>: People seem to be misunderstanding what I'm asking.</p>
<p>My test library is located in say </p>
<blockquote>
<p>C:\projects\myapplication\daotests\bin\Debug\daotests.dll</p>
</blockquote>
<p>and I would like to get this path:</p>
<blockquote>
<p>C:\projects\myapplication\daotests\bin\Debug\</p>
</blockquote>
<p>The three suggestions so far fail me when I run from the MbUnit Gui:</p>
<ul>
<li><p><code>Environment.CurrentDirectory</code>
gives <em>c:\Program Files\MbUnit</em></p></li>
<li><p><code>System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location</code>
gives <em>C:\Documents and
Settings\george\Local
Settings\Temp\ ....\DaoTests.dll</em></p></li>
<li><p><code>System.Reflection.Assembly.GetExecutingAssembly().Location</code>
gives the same as the previous.</p></li>
</ul>
| [
{
"answer_id": 52802,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 5,
"selected": false,
"text": "<p>This should work, unless the assembly is <em>shadow copied</em>:</p>\n\n<pre><code>string path = System.Reflection.Assembly.GetExecutingAssembly().Location\n</code></pre>\n"
},
{
"answer_id": 52803,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 2,
"selected": false,
"text": "<p>The current directory where you exist.</p>\n\n<pre><code>Environment.CurrentDirectory; // This is the current directory of your application\n</code></pre>\n\n<p>If you copy the .xml file out with build you should find it.</p>\n\n<p>or</p>\n\n<pre><code>System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(SomeObject));\n\n// The location of the Assembly\nassembly.Location;\n</code></pre>\n"
},
{
"answer_id": 52956,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 8,
"selected": false,
"text": "<p>Does this help?</p>\n\n<pre><code>//get the full location of the assembly with DaoTests in it\nstring fullPath = System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location;\n\n//get the folder that's in\nstring theDirectory = Path.GetDirectoryName( fullPath );\n</code></pre>\n"
},
{
"answer_id": 52969,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "<pre><code>var assembly = System.Reflection.Assembly.GetExecutingAssembly();\nvar assemblyPath = assembly.GetFiles()[0].Name;\nvar assemblyDir = System.IO.Path.GetDirectoryName(assemblyPath);\n</code></pre>\n"
},
{
"answer_id": 52979,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 4,
"selected": false,
"text": "<p>I suspect that the real issue here is that your test runner is copying your assembly to a different location. There's no way at runtime to tell where the assembly was copied from, but you can probably flip a switch to tell the test runner to run the assembly from where it is and not to copy it to a shadow directory.</p>\n\n<p>Such a switch is likely to be different for each test runner, of course.</p>\n\n<p>Have you considered embedding your XML data as resources inside your test assembly?</p>\n"
},
{
"answer_id": 52987,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 4,
"selected": false,
"text": "<p>What about this:</p>\n\n<pre><code>System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);\n</code></pre>\n"
},
{
"answer_id": 52990,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 1,
"selected": false,
"text": "<pre><code>string path = Path.GetDirectoryName(typeof(DaoTests).Module.FullyQualifiedName);\n</code></pre>\n"
},
{
"answer_id": 52996,
"author": "dan gibson",
"author_id": 4495,
"author_profile": "https://Stackoverflow.com/users/4495",
"pm_score": 3,
"selected": false,
"text": "<p>I've been using Assembly.CodeBase instead of Location:</p>\n\n<pre><code>Assembly a;\na = Assembly.GetAssembly(typeof(DaoTests));\nstring s = a.CodeBase.ToUpper(); // file:///c:/path/name.dll\nAssert.AreEqual(true, s.StartsWith(\"FILE://\"), \"CodeBase is \" + s);\ns = s.Substring(7, s.LastIndexOf('/') - 7); // 7 = \"file://\"\nwhile (s.StartsWith(\"/\")) {\n s = s.Substring(1, s.Length - 1);\n}\ns = s.Replace(\"/\", \"\\\\\");\n</code></pre>\n\n<p>It's been working, but I'm no longer sure it is 100% correct. The page at <a href=\"http://blogs.msdn.com/suzcook/archive/2003/06/26/assembly-codebase-vs-assembly-location.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/suzcook/archive/2003/06/26/assembly-codebase-vs-assembly-location.aspx</a> says:</p>\n\n<p><em>\"The CodeBase is a URL to the place where the file was found, while the Location is the path where it was actually loaded. For example, if the assembly was downloaded from the internet, its CodeBase may start with \"http://\", but its Location may start with \"C:\\\". If the file was shadow-copied, the Location would be the path to the copy of the file in the shadow copy dir.\nIt’s also good to know that the CodeBase is not guaranteed to be set for assemblies in the GAC. Location will always be set for assemblies loaded from disk, however.</em>\"</p>\n\n<p>You <em>may</em> want to use CodeBase instead of Location.</p>\n"
},
{
"answer_id": 283917,
"author": "John Sibly",
"author_id": 1078,
"author_profile": "https://Stackoverflow.com/users/1078",
"pm_score": 11,
"selected": true,
"text": "<p><strong>Note</strong>: Assembly.CodeBase is deprecated in .NET Core/.NET 5+: <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.codebase?view=net-5.0\" rel=\"noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.codebase?view=net-5.0</a></p>\n<p><strong>Original answer:</strong></p>\n<p>I've defined the following property as we use this often in unit testing.</p>\n<pre><code>public static string AssemblyDirectory\n{\n get\n {\n string codeBase = Assembly.GetExecutingAssembly().CodeBase;\n UriBuilder uri = new UriBuilder(codeBase);\n string path = Uri.UnescapeDataString(uri.Path);\n return Path.GetDirectoryName(path);\n }\n}\n</code></pre>\n<p>The <code>Assembly.Location</code> property sometimes gives you some funny results when using NUnit (where assemblies run from a temporary folder), so I prefer to use <code>CodeBase</code> which gives you the path in URI format, then <code>UriBuild.UnescapeDataString</code> removes the <code>File://</code> at the beginning, and <code>GetDirectoryName</code> changes it to the normal windows format.</p>\n"
},
{
"answer_id": 884444,
"author": "Mike Schall",
"author_id": 4231,
"author_profile": "https://Stackoverflow.com/users/4231",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a VB.NET port of John Sibly's code. Visual Basic is not case sensitive, so a couple of his variable names were colliding with type names.</p>\n\n<pre><code>Public Shared ReadOnly Property AssemblyDirectory() As String\n Get\n Dim codeBase As String = Assembly.GetExecutingAssembly().CodeBase\n Dim uriBuilder As New UriBuilder(codeBase)\n Dim assemblyPath As String = Uri.UnescapeDataString(uriBuilder.Path)\n Return Path.GetDirectoryName(assemblyPath)\n End Get\nEnd Property\n</code></pre>\n"
},
{
"answer_id": 2567233,
"author": "Sneal",
"author_id": 82906,
"author_profile": "https://Stackoverflow.com/users/82906",
"pm_score": 6,
"selected": false,
"text": "<p>Same as John's answer, but a slightly less verbose extension method.</p>\n\n<pre><code>public static string GetDirectoryPath(this Assembly assembly)\n{\n string filePath = new Uri(assembly.CodeBase).LocalPath;\n return Path.GetDirectoryName(filePath); \n}\n</code></pre>\n\n<p>Now you can do:</p>\n\n<pre><code>var localDir = Assembly.GetExecutingAssembly().GetDirectoryPath();\n</code></pre>\n\n<p>or if you prefer:</p>\n\n<pre><code>var localDir = typeof(DaoTests).Assembly.GetDirectoryPath();\n</code></pre>\n"
},
{
"answer_id": 2887537,
"author": "Jalal El-Shaer",
"author_id": 95380,
"author_profile": "https://Stackoverflow.com/users/95380",
"pm_score": 8,
"selected": false,
"text": "<p>It's as simple as this:</p>\n\n<pre><code>var dir = AppDomain.CurrentDomain.BaseDirectory;\n</code></pre>\n"
},
{
"answer_id": 3051585,
"author": "user368021",
"author_id": 368021,
"author_profile": "https://Stackoverflow.com/users/368021",
"pm_score": 4,
"selected": false,
"text": "<pre><code>AppDomain.CurrentDomain.BaseDirectory\n</code></pre>\n\n<p>works with MbUnit GUI.</p>\n"
},
{
"answer_id": 8594253,
"author": "rcooley56",
"author_id": 1110393,
"author_profile": "https://Stackoverflow.com/users/1110393",
"pm_score": -1,
"selected": false,
"text": "<p>I use this to get the path to the Bin Directory:</p>\n\n<pre><code>var i = Environment.CurrentDirectory.LastIndexOf(@\"\\\");\nvar path = Environment.CurrentDirectory.Substring(0,i); \n</code></pre>\n\n<p>You get this result:</p>\n\n<blockquote>\n <p>\"c:\\users\\ricooley\\documents\\visual studio\n 2010\\Projects\\Windows_Test_Project\\Windows_Test_Project\\bin\"</p>\n</blockquote>\n"
},
{
"answer_id": 9737418,
"author": "Ignacio Soler Garcia",
"author_id": 166452,
"author_profile": "https://Stackoverflow.com/users/166452",
"pm_score": 6,
"selected": false,
"text": "<p>The only solution that worked for me when using CodeBase and UNC Network shares was:</p>\n\n<pre><code>System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);\n</code></pre>\n\n<p>It also works with normal URIs too.</p>\n"
},
{
"answer_id": 17060539,
"author": "mmmmmm",
"author_id": 767464,
"author_profile": "https://Stackoverflow.com/users/767464",
"pm_score": 0,
"selected": false,
"text": "<p>This should work:</p>\n\n<pre><code>ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();\nAssembly asm = Assembly.GetCallingAssembly();\nString path = Path.GetDirectoryName(new Uri(asm.EscapedCodeBase).LocalPath);\n\nstring strLog4NetConfigPath = System.IO.Path.Combine(path, \"log4net.config\");\n</code></pre>\n\n<p>I am using this to deploy DLL file libraries along with some configuration file (this is to use log4net from within the DLL file).</p>\n"
},
{
"answer_id": 17440241,
"author": "Valamas",
"author_id": 511438,
"author_profile": "https://Stackoverflow.com/users/511438",
"pm_score": 0,
"selected": false,
"text": "<p>This is what I came up with. <strong>In between web projects, unit tests (nunit and resharper test runner)</strong>; I found this worked for me.</p>\n\n<p>I have been looking for code to detect what configuration the build is in, <code>Debug/Release/CustomName</code>. Alas, the <code>#if DEBUG</code>. <em>So if someone can improve that</em>!</p>\n\n<p>Feel free to edit and improve.</p>\n\n<p><strong>Getting app folder</strong>. Useful for web roots, unittests to get the folder of test files.</p>\n\n<pre><code>public static string AppPath\n{\n get\n {\n DirectoryInfo appPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);\n\n while (appPath.FullName.Contains(@\"\\bin\\\", StringComparison.CurrentCultureIgnoreCase)\n || appPath.FullName.EndsWith(@\"\\bin\", StringComparison.CurrentCultureIgnoreCase))\n {\n appPath = appPath.Parent;\n }\n return appPath.FullName;\n }\n}\n</code></pre>\n\n<p><strong>Getting bin folder</strong>: Useful for executing assemblies using reflection. If files are copied there due to build properties. </p>\n\n<pre><code>public static string BinPath\n{\n get\n {\n string binPath = AppDomain.CurrentDomain.BaseDirectory;\n\n if (!binPath.Contains(@\"\\bin\\\", StringComparison.CurrentCultureIgnoreCase)\n && !binPath.EndsWith(@\"\\bin\", StringComparison.CurrentCultureIgnoreCase))\n {\n binPath = Path.Combine(binPath, \"bin\");\n //-- Please improve this if there is a better way\n //-- Also note that apps like webapps do not have a debug or release folder. So we would just return bin.\n#if DEBUG\n if (Directory.Exists(Path.Combine(binPath, \"Debug\"))) \n binPath = Path.Combine(binPath, \"Debug\");\n#else\n if (Directory.Exists(Path.Combine(binPath, \"Release\"))) \n binPath = Path.Combine(binPath, \"Release\");\n#endif\n }\n return binPath;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 24249706,
"author": "spender",
"author_id": 14357,
"author_profile": "https://Stackoverflow.com/users/14357",
"pm_score": 3,
"selected": false,
"text": "<p>As far as I can tell, most of the other answers have a few problems.</p>\n\n<p>The correct way to do this for a <a href=\"http://blogs.msdn.com/b/suzcook/archive/2003/06/26/assembly-codebase-vs-assembly-location.aspx\" rel=\"nofollow noreferrer\">disk-based (as opposed to web-based), non-GACed assembly</a> is to use the currently executing assembly's <code>CodeBase</code> property.</p>\n\n<p>This returns a URL (<code>file://</code>). Instead of messing around with <a href=\"https://stackoverflow.com/a/52996/14357\">string manipulation</a> or <a href=\"https://stackoverflow.com/a/283917/14357\"><code>UnescapeDataString</code></a>, this can be converted with minimal fuss by leveraging the <code>LocalPath</code> property of <code>Uri</code>. </p>\n\n<pre><code>var codeBaseUrl = Assembly.GetExecutingAssembly().CodeBase;\nvar filePathToCodeBase = new Uri(codeBaseUrl).LocalPath;\nvar directoryPath = Path.GetDirectoryName(filePathToCodeBase);\n</code></pre>\n"
},
{
"answer_id": 24283320,
"author": "user2009677",
"author_id": 2009677,
"author_profile": "https://Stackoverflow.com/users/2009677",
"pm_score": -1,
"selected": false,
"text": "<p>Web application?</p>\n\n<pre><code>Server.MapPath(\"~/MyDir/MyFile.ext\")\n</code></pre>\n"
},
{
"answer_id": 32738924,
"author": "Tez Wingfield",
"author_id": 3305976,
"author_profile": "https://Stackoverflow.com/users/3305976",
"pm_score": 0,
"selected": false,
"text": "<p>I find my solution adequate for the retrieval of the location.</p>\n\n<pre><code>var executingAssembly = new FileInfo((Assembly.GetExecutingAssembly().Location)).Directory.FullName;\n</code></pre>\n"
},
{
"answer_id": 32863106,
"author": "Andrey Bushman",
"author_id": 1306132,
"author_profile": "https://Stackoverflow.com/users/1306132",
"pm_score": 0,
"selected": false,
"text": "<p>I got the same behaviour in the <code>NUnit</code> in the past. By default <code>NUnit</code> copies your assembly into the temp directory. You can change this behaviour in the <code>NUnit</code> settings:</p>\n\n<p><a href=\"https://i.stack.imgur.com/VxmI7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VxmI7.png\" alt=\"enter image description here\"></a></p>\n\n<p>Maybe <code>TestDriven.NET</code> and <code>MbUnit</code> GUI have the same settings.</p>\n"
},
{
"answer_id": 32870042,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 3,
"selected": false,
"text": "<p>In all these years, nobody has actually mentioned this one. A trick I learned from the awesome <a href=\"https://github.com/approvals/ApprovalTests.Net/blob/master/ApprovalUtilities/Utilities/PathUtilities.cs\" rel=\"noreferrer\">ApprovalTests project</a>. The trick is that you use the debugging information in the assembly to find the original directory.</p>\n\n<p><strong>This will not work in RELEASE mode, nor with optimizations enabled, nor on a machine different from the one it was compiled on.</strong></p>\n\n<p>But this will get you paths that are <strong>relative to the location of the source code file you call it from</strong></p>\n\n<pre><code>public static class PathUtilities\n{\n public static string GetAdjacentFile(string relativePath)\n {\n return GetDirectoryForCaller(1) + relativePath;\n }\n public static string GetDirectoryForCaller()\n {\n return GetDirectoryForCaller(1);\n }\n\n\n public static string GetDirectoryForCaller(int callerStackDepth)\n {\n var stackFrame = new StackTrace(true).GetFrame(callerStackDepth + 1);\n return GetDirectoryForStackFrame(stackFrame);\n }\n\n public static string GetDirectoryForStackFrame(StackFrame stackFrame)\n {\n return new FileInfo(stackFrame.GetFileName()).Directory.FullName + Path.DirectorySeparatorChar;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 36794977,
"author": "sumitup",
"author_id": 1390728,
"author_profile": "https://Stackoverflow.com/users/1390728",
"pm_score": 2,
"selected": false,
"text": "<p>You can get the bin path by\n AppDomain.CurrentDomain.RelativeSearchPath</p>\n"
},
{
"answer_id": 39216220,
"author": "David C Fuchs",
"author_id": 5719295,
"author_profile": "https://Stackoverflow.com/users/5719295",
"pm_score": 3,
"selected": false,
"text": "<p>How about this ... </p>\n\n<pre><code>string ThisdllDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);\n</code></pre>\n\n<p>Then just hack off what you do not need</p>\n"
},
{
"answer_id": 39549085,
"author": "Bryan",
"author_id": 313072,
"author_profile": "https://Stackoverflow.com/users/313072",
"pm_score": 2,
"selected": false,
"text": "<p>All of the proposed answers work when the developer can change the code to include the required snippet, but if you wanted to do this without changing any code you could use Process Explorer. </p>\n\n<p>It will list all executing dlls on the system, you may need to determine the process id of your running application, but that is usually not too difficult. </p>\n\n<p>I've written a full description of how do this for a dll inside II - <a href=\"http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/\" rel=\"nofollow\">http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/</a></p>\n"
},
{
"answer_id": 47760173,
"author": "gamesguru",
"author_id": 8555624,
"author_profile": "https://Stackoverflow.com/users/8555624",
"pm_score": 2,
"selected": false,
"text": "<p>in a windows form app, you can simply use <code>Application.StartupPath</code></p>\n\n<p>but for DLLs and console apps the code is much harder to remember...</p>\n\n<pre><code>string slash = Path.DirectorySeparatorChar.ToString();\nstring root = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);\n\nroot += slash;\nstring settingsIni = root + \"settings.ini\"\n</code></pre>\n"
},
{
"answer_id": 53048485,
"author": "Fedor Shihantsov",
"author_id": 1518180,
"author_profile": "https://Stackoverflow.com/users/1518180",
"pm_score": 2,
"selected": false,
"text": "<p>You will get incorrect directory if a path contains the '#' symbol.\nSo I use a modification of the John Sibly answer that is combination UriBuilder.Path and UriBuilder.Fragment:</p>\n\n<pre><code>public static string AssemblyDirectory\n{\n get\n {\n string codeBase = Assembly.GetExecutingAssembly().CodeBase;\n UriBuilder uri = new UriBuilder(codeBase);\n //modification of the John Sibly answer \n string path = Uri.UnescapeDataString(uri.Path.Replace(\"/\", \"\\\\\") + \n uri.Fragment.Replace(\"/\", \"\\\\\"));\n return Path.GetDirectoryName(path);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 58051383,
"author": "Ilya Chernomordik",
"author_id": 1671558,
"author_profile": "https://Stackoverflow.com/users/1671558",
"pm_score": 5,
"selected": false,
"text": "<p>I believe this would work for any kind of application:</p>\n\n<pre><code>AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory\n</code></pre>\n"
},
{
"answer_id": 62626131,
"author": "cube45",
"author_id": 2663813,
"author_profile": "https://Stackoverflow.com/users/2663813",
"pm_score": 4,
"selected": false,
"text": "<p>Starting with .net framework 4.6 / .net core 1.0, there is now a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.appcontext.basedirectory\" rel=\"noreferrer\">AppContext.BaseDirectory</a>, which should give the same result as <code>AppDomain.CurrentDomain.BaseDirectory</code>, except that AppDomains were not part of the .net core 1.x /.net standard 1.x API.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>AppContext.BaseDirectory\n</code></pre>\n<p>EDIT: The documentation now even state:</p>\n<blockquote>\n<p>In .NET 5.0 and later versions, for bundled assemblies, the value returned is the containing directory of the host executable.</p>\n</blockquote>\n<p>Indeed, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.location?view=net-5.0\" rel=\"noreferrer\">Assembly.Location doc</a> doc says :</p>\n<blockquote>\n<p>In .NET 5.0 and later versions, for bundled assemblies, the value returned is an empty string.</p>\n</blockquote>\n"
},
{
"answer_id": 63626644,
"author": "TPG",
"author_id": 2463156,
"author_profile": "https://Stackoverflow.com/users/2463156",
"pm_score": 2,
"selected": false,
"text": "<p>For ASP.Net, it doesn't work. I found a better covered solution at <a href=\"https://stackoverflow.com/questions/8669833/why-appdomain-currentdomain-basedirectory-not-contains-bin-in-asp-net-app\">Why AppDomain.CurrentDomain.BaseDirectory not contains "bin" in asp.net app?</a>. It works for both Win Application and ASP.Net Web Application.</p>\n<pre><code>public string ApplicationPath\n {\n get\n {\n if (String.IsNullOrEmpty(AppDomain.CurrentDomain.RelativeSearchPath))\n {\n return AppDomain.CurrentDomain.BaseDirectory; //exe folder for WinForms, Consoles, Windows Services\n }\n else\n {\n return AppDomain.CurrentDomain.RelativeSearchPath; //bin folder for Web Apps \n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 68223295,
"author": "Bennik2000",
"author_id": 4563449,
"author_profile": "https://Stackoverflow.com/users/4563449",
"pm_score": 3,
"selected": false,
"text": "<h2>tl;dr</h2>\n<p>The concept of an assembly and a DLL file are not the same. Depending on how the assembly was loaded the path information gets lost or is <strong>not available at all</strong>.\nMost of the time the provided answers will work, though.</p>\n<hr />\n<p>There is one misconception the question and the previous answers have. In most of the cases the provided answers will work just fine but\nthere are cases where it is <strong>not possible</strong> to get the correct path of the assembly which the current code resides.</p>\n<p>The concept of an assembly - which contains executable code - and a dll file - which contains the assembly - are not tightly coupled. An assembly may\ncome from a DLL file but it does not have to.</p>\n<p>Using the <code>Assembly.Load(Byte[])</code> (<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.load?view=netframework-4.7.2\" rel=\"noreferrer\">MSDN</a>) method you can load an assembly directly from a byte array in memory.\nIt does not matter where the byte array comes from. It could be loaded from a file, downloaded from the internet, dynamically generated,...</p>\n<p>Here is an example which loads an assembly from a byte array. The path information gets lost after the file was loaded. It is not possible to\nget the original file path and all previous described methods do not work.</p>\n<p>This method is located in the executing assembly which is located at "D:/Software/DynamicAssemblyLoad/DynamicAssemblyLoad/bin/Debug/Runner.exe"</p>\n<pre><code>static void Main(string[] args)\n{\n var fileContent = File.ReadAllBytes(@"C:\\Library.dll");\n\n var assembly = Assembly.Load(fileContent);\n\n // Call the method of the library using reflection\n assembly\n ?.GetType("Library.LibraryClass")\n ?.GetMethod("PrintPath", BindingFlags.Public | BindingFlags.Static)\n ?.Invoke(null, null);\n\n Console.WriteLine("Hello from Application:");\n Console.WriteLine($"GetViaAssemblyCodeBase: {GetViaAssemblyCodeBase(assembly)}");\n Console.WriteLine($"GetViaAssemblyLocation: {assembly.Location}");\n Console.WriteLine($"GetViaAppDomain : {AppDomain.CurrentDomain.BaseDirectory}");\n\n Console.ReadLine();\n}\n</code></pre>\n<p>This class is located in the Library.dll:</p>\n<pre><code>public class LibraryClass\n{\n public static void PrintPath()\n {\n var assembly = Assembly.GetAssembly(typeof(LibraryClass));\n Console.WriteLine("Hello from Library:");\n Console.WriteLine($"GetViaAssemblyCodeBase: {GetViaAssemblyCodeBase(assembly)}");\n Console.WriteLine($"GetViaAssemblyLocation: {assembly.Location}");\n Console.WriteLine($"GetViaAppDomain : {AppDomain.CurrentDomain.BaseDirectory}");\n }\n}\n\n</code></pre>\n<p>For the sake of completeness here is the implementations of <code>GetViaAssemblyCodeBase()</code> which is the same for both assemblies:</p>\n<pre><code>private static string GetViaAssemblyCodeBase(Assembly assembly)\n{\n var codeBase = assembly.CodeBase;\n var uri = new UriBuilder(codeBase);\n return Uri.UnescapeDataString(uri.Path);\n}\n\n</code></pre>\n<p>The Runner prints the following output:</p>\n<pre><code>Hello from Library:\nGetViaAssemblyCodeBase: D:/Software/DynamicAssemblyLoad/DynamicAssemblyLoad/bin/Debug/Runner.exe\nGetViaAssemblyLocation:\nGetViaAppDomain : D:\\Software\\DynamicAssemblyLoad\\DynamicAssemblyLoad\\bin\\Debug\\\nHello from Application:\nGetViaAssemblyCodeBase: D:/Software/DynamicAssemblyLoad/DynamicAssemblyLoad/bin/Debug/Runner.exe\nGetViaAssemblyLocation:\nGetViaAppDomain : D:\\Software\\DynamicAssemblyLoad\\DynamicAssemblyLoad\\bin\\Debug\\\n</code></pre>\n<p>As you can see, neither the code base, location or base directory are correct.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | Is there a way to get the path for the assembly in which the current code resides? I do not want the path of the calling assembly, just the one containing the code.
Basically my unit test needs to read some xml test files which are located relative to the dll. I want the path to always resolve correctly regardless of whether the testing dll is run from TestDriven.NET, the MbUnit GUI or something else.
**Edit**: People seem to be misunderstanding what I'm asking.
My test library is located in say
>
> C:\projects\myapplication\daotests\bin\Debug\daotests.dll
>
>
>
and I would like to get this path:
>
> C:\projects\myapplication\daotests\bin\Debug\
>
>
>
The three suggestions so far fail me when I run from the MbUnit Gui:
* `Environment.CurrentDirectory`
gives *c:\Program Files\MbUnit*
* `System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location`
gives *C:\Documents and
Settings\george\Local
Settings\Temp\ ....\DaoTests.dll*
* `System.Reflection.Assembly.GetExecutingAssembly().Location`
gives the same as the previous. | **Note**: Assembly.CodeBase is deprecated in .NET Core/.NET 5+: <https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.codebase?view=net-5.0>
**Original answer:**
I've defined the following property as we use this often in unit testing.
```
public static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
```
The `Assembly.Location` property sometimes gives you some funny results when using NUnit (where assemblies run from a temporary folder), so I prefer to use `CodeBase` which gives you the path in URI format, then `UriBuild.UnescapeDataString` removes the `File://` at the beginning, and `GetDirectoryName` changes it to the normal windows format. |
52,806 | <p>As part of a larger web-app (using CakePHP), I'm putting together a simple blog system. The relationships are exceedingly simple: each User has a Blog, which has many Entries, which have many Comments.</p>
<p>An element I'd like to incorporate is a list of "Popular Entries." Popular Entries have been defined as those with the most Comments in the last month, and ultimately they need to be ordered by the number of recent Comments.</p>
<p>Ideally, I'd like the solution to stay within Cake's Model data-retrieval apparatus (<code>Model->find()</code>, etc.), but I'm not sanguine about this.</p>
<p>Anyone have a clever/elegant solution? I'm steeling myself for some wild SQL hacking to make this work...</p>
| [
{
"answer_id": 52814,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 2,
"selected": false,
"text": "<p>Shouldn't be too bad, you just need a group by (this is off the type of my head, so forgive syntax errors):</p>\n\n<pre><code>SELECT entry-id, count(id) AS c \nFROM comment \nWHERE comment.createdate >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) \nGROUP BY entry-id \nORDER BY c DESC\n</code></pre>\n"
},
{
"answer_id": 52838,
"author": "Lost in Alabama",
"author_id": 5285,
"author_profile": "https://Stackoverflow.com/users/5285",
"pm_score": 0,
"selected": false,
"text": "<p>You probably want a <strong>WHERE</strong> clause to get just last 30 days comments:</p>\n\n<pre><code>SELECT entry-id, count(id) AS c \nFROM comment \nWHERE comment_date + 30 >= sysdate\nGROUP BY entry-id \nORDER BY c DESC\n</code></pre>\n"
},
{
"answer_id": 52848,
"author": "Daniel Wright",
"author_id": 5030,
"author_profile": "https://Stackoverflow.com/users/5030",
"pm_score": 3,
"selected": true,
"text": "<p>Heh, I was just about to come back with essentially the same answer (using Cake's Model::find):</p>\n\n<pre><code>$this->loadModel('Comment');\n\n$this->Comment->find( 'all', array(\n 'fields' => array('COUNT(Comment.id) AS popularCount'),\n 'conditions' => array(\n 'Comment.created >' => strtotime('-1 month')\n ),\n 'group' => 'Comment.blog_post_id',\n 'order' => 'popularCount DESC',\n\n 'contain' => array(\n 'Entry' => array(\n 'fields' => array( 'Entry.title' )\n )\n )\n));\n</code></pre>\n\n<p>It's not perfect, but it works and can be improved on.</p>\n\n<p>I made an additional improvement, using the Containable behaviour to extract the Entry data instead of the Comment data.</p>\n"
},
{
"answer_id": 66801,
"author": "neilcrookes",
"author_id": 9968,
"author_profile": "https://Stackoverflow.com/users/9968",
"pm_score": 1,
"selected": false,
"text": "<p>If you weren't fussed about the time sensitive nature of the comments, you could make use of CakePHP's counterCache functionality by adding a \"comment_count\" field to the entries table, configuring the counterCache key of the Comment belongsTo Entry association with this field, then call find() on the Entry model.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5030/"
] | As part of a larger web-app (using CakePHP), I'm putting together a simple blog system. The relationships are exceedingly simple: each User has a Blog, which has many Entries, which have many Comments.
An element I'd like to incorporate is a list of "Popular Entries." Popular Entries have been defined as those with the most Comments in the last month, and ultimately they need to be ordered by the number of recent Comments.
Ideally, I'd like the solution to stay within Cake's Model data-retrieval apparatus (`Model->find()`, etc.), but I'm not sanguine about this.
Anyone have a clever/elegant solution? I'm steeling myself for some wild SQL hacking to make this work... | Heh, I was just about to come back with essentially the same answer (using Cake's Model::find):
```
$this->loadModel('Comment');
$this->Comment->find( 'all', array(
'fields' => array('COUNT(Comment.id) AS popularCount'),
'conditions' => array(
'Comment.created >' => strtotime('-1 month')
),
'group' => 'Comment.blog_post_id',
'order' => 'popularCount DESC',
'contain' => array(
'Entry' => array(
'fields' => array( 'Entry.title' )
)
)
));
```
It's not perfect, but it works and can be improved on.
I made an additional improvement, using the Containable behaviour to extract the Entry data instead of the Comment data. |
52,821 | <pre><code>var e1 = new E1();
e1.e2s.Add(new e2()); //e2s is null until e1 is saved, i want to save them all at the same time
context.e1s.imsertonsubmit(e1);
context.submitchanges();
</code></pre>
| [
{
"answer_id": 52870,
"author": "John Christensen",
"author_id": 1194,
"author_profile": "https://Stackoverflow.com/users/1194",
"pm_score": 0,
"selected": false,
"text": "<p>Well - I don't know if your initial code block would work, but I'm guessing you have to mark your new e2 as insert on submit. Thus:</p>\n\n<pre><code>var e1 = new E1();\nvar e2 = new e2();\ne1.e2s.Add(e2); //e2s is null until e1 is saved, i want to save them all at the same time\ncontext.e1s.insertonsubmit(e1);\ncontext.e2s.insertonsubmit(e2);\ncontext.submitchanges();\n</code></pre>\n"
},
{
"answer_id": 53018,
"author": "Gabe Anzelini",
"author_id": 5236,
"author_profile": "https://Stackoverflow.com/users/5236",
"pm_score": 0,
"selected": false,
"text": "<p>there we go, apparently when you create another ctor, you have to actually call the no arg ctor in order for the stuff in the ctor to happen</p>\n"
},
{
"answer_id": 91471,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 1,
"selected": false,
"text": "<p>The sub items will be saved along with the main item, and even identities will be set properly, if you give your DataClasses an association between these classes.</p>\n\n<p>You do this by adding LoadOptions to your O/R-Designer DataClasses like this:</p>\n\n<pre><code> MyDataContext mydc = new MyDataContext();\n System.Data.Linq.DataLoadOptions lo = new System.Data.Linq.DataLoadOptions();\n lo.LoadWith<E1>(p => p.e2s);\n mydc.LoadOptions = lo;\n</code></pre>\n\n<p>This way LINQ will take care of adding the sub-items, you don't need to InsertOnSubmit every one by itself.\nA side effect: upon loading the item, the subitems will be retrieved, too.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5236/"
] | ```
var e1 = new E1();
e1.e2s.Add(new e2()); //e2s is null until e1 is saved, i want to save them all at the same time
context.e1s.imsertonsubmit(e1);
context.submitchanges();
``` | The sub items will be saved along with the main item, and even identities will be set properly, if you give your DataClasses an association between these classes.
You do this by adding LoadOptions to your O/R-Designer DataClasses like this:
```
MyDataContext mydc = new MyDataContext();
System.Data.Linq.DataLoadOptions lo = new System.Data.Linq.DataLoadOptions();
lo.LoadWith<E1>(p => p.e2s);
mydc.LoadOptions = lo;
```
This way LINQ will take care of adding the sub-items, you don't need to InsertOnSubmit every one by itself.
A side effect: upon loading the item, the subitems will be retrieved, too. |
52,822 | <p>How can you import a foxpro DBF file in SQL Server?</p>
| [
{
"answer_id": 52828,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 5,
"selected": true,
"text": "<p>Use a linked server or use openrowset, example</p>\n\n<pre><code>SELECT * into SomeTable\nFROM OPENROWSET('MSDASQL', 'Driver=Microsoft Visual FoxPro Driver;\nSourceDB=\\\\SomeServer\\SomePath\\;\nSourceType=DBF',\n'SELECT * FROM SomeDBF')\n</code></pre>\n"
},
{
"answer_id": 52835,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<p>This tools allows you to import to and from SQL Server.</p>\n\n<ul>\n<li><a href=\"http://www.download3000.com/download_17933.html\" rel=\"nofollow noreferrer\">http://www.download3000.com/download_17933.html</a></li>\n</ul>\n"
},
{
"answer_id": 6346611,
"author": "jnovation",
"author_id": 798044,
"author_profile": "https://Stackoverflow.com/users/798044",
"pm_score": 2,
"selected": false,
"text": "<p>What finally worked for us was to use the <a href=\"http://www.microsoft.com/download/en/details.aspx?id=14839\" rel=\"nofollow\">FoxPro OLEDB Driver</a> and use the following syntax. In our case we are using SQL 2008.</p>\n\n<pre><code>select * from \n openrowset('VFPOLEDB','\\\\VM-GIS\\E\\Projects\\mymap.dbf';'';\n '','SELECT * FROM mymap')\n</code></pre>\n\n<p>Substitute the <code>\\\\VM-GIS...</code> with the location of your DBF file, either UNC or drive path. Also, substitute <code>mymap</code> after the <code>FROM</code> with the name of the DBF file without the .dbf extension.</p>\n"
},
{
"answer_id": 6452657,
"author": "Stan",
"author_id": 812017,
"author_profile": "https://Stackoverflow.com/users/812017",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://elphsoft.com/dbfcommander.html\" rel=\"nofollow\">http://elphsoft.com/dbfcommander.html</a> can export from DBF to SQL Server and vice versa</p>\n"
},
{
"answer_id": 11973558,
"author": "mark d",
"author_id": 1601157,
"author_profile": "https://Stackoverflow.com/users/1601157",
"pm_score": 3,
"selected": false,
"text": "<p>I was able to use the answer from jnovation but since there was something wrong with my fields, I simply selected specific fields instead of all, like:</p>\n\n<pre><code>select * into CERTDATA\nfrom openrowset('VFPOLEDB','C:\\SomePath\\CERTDATA.DBF';'';\n '','SELECT ACTUAL, CERTID, FROM CERTDATA')\n</code></pre>\n\n<p>Very exciting to finally have a workable answer thanks to everyone here!</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4685/"
] | How can you import a foxpro DBF file in SQL Server? | Use a linked server or use openrowset, example
```
SELECT * into SomeTable
FROM OPENROWSET('MSDASQL', 'Driver=Microsoft Visual FoxPro Driver;
SourceDB=\\SomeServer\SomePath\;
SourceType=DBF',
'SELECT * FROM SomeDBF')
``` |
52,824 | <p>Is it possible to merge to a branch that is not a direct parent or child in TFS? I suspect that the answer is no as this is what I've experienced while using it. However, it seems that at certain times it would be really useful when there are different features being worked on that may have different approval cycles (ie. feature one <strong>might</strong> be approved before feature two). This becomes exceedingly difficult when we have production branches where we have to merge some feature into a previous branch so we can release before the next full version.</p>
<p>Our current branching strategy is to develop in the trunk (or mainline as we call it), and create a branch to stabilize and release to production. This branch can then be used to create hotfixes and other things while mainline can diverge for upcoming features.</p>
<p>What techniques can be used otherwise to mitigate a scenario such as the one(s) described above?</p>
| [
{
"answer_id": 52841,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 1,
"selected": false,
"text": "<p>AFAIK you can do this as long as the branches were created off of the same original folder.</p>\n\n<ul>\n<li>trunk/</li>\n<li>branches/\n-/feature1 (branched from trunk)\n-/feature2 (branched from trunk)</li>\n</ul>\n\n<p>If you do this then you should be able to merge between feature1 and feature2 as well.</p>\n\n<p>Though my branching/merging experience with TFS leaves me wanting more. I wish we just had SVN.</p>\n"
},
{
"answer_id": 52853,
"author": "Harpreet",
"author_id": 855,
"author_profile": "https://Stackoverflow.com/users/855",
"pm_score": 2,
"selected": false,
"text": "<p>You may want to revisit your branching strategy. How do you get production branches? Are you merging all code from development branches, regression testing and then creating a production branch for fixes? Or are you developing on the trunk and then creating production branches to stabilize and release from? The second way creates problems of the type you're describing. If you are using the first approach -- the trunk is supposed to be only for things that have been built on branches tested and then merged you will run into this much less often. Under that approach if you're still having this problem it may be because your development effort is very large and you may need a relatively complex branching strategy with layers of branching and promotion.</p>\n"
},
{
"answer_id": 52894,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "<pre><code>tf.exe merge /recursive /baseless $/TeamProject/SourceBranch $/TeamProject/TargetBranch\n</code></pre>\n\n<ul>\n<li>MSDN: <a href=\"http://msdn.microsoft.com/en-us/library/bb668976.aspx\" rel=\"noreferrer\">How To: Perform a Baseless Merge in Visual Studio Team Foundation Server</a></li>\n</ul>\n"
},
{
"answer_id": 52895,
"author": "Dan Shield",
"author_id": 4633,
"author_profile": "https://Stackoverflow.com/users/4633",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, you can do a baseless merge, but only from the command line (tf.exe).</p>\n"
},
{
"answer_id": 52907,
"author": "Brian Stewart",
"author_id": 3114,
"author_profile": "https://Stackoverflow.com/users/3114",
"pm_score": 1,
"selected": false,
"text": "<p>TFS will allow you to merge with a branch that is not a parent/child - these are called baseless merges. See these links:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb668976.aspx\" rel=\"nofollow noreferrer\">From MSDN</a></p>\n\n<p><a href=\"http://www.codeplex.com/VSTSGuidance/Wiki/View.aspx?title=How%20To%3A%20Perform%20a%20Baseless%20Merge%20in%20Team%20Foundation%20Server&referringTitle=View%20More\" rel=\"nofollow noreferrer\">From the TFS Team via CodePlex</a></p>\n\n<p>We typically do major or destabilizing changes on a development branch. If close to a major release of one of our products nearly all changes will be done on a branch.</p>\n"
},
{
"answer_id": 52909,
"author": "Justin Dearing",
"author_id": 3110,
"author_profile": "https://Stackoverflow.com/users/3110",
"pm_score": 5,
"selected": true,
"text": "<p>I agree with Harpreet that you may want to revisit how you you have setup you branching structure. However you if you really want to perform this type of merge you can through something called a baseless merge. It runs from the tfs command prompt, </p>\n\n<pre><code>Tf merge /baseless <<source path>> <<target path>> /recursive\n</code></pre>\n\n<p>Additional info about baseless merges can be found <a href=\"http://www.codeplex.com/VSTSGuidance/Wiki/View.aspx?title=How%20To%3A%20Perform%20a%20Baseless%20Merge%20in%20Team%20Foundation%20Server&referringTitle=View%20More\" rel=\"noreferrer\">here</a></p>\n\n<p>Also I found this document to be invaluable when constructing our tfs branching structure\n<a href=\"http://vsarbranchingguide.codeplex.com/\" rel=\"noreferrer\">Microsoft Team Foundation Server Branching Guidance </a></p>\n"
},
{
"answer_id": 56397578,
"author": "Iannazzi",
"author_id": 1303144,
"author_profile": "https://Stackoverflow.com/users/1303144",
"pm_score": 0,
"selected": false,
"text": "<p>I am far from a TFS expert, but I think you can merge siblings, and I think it is not a baseless merge. </p>\n\n<p>We branched off our main branch (branch name \"main\") for a feature (branch name \"feature\"), then I needed some of the work in a branch that was also branched off the main branch (branch name \"dev\"). I would consider feature and dev branches to be siblings as they both came from the same parent. I merged feature to dev and all files (14000) were marked as merge, some were marked as merge,edit. I could not cancel (visual studio would just hang), so I accepted the merge. Then I merged dev to main, then I pulled main to feature, and again 14000 files were marked for merge. I was really upset, and afraid this would continue.</p>\n\n<p>At this point we did a test project. We set up main, then branched dev and feature from main. We repeated the above steps with the same results. Once we completed the merge from main to feature, all future merges only showed the edited files.</p>\n\n<p>After our little test I completed the merge from main to feature. And just like the test our merges now only show the edited files. We can go dev to feature, feature to main, main to dev, etc. </p>\n\n<p>I did notice when branching all file dates were modified. Maybe this is an issue?</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5416/"
] | Is it possible to merge to a branch that is not a direct parent or child in TFS? I suspect that the answer is no as this is what I've experienced while using it. However, it seems that at certain times it would be really useful when there are different features being worked on that may have different approval cycles (ie. feature one **might** be approved before feature two). This becomes exceedingly difficult when we have production branches where we have to merge some feature into a previous branch so we can release before the next full version.
Our current branching strategy is to develop in the trunk (or mainline as we call it), and create a branch to stabilize and release to production. This branch can then be used to create hotfixes and other things while mainline can diverge for upcoming features.
What techniques can be used otherwise to mitigate a scenario such as the one(s) described above? | I agree with Harpreet that you may want to revisit how you you have setup you branching structure. However you if you really want to perform this type of merge you can through something called a baseless merge. It runs from the tfs command prompt,
```
Tf merge /baseless <<source path>> <<target path>> /recursive
```
Additional info about baseless merges can be found [here](http://www.codeplex.com/VSTSGuidance/Wiki/View.aspx?title=How%20To%3A%20Perform%20a%20Baseless%20Merge%20in%20Team%20Foundation%20Server&referringTitle=View%20More)
Also I found this document to be invaluable when constructing our tfs branching structure
[Microsoft Team Foundation Server Branching Guidance](http://vsarbranchingguide.codeplex.com/) |
52,842 | <p><code>System.IO.Directory.GetFiles()</code> returns a <code>string[]</code>. What is the default sort order for the returned values? I'm assuming by name, but if so how much does the current culture effect it? Can you change it to something like creation date? </p>
<p><strong>Update:</strong> MSDN points out that the sort order is not guaranteed for .Net 3.5, but the 2.0 version of the page doesn't say anything at all and neither page will help you sort by things like creation or modification time. That information is lost once you have the array (it contains only strings). I could build a comparer that would check for each file it gets, but that means accessing the file system repeatedly when presumably the .GetFiles() method already does this. Seems very inefficient.</p>
| [
{
"answer_id": 52847,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": false,
"text": "<p></p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Dim Files() As String\nFiles = System.IO.Directory.GetFiles(\"C:\\\")\nArray.Sort(Files)\n</code></pre>\n"
},
{
"answer_id": 52850,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 3,
"selected": false,
"text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/wz42302f.aspx\" rel=\"noreferrer\">msdn</a>:</p>\n\n<blockquote>\n <p>The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required.</p>\n</blockquote>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.array.sort.aspx\" rel=\"noreferrer\">Sort()</a> method is the standard Array.Sort(), which takes in IComparables (among other overloads), so if you sort by creation date, it will handle localization based on the machine settings.</p>\n"
},
{
"answer_id": 52852,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/wz42302f.aspx\" rel=\"nofollow noreferrer\">MSDN Documentation</a> states that there is no guarantee of any order on the return values. You have to use the Sort() method.</p>\n"
},
{
"answer_id": 52854,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 2,
"selected": false,
"text": "<p>You are correct, the default is my name asc. The only way I have found to change the sort order it to create a datatable from the FileInfo collection.</p>\n\n<p>You can then used the DefaultView from the datatable and sort the directory with the .Sort method.</p>\n\n<p>This is quite involve and fairly slow but I'm hoping someone will post a better solution.</p>\n"
},
{
"answer_id": 52859,
"author": "Tina Marie",
"author_id": 4666,
"author_profile": "https://Stackoverflow.com/users/4666",
"pm_score": 2,
"selected": false,
"text": "<p>You could write a custom IComparer interface to sort by creation date, and then pass it to Array.Sort. You probably also want to look at StrCmpLogical, which is what is used to do the sorting Explorer uses (sorting numbers correctly with text).</p>\n"
},
{
"answer_id": 52861,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to sort by something like creation date you probably need to use DirectoryInfo.GetFiles and then sort the resulting array using a suitable Predicate.</p>\n"
},
{
"answer_id": 52865,
"author": "Vertigo",
"author_id": 5468,
"author_profile": "https://Stackoverflow.com/users/5468",
"pm_score": 2,
"selected": false,
"text": "<p>You can implement custom iComparer to do sorting. Read the file info for files and compare as you like. </p>\n\n<pre><code>IComparer comparer = new YourCustomComparer();\nArray.Sort(System.IO.Directory.GetFiles(), comparer);\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.collections.icomparer(VS.80).aspx\" rel=\"nofollow noreferrer\">msdn info IComparer interface</a></p>\n"
},
{
"answer_id": 52867,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 8,
"selected": true,
"text": "<p>If you're interested in properties of the files such as CreationTime, then it would make more sense to use System.IO.DirectoryInfo.GetFileSystemInfos(). \nYou can then sort these using one of the extension methods in System.Linq, e.g.:</p>\n\n<pre><code>DirectoryInfo di = new DirectoryInfo(\"C:\\\\\");\nFileSystemInfo[] files = di.GetFileSystemInfos();\nvar orderedFiles = files.OrderBy(f => f.CreationTime);\n</code></pre>\n\n<p>Edit - sorry, I didn't notice the .NET2.0 tag so ignore the LINQ sorting. The suggestion to use System.IO.DirectoryInfo.GetFileSystemInfos() still holds though.</p>\n"
},
{
"answer_id": 149100,
"author": "sebastiaan",
"author_id": 5018,
"author_profile": "https://Stackoverflow.com/users/5018",
"pm_score": 4,
"selected": false,
"text": "<p>Here's the VB.Net solution that I've used.</p>\n\n<p>First make a class to compare dates:</p>\n\n<pre><code>Private Class DateComparer\n Implements System.Collections.IComparer\n\n Public Function Compare(ByVal info1 As Object, ByVal info2 As Object) As Integer Implements System.Collections.IComparer.Compare\n Dim FileInfo1 As System.IO.FileInfo = DirectCast(info1, System.IO.FileInfo)\n Dim FileInfo2 As System.IO.FileInfo = DirectCast(info2, System.IO.FileInfo)\n\n Dim Date1 As DateTime = FileInfo1.CreationTime\n Dim Date2 As DateTime = FileInfo2.CreationTime\n\n If Date1 > Date2 Then Return 1\n If Date1 < Date2 Then Return -1\n Return 0\n End Function\nEnd Class\n</code></pre>\n\n<p>Then use the comparer while sorting the array:</p>\n\n<pre><code>Dim DirectoryInfo As New System.IO.DirectoryInfo(\"C:\\\")\nDim Files() As System.IO.FileInfo = DirectoryInfo.GetFiles()\nDim comparer As IComparer = New DateComparer()\nArray.Sort(Files, comparer)\n</code></pre>\n"
},
{
"answer_id": 279142,
"author": "Chris Karcher",
"author_id": 2773,
"author_profile": "https://Stackoverflow.com/users/2773",
"pm_score": 4,
"selected": false,
"text": "<p>In .NET 2.0, you'll need to use Array.Sort to sort the FileSystemInfos.</p>\n\n<p>Additionally, you can use a Comparer delegate to avoid having to declare a class just for the comparison:</p>\n\n<pre><code>DirectoryInfo dir = new DirectoryInfo(path);\nFileSystemInfo[] files = dir.GetFileSystemInfos();\n\n// sort them by creation time\nArray.Sort<FileSystemInfo>(files, delegate(FileSystemInfo a, FileSystemInfo b)\n {\n return a.LastWriteTime.CompareTo(b.LastWriteTime);\n });\n</code></pre>\n"
},
{
"answer_id": 2555123,
"author": "Mehdi Anis",
"author_id": 208325,
"author_profile": "https://Stackoverflow.com/users/208325",
"pm_score": 1,
"selected": false,
"text": "<p>Just an idea. I like to find an easy way out and try re use already available resources. if I were to sort files I would've just create a process and make syscal to \"DIR [x:\\Folders\\SubFolders*.*] /s /b /on\" and capture the output. </p>\n\n<p>With system's DIR command you can sort by :</p>\n\n<pre><code>/O List by files in sorted order.\nsortorder N By name (alphabetic) S By size (smallest first)\n E By extension (alphabetic) D By date/time (oldest first)\n G Group directories first - Prefix to reverse order\n\nThe /S switch includes sub folders\n</code></pre>\n\n<p>I AM NOT SURE IF D = By Date/Time is using LastModifiedDate or FileCreateDate. But if the needed sort order is already built-in in the DIR command, I will get that by calling syscall. And it's FAST. I am just the lazy guy ;)</p>\n\n<p><em>After a little googling I found switch to sort by particular date/time:-</em></p>\n\n<pre><code>/t [[:]TimeField] : Specifies which time field to display or use for sorting. The following list describes each of the values you can use for TimeField. \n\nValue Description \nc : Creation\na : Last access\nw : Last written\n</code></pre>\n"
},
{
"answer_id": 15544428,
"author": "Simon Molloy",
"author_id": 942604,
"author_profile": "https://Stackoverflow.com/users/942604",
"pm_score": 1,
"selected": false,
"text": "<p>A more succinct VB.Net version, if anyone is interested</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Dim filePaths As Linq.IOrderedEnumerable(Of IO.FileInfo) = _\n New DirectoryInfo(\"c:\\temp\").GetFiles() _\n .OrderBy(Function(f As FileInfo) f.CreationTime)\nFor Each fi As IO.FileInfo In filePaths\n ' Do whatever you wish here\nNext\n</code></pre>\n"
},
{
"answer_id": 20548522,
"author": "skeltech",
"author_id": 3096197,
"author_profile": "https://Stackoverflow.com/users/3096197",
"pm_score": 2,
"selected": false,
"text": "<p>A more succinct VB.Net version...is very nice. Thank you. \nTo traverse the list in reverse order, add the reverse method...</p>\n\n<pre><code>For Each fi As IO.FileInfo In filePaths.reverse\n ' Do whatever you wish here\nNext\n</code></pre>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] | `System.IO.Directory.GetFiles()` returns a `string[]`. What is the default sort order for the returned values? I'm assuming by name, but if so how much does the current culture effect it? Can you change it to something like creation date?
**Update:** MSDN points out that the sort order is not guaranteed for .Net 3.5, but the 2.0 version of the page doesn't say anything at all and neither page will help you sort by things like creation or modification time. That information is lost once you have the array (it contains only strings). I could build a comparer that would check for each file it gets, but that means accessing the file system repeatedly when presumably the .GetFiles() method already does this. Seems very inefficient. | If you're interested in properties of the files such as CreationTime, then it would make more sense to use System.IO.DirectoryInfo.GetFileSystemInfos().
You can then sort these using one of the extension methods in System.Linq, e.g.:
```
DirectoryInfo di = new DirectoryInfo("C:\\");
FileSystemInfo[] files = di.GetFileSystemInfos();
var orderedFiles = files.OrderBy(f => f.CreationTime);
```
Edit - sorry, I didn't notice the .NET2.0 tag so ignore the LINQ sorting. The suggestion to use System.IO.DirectoryInfo.GetFileSystemInfos() still holds though. |
52,844 | <p>I am using a wxGenericDirCtrl, and I would like to know if there is a way to hide directories, I'd especially like to hide siblings of parent nodes.</p>
<p>For example if my directory structure looks like this:</p>
<pre><code>+-a
|
+-b
| |
| +-whatever
|
+-c
| |
| +-d
| |
| +-e
| |
| +-f
|
+-g
|
+-whatever
</code></pre>
<p>If my currently selected directory is /a/c/d is there any way to hide b and g, so that the tree looks like this in my ctrl:</p>
<pre><code>+-a
|
+-c
|
+-[d]
|
+-e
|
+-f
</code></pre>
<p>I'm currently working with a directory structure that has lots and lots directories that are irrelevant to most users, so it would be nice to be able to clean it up.</p>
<p><strong>Edit</strong>:
If it makes a difference, I am using wxPython, and so far, I have only tested my code on linux using the GTK backend, but I do plan to make it multi-platform and using it on Windows and Mac using the native backends.</p>
| [
{
"answer_id": 60745,
"author": "Gareth Simpson",
"author_id": 147,
"author_profile": "https://Stackoverflow.com/users/147",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think that's possible.</p>\n\n<p>It would be relatively easy to add this functionality to the underlying C++ wxWidgets control, but since you're using wxPython, you'd then have to rebuild that as well which is a tremendous issue.</p>\n"
},
{
"answer_id": 64273,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 2,
"selected": true,
"text": "<p>Listing/walking directories in Python is very easy, so I would recommend trying to \"roll your own\" using one of the simple tree controls (such as TreeCtrl or CustomTreeCtrl). It should really be quite easy to call the directory listing code when some directory is expanded and return the result.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3051/"
] | I am using a wxGenericDirCtrl, and I would like to know if there is a way to hide directories, I'd especially like to hide siblings of parent nodes.
For example if my directory structure looks like this:
```
+-a
|
+-b
| |
| +-whatever
|
+-c
| |
| +-d
| |
| +-e
| |
| +-f
|
+-g
|
+-whatever
```
If my currently selected directory is /a/c/d is there any way to hide b and g, so that the tree looks like this in my ctrl:
```
+-a
|
+-c
|
+-[d]
|
+-e
|
+-f
```
I'm currently working with a directory structure that has lots and lots directories that are irrelevant to most users, so it would be nice to be able to clean it up.
**Edit**:
If it makes a difference, I am using wxPython, and so far, I have only tested my code on linux using the GTK backend, but I do plan to make it multi-platform and using it on Windows and Mac using the native backends. | Listing/walking directories in Python is very easy, so I would recommend trying to "roll your own" using one of the simple tree controls (such as TreeCtrl or CustomTreeCtrl). It should really be quite easy to call the directory listing code when some directory is expanded and return the result. |
52,874 | <p>I have a piece of server-ish software written in Java to run on Windows and OS X. (It is not running on a server, but just a normal user's PC - something like a torrent client.) I would like the software to signal to the OS to keep the machine awake (prevent it from going into sleep mode) while it is active.</p>
<p>Of course I don't expect there to be a cross platform solution, but I would love to have some very minimal C programs/scripts that my app can spawn to inform the OS to stay awake.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 52882,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 0,
"selected": false,
"text": "<p>Run a command inside a timer like pinging the server..</p>\n"
},
{
"answer_id": 52885,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 1,
"selected": false,
"text": "<p>Wouldn't it be easier to disable the power management on the server? It might be argued that servers shouldn't go into powersave mode?</p>\n"
},
{
"answer_id": 52888,
"author": "Keng",
"author_id": 730,
"author_profile": "https://Stackoverflow.com/users/730",
"pm_score": 3,
"selected": false,
"text": "<p>I have a very brute-force technique of moving the mouse 1 point in the x direction and then back every 3 minutes.</p>\n\n<p>There may me a more elegant solution but it's a quick fix.</p>\n"
},
{
"answer_id": 52906,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 4,
"selected": false,
"text": "<p>On Windows, use the <a href=\"http://msdn.microsoft.com/en-us/library/ms724947.aspx\" rel=\"noreferrer\">SystemParametersInfo</a> function. It's a Swiss army-style function that lets you get/set all sorts of system settings.</p>\n\n<p>To disable the screen shutting off, for instance:</p>\n\n<pre><code>SystemParametersInfo( SPI_SETPOWEROFFACTIVE, 0, NULL, 0 );\n</code></pre>\n\n<p>Just be sure to set it back when you're done...</p>\n"
},
{
"answer_id": 52913,
"author": "Paulj",
"author_id": 5433,
"author_profile": "https://Stackoverflow.com/users/5433",
"pm_score": 0,
"selected": false,
"text": "<p>I'd just do a function (or download a freebie app) that moves the mouse around. Inelegant, but easy.</p>\n"
},
{
"answer_id": 52966,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 6,
"selected": true,
"text": "<p>I use this code to keep my workstation from locking. It's currently only set to move the mouse once every minute, you could easily adjust it though.</p>\n\n<p>It's a hack, not an elegant solution.</p>\n\n<pre><code>import java.awt.*;\nimport java.util.*;\npublic class Hal{\n\n public static void main(String[] args) throws Exception{\n Robot hal = new Robot();\n Random random = new Random();\n while(true){\n hal.delay(1000 * 60);\n int x = random.nextInt() % 640;\n int y = random.nextInt() % 480;\n hal.mouseMove(x,y);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 53176,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 3,
"selected": false,
"text": "<p>Wouldn't all the suggestions moving the mouse back and forth drive the user crazy? I know I'd remove any app that would do that as soon as I can isolate it.</p>\n"
},
{
"answer_id": 53276,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 2,
"selected": false,
"text": "<p>I've been using <a href=\"http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/pmset.1.html\" rel=\"nofollow noreferrer\">pmset</a> to control sleep mode on my Mac for awhile now, and it's pretty easy to integrate. Here's a rough example of how you could call that program from Java to disable/enable sleep mode. Note that you need root privileges to run pmset, and therefore you'll need them to run this program.</p>\n\n<pre><code>import java.io.BufferedInputStream;\nimport java.io.IOException;\n\n/**\n * Disable sleep mode (record current setting beforehand), and re-enable sleep\n * mode. Works with Mac OS X using the \"pmset\" command.\n */\npublic class SleepSwitch {\n\n private int sleepTime = -1;\n\n public void disableSleep() throws IOException {\n if (sleepTime != -1) {\n // sleep time is already recorded, assume sleep is disabled\n return;\n }\n\n // query pmset for the current setting\n Process proc = Runtime.getRuntime().exec(\"pmset -g\");\n BufferedInputStream is = new BufferedInputStream(proc.getInputStream());\n StringBuffer output = new StringBuffer();\n int c;\n while ((c = is.read()) != -1) {\n output.append((char) c);\n }\n is.close();\n\n // parse the current setting and store the sleep time\n String outString = output.toString();\n String setting = outString.substring(outString.indexOf(\" sleep\\t\")).trim();\n setting = setting.substring(7, setting.indexOf(\" \")).trim();\n sleepTime = Integer.parseInt(setting);\n\n // set the sleep time to zero (disable sleep)\n Runtime.getRuntime().exec(\"pmset sleep 0\");\n }\n\n public void enableSleep() throws IOException {\n if (sleepTime == -1) {\n // sleep time is not recorded, assume sleep is enabled\n return;\n }\n\n // set the sleep time to the previously stored value\n Runtime.getRuntime().exec(\"pmset sleep \" + sleepTime);\n\n // reset the stored sleep time\n sleepTime = -1;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 93610,
"author": "Milhous",
"author_id": 17712,
"author_profile": "https://Stackoverflow.com/users/17712",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the program Caffeine <a href=\"http://lightheadsw.com/caffeine/\" rel=\"nofollow noreferrer\">caffiene</a> to keep your workstation awake. You could run the program via the open command in os X.</p>\n"
},
{
"answer_id": 10280104,
"author": "asloob",
"author_id": 603125,
"author_profile": "https://Stackoverflow.com/users/603125",
"pm_score": 3,
"selected": false,
"text": "<p>Adding to scarcher2's code snippet above and moving mouse by only 1 pixel. I have moved the mouse twice so that some change occurs even if pointer is on extremes:</p>\n\n<pre><code>while(true){\n hal.delay(1000 * 30); \n Point pObj = MouseInfo.getPointerInfo().getLocation();\n System.out.println(pObj.toString() + \"x>>\" + pObj.x + \" y>>\" + pObj.y);\n hal.mouseMove(pObj.x + 1, pObj.y + 1); \n hal.mouseMove(pObj.x - 1, pObj.y - 1);\n pObj = MouseInfo.getPointerInfo().getLocation();\n System.out.println(pObj.toString() + \"x>>\" + pObj.x + \" y>>\" + pObj.y);\n }\n</code></pre>\n"
},
{
"answer_id": 19349044,
"author": "Javier Carmona",
"author_id": 2041804,
"author_profile": "https://Stackoverflow.com/users/2041804",
"pm_score": 1,
"selected": false,
"text": "<p>This code moves the pointer to the same location where it already is so the user doesn't notice any difference.</p>\n\n<pre><code>while (true) {\n Thread.sleep(180000);//this is how long before it moves\n Point mouseLoc = MouseInfo.getPointerInfo().getLocation();\n Robot rob = new Robot();\n rob.mouseMove(mouseLoc.x, mouseLoc.y);\n}\n</code></pre>\n"
},
{
"answer_id": 30313322,
"author": "ihatetoregister",
"author_id": 517748,
"author_profile": "https://Stackoverflow.com/users/517748",
"pm_score": 2,
"selected": false,
"text": "<p>On OS X, just spawn <code>caffeinate</code>. This will prevent the system from sleeping until <code>caffeinate</code> is terminated.</p>\n"
},
{
"answer_id": 31192583,
"author": "Felinis",
"author_id": 2941664,
"author_profile": "https://Stackoverflow.com/users/2941664",
"pm_score": 2,
"selected": false,
"text": "<p>In Visual Studio create a simple form.\nFrom the toolbar, drag a Timer control onto the form.\nIn the Init code, set the timer interval to 60 seconds (60000 ms.).\nImplement the timer callback with the following code \"SendKeys.Send(\"{F15}\");\"\nRun the new program.</p>\n\n<p>No mouse movement needed.</p>\n\n<p>Edit: At least on my Army workstation, simply programmatically generating mouse and key messages isn't enough to keep my workstation logged in and awake. The early posters with the Java Robot class are on the right track. JAVA Robot works on or below the OS's HAL (Hardware Abstraction Layer) However I recreated and tested the Java/Robot solution and it did not work - until I added a Robot.keyPress(123) to the code.</p>\n"
},
{
"answer_id": 50833568,
"author": "Santosh Jadi",
"author_id": 3805521,
"author_profile": "https://Stackoverflow.com/users/3805521",
"pm_score": 0,
"selected": false,
"text": "<p><strong>This will work:</strong></p>\n\n<pre><code>public class Utils {\n public static void main(String[] args) throws AWTException {\n Robot rob = new Robot();\n PointerInfo ptr = null;\n while (true) {\n rob.delay(4000); // Mouse moves every 4 seconds\n ptr = MouseInfo.getPointerInfo();\n rob.mouseMove((int) ptr.getLocation().getX() + 1, (int) ptr.getLocation().getY() + 1);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 54684339,
"author": "Anand Varkey Philips",
"author_id": 3002336,
"author_profile": "https://Stackoverflow.com/users/3002336",
"pm_score": 2,
"selected": false,
"text": "<p>Here is completed Batch file that generates java code, compile it, cleans the generated files, and runs in the background.. (jdk is required on your laptop)</p>\n<p><strong>Just save and run this as a Bat File. (somefilename.bat) ;)</strong></p>\n<pre><code>@echo off\nsetlocal\n\nrem rem if JAVA is set and run from :startapp labeled section below, else the program exit through :end labeled section.\nif not "[%JAVA_HOME%]"=="[]" goto start_app\necho. JAVA_HOME not set. Application will not run!\ngoto end\n\n\n:start_app\necho. Using java in %JAVA_HOME%\nrem writes below code to Energy.java file.\n@echo import java.awt.MouseInfo; > Energy.java\n@echo import java.awt.Point; >> Energy.java\n@echo import java.awt.Robot; >> Energy.java\n@echo //Mouse Movement Simulation >> Energy.java\n@echo public class Energy { >> Energy.java\n@echo public static void main(String[] args) throws Exception { >> Energy.java\n@echo Robot energy = new Robot(); >> Energy.java\n@echo while (true) { >> Energy.java\n@echo energy.delay(1000 * 60); >> Energy.java\n@echo Point pObj = MouseInfo.getPointerInfo().getLocation(); >> Energy.java\n@echo Point pObj2 = pObj; >> Energy.java\n@echo System.out.println(pObj.toString() + "x>>" + pObj.x + " y>>" + pObj.y); >> Energy.java\n@echo energy.mouseMove(pObj.x + 10, pObj.y + 10); >> Energy.java\n@echo energy.mouseMove(pObj.x - 10, pObj.y - 10); >> Energy.java\n@echo energy.mouseMove(pObj2.x, pObj.y); >> Energy.java\n@echo pObj = MouseInfo.getPointerInfo().getLocation(); >> Energy.java\n@echo System.out.println(pObj.toString() + "x>>" + pObj.x + " y>>" + pObj.y); >> Energy.java\n@echo } >> Energy.java\n@echo } >> Energy.java\n@echo } >> Energy.java\n\nrem compile java code.\njavac Energy.java\nrem run java application in background.\nstart javaw Energy\necho. Your Secret Energy program is running...\ngoto end\n\n:end\nrem clean if files are created.\npause\ndel "Energy.class"\ndel "Energy.java"\n</code></pre>\n"
},
{
"answer_id": 56146892,
"author": "maris",
"author_id": 3853452,
"author_profile": "https://Stackoverflow.com/users/3853452",
"pm_score": -1,
"selected": false,
"text": "<p>One simple way which i use to avoid \"Windows desktop Auto lock\" is \"Switch On/Off NumLock\" every 6 seconds.</p>\n\n<p>Here a Java Program to Switch ON/OFF NumLock.</p>\n\n<pre><code>import java.util.*;\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class NumLock extends Thread {\n public void run() {\n try {\n boolean flag = true;\n do {\n flag = !flag;\n\n Thread.sleep(6000);\n Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent. VK_NUM_LOCK, flag);\n }\n while(true);\n }\n catch(Exception e) {}\n }\n\n public static void main(String[] args) throws Exception {\n new NumLock().start();\n }\n}\n</code></pre>\n\n<p>Run this Java program in a separate command prompt; :-)</p>\n"
},
{
"answer_id": 65890299,
"author": "Gili",
"author_id": 14731,
"author_profile": "https://Stackoverflow.com/users/14731",
"pm_score": 3,
"selected": false,
"text": "<p>A much cleaner solution is use JNA to tap into the native OS API. Check your platform at runtime, and if it happens to be Windows then the following will work:</p>\n<pre><code>import com.sun.jna.Native;\nimport com.sun.jna.Structure;\nimport com.sun.jna.Structure.FieldOrder;\nimport com.sun.jna.platform.win32.WTypes.LPWSTR;\nimport com.sun.jna.platform.win32.WinBase;\nimport com.sun.jna.platform.win32.WinDef.DWORD;\nimport com.sun.jna.platform.win32.WinDef.ULONG;\nimport com.sun.jna.platform.win32.WinNT.HANDLE;\nimport com.sun.jna.win32.StdCallLibrary;\n\n/**\n * Power management.\n *\n * @see <a href="https://stackoverflow.com/a/20996135/14731">https://stackoverflow.com/a/20996135/14731</a>\n */\npublic enum PowerManagement\n{\n INSTANCE;\n\n @FieldOrder({"version", "flags", "simpleReasonString"})\n public static class REASON_CONTEXT extends Structure\n {\n public static class ByReference extends REASON_CONTEXT implements Structure.ByReference\n {\n }\n\n public ULONG version;\n public DWORD flags;\n public LPWSTR simpleReasonString;\n }\n\n private interface Kernel32 extends StdCallLibrary\n {\n HANDLE PowerCreateRequest(REASON_CONTEXT.ByReference context);\n\n /**\n * @param powerRequestHandle the handle returned by {@link #PowerCreateRequest(REASON_CONTEXT.ByReference)}\n * @param requestType requestType is the ordinal value of {@link PowerRequestType}\n * @return true on success\n */\n boolean PowerSetRequest(HANDLE powerRequestHandle, int requestType);\n\n /**\n * @param powerRequestHandle the handle returned by {@link #PowerCreateRequest(REASON_CONTEXT.ByReference)}\n * @param requestType requestType is the ordinal value of {@link PowerRequestType}\n * @return true on success\n */\n boolean PowerClearRequest(HANDLE powerRequestHandle, int requestType);\n\n enum PowerRequestType\n {\n PowerRequestDisplayRequired,\n PowerRequestSystemRequired,\n PowerRequestAwayModeRequired,\n PowerRequestMaximum\n }\n }\n\n private final Kernel32 kernel32;\n private HANDLE handle = null;\n\n PowerManagement()\n {\n // Found in winnt.h\n ULONG POWER_REQUEST_CONTEXT_VERSION = new ULONG(0);\n DWORD POWER_REQUEST_CONTEXT_SIMPLE_STRING = new DWORD(0x1);\n\n kernel32 = Native.load("kernel32", Kernel32.class);\n REASON_CONTEXT.ByReference context = new REASON_CONTEXT.ByReference();\n context.version = POWER_REQUEST_CONTEXT_VERSION;\n context.flags = POWER_REQUEST_CONTEXT_SIMPLE_STRING;\n context.simpleReasonString = new LPWSTR("Your reason for changing the power setting");\n handle = kernel32.PowerCreateRequest(context);\n if (handle == WinBase.INVALID_HANDLE_VALUE)\n throw new AssertionError(Native.getLastError());\n }\n\n /**\n * Prevent the computer from going to sleep while the application is running.\n */\n public void preventSleep()\n {\n if (!kernel32.PowerSetRequest(handle, Kernel32.PowerRequestType.PowerRequestSystemRequired.ordinal()))\n throw new AssertionError("PowerSetRequest() failed");\n }\n\n /**\n * Allow the computer to go to sleep.\n */\n public void allowSleep()\n {\n if (!kernel32.PowerClearRequest(handle, Kernel32.PowerRequestType.PowerRequestSystemRequired.ordinal()))\n throw new AssertionError("PowerClearRequest() failed");\n }\n}\n</code></pre>\n<p>Then when the user runs <code>powercfg /requests</code> they see:</p>\n<pre><code>SYSTEM:\n[PROCESS] \\Device\\HarddiskVolume1\\Users\\Gili\\.jdks\\openjdk-15.0.2\\bin\\java.exe\nYour reason for changing the power setting\n</code></pre>\n<p>You should be able to do something similar for macOS and Linux.</p>\n"
},
{
"answer_id": 67442227,
"author": "Douglas Patriarche",
"author_id": 92137,
"author_profile": "https://Stackoverflow.com/users/92137",
"pm_score": 2,
"selected": false,
"text": "<p>To go with the solution provided by user Gili for Windows using JNA, here's the JNA solution for MacOS.</p>\n<p>First, the JNA library interface:</p>\n<pre><code>import com.sun.jna.Library;\nimport com.sun.jna.Native;\nimport com.sun.jna.platform.mac.CoreFoundation;\nimport com.sun.jna.ptr.IntByReference;\n\npublic interface ExampleIOKit extends Library {\n ExampleIOKit INSTANCE = Native.load("IOKit", ExampleIOKit.class);\n\n CoreFoundation.CFStringRef kIOPMAssertPreventUserIdleSystemSleep = CoreFoundation.CFStringRef.createCFString("PreventUserIdleSystemSleep");\n CoreFoundation.CFStringRef kIOPMAssertPreventUserIdleDisplaySleep = CoreFoundation.CFStringRef.createCFString("PreventUserIdleDisplaySleep");\n\n int kIOReturnSuccess = 0;\n\n int kIOPMAssertionLevelOff = 0;\n int kIOPMAssertionLevelOn = 255;\n\n int IOPMAssertionCreateWithName(CoreFoundation.CFStringRef assertionType,\n int assertionLevel,\n CoreFoundation.CFStringRef reasonForActivity,\n IntByReference assertionId);\n\n int IOPMAssertionRelease(int assertionId);\n}\n</code></pre>\n<p>Here's an example of invoking the JNA method to turn sleep prevention on or off:</p>\n<pre><code>public class Example {\n private static final Logger _log = LoggerFactory.getLogger(Example.class);\n\n private int sleepPreventionAssertionId = 0;\n\n public void updateSleepPrevention(final boolean isEnabled) {\n if (isEnabled) {\n if (sleepPreventionAssertionId == 0) {\n final var assertionIdRef = new IntByReference(0);\n final var reason = CoreFoundation.CFStringRef.createCFString(\n "Example preventing display sleep");\n final int result = ExampleIOKit.INSTANCE.IOPMAssertionCreateWithName(\n ExampleIOKit.kIOPMAssertPreventUserIdleDisplaySleep,\n ExampleIOKit.kIOPMAssertionLevelOn, reason, assertionIdRef);\n if (result == ExampleIOKit.kIOReturnSuccess) {\n _log.info("Display sleep prevention enabled");\n sleepPreventionAssertionId = assertionIdRef.getValue();\n }\n else {\n _log.error("IOPMAssertionCreateWithName returned {}", result);\n }\n }\n }\n else {\n if (sleepPreventionAssertionId != 0) {\n final int result = ExampleIOKit.INSTANCE.IOPMAssertionRelease(sleepPreventionAssertionId);\n if (result == ExampleIOKit.kIOReturnSuccess) {\n _log.info("Display sleep prevention disabled");\n }\n else {\n _log.error("IOPMAssertionRelease returned {}", result);\n }\n sleepPreventionAssertionId = 0;\n }\n }\n }\n}\n</code></pre>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] | I have a piece of server-ish software written in Java to run on Windows and OS X. (It is not running on a server, but just a normal user's PC - something like a torrent client.) I would like the software to signal to the OS to keep the machine awake (prevent it from going into sleep mode) while it is active.
Of course I don't expect there to be a cross platform solution, but I would love to have some very minimal C programs/scripts that my app can spawn to inform the OS to stay awake.
Any ideas? | I use this code to keep my workstation from locking. It's currently only set to move the mouse once every minute, you could easily adjust it though.
It's a hack, not an elegant solution.
```
import java.awt.*;
import java.util.*;
public class Hal{
public static void main(String[] args) throws Exception{
Robot hal = new Robot();
Random random = new Random();
while(true){
hal.delay(1000 * 60);
int x = random.nextInt() % 640;
int y = random.nextInt() % 480;
hal.mouseMove(x,y);
}
}
}
``` |
52,880 | <p>Does Google Reader have an API and if so, how can I get the count of the number of unread posts for a specific user knowing their username and password?</p>
| [
{
"answer_id": 52886,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 4,
"selected": false,
"text": "<p>It is <a href=\"http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI\" rel=\"nofollow noreferrer\">there</a>. Still in Beta though.</p>\n"
},
{
"answer_id": 582108,
"author": "jimmyorr",
"author_id": 19239,
"author_profile": "https://Stackoverflow.com/users/19239",
"pm_score": 7,
"selected": true,
"text": "<p>This URL will give you a count of unread posts per feed. You can then iterate over the feeds and sum up the counts.</p>\n\n<p><a href=\"http://www.google.com/reader/api/0/unread-count?all=true\" rel=\"nofollow noreferrer\">http://www.google.com/reader/api/0/unread-count?all=true</a></p>\n\n<p>Here is a minimalist example in Python...parsing the xml/json and summing the counts is left as an exercise for the reader:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import urllib\nimport urllib2\n\nusername = 'username@gmail.com'\npassword = '******'\n\n# Authenticate to obtain SID\nauth_url = 'https://www.google.com/accounts/ClientLogin'\nauth_req_data = urllib.urlencode({'Email': username,\n 'Passwd': password,\n 'service': 'reader'})\nauth_req = urllib2.Request(auth_url, data=auth_req_data)\nauth_resp = urllib2.urlopen(auth_req)\nauth_resp_content = auth_resp.read()\nauth_resp_dict = dict(x.split('=') for x in auth_resp_content.split('\\n') if x)\nauth_token = auth_resp_dict[\"Auth\"]\n\n# Create a cookie in the header using the SID \nheader = {}\nheader['Authorization'] = 'GoogleLogin auth=%s' % auth_token\n\nreader_base_url = 'http://www.google.com/reader/api/0/unread-count?%s'\nreader_req_data = urllib.urlencode({'all': 'true',\n 'output': 'xml'})\nreader_url = reader_base_url % (reader_req_data)\nreader_req = urllib2.Request(reader_url, None, header)\nreader_resp = urllib2.urlopen(reader_req)\nreader_resp_content = reader_resp.read()\n\nprint reader_resp_content\n</code></pre>\n\n<p>And some additional links on the topic:</p>\n\n<ul>\n<li><a href=\"http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI\" rel=\"nofollow noreferrer\">http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI</a></li>\n<li><a href=\"https://stackoverflow.com/questions/101742/how-do-you-access-an-authenticated-google-app-engine-service-from-a-non-web-pyt\">How do you access an authenticated Google App Engine service from a (non-web) python client?</a></li>\n<li><a href=\"http://blog.gpowered.net/2007/08/google-reader-api-functions.html\" rel=\"nofollow noreferrer\">http://blog.gpowered.net/2007/08/google-reader-api-functions.html</a></li>\n</ul>\n"
},
{
"answer_id": 2594683,
"author": "yassin",
"author_id": 256763,
"author_profile": "https://Stackoverflow.com/users/256763",
"pm_score": 0,
"selected": false,
"text": "<p>In the API posted in [1], the \"token\" field should be \"T\"</p>\n\n<p>[1] <a href=\"http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI\" rel=\"nofollow noreferrer\">http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI</a></p>\n"
},
{
"answer_id": 3517599,
"author": "livibetter",
"author_id": 242583,
"author_profile": "https://Stackoverflow.com/users/242583",
"pm_score": 3,
"selected": false,
"text": "<p>Here is an update to <a href=\"https://stackoverflow.com/questions/52880/google-reader-api-unread-count/582108#582108\">this answer</a></p>\n\n<pre><code>import urllib\nimport urllib2\n\nusername = 'username@gmail.com'\npassword = '******'\n\n# Authenticate to obtain Auth\nauth_url = 'https://www.google.com/accounts/ClientLogin'\n#auth_req_data = urllib.urlencode({'Email': username,\n# 'Passwd': password})\nauth_req_data = urllib.urlencode({'Email': username,\n 'Passwd': password,\n 'service': 'reader'})\nauth_req = urllib2.Request(auth_url, data=auth_req_data)\nauth_resp = urllib2.urlopen(auth_req)\nauth_resp_content = auth_resp.read()\nauth_resp_dict = dict(x.split('=') for x in auth_resp_content.split('\\n') if x)\n# SID = auth_resp_dict[\"SID\"]\nAUTH = auth_resp_dict[\"Auth\"]\n\n# Create a cookie in the header using the Auth\nheader = {}\n#header['Cookie'] = 'Name=SID;SID=%s;Domain=.google.com;Path=/;Expires=160000000000' % SID\nheader['Authorization'] = 'GoogleLogin auth=%s' % AUTH\n\nreader_base_url = 'http://www.google.com/reader/api/0/unread-count?%s'\nreader_req_data = urllib.urlencode({'all': 'true',\n 'output': 'xml'})\nreader_url = reader_base_url % (reader_req_data)\nreader_req = urllib2.Request(reader_url, None, header)\nreader_resp = urllib2.urlopen(reader_req)\nreader_resp_content = reader_resp.read()\n\nprint reader_resp_content\n</code></pre>\n\n<p>Google Reader removed SID auth around June, 2010 (I think), using new Auth from ClientLogin is the new way and it's a bit simpler (header is shorter). You will have to add <code>service</code> in data for requesting <code>Auth</code>, I noticed no <code>Auth</code> returned if you don't send the <code>service=reader</code>.</p>\n\n<p>You can read more about the change of authentication method in <a href=\"http://groups.google.com/group/fougrapi/browse_thread/thread/e331f37f7f126c00/\" rel=\"nofollow noreferrer\">this thread</a>.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | Does Google Reader have an API and if so, how can I get the count of the number of unread posts for a specific user knowing their username and password? | This URL will give you a count of unread posts per feed. You can then iterate over the feeds and sum up the counts.
<http://www.google.com/reader/api/0/unread-count?all=true>
Here is a minimalist example in Python...parsing the xml/json and summing the counts is left as an exercise for the reader:
```py
import urllib
import urllib2
username = 'username@gmail.com'
password = '******'
# Authenticate to obtain SID
auth_url = 'https://www.google.com/accounts/ClientLogin'
auth_req_data = urllib.urlencode({'Email': username,
'Passwd': password,
'service': 'reader'})
auth_req = urllib2.Request(auth_url, data=auth_req_data)
auth_resp = urllib2.urlopen(auth_req)
auth_resp_content = auth_resp.read()
auth_resp_dict = dict(x.split('=') for x in auth_resp_content.split('\n') if x)
auth_token = auth_resp_dict["Auth"]
# Create a cookie in the header using the SID
header = {}
header['Authorization'] = 'GoogleLogin auth=%s' % auth_token
reader_base_url = 'http://www.google.com/reader/api/0/unread-count?%s'
reader_req_data = urllib.urlencode({'all': 'true',
'output': 'xml'})
reader_url = reader_base_url % (reader_req_data)
reader_req = urllib2.Request(reader_url, None, header)
reader_resp = urllib2.urlopen(reader_req)
reader_resp_content = reader_resp.read()
print reader_resp_content
```
And some additional links on the topic:
* <http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI>
* [How do you access an authenticated Google App Engine service from a (non-web) python client?](https://stackoverflow.com/questions/101742/how-do-you-access-an-authenticated-google-app-engine-service-from-a-non-web-pyt)
* <http://blog.gpowered.net/2007/08/google-reader-api-functions.html> |
52,898 | <p>I've noticed that Visual Studio 2008 is placing square brackets around column names in sql. Do the brackets offer any advantage? When I hand code T-SQL I've never bothered with them.</p>
<p>Example:</p>
<p>Visual Studio:</p>
<pre><code>SELECT [column1], [column2] etc...
</code></pre>
<p>My own way:</p>
<pre><code>SELECT column1, column2 etc...
</code></pre>
| [
{
"answer_id": 52900,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 3,
"selected": false,
"text": "<p>The brackets can be used when column names are reserved words.</p>\n\n<p>If you are programatically generating the SQL statement from a collection of column names you don't control, then you can avoid problems by always using the brackets.</p>\n"
},
{
"answer_id": 52901,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 9,
"selected": true,
"text": "<p>The brackets are required if you use keywords or special chars in the column names or identifiers. You could name a column <code>[First Name]</code> (with a space) – but then you'd need to use brackets every time you referred to that column.</p>\n<p>The newer tools add them everywhere just in case or for consistency.</p>\n"
},
{
"answer_id": 52902,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Column names can contain characters and reserved words that will confuse the query execution engine, so placing brackets around them at all times prevents this from happening. Easier than checking for an issue and then dealing with it, I guess.</p>\n"
},
{
"answer_id": 52905,
"author": "Jeff Donnici",
"author_id": 821,
"author_profile": "https://Stackoverflow.com/users/821",
"pm_score": 2,
"selected": false,
"text": "<p>I believe it adds them there for consistency... they're only required when you have a space or special character in the column name, but it's cleaner to just include them all the time when the IDE generates SQL.</p>\n"
},
{
"answer_id": 52910,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 6,
"selected": false,
"text": "<p>They're handy if your columns have the same names as SQL keywords, or have spaces in them.</p>\n\n<p>Example:</p>\n\n<pre><code>create table test ( id int, user varchar(20) )\n</code></pre>\n\n<p>Oh no! Incorrect syntax near the keyword 'user'.\nBut this:</p>\n\n<pre><code>create table test ( id int, [user] varchar(20) )\n</code></pre>\n\n<p>Works fine.</p>\n"
},
{
"answer_id": 52912,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 4,
"selected": false,
"text": "<p>They are useful if you are (for some reason) using column names with certain characters for example.</p>\n\n<pre><code>Select First Name From People\n</code></pre>\n\n<p>would not work, but putting square brackets around the column name would work</p>\n\n<pre><code>Select [First Name] From People\n</code></pre>\n\n<p>In short, it's a way of explicitly declaring a object name; column, table, database, user or server.</p>\n"
},
{
"answer_id": 11163930,
"author": "HSchlarb",
"author_id": 1475915,
"author_profile": "https://Stackoverflow.com/users/1475915",
"pm_score": 2,
"selected": false,
"text": "<p>In addition\nSome Sharepoint databases contain hyphens in their names. Using square brackets in SQL Statements allow the names to be parsed correctly. </p>\n"
},
{
"answer_id": 33579501,
"author": "Bill",
"author_id": 3516476,
"author_profile": "https://Stackoverflow.com/users/3516476",
"pm_score": 3,
"selected": false,
"text": "<p>Regardless of following a naming convention that avoids using reserved words, Microsoft does add new reserved words. Using brackets allows your code to be upgraded to a new SQL Server version, without first needing to edit Microsoft's newly reserved words out of your client code. That editing can be a significant concern. It may cause your project to be prematurely retired....</p>\n\n<p>Brackets can also be useful when you want to Replace All in a script. If your batch contains a variable named @String and a column named [String], you can rename the column to [NewString], without renaming @String to @NewString. </p>\n"
},
{
"answer_id": 37642361,
"author": "Lothar",
"author_id": 155082,
"author_profile": "https://Stackoverflow.com/users/155082",
"pm_score": 3,
"selected": false,
"text": "<p>During the dark ages of SQL in the 1990s it was a good practice as the SQL designers were trying to add each word in the dictionary as keyword for endless avalanche of new features and they called it the SQL3 draft. </p>\n\n<p>So it keeps forward compatibility. </p>\n\n<p>And i found that it has another nice side effect, it helps a lot when you use grep in code reviews and refactoring.</p>\n"
},
{
"answer_id": 65964158,
"author": "zar",
"author_id": 841330,
"author_profile": "https://Stackoverflow.com/users/841330",
"pm_score": 2,
"selected": false,
"text": "<p>They are useful to identify each elements in SQL.</p>\n<p>For example:</p>\n<pre><code>CREATE TABLE SchemaName.TableName (\n</code></pre>\n<p>This would actually create a table by the name <code>SchemaName.TableName</code> under default <code>dbo</code> schema even though the intention might be to create the table inside the <code>SchemaName</code> schema.</p>\n<p>The correct way would be the following:</p>\n<pre><code>CREATE TABLE [SchemaName].[TableName] (\n</code></pre>\n<p>Now it it knows what is the table name and in which schema should it be created in (rightly in the <code>SchemaName</code> schema and not in the default <code>dbo</code> schema)</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5433/"
] | I've noticed that Visual Studio 2008 is placing square brackets around column names in sql. Do the brackets offer any advantage? When I hand code T-SQL I've never bothered with them.
Example:
Visual Studio:
```
SELECT [column1], [column2] etc...
```
My own way:
```
SELECT column1, column2 etc...
``` | The brackets are required if you use keywords or special chars in the column names or identifiers. You could name a column `[First Name]` (with a space) – but then you'd need to use brackets every time you referred to that column.
The newer tools add them everywhere just in case or for consistency. |
52,927 | <p>I frequently find myself writing code like this:</p>
<pre><code>List<int> list = new List<int> { 1, 3, 5 };
foreach (int i in list) {
Console.Write("{0}\t", i.ToString()); }
Console.WriteLine();
</code></pre>
<p>Better would be something like this:</p>
<pre><code>List<int> list = new List<int> { 1, 3, 5 };
Console.WriteLine("{0}\t", list);
</code></pre>
<p>I suspect there's some clever way of doing this, but I don't see it. Does anybody have a better solution than the first block? </p>
| [
{
"answer_id": 52940,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 8,
"selected": true,
"text": "<p>Do this:</p>\n\n<pre><code>list.ForEach(i => Console.Write(\"{0}\\t\", i));\n</code></pre>\n\n<hr>\n\n<p>EDIT: To others that have responded - he wants them all on the same line, with tabs between them. :)</p>\n"
},
{
"answer_id": 52941,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 2,
"selected": false,
"text": "<pre><code> List<int> a = new List<int>() { 1, 2, 3, 4, 5 };\n a.ForEach(p => Console.WriteLine(p));\n</code></pre>\n\n<p>edit: ahhh he beat me to it.</p>\n"
},
{
"answer_id": 52942,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<pre><code>list.ForEach(x=>Console.WriteLine(x));\n</code></pre>\n"
},
{
"answer_id": 52960,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 2,
"selected": false,
"text": "<pre><code>List<int> list = new List<int> { 1, 3, 5 };\nlist.ForEach(x => Console.WriteLine(x));\n</code></pre>\n\n<p>Edit: Dammit! took too long to open visual studio to test it.</p>\n"
},
{
"answer_id": 52972,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": false,
"text": "<p>A different approach, just for kicks:</p>\n\n<pre><code>Console.WriteLine(string.Join(\"\\t\", list));\n</code></pre>\n"
},
{
"answer_id": 65692,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public static void WriteLine(this List<int> theList)\n{\n foreach (int i in list)\n {\n Console.Write(\"{0}\\t\", t.ToString());\n }\n Console.WriteLine();\n}\n</code></pre>\n\n<p>Then, later...</p>\n\n<pre><code>list.WriteLine();\n</code></pre>\n"
},
{
"answer_id": 767963,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>new List<int> { 1, 3, 5 }.ForEach(Console.WriteLine);\n</code></pre>\n"
},
{
"answer_id": 949955,
"author": "Ed Sykes",
"author_id": 98551,
"author_profile": "https://Stackoverflow.com/users/98551",
"pm_score": 2,
"selected": false,
"text": "<p>If there is a piece of code that you repeat all the time according to Don't Repeat Yourself you should put it in your own library and call that. With that in mind there are 2 aspects to getting the right answer here. The first is clarity and brevity in the code that calls the library function. The second is the performance implications of foreach. </p>\n\n<p>First let's think about the clarity and brevity in the calling code. </p>\n\n<p>You can do foreach in a number of ways:</p>\n\n<ol>\n<li>for loop</li>\n<li>foreach loop</li>\n<li>Collection.ForEach</li>\n</ol>\n\n<p>Out of all the ways to do a foreach List.ForEach with a lamba is the clearest and briefest.</p>\n\n<pre><code>list.ForEach(i => Console.Write(\"{0}\\t\", i));\n</code></pre>\n\n<p>So at this stage it may look like the List.ForEach is the way to go. However what's the performance of this? It's true that in this case the time to write to the console will govern the performance of the code. When we know something about performance of a particular language feature we should certainly at least consider it.</p>\n\n<p>According to <a href=\"http://diditwith.net/2006/10/05/PerformanceOfForeachVsListForEach.aspx\" rel=\"nofollow noreferrer\">Duston Campbell's performance measurements of foreach</a> the fastest way of iterating the list under optimised code is using a for loop without a call to List.Count.</p>\n\n<p>The for loop however is a verbose construct. It's also seen as a very iterative way of doing things which doesn't match with the current trend towards functional idioms.</p>\n\n<p>So can we get brevity, clarity and performance? We can by using an extension method. In an ideal world we would create an extension method on Console that takes a list and writes it with a delimiter. We can't do this because Console is a static class and extension methods only work on instances of classes. Instead we need to put the extension method on the list itself (as per David B's suggestion):</p>\n\n<pre><code>public static void WriteLine(this List<int> theList)\n{\n foreach (int i in list)\n {\n Console.Write(\"{0}\\t\", t.ToString());\n }\n Console.WriteLine();\n}\n</code></pre>\n\n<p>This code is going to used in many places so we should carry out the following improvements:</p>\n\n<ul>\n<li>Instead of using foreach we should use the fastest way of iterating the collection which is a for loop with a cached count. </li>\n<li>Currently only List can be passed as an argument. As a library function we can generalise it through a small amount of effort. </li>\n<li>Using List limits us to just Lists, Using IList allows this code to work with Arrays too.</li>\n<li>Since the extension method will be on an IList we need to change the name to make it clearer what we are writing to:</li>\n</ul>\n\n<p>Here's how the code for the function would look:</p>\n\n<pre><code>public static void WriteToConsole<T>(this IList<T> collection)\n{\n int count = collection.Count();\n for(int i = 0; i < count; ++i)\n {\n Console.Write(\"{0}\\t\", collection[i].ToString(), delimiter);\n }\n Console.WriteLine();\n}\n</code></pre>\n\n<p>We can improve this even further by allowing the client to pass in the delimiter. We could then provide a second function that writes to console with the standard delimiter like this:</p>\n\n<pre><code>public static void WriteToConsole<T>(this IList<T> collection)\n{\n WriteToConsole<T>(collection, \"\\t\");\n}\n\npublic static void WriteToConsole<T>(this IList<T> collection, string delimiter)\n{\n int count = collection.Count();\n for(int i = 0; i < count; ++i)\n {\n Console.Write(\"{0}{1}\", collection[i].ToString(), delimiter);\n }\n Console.WriteLine();\n}\n</code></pre>\n\n<p>So now, given that we want a brief, clear performant way of writing lists to the console we have one. Here is entire source code including a demonstration of using the the library function:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ConsoleWritelineTest\n{\n public static class Extensions\n {\n public static void WriteToConsole<T>(this IList<T> collection)\n {\n WriteToConsole<T>(collection, \"\\t\");\n }\n\n public static void WriteToConsole<T>(this IList<T> collection, string delimiter)\n {\n int count = collection.Count();\n for(int i = 0; i < count; ++i)\n {\n Console.Write(\"{0}{1}\", collection[i].ToString(), delimiter);\n }\n Console.WriteLine();\n }\n }\n\n internal class Foo\n {\n override public string ToString()\n {\n return \"FooClass\";\n }\n }\n\n internal class Program\n {\n\n static void Main(string[] args)\n {\n var myIntList = new List<int> {1, 2, 3, 4, 5};\n var myDoubleList = new List<double> {1.1, 2.2, 3.3, 4.4};\n var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};\n var myFooList = new List<Foo> {new Foo(), new Foo(), new Foo()};\n // Using the standard delimiter /t\n myIntList.WriteToConsole();\n myDoubleList.WriteToConsole();\n myDoubleArray.WriteToConsole();\n myFooList.WriteToConsole();\n // Using our own delimiter ~\n myIntList.WriteToConsole(\"~\");\n Console.Read();\n }\n }\n}\n</code></pre>\n\n<p>=======================================================</p>\n\n<p>You might think that this should be the end of the answer. However there is a further piece of generalisation that can be done. It's not clear from fatcat's question if he is always writing to the console. Perhaps something else is to be done in the foreach. In that case Jason Bunting's answer is going to give that generality. Here is his answer again:</p>\n\n<pre><code>list.ForEach(i => Console.Write(\"{0}\\t\", i));\n</code></pre>\n\n<p>That is unless we make one more refinement to our extension methods and add FastForEach as below:</p>\n\n<pre><code>public static void FastForEach<T>(this IList<T> collection, Action<T> actionToPerform)\n {\n int count = collection.Count();\n for (int i = 0; i < count; ++i)\n {\n actionToPerform(collection[i]); \n }\n Console.WriteLine();\n }\n</code></pre>\n\n<p><strong>This allows us to execute any arbitrary code against every element in the collection <em>using the fastest possible iteration method</em>.</strong></p>\n\n<p>We can even change the WriteToConsole function to use FastForEach</p>\n\n<pre><code>public static void WriteToConsole<T>(this IList<T> collection, string delimiter)\n{\n collection.FastForEach(item => Console.Write(\"{0}{1}\", item.ToString(), delimiter));\n}\n</code></pre>\n\n<p>So now the entire source code, including an example usage of FastForEach is:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ConsoleWritelineTest\n{\n public static class Extensions\n {\n public static void WriteToConsole<T>(this IList<T> collection)\n {\n WriteToConsole<T>(collection, \"\\t\");\n }\n\n public static void WriteToConsole<T>(this IList<T> collection, string delimiter)\n {\n collection.FastForEach(item => Console.Write(\"{0}{1}\", item.ToString(), delimiter));\n }\n\n public static void FastForEach<T>(this IList<T> collection, Action<T> actionToPerform)\n {\n int count = collection.Count();\n for (int i = 0; i < count; ++i)\n {\n actionToPerform(collection[i]); \n }\n Console.WriteLine();\n }\n }\n\n internal class Foo\n {\n override public string ToString()\n {\n return \"FooClass\";\n }\n }\n\n internal class Program\n {\n\n static void Main(string[] args)\n {\n var myIntList = new List<int> {1, 2, 3, 4, 5};\n var myDoubleList = new List<double> {1.1, 2.2, 3.3, 4.4};\n var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};\n var myFooList = new List<Foo> {new Foo(), new Foo(), new Foo()};\n\n // Using the standard delimiter /t\n myIntList.WriteToConsole();\n myDoubleList.WriteToConsole();\n myDoubleArray.WriteToConsole();\n myFooList.WriteToConsole();\n\n // Using our own delimiter ~\n myIntList.WriteToConsole(\"~\");\n\n // What if we want to write them to separate lines?\n myIntList.FastForEach(item => Console.WriteLine(item.ToString()));\n Console.Read();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 15260381,
"author": "Lev Lukomsky",
"author_id": 406642,
"author_profile": "https://Stackoverflow.com/users/406642",
"pm_score": 1,
"selected": false,
"text": "<p>Also you can do join:</p>\n\n<pre><code>var qwe = new List<int> {5, 2, 3, 8};\nConsole.WriteLine(string.Join(\"\\t\", qwe));\n</code></pre>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4593/"
] | I frequently find myself writing code like this:
```
List<int> list = new List<int> { 1, 3, 5 };
foreach (int i in list) {
Console.Write("{0}\t", i.ToString()); }
Console.WriteLine();
```
Better would be something like this:
```
List<int> list = new List<int> { 1, 3, 5 };
Console.WriteLine("{0}\t", list);
```
I suspect there's some clever way of doing this, but I don't see it. Does anybody have a better solution than the first block? | Do this:
```
list.ForEach(i => Console.Write("{0}\t", i));
```
---
EDIT: To others that have responded - he wants them all on the same line, with tabs between them. :) |
52,950 | <p>I'm not too sure what is going on here, but sometimes a particular file in my repository will change the case of its name. e.g.,:</p>
<p>before: <code>File.h</code></p>
<p>after: <code>file.h</code></p>
<p>I don't really care why this is happening, but this causes git to think it is a new file, and then I have to go and change the file name back. Can you just make git ignore case changes?</p>
<p><strong>[edit]</strong>
I suspect it is Visual Studio doing something weird with that particular file, because it seems to happen most often when I open and save it after changes. I don't have any way to fix bugs in VS however, but git should be a bit more capable I hope.</p>
| [
{
"answer_id": 53116,
"author": "MarkB",
"author_id": 2996,
"author_profile": "https://Stackoverflow.com/users/2996",
"pm_score": 9,
"selected": true,
"text": "<p>Since version 1.5.6 there is an <code>ignorecase</code> option available in the <code>[core]</code> section of <code>.git/config</code></p>\n\n<p>e.g. add <code>ignorecase = true</code></p>\n\n<p>To change it for just one repo, from that folder run:</p>\n\n<pre><code>git config core.ignorecase true\n</code></pre>\n\n<p>To change it globally: </p>\n\n<pre><code>git config --global core.ignorecase true\n</code></pre>\n"
},
{
"answer_id": 535575,
"author": "John C",
"author_id": 64794,
"author_profile": "https://Stackoverflow.com/users/64794",
"pm_score": 4,
"selected": false,
"text": "<p>In git version 1.6.1.9 for windows I found that \"ignorecase=true' in config was already set by default.</p>\n"
},
{
"answer_id": 8094870,
"author": "akauppi",
"author_id": 14455,
"author_profile": "https://Stackoverflow.com/users/14455",
"pm_score": 3,
"selected": false,
"text": "<p>The situation described in the question is now re-occuring with Mac OS X, git version >= 1.7.4 (I think). The cure is to set your ignorecase=false and rename the lowercased files (that git changed that way, not Visual Studio) back to their UsualCase by hand (i.e. 'mv myname MyName').</p>\n\n<p>More info <a href=\"http://tapestryjava.blogspot.com/2010/07/git-on-mac-os-x-dont-ignore-case.html\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 38288815,
"author": "Andrew Arnott",
"author_id": 46926,
"author_profile": "https://Stackoverflow.com/users/46926",
"pm_score": 4,
"selected": false,
"text": "<p>You can force git to rename the file in a case-only way with this command:</p>\n\n<pre><code>git mv --cached name.txt NAME.TXT\n</code></pre>\n\n<p>Note this doesn't change the case of the file in your checked out copy on a Windows partition, but git records the casing change and you can commit that change. Future checkouts will use the new casing.</p>\n"
},
{
"answer_id": 64270783,
"author": "FoxDeploy",
"author_id": 1238413,
"author_profile": "https://Stackoverflow.com/users/1238413",
"pm_score": 2,
"selected": false,
"text": "<p>To force git to recognize the change of casing to a file, you can run this command.</p>\n<ol>\n<li>Change the File casing however you like</li>\n<li><code>git mv -f mynewapp.sln MyNewApp.sln</code></li>\n</ol>\n<p>The previous command seems to be deprecated now.</p>\n"
},
{
"answer_id": 65411150,
"author": "Mario",
"author_id": 14306183,
"author_profile": "https://Stackoverflow.com/users/14306183",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li>From the console: git config core.ignorecase true</li>\n<li>Change file name capitalisation</li>\n<li>Commit</li>\n<li>From the console: git config core.ignorecase false</li>\n</ol>\n<p>Step 4 fixed problems checking out branches with a different capitalisation.</p>\n"
},
{
"answer_id": 68185614,
"author": "Matthew Barbara",
"author_id": 3861691,
"author_profile": "https://Stackoverflow.com/users/3861691",
"pm_score": 0,
"selected": false,
"text": "<p><code>git mv FileName fileNameTemp</code></p>\n<p>then</p>\n<p><code>git mv fileNameTemp fileName</code></p>\n<p>will solve your problem without the need to commit.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
] | I'm not too sure what is going on here, but sometimes a particular file in my repository will change the case of its name. e.g.,:
before: `File.h`
after: `file.h`
I don't really care why this is happening, but this causes git to think it is a new file, and then I have to go and change the file name back. Can you just make git ignore case changes?
**[edit]**
I suspect it is Visual Studio doing something weird with that particular file, because it seems to happen most often when I open and save it after changes. I don't have any way to fix bugs in VS however, but git should be a bit more capable I hope. | Since version 1.5.6 there is an `ignorecase` option available in the `[core]` section of `.git/config`
e.g. add `ignorecase = true`
To change it for just one repo, from that folder run:
```
git config core.ignorecase true
```
To change it globally:
```
git config --global core.ignorecase true
``` |
52,952 | <p>So I'm using an IDataReader to hydrate some business objects, but I don't know at runtime exactly what fields will be in the reader. Any fields that aren't in the reader would be left null on the resulting object. How do you test if a reader contains a specific field without just wrapping it in a try/catch?</p>
| [
{
"answer_id": 299772,
"author": "adparadox",
"author_id": 1962,
"author_profile": "https://Stackoverflow.com/users/1962",
"pm_score": -1,
"selected": false,
"text": "<p>You can't just test reader[\"field\"] for null or DBNull because a IndexOutOfRangeException is thrown if the column isn't in the reader.</p>\n\n<p>The code I use in my mapping layer for creating domain objects and the stored procedures that use the mapping layer might have different column names is below; you could modify it to not throw an exception if the column isn't found and return default(t) or null.</p>\n\n<p>I understand this isn't the most elegant or optimal solution (and really, if you can avoid it then you should), however, legacy stored procedures or Sql queries might warrant a work-around.</p>\n\n<pre><code> /// <summary>\n /// Grabs the value from a specific datareader for a list of column names.\n /// </summary>\n /// <typeparam name=\"T\">Type of the value.</typeparam>\n /// <param name=\"reader\">Reader to grab data off of.</param>\n /// <param name=\"columnNames\">Column names that should be interrogated.</param>\n /// <returns>Value from the first correct column name or an exception if none of the columns exist.</returns>\n public static T GetColumnValue<T>(IDataReader reader, params string[] columnNames)\n {\n bool foundValue = false;\n T value = default(T);\n IndexOutOfRangeException lastException = null;\n\n foreach (string columnName in columnNames)\n {\n try\n {\n int ordinal = reader.GetOrdinal(columnName);\n value = (T)reader.GetValue(ordinal);\n foundValue = true;\n }\n catch (IndexOutOfRangeException ex)\n {\n lastException = ex;\n }\n }\n\n if (!foundValue)\n {\n string message = string.Format(\"Column(s) {0} could not be not found.\",\n string.Join(\", \", columnNames));\n\n throw new IndexOutOfRangeException(message, lastException);\n }\n\n return value;\n }\n</code></pre>\n"
},
{
"answer_id": 299789,
"author": "Craig Wilson",
"author_id": 25333,
"author_profile": "https://Stackoverflow.com/users/25333",
"pm_score": -1,
"selected": false,
"text": "<p>While I disagree with this approach (I think when accessing data, you should know the shape before hand), I understand that there are exceptions.</p>\n\n<p>You could always load up a datatable with the reader and then iterate through it. You can then check to see if the column exists. This will be less performant, but you won't need try/catch blocks (so maybe it is more performant for your needs).</p>\n"
},
{
"answer_id": 1271870,
"author": "mrrrk",
"author_id": 155791,
"author_profile": "https://Stackoverflow.com/users/155791",
"pm_score": 3,
"selected": false,
"text": "<p>This should do the trick:</p>\n\n<pre><code> Public Shared Function ReaderContainsColumn(ByVal reader As IDataReader, ByVal name As String) As Boolean\n For i As Integer = 0 To reader.FieldCount - 1\n If reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase) Then Return True\n Next\n Return False\n End Function\n</code></pre>\n\n<p>or (in C#)</p>\n\n<pre><code>public static bool ReaderContainsColumn(IDataReader reader, string name)\n{\n for (int i = 0; i < reader.FieldCount; i++) {\n if (reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase)) return true; \n }\n return false;\n}\n</code></pre>\n\n<p>:o)</p>\n"
},
{
"answer_id": 1271929,
"author": "Tadmas",
"author_id": 3750,
"author_profile": "https://Stackoverflow.com/users/3750",
"pm_score": 3,
"selected": false,
"text": "<p>You can also use <code>IDataReader.GetSchemaTable</code> to get a list of all the columns in the reader.</p>\n\n<p><a href=\"http://support.microsoft.com/kb/310107\" rel=\"noreferrer\">http://support.microsoft.com/kb/310107</a></p>\n"
},
{
"answer_id": 1271952,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 0,
"selected": false,
"text": "<p>The best solution I've used is doing it like this:</p>\n\n<pre><code>DataTable dataTable = new DataTable();\ndataTable.Load(reader);\nforeach (var item in dataTable.Rows) \n{\n bool columnExists = item.Table.Columns.Contains(\"ColumnName\");\n}\n</code></pre>\n\n<p>Trying to access it through <em>reader[\"ColumnName\"]</em> and checking for null or DBNull will throw an exception.</p>\n"
},
{
"answer_id": 22367187,
"author": "Clement",
"author_id": 552183,
"author_profile": "https://Stackoverflow.com/users/552183",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Enumerable.Range(0, reader.FieldCount).Any(i => reader.GetName(i) == \"ColumnName\")\n</code></pre>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] | So I'm using an IDataReader to hydrate some business objects, but I don't know at runtime exactly what fields will be in the reader. Any fields that aren't in the reader would be left null on the resulting object. How do you test if a reader contains a specific field without just wrapping it in a try/catch? | This should do the trick:
```
Public Shared Function ReaderContainsColumn(ByVal reader As IDataReader, ByVal name As String) As Boolean
For i As Integer = 0 To reader.FieldCount - 1
If reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase) Then Return True
Next
Return False
End Function
```
or (in C#)
```
public static bool ReaderContainsColumn(IDataReader reader, string name)
{
for (int i = 0; i < reader.FieldCount; i++) {
if (reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase)) return true;
}
return false;
}
```
:o) |
52,954 | <p>Right now my ant task looks like.</p>
<pre><code><javadoc sourcepath="${source}" destdir="${doc}">
<link href="http://java.sun.com/j2se/1.5.0/docs/api/" />
</javadoc>
</code></pre>
<p>And I'm getting this warning:</p>
<pre><code>javadoc: warning - Error fetching URL: http://java.sun.com/j2se/1.5.0/docs/api/package-list
</code></pre>
<p>How do I get the javadoc to properly link to the API? I am behind a proxy.</p>
| [
{
"answer_id": 52973,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 4,
"selected": true,
"text": "<p>You probably need the <a href=\"http://java.sun.com/j2se/1.4.2/docs/guide/net/properties.html\" rel=\"noreferrer\">http.proxyHost and http.proxyPort system properties</a> set. For example, <code>ANT_OPTS=\"-Dhttp.proxyHost=proxy.y.com\" ant doc</code></p>\n\n<p>Alternatively, you could set the \"offline\" flag and provide a package list, but that could be a pain for the Java core.</p>\n"
},
{
"answer_id": 54281,
"author": "Rob Spieldenner",
"author_id": 5118,
"author_profile": "https://Stackoverflow.com/users/5118",
"pm_score": 4,
"selected": false,
"text": "<p>You can also pass the arguments inside the ant task</p>\n\n<pre><code><arg value=\"-J-Dhttp.proxyHost=your.proxy.here\"/>\n<arg value=\"-J-Dhttp.proxyPort=##\"/>\n</code></pre>\n\n<p>If going the offline link route. Download the package list by going to the URL of the Java API (<a href=\"http://java.sun.com/j2se/1.5.0/docs/api/package-list\" rel=\"noreferrer\">http://java.sun.com/j2se/1.5.0/docs/api/package-list</a>) and saving it as a text file and then using this Ant task.</p>\n\n<pre><code><javadoc sourcepath=\"${source}\" destdir=\"${doc}\">\n <link offline=\"true\" href=\"http://java.sun.com/j2se/1.5.0/docs/api/\" packagelistloc=\"path-containing-package-list\"/>\n</javadoc>\n</code></pre>\n"
},
{
"answer_id": 27277943,
"author": "Patrice M.",
"author_id": 366749,
"author_profile": "https://Stackoverflow.com/users/366749",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use the \"offline\" mode that allows you to build (faster!) without accessing the internet. Please see this answer: <a href=\"https://stackoverflow.com/a/24089805/366749\">https://stackoverflow.com/a/24089805/366749</a></p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5118/"
] | Right now my ant task looks like.
```
<javadoc sourcepath="${source}" destdir="${doc}">
<link href="http://java.sun.com/j2se/1.5.0/docs/api/" />
</javadoc>
```
And I'm getting this warning:
```
javadoc: warning - Error fetching URL: http://java.sun.com/j2se/1.5.0/docs/api/package-list
```
How do I get the javadoc to properly link to the API? I am behind a proxy. | You probably need the [http.proxyHost and http.proxyPort system properties](http://java.sun.com/j2se/1.4.2/docs/guide/net/properties.html) set. For example, `ANT_OPTS="-Dhttp.proxyHost=proxy.y.com" ant doc`
Alternatively, you could set the "offline" flag and provide a package list, but that could be a pain for the Java core. |
52,964 | <p>What is the best way to sort the results of a sql query into a random order within a stored procedure?</p>
| [
{
"answer_id": 52976,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 4,
"selected": false,
"text": "<pre><code>select foo from Bar order by newid()\n</code></pre>\n"
},
{
"answer_id": 52982,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 2,
"selected": false,
"text": "<p>You can't just ORDER BY RAND(), as you know, because it will only generate one value. So use a key for a seed value.</p>\n\n<pre>\nSELECT RAND(object_id), object_id, name\n FROM sys.objects\n ORDER BY 1\n</pre>\n"
},
{
"answer_id": 52988,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 7,
"selected": true,
"text": "<p>This is a duplicate of <a href=\"https://stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sql\">SO# 19412</a>. Here's the answer I gave there:</p>\n\n<pre><code>select top 1 * from mytable order by newid()\n</code></pre>\n\n<p>In SQL Server 2005 and up, you can use TABLESAMPLE to get a random sample that's repeatable:</p>\n\n<pre><code>SELECT FirstName, LastName FROM Contact TABLESAMPLE (1 ROWS) ;\n</code></pre>\n"
},
{
"answer_id": 3942379,
"author": "endo64",
"author_id": 333153,
"author_profile": "https://Stackoverflow.com/users/333153",
"pm_score": 3,
"selected": false,
"text": "<p>Or use the following query, which returns a better random sample result:</p>\n\n<pre><code>SELECT * FROM a_table WHERE 0.01 >= CAST(CHECKSUM(NEWID(), a_column) & 0x7fffffff AS float) / CAST (0x7fffffff AS int)\n</code></pre>\n\n<p>0.01 means ~1 percent of total rows.</p>\n\n<p>Quote from SQL 2008 Books Online:</p>\n\n<blockquote>\n <p>If you really want a random sample of\n individual rows, modify your query to\n filter out rows randomly, instead of\n using TABLESAMPLE.</p>\n</blockquote>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5466/"
] | What is the best way to sort the results of a sql query into a random order within a stored procedure? | This is a duplicate of [SO# 19412](https://stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sql). Here's the answer I gave there:
```
select top 1 * from mytable order by newid()
```
In SQL Server 2005 and up, you can use TABLESAMPLE to get a random sample that's repeatable:
```
SELECT FirstName, LastName FROM Contact TABLESAMPLE (1 ROWS) ;
``` |
52,981 | <p>So, I have 2 database instances, one is for development in general, another was copied from development for unit tests.</p>
<p>Something changed in the development database that I can't figure out, and I don't know how to see what is different.</p>
<p>When I try to delete from a particular table, with for example:</p>
<pre><code>delete from myschema.mytable where id = 555
</code></pre>
<p>I get the following normal response from the unit test DB indicating no row was deleted:</p>
<blockquote>
<p>SQL0100W No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table. SQLSTATE=02000</p>
</blockquote>
<p>However, the development database fails to delete at all with the following error:</p>
<blockquote>
<p>DB21034E The command was processed as an SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: SQL0440N No authorized routine named "=" of type "FUNCTION" having compatible arguments was found. SQLSTATE=42884</p>
</blockquote>
<p>My best guess is there is some trigger or view that was added or changed that is causing the problem, but I have no idea how to go about finding the problem... has anyone had this problem or know how to figure out what the root of the problem is?</p>
<p>(note that this is a DB2 database)</p>
| [
{
"answer_id": 53000,
"author": "w4ik",
"author_id": 4232,
"author_profile": "https://Stackoverflow.com/users/4232",
"pm_score": 0,
"selected": false,
"text": "<p>You might have an open transaction on the dev db...that gets me sometimes on SQL Server</p>\n"
},
{
"answer_id": 53015,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 0,
"selected": false,
"text": "<p>Is the type of id compatible with 555? Or has it been changed to a non-integer type?</p>\n\n<p>Alternatively, does the 555 argument somehow go missing (e.g. if you are using JDBC and the prepared statement did not get its arguments set before executing the query)?</p>\n"
},
{
"answer_id": 53169,
"author": "castaway",
"author_id": 4840,
"author_profile": "https://Stackoverflow.com/users/4840",
"pm_score": 0,
"selected": false,
"text": "<p>Can you add more to your question? That error sounds like the sql statement parser is very confused about your statement. Can you do a select on that table for the row where id = 555 ? </p>\n\n<p>You could try running a RUNSTATS and REORG TABLE on that table, those are supposed to sort out wonky tables.</p>\n"
},
{
"answer_id": 53192,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/52981/cannot-delete-from-the-database#53169\">@castaway</a></p>\n\n<p>A select with the same \"where\" condition works just fine, just not delete. Neither runstats nor reorg table have any affect on the problem.</p>\n"
},
{
"answer_id": 53231,
"author": "castaway",
"author_id": 4840,
"author_profile": "https://Stackoverflow.com/users/4840",
"pm_score": 2,
"selected": true,
"text": "<p>Hmm, applying the great oracle to this question, I came up with:</p>\n\n<p><a href=\"http://bytes.com/forum/thread830774.html\" rel=\"nofollow noreferrer\">http://bytes.com/forum/thread830774.html</a></p>\n\n<p>It seems to suggest that another table has a foreign key pointing at the problematic one, when that FK on the other table is dropped, the delete should work again. (Presumably you can re-create the foreign key as well)</p>\n\n<p>Does that help any?</p>\n"
},
{
"answer_id": 53241,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/52981/cannot-delete-from-the-database#53231\">@castaway</a></p>\n\n<p>We actually just solved the problem, and indeed it is just what you said (a coworker found that exact same page too).</p>\n\n<p>The solution was to drop foreign key constraints and re-add them.</p>\n\n<p>Another post on the subject:</p>\n\n<p><a href=\"http://www.ibm.com/developerworks/forums/thread.jspa?threadID=208277&tstart=-1\" rel=\"nofollow noreferrer\">http://www.ibm.com/developerworks/forums/thread.jspa?threadID=208277&tstart=-1</a></p>\n\n<p>Which indicates that the problem is a referential constraint corruption, and is actually, or supposedly anyways, fixed in a later version of db2 V9 (which we are not yet using).</p>\n\n<p>Thanks for the help!</p>\n"
},
{
"answer_id": 163347,
"author": "Fuangwith S.",
"author_id": 24550,
"author_profile": "https://Stackoverflow.com/users/24550",
"pm_score": 0,
"selected": false,
"text": "<p>Please check \n1. your arguments of triggers, procedure, functions and etc.\n2. datatype of arguments.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | So, I have 2 database instances, one is for development in general, another was copied from development for unit tests.
Something changed in the development database that I can't figure out, and I don't know how to see what is different.
When I try to delete from a particular table, with for example:
```
delete from myschema.mytable where id = 555
```
I get the following normal response from the unit test DB indicating no row was deleted:
>
> SQL0100W No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table. SQLSTATE=02000
>
>
>
However, the development database fails to delete at all with the following error:
>
> DB21034E The command was processed as an SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: SQL0440N No authorized routine named "=" of type "FUNCTION" having compatible arguments was found. SQLSTATE=42884
>
>
>
My best guess is there is some trigger or view that was added or changed that is causing the problem, but I have no idea how to go about finding the problem... has anyone had this problem or know how to figure out what the root of the problem is?
(note that this is a DB2 database) | Hmm, applying the great oracle to this question, I came up with:
<http://bytes.com/forum/thread830774.html>
It seems to suggest that another table has a foreign key pointing at the problematic one, when that FK on the other table is dropped, the delete should work again. (Presumably you can re-create the foreign key as well)
Does that help any? |
52,984 | <p>How do I setup an Ant task to generate <a href="http://emma.sourceforge.net" rel="noreferrer">Emma</a> code coverage reports?</p>
| [
{
"answer_id": 52994,
"author": "Rob Spieldenner",
"author_id": 5118,
"author_profile": "https://Stackoverflow.com/users/5118",
"pm_score": 5,
"selected": true,
"text": "<p>To answer questions about where the source and instrumented directories are (these can be switched to whatever your standard directory structure is):</p>\n\n<pre><code><property file=\"build.properties\" />\n<property name=\"source\" location=\"src/main/java\" />\n<property name=\"test.source\" location=\"src/test/java\" />\n<property name=\"target.dir\" location=\"target\" />\n<property name=\"target\" location=\"${target.dir}/classes\" />\n<property name=\"test.target\" location=\"${target.dir}/test-classes\" />\n<property name=\"instr.target\" location=\"${target.dir}/instr-classes\" />\n</code></pre>\n\n<p>Classpaths:</p>\n\n<pre><code><path id=\"compile.classpath\">\n <fileset dir=\"lib/main\">\n <include name=\"*.jar\" />\n </fileset>\n</path>\n\n<path id=\"test.compile.classpath\">\n <path refid=\"compile.classpath\" />\n <pathelement location=\"lib/test/junit-4.6.jar\" />\n <pathelement location=\"${target}\" />\n</path>\n\n<path id=\"junit.classpath\">\n <path refid=\"test.compile.classpath\" />\n <pathelement location=\"${test.target}\" />\n</path>\n</code></pre>\n\n<p>First you need to setup where Ant can find the Emma libraries:</p>\n\n<pre><code><path id=\"emma.lib\" >\n <pathelement location=\"${emma.dir}/emma.jar\" />\n <pathelement location=\"${emma.dir}/emma_ant.jar\" />\n</path>\n</code></pre>\n\n<p>Then import the task:</p>\n\n<pre><code><taskdef resource=\"emma_ant.properties\" classpathref=\"emma.lib\" />\n</code></pre>\n\n<p>Then instrument the code:</p>\n\n<pre><code><target name=\"coverage.instrumentation\">\n <mkdir dir=\"${instr.target}\"/>\n <mkdir dir=\"${coverage}\"/>\n <emma>\n <instr instrpath=\"${target}\" destdir=\"${instr.target}\" metadatafile=\"${coverage}/metadata.emma\" mode=\"copy\">\n <filter excludes=\"*Test*\"/>\n </instr>\n </emma>\n <!-- Update the that will run the instrumented code -->\n <path id=\"test.classpath\">\n <pathelement location=\"${instr.target}\"/>\n <path refid=\"junit.classpath\"/>\n <pathelement location=\"${emma.dir}/emma.jar\"/>\n </path>\n</target>\n</code></pre>\n\n<p>Then run a target with the proper VM arguments like:</p>\n\n<pre><code><jvmarg value=\"-Demma.coverage.out.file=${coverage}/coverage.emma\" />\n<jvmarg value=\"-Demma.coverage.out.merge=true\" />\n</code></pre>\n\n<p>Finally generate your report:</p>\n\n<pre><code><target name=\"coverage.report\" depends=\"coverage.instrumentation\">\n <emma>\n <report sourcepath=\"${source}\" depth=\"method\">\n <fileset dir=\"${coverage}\" >\n <include name=\"*.emma\" />\n </fileset>\n <html outfile=\"${coverage}/coverage.html\" />\n </report>\n </emma>\n</target>\n</code></pre>\n"
},
{
"answer_id": 143208,
"author": "wheleph",
"author_id": 15647,
"author_profile": "https://Stackoverflow.com/users/15647",
"pm_score": 0,
"selected": false,
"text": "<p>Emma 2.1 introduces another way of obtaining runtime coverage information (.ec file). One can remotely request the data from the given port of the computer where an instrumented application is runnig. So there's no need to stop VM.</p>\n\n<p>To get the file with runtime coverage data you need to insert the following snippet in your Ant script between running of your tests and generating coverage report:</p>\n\n<pre><code><emma>\n <ctl connect=\"${emma.rt.host}:${emma.rt.port}\" >\n <command name=\"coverage.get\" args=\"${emma.ec.file}\" />\n <command name=\"coverage.reset\" />\n </ctl>\n</emma>\n</code></pre>\n\n<p>Other steps are similar to Emma 2.0. They are perfectly described in <a href=\"https://stackoverflow.com/questions/52984/how-do-i-generate-emma-code-coverage-raeports-using-ant#52994\">previous post</a></p>\n\n<p>More information on Emma 2.1 features: <a href=\"http://sourceforge.net/project/shownotes.php?group_id=108932&release_id=336859\" rel=\"nofollow noreferrer\">http://sourceforge.net/project/shownotes.php?group_id=108932&release_id=336859</a></p>\n"
},
{
"answer_id": 201683,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://emma.sourceforge.net/userguide_single/userguide.html#N10291\" rel=\"nofollow noreferrer\">User Guide has a good example of how to set up your build script</a> so that you not only seperate the instrumented code from the execution, but it's also all contained in the same <code><target></code> so that you don't have to run a series of different targets, but instead you can just do something like <code>ant emma tests</code> (if <code>ant tests</code> was how you normally ran your unit tests, for example).</p>\n\n<p>Here's their example:</p>\n\n<pre><code><target name=\"emma\" description=\"turns on EMMA instrumentation/reporting\" >\n <property name=\"emma.enabled\" value=\"true\" />\n <!-- EMMA instr class output directory: -->\n <property name=\"out.instr.dir\" value=\"${basedir}/outinstr\" />\n <mkdir dir=\"${out.instr.dir}\" />\n</target>\n\n<target name=\"run\" depends=\"init, compile\" description=\"runs the examples\" >\n <emma enabled=\"${emma.enabled}\" >\n <instr instrpathref=\"run.classpath\"\n destdir=\"${out.instr.dir}\" \n metadatafile=\"${coverage.dir}/metadata.emma\"\n merge=\"true\"\n />\n </emma>\n\n <!-- note from matt b: you could just as easily have a <junit> task here! -->\n <java classname=\"Main\" fork=\"true\" >\n <classpath>\n <pathelement location=\"${out.instr.dir}\" />\n <path refid=\"run.classpath\" />\n <path refid=\"emma.lib\" />\n </classpath> \n <jvmarg value=\"-Demma.coverage.out.file=${coverage.dir}/coverage.emma\" />\n <jvmarg value=\"-Demma.coverage.out.merge=true\" />\n </java>\n\n <emma enabled=\"${emma.enabled}\" >\n <report sourcepath=\"${src.dir}\" >\n <fileset dir=\"${coverage.dir}\" >\n <include name=\"*.emma\" />\n </fileset>\n\n <txt outfile=\"${coverage.dir}/coverage.txt\" />\n <html outfile=\"${coverage.dir}/coverage.html\" />\n </report>\n </emma>\n</target>\n</code></pre>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5118/"
] | How do I setup an Ant task to generate [Emma](http://emma.sourceforge.net) code coverage reports? | To answer questions about where the source and instrumented directories are (these can be switched to whatever your standard directory structure is):
```
<property file="build.properties" />
<property name="source" location="src/main/java" />
<property name="test.source" location="src/test/java" />
<property name="target.dir" location="target" />
<property name="target" location="${target.dir}/classes" />
<property name="test.target" location="${target.dir}/test-classes" />
<property name="instr.target" location="${target.dir}/instr-classes" />
```
Classpaths:
```
<path id="compile.classpath">
<fileset dir="lib/main">
<include name="*.jar" />
</fileset>
</path>
<path id="test.compile.classpath">
<path refid="compile.classpath" />
<pathelement location="lib/test/junit-4.6.jar" />
<pathelement location="${target}" />
</path>
<path id="junit.classpath">
<path refid="test.compile.classpath" />
<pathelement location="${test.target}" />
</path>
```
First you need to setup where Ant can find the Emma libraries:
```
<path id="emma.lib" >
<pathelement location="${emma.dir}/emma.jar" />
<pathelement location="${emma.dir}/emma_ant.jar" />
</path>
```
Then import the task:
```
<taskdef resource="emma_ant.properties" classpathref="emma.lib" />
```
Then instrument the code:
```
<target name="coverage.instrumentation">
<mkdir dir="${instr.target}"/>
<mkdir dir="${coverage}"/>
<emma>
<instr instrpath="${target}" destdir="${instr.target}" metadatafile="${coverage}/metadata.emma" mode="copy">
<filter excludes="*Test*"/>
</instr>
</emma>
<!-- Update the that will run the instrumented code -->
<path id="test.classpath">
<pathelement location="${instr.target}"/>
<path refid="junit.classpath"/>
<pathelement location="${emma.dir}/emma.jar"/>
</path>
</target>
```
Then run a target with the proper VM arguments like:
```
<jvmarg value="-Demma.coverage.out.file=${coverage}/coverage.emma" />
<jvmarg value="-Demma.coverage.out.merge=true" />
```
Finally generate your report:
```
<target name="coverage.report" depends="coverage.instrumentation">
<emma>
<report sourcepath="${source}" depth="method">
<fileset dir="${coverage}" >
<include name="*.emma" />
</fileset>
<html outfile="${coverage}/coverage.html" />
</report>
</emma>
</target>
``` |
52,989 | <p>I have a generic Repository<T> class I want to use with an ObjectDataSource. Repository<T> lives in a separate project called DataAccess. According to <a href="http://groups.google.com/group/microsoft.public.dotnet.framework.aspnet/browse_thread/thread/767f1a821d9b23da/b1e045958ae427a5?lnk=st#b1e045958ae427a5" rel="noreferrer">this post from the MS newsgroups</a> (relevant part copied below):</p>
<blockquote>
<p>Internally, the ObjectDataSource is calling Type.GetType(string) to get the
type, so we need to follow the guideline documented in Type.GetType on how
to get type using generics. You can refer to MSDN Library on Type.GetType:</p>
<p><a href="http://msdn2.microsoft.com/en-us/library/w3f99sx1.aspx" rel="noreferrer">http://msdn2.microsoft.com/en-us/library/w3f99sx1.aspx</a></p>
<p>From the document, you will learn that you need to use backtick (`) to
denotes the type name which is using generics.</p>
<p>Also, here we must specify the assembly name in the type name string.</p>
<p>So, for your question, the answer is to use type name like follows:</p>
<p>TypeName="TestObjectDataSourceAssembly.MyDataHandler`1[System.String],TestObjectDataSourceAssembly"</p>
</blockquote>
<p>Okay, makes sense. When I try it, however, the page throws an exception:</p>
<pre><code><asp:ObjectDataSource ID="MyDataSource" TypeName="MyProject.Repository`1[MyProject.MessageCategory],DataAccess" />
</code></pre>
<blockquote>
<p>[InvalidOperationException: The type specified in the TypeName property of ObjectDataSource 'MyDataSource' could not be found.]</p>
</blockquote>
<p>The curious thing is that this only happens when I'm viewing the page. When I open the "Configure Data Source" dialog from the VS2008 designer, it properly shows me the methods on my generic Repository class. Passing the TypeName string to Type.GetType() while debugging also returns a valid type. So what gives?</p>
| [
{
"answer_id": 53106,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 5,
"selected": true,
"text": "<p>Do something like this.</p>\n\n<pre><code>Type type = typeof(Repository<MessageCategory);\nstring assemblyQualifiedName = type.AssemblyQualifiedName;\n</code></pre>\n\n<p>get the value of assemblyQualifiedName and paste it into the TypeName field. Note that Type.GetType(string), the value passed in must be</p>\n\n<blockquote>\n <p>The assembly-qualified name of the type to get. See <a href=\"http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx\" rel=\"noreferrer\">AssemblyQualifiedName</a>. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.</p>\n</blockquote>\n\n<p>So, it may work by passing in that string in your code, because that class is in the currently executing assembly (where you are calling it), where as the ObjectDataSource is not.</p>\n\n<p>Most likely the type you are looking for is </p>\n\n<pre><code>MyProject.Repository`1[MyProject.MessageCategory, DataAccess, Version=1.0.0.0, Culture=neutral, PublicKey=null], DataAccess, Version=1.0.0.0, Culture=neutral, PublicKey=null\n</code></pre>\n"
},
{
"answer_id": 1499638,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Darren,</p>\n\n<p>Many, many thanks for your post. I've been fighting with this all day. Strangely, in my case, I need to double the square brackets, e.g. for your piece of code:</p>\n\n<p>MyProject.Repository`1[[MyProject.MessageCategory, DataAccess, Version=1.0.0.0, Culture=neutral, PublicKey=null]], DataAccess, Version=1.0.0.0, Culture=neutral, PublicKey=null</p>\n\n<p>Roger</p>\n"
},
{
"answer_id": 26492169,
"author": "Philip Johnson",
"author_id": 3365923,
"author_profile": "https://Stackoverflow.com/users/3365923",
"pm_score": 1,
"selected": false,
"text": "<p>I know this is an old post but I have recently had this problem myself. Another solution would be to replace the inheritance with object composition, e.g.</p>\n\n<pre><code>[DataObject]\npublic class DataAccessObject {\n private Repository<MessageCategory> _repository;\n\n // ctor omitted for clarity\n // ...\n\n [DataObjectMethod(DataObjectMethodType.Select)]\n public MessageCategory Get(int key) {\n return _repository.Get(key);\n }\n}\n</code></pre>\n\n<p>This way the ObjectDataSource doesn't know about the repository because its hidden within the class. I have a class library in my facade layer that is a perfectly reasonable place to put this code in the project I am working on.</p>\n\n<p>In addition, if you are using Resharper and interfaces, its possible to get Resharper to do the refactoring using Resharpers \"Implement using field\" function.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/52989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4160/"
] | I have a generic Repository<T> class I want to use with an ObjectDataSource. Repository<T> lives in a separate project called DataAccess. According to [this post from the MS newsgroups](http://groups.google.com/group/microsoft.public.dotnet.framework.aspnet/browse_thread/thread/767f1a821d9b23da/b1e045958ae427a5?lnk=st#b1e045958ae427a5) (relevant part copied below):
>
> Internally, the ObjectDataSource is calling Type.GetType(string) to get the
> type, so we need to follow the guideline documented in Type.GetType on how
> to get type using generics. You can refer to MSDN Library on Type.GetType:
>
>
> <http://msdn2.microsoft.com/en-us/library/w3f99sx1.aspx>
>
>
> From the document, you will learn that you need to use backtick (`) to
> denotes the type name which is using generics.
>
>
> Also, here we must specify the assembly name in the type name string.
>
>
> So, for your question, the answer is to use type name like follows:
>
>
> TypeName="TestObjectDataSourceAssembly.MyDataHandler`1[System.String],TestObjectDataSourceAssembly"
>
>
>
Okay, makes sense. When I try it, however, the page throws an exception:
```
<asp:ObjectDataSource ID="MyDataSource" TypeName="MyProject.Repository`1[MyProject.MessageCategory],DataAccess" />
```
>
> [InvalidOperationException: The type specified in the TypeName property of ObjectDataSource 'MyDataSource' could not be found.]
>
>
>
The curious thing is that this only happens when I'm viewing the page. When I open the "Configure Data Source" dialog from the VS2008 designer, it properly shows me the methods on my generic Repository class. Passing the TypeName string to Type.GetType() while debugging also returns a valid type. So what gives? | Do something like this.
```
Type type = typeof(Repository<MessageCategory);
string assemblyQualifiedName = type.AssemblyQualifiedName;
```
get the value of assemblyQualifiedName and paste it into the TypeName field. Note that Type.GetType(string), the value passed in must be
>
> The assembly-qualified name of the type to get. See [AssemblyQualifiedName](http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx). If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.
>
>
>
So, it may work by passing in that string in your code, because that class is in the currently executing assembly (where you are calling it), where as the ObjectDataSource is not.
Most likely the type you are looking for is
```
MyProject.Repository`1[MyProject.MessageCategory, DataAccess, Version=1.0.0.0, Culture=neutral, PublicKey=null], DataAccess, Version=1.0.0.0, Culture=neutral, PublicKey=null
``` |
53,025 | <p>I've been utilizing the <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="nofollow noreferrer">command pattern</a> in my Flex projects, with asynchronous callback routes required between:</p>
<ul>
<li>whoever instantiated a given command object and the command object,</li>
<li>the command object and the "data access" object (i.e. someone who handles the remote procedure calls over the network to the servers) that the command object calls.</li>
</ul>
<p>Each of these two callback routes has to be able to be a one-to-one relationship. This is due to the fact that I might have several instances of a given command class running the exact same job at the same time but with slightly different parameters, and I don't want their callbacks getting mixed up. Using events, the default way of handling asynchronicity in AS3, is thus pretty much out since they're inherently based on one-to-many relationships.</p>
<p>Currently I have done this using <strong>callback function references</strong> with specific kinds of signatures, but I was wondering <em>if someone knew of a better (or an alternative) way?</em></p>
<p>Here's an example to illustrate my current method:</p>
<ul>
<li>I might have a view object that spawns a <code>DeleteObjectCommand</code> instance due to some user action, passing references to two of its own private member functions (one for success, one for failure: let's say <code>"deleteObjectSuccessHandler()"</code> and <code>"deleteObjectFailureHandler()"</code> in this example) as callback function references to the command class's constructor.</li>
<li>Then the command object would repeat this pattern with its connection to the "data access" object.</li>
<li>When the RPC over the network has successfully been completed (or has failed), the appropriate callback functions are called, first by the "data access" object and then the command object, so that finally the view object that instantiated the operation in the first place gets notified by having its <code>deleteObjectSuccessHandler()</code> or <code>deleteObjectFailureHandler()</code> called.</li>
</ul>
| [
{
"answer_id": 53743,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 1,
"selected": false,
"text": "<p>Many of the Flex RPC classes, like <code>RemoteObject</code>, <code>HTTPService</code>, etc. return <a href=\"http://livedocs.adobe.com/flex/2/langref/mx/rpc/AsyncToken.html\" rel=\"nofollow noreferrer\"><code>AsyncToken</code></a>s when you call them. It sounds like this is what you're after. Basically the <code>AsyncToken</code> encapsulates the pending call, making it possible to register callbacks (in the form of <a href=\"http://livedocs.adobe.com/flex/2/langref/mx/rpc/IResponder.html\" rel=\"nofollow noreferrer\"><code>IResponder</code></a> instances) to a specific call. </p>\n\n<p>In the case of <code>HTTPService</code>, when you call <code>send()</code> an <code>AsyncToken</code> is returned, and you can use this object to track the specific call, unlike the <code>ResultEvent.RESULT</code>, which gets triggered regardless of which call it is (and calls can easily come in in a different order than they were sent).</p>\n"
},
{
"answer_id": 53843,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 3,
"selected": true,
"text": "<p>I'll try one more idea:</p>\n\n<p>Have your Data Access Object return their own AsyncTokens (or some other objects that encapsulate a pending call), instead of the AsyncToken that comes from the RPC call. So, in the DAO it would look something like this (this is very sketchy code):</p>\n\n<pre><code>public function deleteThing( id : String ) : DeferredResponse {\n var deferredResponse : DeferredResponse = new DeferredResponse();\n\n var asyncToken : AsyncToken = theRemoteObject.deleteThing(id);\n\n var result : Function = function( o : Object ) : void {\n deferredResponse.notifyResultListeners(o);\n }\n\n var fault : Function = function( o : Object ) : void {\n deferredResponse.notifyFaultListeners(o);\n }\n\n asyncToken.addResponder(new ClosureResponder(result, fault));\n\n return localAsyncToken;\n}\n</code></pre>\n\n<p>The <code>DeferredResponse</code> and <code>ClosureResponder</code> classes don't exist, of course. Instead of inventing your own you could use <code>AsyncToken</code> instead of <code>DeferredResponse</code>, but the public version of <code>AsyncToken</code> doesn't seem to have any way of triggering the responders, so you would probably have to subclass it anyway. <code>ClosureResponder</code> is just an implementation of <code>IResponder</code> that can call a function on success or failure.</p>\n\n<p>Anyway, the way the code above does it's business is that it calls an RPC service, creates an object encapsulating the pending call, returns that object, and then when the RPC returns, one of the closures <code>result</code> or <code>fault</code> gets called, and since they still have references to the scope as it was when the RPC call was made, they can trigger the methods on the pending call/deferred response.</p>\n\n<p>In the command it would look something like this:</p>\n\n<pre><code>public function execute( ) : void {\n var deferredResponse : DeferredResponse = dao.deleteThing(\"3\");\n\n deferredResponse.addEventListener(ResultEvent.RESULT, onResult);\n deferredResponse.addEventListener(FaultEvent.FAULT, onFault);\n}\n</code></pre>\n\n<p>or, you could repeat the pattern, having the <code>execute</code> method return a deferred response of its own that would get triggered when the deferred response that the command gets from the DAO is triggered.</p>\n\n<p>But. I don't think this is particularly pretty. You could probably do something nicer, less complex and less entangled by using one of the many application frameworks that exist to solve more or less exactly this kind of problem. My suggestion would be <a href=\"http://mate.asfusion.com\" rel=\"nofollow noreferrer\">Mate</a>.</p>\n"
},
{
"answer_id": 2824575,
"author": "nsdevaraj",
"author_id": 339958,
"author_profile": "https://Stackoverflow.com/users/339958",
"pm_score": 0,
"selected": false,
"text": "<p>The AbstractCollection is the best way to deal with Persistent Objects in Flex / AIR. The GenericDAO provides the answer.</p>\n\n<p>DAO is the Object which manages to perform CRUD Operation and other Common\nOperations to be done over a ValueObject ( known as Pojo in Java ).\nGenericDAO is a reusable DAO class which can be used generically.\nGoal:</p>\n\n<p>In JAVA IBM GenericDAO, to add a new DAO, the steps to be done is simply,\nAdd a valueobject (pojo).\nAdd a hbm.xml mapping file for the valueobject.\nAdd the 10-line Spring configuration file for the DAO.</p>\n\n<p>Similarly, in AS3 Project Swiz DAO. We want to attain a similar feet of achievement.</p>\n\n<p>Client Side GenericDAO model:\nAs we were working on a Client Side language, also we should be managing a persistent object Collection (for every valueObject) .\nUsage:\n\nSource: \n<a href=\"http://github.com/nsdevaraj/SwizDAO\" rel=\"nofollow noreferrer\">http://github.com/nsdevaraj/SwizDAO</a></p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/53025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4111/"
] | I've been utilizing the [command pattern](http://en.wikipedia.org/wiki/Command_pattern) in my Flex projects, with asynchronous callback routes required between:
* whoever instantiated a given command object and the command object,
* the command object and the "data access" object (i.e. someone who handles the remote procedure calls over the network to the servers) that the command object calls.
Each of these two callback routes has to be able to be a one-to-one relationship. This is due to the fact that I might have several instances of a given command class running the exact same job at the same time but with slightly different parameters, and I don't want their callbacks getting mixed up. Using events, the default way of handling asynchronicity in AS3, is thus pretty much out since they're inherently based on one-to-many relationships.
Currently I have done this using **callback function references** with specific kinds of signatures, but I was wondering *if someone knew of a better (or an alternative) way?*
Here's an example to illustrate my current method:
* I might have a view object that spawns a `DeleteObjectCommand` instance due to some user action, passing references to two of its own private member functions (one for success, one for failure: let's say `"deleteObjectSuccessHandler()"` and `"deleteObjectFailureHandler()"` in this example) as callback function references to the command class's constructor.
* Then the command object would repeat this pattern with its connection to the "data access" object.
* When the RPC over the network has successfully been completed (or has failed), the appropriate callback functions are called, first by the "data access" object and then the command object, so that finally the view object that instantiated the operation in the first place gets notified by having its `deleteObjectSuccessHandler()` or `deleteObjectFailureHandler()` called. | I'll try one more idea:
Have your Data Access Object return their own AsyncTokens (or some other objects that encapsulate a pending call), instead of the AsyncToken that comes from the RPC call. So, in the DAO it would look something like this (this is very sketchy code):
```
public function deleteThing( id : String ) : DeferredResponse {
var deferredResponse : DeferredResponse = new DeferredResponse();
var asyncToken : AsyncToken = theRemoteObject.deleteThing(id);
var result : Function = function( o : Object ) : void {
deferredResponse.notifyResultListeners(o);
}
var fault : Function = function( o : Object ) : void {
deferredResponse.notifyFaultListeners(o);
}
asyncToken.addResponder(new ClosureResponder(result, fault));
return localAsyncToken;
}
```
The `DeferredResponse` and `ClosureResponder` classes don't exist, of course. Instead of inventing your own you could use `AsyncToken` instead of `DeferredResponse`, but the public version of `AsyncToken` doesn't seem to have any way of triggering the responders, so you would probably have to subclass it anyway. `ClosureResponder` is just an implementation of `IResponder` that can call a function on success or failure.
Anyway, the way the code above does it's business is that it calls an RPC service, creates an object encapsulating the pending call, returns that object, and then when the RPC returns, one of the closures `result` or `fault` gets called, and since they still have references to the scope as it was when the RPC call was made, they can trigger the methods on the pending call/deferred response.
In the command it would look something like this:
```
public function execute( ) : void {
var deferredResponse : DeferredResponse = dao.deleteThing("3");
deferredResponse.addEventListener(ResultEvent.RESULT, onResult);
deferredResponse.addEventListener(FaultEvent.FAULT, onFault);
}
```
or, you could repeat the pattern, having the `execute` method return a deferred response of its own that would get triggered when the deferred response that the command gets from the DAO is triggered.
But. I don't think this is particularly pretty. You could probably do something nicer, less complex and less entangled by using one of the many application frameworks that exist to solve more or less exactly this kind of problem. My suggestion would be [Mate](http://mate.asfusion.com). |
53,026 | <p>I have a table with an XML column. This column is storing some values I keep for configuring my application. I created it to have a more flexible schema.
I can't find a way to update this column directly from the table view in SQL Management Studio. Other (INT or Varchar for example) columns are editable. I know I can write an UPDATE statement or create some code to update it. But I'm looking for something more flexible that will let power users edit the XML directly.</p>
<p>Any ideas?</p>
<blockquote>
<p>Reiterating again: Please don't answer
I can write an application. I know
that, And that is exactly what I'm
trying to avoid.</p>
</blockquote>
| [
{
"answer_id": 53032,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>I do not think you can use the Management Studio GUI to update XML-columns without writing the UPDATE-command yourself.</p>\n\n<p>One way you could let users update xml-data is to write a simple .net based program (winforms or asp.net) and then select/update the data from there. This way you can also sanitize the data and easily validate it against any given schema before inserting/updating the information.</p>\n"
},
{
"answer_id": 53051,
"author": "Paulj",
"author_id": 5433,
"author_profile": "https://Stackoverflow.com/users/5433",
"pm_score": 2,
"selected": false,
"text": "<p>I wound up writing a .net c# UI to deal with the xml data. Using xsl for display and an xml schema helped display the xml nicely and maintain it's integrity.</p>\n\n<p>edit: Also c# contains the xmldocument class that simplifies reading/writing the data.</p>\n"
},
{
"answer_id": 53084,
"author": "Almond",
"author_id": 1603,
"author_profile": "https://Stackoverflow.com/users/1603",
"pm_score": 0,
"selected": false,
"text": "<p>I'm a bit fuzzy in this are but could you not use the OPENXML method to shred the XML into relational format then save it back in XML once the user has finished?</p>\n\n<p>Like others have said I think it might be easier to write a small app to do it!</p>\n"
},
{
"answer_id": 3474289,
"author": "Todd",
"author_id": 419230,
"author_profile": "https://Stackoverflow.com/users/419230",
"pm_score": 4,
"selected": false,
"text": "<p>sql server management studio is missing this feature.</p>\n\n<p>I can see Homer Simpson as the Microsoft project manager\nbanging his head with the palm of his hand:\n\"Duh!\"</p>\n\n<p>Of course, we want to edit xml columns.</p>\n"
},
{
"answer_id": 8827253,
"author": "Jacob",
"author_id": 181298,
"author_profile": "https://Stackoverflow.com/users/181298",
"pm_score": 6,
"selected": true,
"text": "<p>This is an old question, but I needed to do this today. The best I can come up with is to write a query that generates SQL code that can be edited in the query editor - it's sort of lame but it saves you copy/pasting stuff.</p>\n\n<p>Note: you may need to go into Tools > Options > Query Results > Results to Text and set the maximum number of characters displayed to a large enough number to fit your XML fields.</p>\n\n<p>e.g.</p>\n\n<pre><code>select 'update [table name] set [xml field name] = ''' + \nconvert(varchar(max), [xml field name]) +\n''' where [primary key name] = ' + \nconvert(varchar(max), [primary key name]) from [table name]\n</code></pre>\n\n<p>which produces a lot of queries that look like this (with some sample table/field names):</p>\n\n<pre><code>update thetable set thedata = '<root><name>Bob</name></root>' where thekey = 1\n</code></pre>\n\n<p>You then copy these queries from the results window back up to the query window, edit the xml strings, and then run the queries.</p>\n\n<p>(Edit: changed 10 to max to avoid error)</p>\n"
},
{
"answer_id": 16287206,
"author": "laktak",
"author_id": 52817,
"author_profile": "https://Stackoverflow.com/users/52817",
"pm_score": 2,
"selected": false,
"text": "<p>@Jacob's answer works very well, though you should add a REPLACE if you XML contains any ' characters:</p>\n\n<pre><code>select 'update [table name] set [xml field name] = ''' + \nREPLACE(convert(varchar(max), [xml field name]), '''', '''''') +\n''' where [primary key name] = ' + \nconvert(varchar(max), [primary key name]) from [table name]\n</code></pre>\n"
},
{
"answer_id": 23250530,
"author": "NightShovel",
"author_id": 895218,
"author_profile": "https://Stackoverflow.com/users/895218",
"pm_score": 1,
"selected": false,
"text": "<p>Ignoring the \"easily\" part the question title, here is a giant hack that is fairly decent, provided you deal with small XML columns.</p>\n\n<p>This is a proof of concept without much thought to optimization. Written against 2008 R2.</p>\n\n<pre><code>--Drop any previously existing objects, so we can run this multiple times.\nIF EXISTS (SELECT * FROM sysobjects WHERE Name = 'TableToUpdate')\n DROP TABLE TableToUpdate\nIF EXISTS (SELECT * FROM sysobjects WHERE Name = 'vw_TableToUpdate')\n DROP VIEW vw_TableToUpdate\n\n--Create our table with the XML column.\nCREATE TABLE TableToUpdate(\n Id INT NOT NULL CONSTRAINT Pk_TableToUpdate PRIMARY KEY CLUSTERED IDENTITY(1,1),\n XmlData XML NULL\n)\n\nGO\n\n--Create our view updatable view.\nCREATE VIEW dbo.vw_TableToUpdate\nAS\nSELECT\n Id,\n CONVERT(VARCHAR(MAX), XmlData) AS XmlText,\n XmlData\nFROM dbo.TableToUpdate\n\nGO\n\n--Create our trigger which takes the data keyed into a VARCHAR column and shims it into an XML format.\nCREATE TRIGGER TR_TableToView_Update\nON dbo.vw_TableToUpdate\nINSTEAD OF UPDATE\n\nAS\n\nSET NOCOUNT ON\n\nDECLARE\n@Id INT,\n@XmlText VARCHAR(MAX)\n\nDECLARE c CURSOR LOCAL STATIC FOR\nSELECT Id, XmlText FROM inserted\nOPEN c\n\nFETCH NEXT FROM c INTO @Id, @XmlText\nWHILE @@FETCH_STATUS = 0\nBEGIN\n /*\n Slight limitation here. We can't really do any error handling here because errors aren't really \"allowed\" in triggers.\n Ideally I would have liked to do a TRY/CATCH but meh.\n */\n UPDATE TableToUpdate\n SET\n XmlData = CONVERT(XML, @XmlText)\n WHERE\n Id = @Id\n\n FETCH NEXT FROM c INTO @Id, @XmlText\nEND\n\nCLOSE c\nDEALLOCATE c\n\nGO\n\n--Quick test before we go to SSMS\nINSERT INTO TableToUpdate(XmlData) SELECT '<Node1/>'\nUPDATE vw_TableToUpdate SET XmlText = '<Node1a/>'\nSELECT * FROM TableToUpdate\n</code></pre>\n\n<p>If you open vw_TableToUpdate in SSMS, you are allowed to change the \"XML\", which will then update the \"real\" XML value.</p>\n\n<p>Again, ugly hack, but it works for what I need it to do.</p>\n"
},
{
"answer_id": 37735167,
"author": "Vinnie Amir",
"author_id": 5336001,
"author_profile": "https://Stackoverflow.com/users/5336001",
"pm_score": 2,
"selected": false,
"text": "<p>I have a cheap and nasty workaround, but is ok. So, do a query of the record, i.e. </p>\n\n<pre><code>SELECT XMLData FROM [YourTable]\nWHERE ID = @SomeID\n</code></pre>\n\n<p>Click on the xml data field, which should be 'hyperlinked'. This will open the XML in a new window. Edit it, then copy and paste the XML back into a new query window:</p>\n\n<pre><code>UPDATE [YourTable] SET XMLData = '<row><somefield1>Somedata</somefield1> \n </row>'\nWHERE ID = @SomeID\n</code></pre>\n\n<p>But yes, WE Desparately need to be able to edit. If you are listening Mr. Soft, please look at Oracle, you can edit XML in their Mgt Studio equivalent. Let's chalk it up to an oversight, I am still a HUGE fan of SQL server.</p>\n"
},
{
"answer_id": 49806856,
"author": "Jeremy",
"author_id": 1203651,
"author_profile": "https://Stackoverflow.com/users/1203651",
"pm_score": 0,
"selected": false,
"text": "<p>Another non-answer answer. You can use LinqPad. (<a href=\"https://www.linqpad.net/\" rel=\"nofollow noreferrer\">https://www.linqpad.net/</a>). It has the ability to edit SQL rows, including XML fields. You can also query for the rows you want to edit via SQL if you're not into LINQ.</p>\n\n<p>My particular issue was attempting to edit an empty XML value into a NULL value. In SSMS the value showed as blank. However in LinqPad it showed as null. So in LinqPad I had to change it to , then back to null in order for the change to be saved. Now SSMS shows it as null too. </p>\n"
},
{
"answer_id": 72232414,
"author": "A P",
"author_id": 1149580,
"author_profile": "https://Stackoverflow.com/users/1149580",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is a really old question but I hope this might help someone.</p>\n<p>If you do not wish to write an update statement or an application as the question suggests, then I believe the following will help given that you are a power user.</p>\n<p>Alter the XML column to varchar and you will be able to modify this column in the SSMS edit table screen. I could not alter the column using the SSMS table designer. The Following script worked.</p>\n<pre><code>ALTER TABLE [tablename]\nALTER COLUMN [columnname] varchar(max);\n</code></pre>\n<p>Once you are done with edits, alter the column back to XML.</p>\n<pre><code>ALTER TABLE [tablename]\nALTER COLUMN [columnname] XML;\n</code></pre>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/53026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1363/"
] | I have a table with an XML column. This column is storing some values I keep for configuring my application. I created it to have a more flexible schema.
I can't find a way to update this column directly from the table view in SQL Management Studio. Other (INT or Varchar for example) columns are editable. I know I can write an UPDATE statement or create some code to update it. But I'm looking for something more flexible that will let power users edit the XML directly.
Any ideas?
>
> Reiterating again: Please don't answer
> I can write an application. I know
> that, And that is exactly what I'm
> trying to avoid.
>
>
> | This is an old question, but I needed to do this today. The best I can come up with is to write a query that generates SQL code that can be edited in the query editor - it's sort of lame but it saves you copy/pasting stuff.
Note: you may need to go into Tools > Options > Query Results > Results to Text and set the maximum number of characters displayed to a large enough number to fit your XML fields.
e.g.
```
select 'update [table name] set [xml field name] = ''' +
convert(varchar(max), [xml field name]) +
''' where [primary key name] = ' +
convert(varchar(max), [primary key name]) from [table name]
```
which produces a lot of queries that look like this (with some sample table/field names):
```
update thetable set thedata = '<root><name>Bob</name></root>' where thekey = 1
```
You then copy these queries from the results window back up to the query window, edit the xml strings, and then run the queries.
(Edit: changed 10 to max to avoid error) |
53,041 | <p>Visual Studio Solution files contain two GUID's per project entry. I figure one of them is from the AssemblyInfo.cs</p>
<p>Does anyone know for sure where these come from, and what they are used for?</p>
| [
{
"answer_id": 53048,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/bb165951(VS.80).aspx\" rel=\"noreferrer\">According to MSDN</a>: </p>\n\n<blockquote>\n <p>[The <code>Project</code>] statement contains the\n unique project GUID and the project\n type GUID. This information is used by\n the environment to find the project\n file or files belonging to the\n solution, and the VSPackage required\n for each project. The project GUID is\n passed to IVsProjectFactory to load\n the specific VSPackage related to the\n project, then the project is loaded by\n the VSPackage.</p>\n</blockquote>\n"
},
{
"answer_id": 53050,
"author": "Jason Olson",
"author_id": 5418,
"author_profile": "https://Stackoverflow.com/users/5418",
"pm_score": 5,
"selected": true,
"text": "<p>Neither GUID is the same GUID as from AssemblyInfo.cs (that is the GUID for the assembly itself, not tied to Visual Studio but the end product of the build).</p>\n\n<p>So, for a typical line in the sln file (open the .sln in notepad or editor-of-choice if you wish to see this):</p>\n\n<pre><code>Project(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"ConsoleSandbox\", \"ConsoleSandbox\\ConsoleSandbox.csproj\", \"{55A1FD06-FB00-4F8A-9153-C432357F5CAC}\"\n</code></pre>\n\n<p>The second GUID is a unique GUID for the project itself. The solution file uses this to map other settings to that project:</p>\n\n<pre><code>GlobalSection(ProjectConfigurationPlatforms) = postSolution\n {55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n {55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Debug|Any CPU.Build.0 = Debug|Any CPU\n {55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Release|Any CPU.ActiveCfg = Release|Any CPU\n {55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Release|Any CPU.Build.0 = Release|Any CPU\nEndGlobalSection\n</code></pre>\n\n<p>The first GUID is actually a GUID that is the unique GUID for the solution itself (I believe). If you have a solution with more than one project, you'll actually see something like the following:</p>\n\n<pre><code>Project(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"ConsoleSandbox\", \"ConsoleSandbox\\ConsoleSandbox.csproj\", \"{55A1FD06-FB00-4F8A-9153-C432357F5CAC}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Composite\", \"..\\CompositeWPF\\Source\\CAL\\Composite\\Composite.csproj\", \"{77138947-1D13-4E22-AEE0-5D0DD046CA34}\"\nEndProject\n</code></pre>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/53041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | Visual Studio Solution files contain two GUID's per project entry. I figure one of them is from the AssemblyInfo.cs
Does anyone know for sure where these come from, and what they are used for? | Neither GUID is the same GUID as from AssemblyInfo.cs (that is the GUID for the assembly itself, not tied to Visual Studio but the end product of the build).
So, for a typical line in the sln file (open the .sln in notepad or editor-of-choice if you wish to see this):
```
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleSandbox", "ConsoleSandbox\ConsoleSandbox.csproj", "{55A1FD06-FB00-4F8A-9153-C432357F5CAC}"
```
The second GUID is a unique GUID for the project itself. The solution file uses this to map other settings to that project:
```
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
```
The first GUID is actually a GUID that is the unique GUID for the solution itself (I believe). If you have a solution with more than one project, you'll actually see something like the following:
```
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleSandbox", "ConsoleSandbox\ConsoleSandbox.csproj", "{55A1FD06-FB00-4F8A-9153-C432357F5CAC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Composite", "..\CompositeWPF\Source\CAL\Composite\Composite.csproj", "{77138947-1D13-4E22-AEE0-5D0DD046CA34}"
EndProject
``` |
53,046 | <p>In python, there are some special variables and filenames that are surrounded by double-underscores. For example, there is the</p>
<pre><code>__file__
</code></pre>
<p>variable. I am only able to get them to show up correctly inside of a code block. What do I need to enter to get double underscores in regular text without having them interpreted as an emphasis?</p>
| [
{
"answer_id": 53052,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 6,
"selected": true,
"text": "<p>__file__</p>\n\n<p>Put a backslash before the first underscore.</p>\n\n<p>Like this:</p>\n\n<pre><code>\\__file__\n</code></pre>\n"
},
{
"answer_id": 53054,
"author": "Chris Upchurch",
"author_id": 2600,
"author_profile": "https://Stackoverflow.com/users/2600",
"pm_score": 3,
"selected": false,
"text": "<p>You can also put a backslash before the final underscore</p>\n\n<pre><code>__file_\\_\n</code></pre>\n\n<p>gives you</p>\n\n<p>__file__</p>\n"
},
{
"answer_id": 54594,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <code>&#95;</code> in place of left underscores. Example: \n__file__</p>\n"
},
{
"answer_id": 7545179,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p><code>`*</code> ` The same holds true for the star-character or any markdown syntax. Bbackticking works well.</p>\n"
},
{
"answer_id": 54740109,
"author": "WAN QIAN",
"author_id": 9229077,
"author_profile": "https://Stackoverflow.com/users/9229077",
"pm_score": 0,
"selected": false,
"text": "<p><code>_\\_file__</code>\nenter this will help you.</p>\n"
},
{
"answer_id": 55482838,
"author": "Fouzi TAKELAIT",
"author_id": 7916257,
"author_profile": "https://Stackoverflow.com/users/7916257",
"pm_score": 3,
"selected": false,
"text": "<p>Just you need to write it like this in markdown</p>\n\n<pre><code>\\_\\_file\\_\\_\n</code></pre>\n"
},
{
"answer_id": 65333812,
"author": "NachtgeistW",
"author_id": 11090451,
"author_profile": "https://Stackoverflow.com/users/11090451",
"pm_score": 3,
"selected": false,
"text": "<p>Put a backslash before the first and the second underscore, like:</p>\n<pre><code>\\_\\_main.py__\n</code></pre>\n<p>It will show like this:</p>\n<pre><code>__main.py__\n</code></pre>\n<p>Only one backslash is not enough, because it will make your text shown in Italic.</p>\n<p>By the way, considering they are variables and filenames, I suggest enclosing it in backticks(`):</p>\n<pre><code>`__main.py__`\n</code></pre>\n<p>It will show like <code>__main.py__</code>.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/53046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | In python, there are some special variables and filenames that are surrounded by double-underscores. For example, there is the
```
__file__
```
variable. I am only able to get them to show up correctly inside of a code block. What do I need to enter to get double underscores in regular text without having them interpreted as an emphasis? | \_\_file\_\_
Put a backslash before the first underscore.
Like this:
```
\__file__
``` |
53,064 | <p>I want to embed an .asp page on an html page. I cannot use an iframe. I tried:</p>
<pre><code><object width="100%" height="1500" type="text/html" data="url.asp">
alt : <a href="url.asp">url</a>
</object>"
</code></pre>
<p>works great in ff but not ie7. Any ideas? Is it possible to use the object tag to embed .asp pages for IE or does it only work in ff?</p>
| [
{
"answer_id": 53083,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 1,
"selected": false,
"text": "<p>You might be able to fake it using javascript. You could either use AJAX to load the page, then insert the HTML, or load \"url.asp\" in a hidden iframe and copy the HTML from there.</p>\n\n<p>One downside (or maybe this is what you want) is that the pages aren't completely independent, so CSS rules from the outer page will affect the embedded page.</p>\n"
},
{
"answer_id": 53131,
"author": "Pedro",
"author_id": 5488,
"author_profile": "https://Stackoverflow.com/users/5488",
"pm_score": 2,
"selected": true,
"text": "<p>I've solved it in the past using Javascript and XMLHttp. It can get a bit hacky depending on the circumstances. In particular, you have to watch out for the inner page failing and how it affects/downgrades the outer one (hopefully you can keep it downgrading elegantly).</p>\n\n<p>Search for XMLHttp (or check <a href=\"http://www.jibbering.com/2002/4/httprequest.html\" rel=\"nofollow noreferrer\">this great tutorial</a>) and request the \"child\" page from the outer one, rendering the HTML you need. Preferably you can get just the specific data you need and process it in Javascript.</p>\n"
},
{
"answer_id": 54643,
"author": "mrjrdnthms",
"author_id": 5234,
"author_profile": "https://Stackoverflow.com/users/5234",
"pm_score": 0,
"selected": false,
"text": "<p>Well, after searching around and testing I don't think it is possible. It looks to me like IE does not allow the object tag access to a resource that is not on the same domain as the parent. It would have worked for me if the content I was trying to pull in was on same domain but it wasn't. If anyone could confirm my interpretation of this it would be appreciated.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/53064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5234/"
] | I want to embed an .asp page on an html page. I cannot use an iframe. I tried:
```
<object width="100%" height="1500" type="text/html" data="url.asp">
alt : <a href="url.asp">url</a>
</object>"
```
works great in ff but not ie7. Any ideas? Is it possible to use the object tag to embed .asp pages for IE or does it only work in ff? | I've solved it in the past using Javascript and XMLHttp. It can get a bit hacky depending on the circumstances. In particular, you have to watch out for the inner page failing and how it affects/downgrades the outer one (hopefully you can keep it downgrading elegantly).
Search for XMLHttp (or check [this great tutorial](http://www.jibbering.com/2002/4/httprequest.html)) and request the "child" page from the outer one, rendering the HTML you need. Preferably you can get just the specific data you need and process it in Javascript. |
53,102 | <p>From the <em>Immediate Window</em> in Visual Studio: </p>
<pre><code>> Path.Combine(@"C:\x", "y")
"C:\\x\\y"
> Path.Combine(@"C:\x", @"\y")
"\\y"
</code></pre>
<p>It seems that they should both be the same. </p>
<p>The old FileSystemObject.BuildPath() didn't work this way...</p>
| [
{
"answer_id": 53110,
"author": "elarson",
"author_id": 5434,
"author_profile": "https://Stackoverflow.com/users/5434",
"pm_score": 2,
"selected": false,
"text": "<p>Not knowing the actual details, my guess is that it makes an attempt to join like you might join relative URIs. For example:</p>\n\n<pre><code>urljoin('/some/abs/path', '../other') = '/some/abs/other'\n</code></pre>\n\n<p>This means that when you join a path with a preceding slash, you are actually joining one base to another, in which case the second gets precedence. </p>\n"
},
{
"answer_id": 53113,
"author": "nickd",
"author_id": 2373,
"author_profile": "https://Stackoverflow.com/users/2373",
"pm_score": 3,
"selected": false,
"text": "<p>From <a href=\"https://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx\" rel=\"nofollow noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p>If one of the specified paths is a zero-length string, this method returns the other path. If path2 contains an absolute path, this method returns path2. </p>\n</blockquote>\n\n<p>In your example, path2 is absolute.</p>\n"
},
{
"answer_id": 53118,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 9,
"selected": true,
"text": "<p>This is kind of a philosophical question (which perhaps only Microsoft can truly answer), since it's doing exactly what the documentation says.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx\" rel=\"noreferrer\">System.IO.Path.Combine</a></p>\n\n<p>\"If path2 contains an absolute path, this method returns path2.\"</p>\n\n<p><a href=\"http://referencesource.microsoft.com/#mscorlib/system/io/path.cs,2d7263f86a526264\" rel=\"noreferrer\">Here's the actual Combine method</a> from the .NET source. You can see that it calls <a href=\"http://referencesource.microsoft.com/mscorlib/system/io/path.cs.html#16ed6da326ce4745\" rel=\"noreferrer\">CombineNoChecks</a>, which then calls <a href=\"http://referencesource.microsoft.com/mscorlib/system/io/path.cs.html#807960f08fca497d\" rel=\"noreferrer\">IsPathRooted</a> on path2 and returns that path if so:</p>\n\n<pre><code>public static String Combine(String path1, String path2) {\n if (path1==null || path2==null)\n throw new ArgumentNullException((path1==null) ? \"path1\" : \"path2\");\n Contract.EndContractBlock();\n CheckInvalidPathChars(path1);\n CheckInvalidPathChars(path2);\n\n return CombineNoChecks(path1, path2);\n}\n\ninternal static string CombineNoChecks(string path1, string path2)\n{\n if (path2.Length == 0)\n return path1;\n\n if (path1.Length == 0)\n return path2;\n\n if (IsPathRooted(path2))\n return path2;\n\n char ch = path1[path1.Length - 1];\n if (ch != DirectorySeparatorChar && ch != AltDirectorySeparatorChar &&\n ch != VolumeSeparatorChar) \n return path1 + DirectorySeparatorCharAsString + path2;\n return path1 + path2;\n}\n</code></pre>\n\n<p>I don't know what the rationale is. I guess the solution is to strip off (or Trim) DirectorySeparatorChar from the beginning of the second path; maybe write your own Combine method that does that and then calls Path.Combine().</p>\n"
},
{
"answer_id": 53122,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 5,
"selected": false,
"text": "<p>This is the disassembled code from <a href=\"http://en.wikipedia.org/wiki/.NET_Reflector\" rel=\"nofollow noreferrer\">.NET Reflector</a> for Path.Combine method. Check IsPathRooted function. If the second path is rooted (starts with a DirectorySeparatorChar), return second path as it is.</p>\n\n<pre><code>public static string Combine(string path1, string path2)\n{\n if ((path1 == null) || (path2 == null))\n {\n throw new ArgumentNullException((path1 == null) ? \"path1\" : \"path2\");\n }\n CheckInvalidPathChars(path1);\n CheckInvalidPathChars(path2);\n if (path2.Length == 0)\n {\n return path1;\n }\n if (path1.Length == 0)\n {\n return path2;\n }\n if (IsPathRooted(path2))\n {\n return path2;\n }\n char ch = path1[path1.Length - 1];\n if (((ch != DirectorySeparatorChar) &&\n (ch != AltDirectorySeparatorChar)) &&\n (ch != VolumeSeparatorChar))\n {\n return (path1 + DirectorySeparatorChar + path2);\n }\n return (path1 + path2);\n}\n\n\npublic static bool IsPathRooted(string path)\n{\n if (path != null)\n {\n CheckInvalidPathChars(path);\n int length = path.Length;\n if (\n (\n (length >= 1) &&\n (\n (path[0] == DirectorySeparatorChar) ||\n (path[0] == AltDirectorySeparatorChar)\n )\n )\n\n ||\n\n ((length >= 2) &&\n (path[1] == VolumeSeparatorChar))\n )\n {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 53551,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 5,
"selected": false,
"text": "<p>In my opinion this is a bug. The problem is that there are two different types of \"absolute\" paths. The path \"d:\\mydir\\myfile.txt\" is absolute, the path \"\\mydir\\myfile.txt\" is also considered to be \"absolute\" even though it is missing the drive letter. The correct behavior, in my opinion, would be to prepend the drive letter from the first path when the second path starts with the directory separator (and is not a UNC path). I would recommend writing your own helper wrapper function which has the behavior you desire if you need it.</p>\n"
},
{
"answer_id": 23255902,
"author": "Estevez",
"author_id": 617640,
"author_profile": "https://Stackoverflow.com/users/617640",
"pm_score": 0,
"selected": false,
"text": "<p>This \\ means \"the root directory of the current drive\". In your example it means the \"test\" folder in the current drive's root directory. So, this can be equal to \"c:\\test\".</p>\n"
},
{
"answer_id": 24823642,
"author": "Ferri",
"author_id": 3780016,
"author_profile": "https://Stackoverflow.com/users/3780016",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to combine both paths without losing any path you can use this:</p>\n\n<pre><code>?Path.Combine(@\"C:\\test\", @\"\\test\".Substring(0, 1) == @\"\\\" ? @\"\\test\".Substring(1, @\"\\test\".Length - 1) : @\"\\test\");\n</code></pre>\n\n<p>Or with variables:</p>\n\n<pre><code>string Path1 = @\"C:\\Test\";\nstring Path2 = @\"\\test\";\nstring FullPath = Path.Combine(Path1, Path2.IsRooted() ? Path2.Substring(1, Path2.Length - 1) : Path2);\n</code></pre>\n\n<p>Both cases return \"C:\\test\\test\".</p>\n\n<p>First, I evaluate if Path2 starts with / and if it is true, return Path2 without the first character. Otherwise, return the full Path2.</p>\n"
},
{
"answer_id": 27271258,
"author": "The King",
"author_id": 733566,
"author_profile": "https://Stackoverflow.com/users/733566",
"pm_score": 3,
"selected": false,
"text": "<p>This code should do the trick: </p>\n\n<pre><code> string strFinalPath = string.Empty;\n string normalizedFirstPath = Path1.TrimEnd(new char[] { '\\\\' });\n string normalizedSecondPath = Path2.TrimStart(new char[] { '\\\\' });\n strFinalPath = Path.Combine(normalizedFirstPath, normalizedSecondPath);\n return strFinalPath;\n</code></pre>\n"
},
{
"answer_id": 31131504,
"author": "anhoppe",
"author_id": 1178267,
"author_profile": "https://Stackoverflow.com/users/1178267",
"pm_score": 5,
"selected": false,
"text": "<p>I wanted to solve this problem:</p>\n\n<pre><code>string sample1 = \"configuration/config.xml\";\nstring sample2 = \"/configuration/config.xml\";\nstring sample3 = \"\\\\configuration/config.xml\";\n\nstring dir1 = \"c:\\\\temp\";\nstring dir2 = \"c:\\\\temp\\\\\";\nstring dir3 = \"c:\\\\temp/\";\n\nstring path1 = PathCombine(dir1, sample1);\nstring path2 = PathCombine(dir1, sample2);\nstring path3 = PathCombine(dir1, sample3);\n\nstring path4 = PathCombine(dir2, sample1);\nstring path5 = PathCombine(dir2, sample2);\nstring path6 = PathCombine(dir2, sample3);\n\nstring path7 = PathCombine(dir3, sample1);\nstring path8 = PathCombine(dir3, sample2);\nstring path9 = PathCombine(dir3, sample3);\n</code></pre>\n\n<p>Of course, all paths 1-9 should contain an equivalent string in the end. Here is the PathCombine method I came up with:</p>\n\n<pre><code>private string PathCombine(string path1, string path2)\n{\n if (Path.IsPathRooted(path2))\n {\n path2 = path2.TrimStart(Path.DirectorySeparatorChar);\n path2 = path2.TrimStart(Path.AltDirectorySeparatorChar);\n }\n\n return Path.Combine(path1, path2);\n}\n</code></pre>\n\n<p>I also think that it is quite annoying that this string handling has to be done manually, and I'd be interested in the reason behind this.</p>\n"
},
{
"answer_id": 41615722,
"author": "marsze",
"author_id": 2060966,
"author_profile": "https://Stackoverflow.com/users/2060966",
"pm_score": 2,
"selected": false,
"text": "<p>This actually makes sense, in some way, considering how (relative) paths are treated usually:</p>\n\n<pre><code>string GetFullPath(string path)\n{\n string baseDir = @\"C:\\Users\\Foo.Bar\";\n return Path.Combine(baseDir, path);\n}\n\n// Get full path for RELATIVE file path\nGetFullPath(\"file.txt\"); // = C:\\Users\\Foo.Bar\\file.txt\n\n// Get full path for ROOTED file path\nGetFullPath(@\"C:\\Temp\\file.txt\"); // = C:\\Temp\\file.txt\n</code></pre>\n\n<p>The real question is: Why are paths, which start with <code>\"\\\"</code>, considered \"rooted\"? This was new to me too, but <a href=\"https://blogs.msdn.microsoft.com/jeremykuhne/2016/04/21/path-normalization/\" rel=\"nofollow noreferrer\">it works that way on Windows</a>:</p>\n\n<pre><code>new FileInfo(\"\\windows\"); // FullName = C:\\Windows, Exists = True\nnew FileInfo(\"windows\"); // FullName = C:\\Users\\Foo.Bar\\Windows, Exists = False\n</code></pre>\n"
},
{
"answer_id": 43507984,
"author": "ergohack",
"author_id": 4151626,
"author_profile": "https://Stackoverflow.com/users/4151626",
"pm_score": 3,
"selected": false,
"text": "<p>Following <a href=\"https://www.blogger.com/profile/13444285493681626756\" rel=\"noreferrer\" title=\"Christian Graus\">Christian Graus</a>' advice in his \"Things I Hate about Microsoft\" blog titled \"<a href=\"http://thingsihateaboutmicrosoft.blogspot.com/2009/08/pathcombine-is-essentially-useless.html\" rel=\"noreferrer\" title=\"Path.Combine is essentially useless.\">Path.Combine is essentially useless.</a>\", here is my solution:</p>\n\n<pre><code>public static class Pathy\n{\n public static string Combine(string path1, string path2)\n {\n if (path1 == null) return path2\n else if (path2 == null) return path1\n else return path1.Trim().TrimEnd(System.IO.Path.DirectorySeparatorChar)\n + System.IO.Path.DirectorySeparatorChar\n + path2.Trim().TrimStart(System.IO.Path.DirectorySeparatorChar);\n }\n\n public static string Combine(string path1, string path2, string path3)\n {\n return Combine(Combine(path1, path2), path3);\n }\n}\n</code></pre>\n\n<p>Some advise that the namespaces should collide, ... I went with <code>Pathy</code>, as a slight, and to avoid namespace collision with <code>System.IO.Path</code>.</p>\n\n<p><strong>Edit</strong>: Added null parameter checks</p>\n"
},
{
"answer_id": 45443974,
"author": "Don Rolling",
"author_id": 441862,
"author_profile": "https://Stackoverflow.com/users/441862",
"pm_score": 0,
"selected": false,
"text": "<p>These two methods should save you from accidentally joining two strings that both have the delimiter in them.</p>\n\n<pre><code> public static string Combine(string x, string y, char delimiter) {\n return $\"{ x.TrimEnd(delimiter) }{ delimiter }{ y.TrimStart(delimiter) }\";\n }\n\n public static string Combine(string[] xs, char delimiter) {\n if (xs.Length < 1) return string.Empty;\n if (xs.Length == 1) return xs[0];\n var x = Combine(xs[0], xs[1], delimiter);\n if (xs.Length == 2) return x;\n var ys = new List<string>();\n ys.Add(x);\n ys.AddRange(xs.Skip(2).ToList());\n return Combine(ys.ToArray(), delimiter);\n }\n</code></pre>\n"
},
{
"answer_id": 50339209,
"author": "Arad",
"author_id": 7734384,
"author_profile": "https://Stackoverflow.com/users/7734384",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Reason:</strong></p>\n<p>Your second URL is considered an absolute path, and the <code>Combine</code> method will only return the last path if the last path is an absolute path.</p>\n<p><strong>Solution:</strong></p>\n<p>Just remove the leading slash <code>/</code> from your second Path (<code>/SecondPath</code> to <code>SecondPath</code>), and it would work as excepted.</p>\n"
},
{
"answer_id": 57914892,
"author": "shanmuga raja",
"author_id": 6581571,
"author_profile": "https://Stackoverflow.com/users/6581571",
"pm_score": 1,
"selected": false,
"text": "<p>Remove the starting slash ('\\') in the second parameter (path2) of Path.Combine.</p>\n"
},
{
"answer_id": 58023547,
"author": "LazZiya",
"author_id": 5519026,
"author_profile": "https://Stackoverflow.com/users/5519026",
"pm_score": 2,
"selected": false,
"text": "<p>I used aggregate function to force paths combine as below:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class MyPath \n{\n public static string ForceCombine(params string[] paths)\n {\n return paths.Aggregate((x, y) => Path.Combine(x, y.TrimStart('\\\\')));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 59379466,
"author": "ilias iliadis",
"author_id": 2362556,
"author_profile": "https://Stackoverflow.com/users/2362556",
"pm_score": 0,
"selected": false,
"text": "<p>As mentiond by Ryan it's doing exactly what the documentation says.</p>\n\n<p>From DOS times, current disk, and current path are distinguished.\n<code>\\</code> is the root path, but for the CURRENT DISK.</p>\n\n<p>For every \"<em>disk</em>\" there is a separate \"<em>current path</em>\".\nIf you change the disk using <code>cd D:</code> you do not change the current path to <code>D:\\</code>, but to: \"D:\\whatever\\was\\the\\last\\path\\accessed\\on\\this\\disk\"...</p>\n\n<p>So, in windows, a literal <code>@\"\\x\"</code> means: \"CURRENTDISK:\\x\".\nHence <code>Path.Combine(@\"C:\\x\", @\"\\y\")</code> has as second parameter a root path, not a relative, though not in a known disk...\nAnd since it is not known which might be the «current disk», python returns <code>\"\\\\y\"</code>.</p>\n\n<pre><code>>cd C:\n>cd \\mydironC\\apath\n>cd D:\n>cd \\mydironD\\bpath\n>cd C:\n>cd\n>C:\\mydironC\\apath\n</code></pre>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/53102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] | From the *Immediate Window* in Visual Studio:
```
> Path.Combine(@"C:\x", "y")
"C:\\x\\y"
> Path.Combine(@"C:\x", @"\y")
"\\y"
```
It seems that they should both be the same.
The old FileSystemObject.BuildPath() didn't work this way... | This is kind of a philosophical question (which perhaps only Microsoft can truly answer), since it's doing exactly what the documentation says.
[System.IO.Path.Combine](http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx)
"If path2 contains an absolute path, this method returns path2."
[Here's the actual Combine method](http://referencesource.microsoft.com/#mscorlib/system/io/path.cs,2d7263f86a526264) from the .NET source. You can see that it calls [CombineNoChecks](http://referencesource.microsoft.com/mscorlib/system/io/path.cs.html#16ed6da326ce4745), which then calls [IsPathRooted](http://referencesource.microsoft.com/mscorlib/system/io/path.cs.html#807960f08fca497d) on path2 and returns that path if so:
```
public static String Combine(String path1, String path2) {
if (path1==null || path2==null)
throw new ArgumentNullException((path1==null) ? "path1" : "path2");
Contract.EndContractBlock();
CheckInvalidPathChars(path1);
CheckInvalidPathChars(path2);
return CombineNoChecks(path1, path2);
}
internal static string CombineNoChecks(string path1, string path2)
{
if (path2.Length == 0)
return path1;
if (path1.Length == 0)
return path2;
if (IsPathRooted(path2))
return path2;
char ch = path1[path1.Length - 1];
if (ch != DirectorySeparatorChar && ch != AltDirectorySeparatorChar &&
ch != VolumeSeparatorChar)
return path1 + DirectorySeparatorCharAsString + path2;
return path1 + path2;
}
```
I don't know what the rationale is. I guess the solution is to strip off (or Trim) DirectorySeparatorChar from the beginning of the second path; maybe write your own Combine method that does that and then calls Path.Combine(). |
53,108 | <p>I have a table similar to this:</p>
<pre><code>CREATE TABLE example (
id integer primary key,
name char(200),
parentid integer,
value integer);
</code></pre>
<p>I can use the parentid field to arrange data into a tree structure.</p>
<p>Now here's the bit I can't work out. Given a parentid, is it possible to write an SQL statement to add up all the value fields under that parentid and recurse down the branch of the tree ?</p>
<p><strong>UPDATE:</strong> I'm using posgreSQL so the fancy MS-SQL features are not available to me. In any case, I'd like this to be treated as a generic SQL question.</p>
<p>BTW, I'm very impressed to have 6 answers within 15 minutes of asking the question! Go stack overflow!</p>
| [
{
"answer_id": 53119,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 0,
"selected": false,
"text": "<p>is this SQL Server? Couldn't you write a TSQL stored procedure that loops through and unions the results together? </p>\n\n<p>I am also interested if there is a SQL-only way of doing this though. From the bits I remember from my geographic databases class, there should be.</p>\n"
},
{
"answer_id": 53121,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 3,
"selected": false,
"text": "<p>use a <a href=\"http://msdn.microsoft.com/en-us/library/ms186243.aspx\" rel=\"nofollow noreferrer\">common table expression</a>. </p>\n\n<blockquote>\n <p>May want to indicate this is SQL Server 2005 or above only. <a href=\"https://stackoverflow.com/users/1117/dale-ragan\">Dale Ragan</a></p>\n</blockquote>\n\n<p><a href=\"http://www.sqlteam.com/article/more-trees-hierarchies-in-sql\" rel=\"nofollow noreferrer\">here's an article</a> on recursion by SqlTeam without common table expressions.</p>\n"
},
{
"answer_id": 53129,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 0,
"selected": false,
"text": "<p>I think it is easier in SQL 2008 with <a href=\"http://msdn.microsoft.com/en-us/magazine/cc794278.aspx\" rel=\"nofollow noreferrer\">HierarchyID</a></p>\n"
},
{
"answer_id": 53130,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "<p>If your using SQL Server 2005, there is a really cool way to do this using Common Table Expressions.</p>\n\n<p>It takes all of the gruntwork out of creating a temporary table, and basicly allows you to do it all with just a WITH and a UNION.</p>\n\n<p>Here is a good tutorial:</p>\n\n<p><a href=\"http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci1278207,00.html\" rel=\"nofollow noreferrer\">http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci1278207,00.html</a></p>\n"
},
{
"answer_id": 53137,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 1,
"selected": false,
"text": "<p>Oracle has \"START WITH\" and \"CONNECT BY\" </p>\n\n<pre><code>select \n lpad(' ',2*(level-1)) || to_char(child) s\n\nfrom \n test_connect_by \n\nstart with parent is null\nconnect by prior child = parent;\n</code></pre>\n\n<p><a href=\"http://www.adp-gmbh.ch/ora/sql/connect_by.html\" rel=\"nofollow noreferrer\">http://www.adp-gmbh.ch/ora/sql/connect_by.html</a></p>\n"
},
{
"answer_id": 53158,
"author": "Portman",
"author_id": 1690,
"author_profile": "https://Stackoverflow.com/users/1690",
"pm_score": 4,
"selected": false,
"text": "<p>If you want a portable solution that will work on any ANSI <a href=\"http://en.wikipedia.org/wiki/SQL-92\" rel=\"noreferrer\">SQL-92</a> RDBMS, you will need to add a new column to your table.</p>\n\n<p>Joe Celko is the original author of the <strong><a href=\"http://www.intelligententerprise.com/001020/celko.jhtml\" rel=\"noreferrer\">Nested Sets</a></strong> approach to storing hierarchies in SQL. You can Google <a href=\"http://www.google.com/search?q=%22nested+sets%22+hierarchy\" rel=\"noreferrer\">\"nested sets\" hierarchy</a> to understand more about the background.</p>\n\n<p>Or you can just rename parentid to <strong>leftid</strong> and add a <strong>rightid</strong>. </p>\n\n<p>Here is my attempt to summarize Nested Sets, which will fall woefully short because I'm no Joe Celko: SQL is a set-based language, and the adjacency model (storing parent ID) is NOT a set-based representation of a hierarchy. Therefore there is no pure set-based method to query an adjacency schema.</p>\n\n<p><strong>However</strong>, most of the major platforms have introduced extensions in recent years to deal with this precise problem. So if someone replies with a Postgres-specific solution, use that by all means.</p>\n"
},
{
"answer_id": 53223,
"author": "Jacob Rigby",
"author_id": 5357,
"author_profile": "https://Stackoverflow.com/users/5357",
"pm_score": -1,
"selected": false,
"text": "<p>If you need to store arbitrary graphs, not just hierarchies, you could push Postgres to the side and try a graph database such as <a href=\"http://agraph.franz.com/support/learning/\" rel=\"nofollow noreferrer\">AllegroGraph</a>:</p>\n\n<p>Everything in the graph database is stored as a triple (source node, edge, target node) and it gives you first class support for manipulating the graph structure and querying it using a SQL like language. </p>\n\n<p>It doesn't integrate well with something like Hibernate or Django ORM but if you are serious about graph structures (not just hierarchies like the Nested Set model gives you) check it out. </p>\n\n<p>I also believe Oracle has finally added a support for real Graphs in their latest products, but I'm amazed it's taken so long, lots of problems could benefit from this model.</p>\n"
},
{
"answer_id": 54362,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>There are a few ways to do what you need in PostgreSQL.</p>\n\n<ul>\n<li><p>If you can install modules, look at the tablefunc contrib. It has a connectby() function that handles traversing trees. <a href=\"http://www.postgresql.org/docs/8.3/interactive/tablefunc.html\" rel=\"noreferrer\">http://www.postgresql.org/docs/8.3/interactive/tablefunc.html</a></p></li>\n<li><p>Also check out the ltree contrib, which you could adapt your table to use: <a href=\"http://www.postgresql.org/docs/8.3/interactive/ltree.html\" rel=\"noreferrer\">http://www.postgresql.org/docs/8.3/interactive/ltree.html</a></p></li>\n<li><p>Or you can traverse the tree yourself with a PL/PGSQL function.</p></li>\n</ul>\n\n<p>Something like this:</p>\n\n<pre><code>create or replace function example_subtree (integer)\nreturns setof example as\n'declare results record;\n child record;\n begin\n select into results * from example where parent_id = $1;\n if found then\n return next results;\n for child in select id from example\n where parent_id = $1\n loop\n for temp in select * from example_subtree(child.id)\n loop\n return next temp;\n end loop;\n end loop;\n end if;\n return null;\nend;' language 'plpgsql';\n\nselect sum(value) as value_sum\n from example_subtree(1234);\n</code></pre>\n"
},
{
"answer_id": 508921,
"author": "Richard Gomes",
"author_id": 62131,
"author_profile": "https://Stackoverflow.com/users/62131",
"pm_score": 2,
"selected": false,
"text": "<p>The following code compiles and it's tested OK.</p>\n\n<pre>\ncreate or replace function subtree (bigint)\nreturns setof example as $$\ndeclare\n results record;\n entry record;\n recs record;\nbegin\n select into results * from example where parent = $1;\n if found then\n for entry in select child from example where parent = $1 and child parent loop\n for recs in select * from subtree(entry.child) loop\n return next recs;\n end loop;\n end loop;\n end if;\n return next results;\nend;\n$$ language 'plpgsql';\n</pre>\n\n<p>The condition \"child <> parent\" is needed in my case because nodes point to themselves.</p>\n\n<p>Have fun :)</p>\n"
},
{
"answer_id": 548619,
"author": "Chris KL",
"author_id": 58110,
"author_profile": "https://Stackoverflow.com/users/58110",
"pm_score": 5,
"selected": false,
"text": "<p>Since version 8.4, PostgreSQL has <a href=\"http://www.postgresql.org/docs/current/static/queries-with.html\" rel=\"noreferrer\">recursive query support</a> for common table expressions using the SQL standard <code>WITH</code> syntax.</p>\n"
},
{
"answer_id": 656309,
"author": "Dr.Pil",
"author_id": 74881,
"author_profile": "https://Stackoverflow.com/users/74881",
"pm_score": 1,
"selected": false,
"text": "<p>Just as a brief aside although the question has been answered very well, it should be noted that if we treat this as a:</p>\n\n<blockquote>\n <p>generic SQL question</p>\n</blockquote>\n\n<p>then the SQL implementation is fairly straight-forward, as SQL'99 allows linear recursion in the specification (although I believe no RDBMSs implement the standard fully) through the <code>WITH RECURSIVE</code> statement. So from a theoretical perspective we can do this right now.</p>\n"
},
{
"answer_id": 4659648,
"author": "Slawa",
"author_id": 417153,
"author_profile": "https://Stackoverflow.com/users/417153",
"pm_score": 1,
"selected": false,
"text": "<p>None of the examples worked OK for me so I've fixed it like this:</p>\n\n<pre>\ndeclare\n results record;\n entry record;\n recs record;\nbegin\n for results in select * from project where pid = $1 loop\n return next results;\n for recs in select * from project_subtree(results.id) loop\n return next recs;\n end loop;\n end loop;\n return;\nend;\n</pre>\n"
},
{
"answer_id": 4659750,
"author": "Quassnoi",
"author_id": 55159,
"author_profile": "https://Stackoverflow.com/users/55159",
"pm_score": 3,
"selected": false,
"text": "<p>A standard way to make a recursive query in <code>SQL</code> are recursive <code>CTE</code>. <code>PostgreSQL</code> supports them since <code>8.4</code>.</p>\n\n<p>In earlier versions, you can write a recursive set-returning function:</p>\n\n<pre><code>CREATE FUNCTION fn_hierarchy (parent INT)\nRETURNS SETOF example\nAS\n$$\n SELECT example\n FROM example\n WHERE id = $1\n UNION ALL\n SELECT fn_hierarchy(id)\n FROM example\n WHERE parentid = $1\n$$\nLANGUAGE 'sql';\n\nSELECT *\nFROM fn_hierarchy(1)\n</code></pre>\n\n<p>See this article:</p>\n\n<ul>\n<li><a href=\"http://explainextended.com/2009/05/29/hierarchical-queries-in-postgresql/\" rel=\"noreferrer\"><strong>Hierarchical queries in PostgreSQL</strong></a></li>\n</ul>\n"
},
{
"answer_id": 5701124,
"author": "Endy Tjahjono",
"author_id": 196451,
"author_profile": "https://Stackoverflow.com/users/196451",
"pm_score": 5,
"selected": false,
"text": "<p>Here is an example script using common table expression:</p>\n\n<pre><code>with recursive sumthis(id, val) as (\n select id, value\n from example\n where id = :selectedid\n union all\n select C.id, C.value\n from sumthis P\n inner join example C on P.id = C.parentid\n)\nselect sum(val) from sumthis\n</code></pre>\n\n<p>The script above creates a 'virtual' table called <code>sumthis</code> that has columns <code>id</code> and <code>val</code>. It is defined as the result of two selects merged with <code>union all</code>.</p>\n\n<p>First <code>select</code> gets the root (<code>where id = :selectedid</code>).</p>\n\n<p>Second <code>select</code> follows the children of the previous results iteratively until there is nothing to return.</p>\n\n<p>The end result can then be processed like a normal table. In this case the val column is summed.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/53108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324/"
] | I have a table similar to this:
```
CREATE TABLE example (
id integer primary key,
name char(200),
parentid integer,
value integer);
```
I can use the parentid field to arrange data into a tree structure.
Now here's the bit I can't work out. Given a parentid, is it possible to write an SQL statement to add up all the value fields under that parentid and recurse down the branch of the tree ?
**UPDATE:** I'm using posgreSQL so the fancy MS-SQL features are not available to me. In any case, I'd like this to be treated as a generic SQL question.
BTW, I'm very impressed to have 6 answers within 15 minutes of asking the question! Go stack overflow! | There are a few ways to do what you need in PostgreSQL.
* If you can install modules, look at the tablefunc contrib. It has a connectby() function that handles traversing trees. <http://www.postgresql.org/docs/8.3/interactive/tablefunc.html>
* Also check out the ltree contrib, which you could adapt your table to use: <http://www.postgresql.org/docs/8.3/interactive/ltree.html>
* Or you can traverse the tree yourself with a PL/PGSQL function.
Something like this:
```
create or replace function example_subtree (integer)
returns setof example as
'declare results record;
child record;
begin
select into results * from example where parent_id = $1;
if found then
return next results;
for child in select id from example
where parent_id = $1
loop
for temp in select * from example_subtree(child.id)
loop
return next temp;
end loop;
end loop;
end if;
return null;
end;' language 'plpgsql';
select sum(value) as value_sum
from example_subtree(1234);
``` |
53,112 | <p>What are good ways of dealing with the issues surrounding plugin code that interacts with outside system?</p>
<p>To give a concrete and representative example, suppose I would like to use Subversion and Eclipse to develop plugins for WordPress. The main code body of WordPress is installed on the webserver, and the plugin code needs to be available in a subdirectory of that server.</p>
<p>I could see how you could simply checkout a copy of your code directly under the web directory on a development machine, but how would you also then integrate this with the IDE?</p>
<p>I am making the assumption here that all the code for the plugin is located under a single directory.</p>
<p>Do most people just add the plugin as a project in an IDE and then place the working folder for the project wherever the 'main' software system wants it to be? Or do people use some kind of symlinks to their home directory?</p>
| [
{
"answer_id": 53119,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 0,
"selected": false,
"text": "<p>is this SQL Server? Couldn't you write a TSQL stored procedure that loops through and unions the results together? </p>\n\n<p>I am also interested if there is a SQL-only way of doing this though. From the bits I remember from my geographic databases class, there should be.</p>\n"
},
{
"answer_id": 53121,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 3,
"selected": false,
"text": "<p>use a <a href=\"http://msdn.microsoft.com/en-us/library/ms186243.aspx\" rel=\"nofollow noreferrer\">common table expression</a>. </p>\n\n<blockquote>\n <p>May want to indicate this is SQL Server 2005 or above only. <a href=\"https://stackoverflow.com/users/1117/dale-ragan\">Dale Ragan</a></p>\n</blockquote>\n\n<p><a href=\"http://www.sqlteam.com/article/more-trees-hierarchies-in-sql\" rel=\"nofollow noreferrer\">here's an article</a> on recursion by SqlTeam without common table expressions.</p>\n"
},
{
"answer_id": 53129,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 0,
"selected": false,
"text": "<p>I think it is easier in SQL 2008 with <a href=\"http://msdn.microsoft.com/en-us/magazine/cc794278.aspx\" rel=\"nofollow noreferrer\">HierarchyID</a></p>\n"
},
{
"answer_id": 53130,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "<p>If your using SQL Server 2005, there is a really cool way to do this using Common Table Expressions.</p>\n\n<p>It takes all of the gruntwork out of creating a temporary table, and basicly allows you to do it all with just a WITH and a UNION.</p>\n\n<p>Here is a good tutorial:</p>\n\n<p><a href=\"http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci1278207,00.html\" rel=\"nofollow noreferrer\">http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci1278207,00.html</a></p>\n"
},
{
"answer_id": 53137,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 1,
"selected": false,
"text": "<p>Oracle has \"START WITH\" and \"CONNECT BY\" </p>\n\n<pre><code>select \n lpad(' ',2*(level-1)) || to_char(child) s\n\nfrom \n test_connect_by \n\nstart with parent is null\nconnect by prior child = parent;\n</code></pre>\n\n<p><a href=\"http://www.adp-gmbh.ch/ora/sql/connect_by.html\" rel=\"nofollow noreferrer\">http://www.adp-gmbh.ch/ora/sql/connect_by.html</a></p>\n"
},
{
"answer_id": 53158,
"author": "Portman",
"author_id": 1690,
"author_profile": "https://Stackoverflow.com/users/1690",
"pm_score": 4,
"selected": false,
"text": "<p>If you want a portable solution that will work on any ANSI <a href=\"http://en.wikipedia.org/wiki/SQL-92\" rel=\"noreferrer\">SQL-92</a> RDBMS, you will need to add a new column to your table.</p>\n\n<p>Joe Celko is the original author of the <strong><a href=\"http://www.intelligententerprise.com/001020/celko.jhtml\" rel=\"noreferrer\">Nested Sets</a></strong> approach to storing hierarchies in SQL. You can Google <a href=\"http://www.google.com/search?q=%22nested+sets%22+hierarchy\" rel=\"noreferrer\">\"nested sets\" hierarchy</a> to understand more about the background.</p>\n\n<p>Or you can just rename parentid to <strong>leftid</strong> and add a <strong>rightid</strong>. </p>\n\n<p>Here is my attempt to summarize Nested Sets, which will fall woefully short because I'm no Joe Celko: SQL is a set-based language, and the adjacency model (storing parent ID) is NOT a set-based representation of a hierarchy. Therefore there is no pure set-based method to query an adjacency schema.</p>\n\n<p><strong>However</strong>, most of the major platforms have introduced extensions in recent years to deal with this precise problem. So if someone replies with a Postgres-specific solution, use that by all means.</p>\n"
},
{
"answer_id": 53223,
"author": "Jacob Rigby",
"author_id": 5357,
"author_profile": "https://Stackoverflow.com/users/5357",
"pm_score": -1,
"selected": false,
"text": "<p>If you need to store arbitrary graphs, not just hierarchies, you could push Postgres to the side and try a graph database such as <a href=\"http://agraph.franz.com/support/learning/\" rel=\"nofollow noreferrer\">AllegroGraph</a>:</p>\n\n<p>Everything in the graph database is stored as a triple (source node, edge, target node) and it gives you first class support for manipulating the graph structure and querying it using a SQL like language. </p>\n\n<p>It doesn't integrate well with something like Hibernate or Django ORM but if you are serious about graph structures (not just hierarchies like the Nested Set model gives you) check it out. </p>\n\n<p>I also believe Oracle has finally added a support for real Graphs in their latest products, but I'm amazed it's taken so long, lots of problems could benefit from this model.</p>\n"
},
{
"answer_id": 54362,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>There are a few ways to do what you need in PostgreSQL.</p>\n\n<ul>\n<li><p>If you can install modules, look at the tablefunc contrib. It has a connectby() function that handles traversing trees. <a href=\"http://www.postgresql.org/docs/8.3/interactive/tablefunc.html\" rel=\"noreferrer\">http://www.postgresql.org/docs/8.3/interactive/tablefunc.html</a></p></li>\n<li><p>Also check out the ltree contrib, which you could adapt your table to use: <a href=\"http://www.postgresql.org/docs/8.3/interactive/ltree.html\" rel=\"noreferrer\">http://www.postgresql.org/docs/8.3/interactive/ltree.html</a></p></li>\n<li><p>Or you can traverse the tree yourself with a PL/PGSQL function.</p></li>\n</ul>\n\n<p>Something like this:</p>\n\n<pre><code>create or replace function example_subtree (integer)\nreturns setof example as\n'declare results record;\n child record;\n begin\n select into results * from example where parent_id = $1;\n if found then\n return next results;\n for child in select id from example\n where parent_id = $1\n loop\n for temp in select * from example_subtree(child.id)\n loop\n return next temp;\n end loop;\n end loop;\n end if;\n return null;\nend;' language 'plpgsql';\n\nselect sum(value) as value_sum\n from example_subtree(1234);\n</code></pre>\n"
},
{
"answer_id": 508921,
"author": "Richard Gomes",
"author_id": 62131,
"author_profile": "https://Stackoverflow.com/users/62131",
"pm_score": 2,
"selected": false,
"text": "<p>The following code compiles and it's tested OK.</p>\n\n<pre>\ncreate or replace function subtree (bigint)\nreturns setof example as $$\ndeclare\n results record;\n entry record;\n recs record;\nbegin\n select into results * from example where parent = $1;\n if found then\n for entry in select child from example where parent = $1 and child parent loop\n for recs in select * from subtree(entry.child) loop\n return next recs;\n end loop;\n end loop;\n end if;\n return next results;\nend;\n$$ language 'plpgsql';\n</pre>\n\n<p>The condition \"child <> parent\" is needed in my case because nodes point to themselves.</p>\n\n<p>Have fun :)</p>\n"
},
{
"answer_id": 548619,
"author": "Chris KL",
"author_id": 58110,
"author_profile": "https://Stackoverflow.com/users/58110",
"pm_score": 5,
"selected": false,
"text": "<p>Since version 8.4, PostgreSQL has <a href=\"http://www.postgresql.org/docs/current/static/queries-with.html\" rel=\"noreferrer\">recursive query support</a> for common table expressions using the SQL standard <code>WITH</code> syntax.</p>\n"
},
{
"answer_id": 656309,
"author": "Dr.Pil",
"author_id": 74881,
"author_profile": "https://Stackoverflow.com/users/74881",
"pm_score": 1,
"selected": false,
"text": "<p>Just as a brief aside although the question has been answered very well, it should be noted that if we treat this as a:</p>\n\n<blockquote>\n <p>generic SQL question</p>\n</blockquote>\n\n<p>then the SQL implementation is fairly straight-forward, as SQL'99 allows linear recursion in the specification (although I believe no RDBMSs implement the standard fully) through the <code>WITH RECURSIVE</code> statement. So from a theoretical perspective we can do this right now.</p>\n"
},
{
"answer_id": 4659648,
"author": "Slawa",
"author_id": 417153,
"author_profile": "https://Stackoverflow.com/users/417153",
"pm_score": 1,
"selected": false,
"text": "<p>None of the examples worked OK for me so I've fixed it like this:</p>\n\n<pre>\ndeclare\n results record;\n entry record;\n recs record;\nbegin\n for results in select * from project where pid = $1 loop\n return next results;\n for recs in select * from project_subtree(results.id) loop\n return next recs;\n end loop;\n end loop;\n return;\nend;\n</pre>\n"
},
{
"answer_id": 4659750,
"author": "Quassnoi",
"author_id": 55159,
"author_profile": "https://Stackoverflow.com/users/55159",
"pm_score": 3,
"selected": false,
"text": "<p>A standard way to make a recursive query in <code>SQL</code> are recursive <code>CTE</code>. <code>PostgreSQL</code> supports them since <code>8.4</code>.</p>\n\n<p>In earlier versions, you can write a recursive set-returning function:</p>\n\n<pre><code>CREATE FUNCTION fn_hierarchy (parent INT)\nRETURNS SETOF example\nAS\n$$\n SELECT example\n FROM example\n WHERE id = $1\n UNION ALL\n SELECT fn_hierarchy(id)\n FROM example\n WHERE parentid = $1\n$$\nLANGUAGE 'sql';\n\nSELECT *\nFROM fn_hierarchy(1)\n</code></pre>\n\n<p>See this article:</p>\n\n<ul>\n<li><a href=\"http://explainextended.com/2009/05/29/hierarchical-queries-in-postgresql/\" rel=\"noreferrer\"><strong>Hierarchical queries in PostgreSQL</strong></a></li>\n</ul>\n"
},
{
"answer_id": 5701124,
"author": "Endy Tjahjono",
"author_id": 196451,
"author_profile": "https://Stackoverflow.com/users/196451",
"pm_score": 5,
"selected": false,
"text": "<p>Here is an example script using common table expression:</p>\n\n<pre><code>with recursive sumthis(id, val) as (\n select id, value\n from example\n where id = :selectedid\n union all\n select C.id, C.value\n from sumthis P\n inner join example C on P.id = C.parentid\n)\nselect sum(val) from sumthis\n</code></pre>\n\n<p>The script above creates a 'virtual' table called <code>sumthis</code> that has columns <code>id</code> and <code>val</code>. It is defined as the result of two selects merged with <code>union all</code>.</p>\n\n<p>First <code>select</code> gets the root (<code>where id = :selectedid</code>).</p>\n\n<p>Second <code>select</code> follows the children of the previous results iteratively until there is nothing to return.</p>\n\n<p>The end result can then be processed like a normal table. In this case the val column is summed.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/53112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] | What are good ways of dealing with the issues surrounding plugin code that interacts with outside system?
To give a concrete and representative example, suppose I would like to use Subversion and Eclipse to develop plugins for WordPress. The main code body of WordPress is installed on the webserver, and the plugin code needs to be available in a subdirectory of that server.
I could see how you could simply checkout a copy of your code directly under the web directory on a development machine, but how would you also then integrate this with the IDE?
I am making the assumption here that all the code for the plugin is located under a single directory.
Do most people just add the plugin as a project in an IDE and then place the working folder for the project wherever the 'main' software system wants it to be? Or do people use some kind of symlinks to their home directory? | There are a few ways to do what you need in PostgreSQL.
* If you can install modules, look at the tablefunc contrib. It has a connectby() function that handles traversing trees. <http://www.postgresql.org/docs/8.3/interactive/tablefunc.html>
* Also check out the ltree contrib, which you could adapt your table to use: <http://www.postgresql.org/docs/8.3/interactive/ltree.html>
* Or you can traverse the tree yourself with a PL/PGSQL function.
Something like this:
```
create or replace function example_subtree (integer)
returns setof example as
'declare results record;
child record;
begin
select into results * from example where parent_id = $1;
if found then
return next results;
for child in select id from example
where parent_id = $1
loop
for temp in select * from example_subtree(child.id)
loop
return next temp;
end loop;
end loop;
end if;
return null;
end;' language 'plpgsql';
select sum(value) as value_sum
from example_subtree(1234);
``` |
53,128 | <p>I have a webapp that uses JNDI lookups to get a connection to the database.</p>
<p>The connection works fine and returns the query no problems. The issue us that the connection does not close properly and is stuck in the 'sleep' mode (according to mysql administrator). This means that they become unusable nad then I run out of connections.</p>
<p>Can someone give me a few pointers as to what I can do to make the connection return to the pool successfully.</p>
<pre><code>public class DatabaseBean {
private static final Logger logger = Logger.getLogger(DatabaseBean.class);
private Connection conn;
private PreparedStatement prepStmt;
/**
* Zero argument constructor
* Setup generic databse connection in here to avoid redundancy
* The connection details are in /META-INF/context.xml
*/
public DatabaseBean() {
try {
InitialContext initContext = new InitialContext();
DataSource ds = (DataSource) initContext.lookup("java:/comp/env/jdbc/mysite");
conn = ds.getConnection();
}
catch (SQLException SQLEx) {
logger.fatal("There was a problem with the database connection.");
logger.fatal(SQLEx);
logger.fatal(SQLEx.getCause());
}
catch (NamingException nameEx) {
logger.fatal("There was a naming exception");
logger.fatal(nameEx);
logger.fatal(nameEx.getCause());
}
}
/**
* Execute a query. Do not use for statements (update delete insert etc).
*
* @return A ResultSet of the execute query. A set of size zero if no results were returned. It is never null.
* @see #executeUpdate() for running update, insert delete etc.
*/
public ResultSet executeQuery() {
ResultSet result = null;
try {
result = prepStmt.executeQuery();
logger.debug(prepStmt.toString());
}
catch (SQLException SQLEx) {
logger.fatal("There was an error running a query");
logger.fatal(SQLEx);
}
return result;
}
</code></pre>
<p><em>SNIP</em></p>
<pre><code>public void close() {
try {
prepStmt.close();
prepStmt = null;
conn.close();
conn = null;
} catch (SQLException SQLEx) {
logger.warn("There was an error closing the database connection.");
}
}
}
</code></pre>
<p>This is inside a javabean that uses the database connection.</p>
<pre><code>public LinkedList<ImportantNoticeBean> getImportantNotices() {
DatabaseBean noticesDBBean = new DatabaseBean();
LinkedList<ImportantNoticeBean> listOfNotices = new LinkedList<ImportantNoticeBean>();
try {
PreparedStatement preStmt = noticesDBBean.getConn().prepareStatement("SELECT pseudonym, message, date_to, date_from " +
"FROM importantnotices, users " +
"WHERE importantnotices.username = users.username " +
"AND NOW() >= date_from AND NOW() <= date_to;");
noticesDBBean.setPrepStmt(preStmt);
ResultSet result = noticesDBBean.executeQuery();
while (result.next()) {
ImportantNoticeBean noticeBean = new ImportantNoticeBean();
noticeBean.setAuthor(result.getString("pseudonym"));
noticeBean.setMessage(result.getString("message"));
noticeBean.setDateTo(result.getDate("date_to"));
noticeBean.setDateFrom(result.getDate("date_from"));
listOfNotices.add(noticeBean);
}
result.close();
} catch (SQLException SQLEx) {
logger.error("There was an error in ImportantNoticesBean.getImportantNotices()");
logger.error(SQLEx);
} finally {
noticesDBBean.close();
}
return listOfNotices;
}
<Context reloadable="true">
<Resource name="jdbc/mysite"
auth="Container"
type="javax.sql.DataSource"
username="user"
password="password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mysite"
maxActive="10"
maxIdle="5"
maxWait="6000"
removeAbandoned="true"
logAbandoned="false"
removeAbandonedTimeout="20"
/>
</Context>
</code></pre>
| [
{
"answer_id": 53285,
"author": "Binil Thomas",
"author_id": 3973,
"author_profile": "https://Stackoverflow.com/users/3973",
"pm_score": 2,
"selected": false,
"text": "<p>You seem to be closing the connection properly - except for the case where prepStmt.close() throws a SQLException, I can't find a connection leak.</p>\n\n<p>What pool implementation are you using? When you close a connection, the pool need not close the underlying MySQL connection immediately - after all that is the point of a connection pool! So from MySQL side, the connections would look alive, although your app is not using any; they might simply be held by the TC connection pool.</p>\n\n<p>You might want to experiment with the settings of the connection pool.Ask it to shrink the pool when the system is idle. Or, ask it to refresh all connections periodically. Or, have a strict upper bound on the number of concurrent connections it ever gets from MySQL etc.</p>\n\n<p>One way to check if your code has a connection leak is to force the ds.getConnection() to always open a new physical connection and conn.close() to release the connection (if your connection pool has settings for those). Then if you watch the connections on MySQL side, you might be able to figure out if the code really has a connection leak or not.</p>\n"
},
{
"answer_id": 53912,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 0,
"selected": false,
"text": "<p>One thing that @binil missed, you are not closing the result set in the case of an exception. Depending on the driver implementation this may cause the connection to stay open. Move the result.close() call to the finally block. </p>\n"
},
{
"answer_id": 54095,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 2,
"selected": false,
"text": "<p>This is a similar question - <a href=\"https://stackoverflow.com/questions/15949/javatomcat-dying-databse-connection#16168\">Connection Pool Settings for Tomcat</a> </p>\n\n<p>This is my response to that question and it fixed the problem for the other guy. It may help you out too.</p>\n\n<p><a href=\"http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html\" rel=\"nofollow noreferrer\">Tomcat Documentation</a></p>\n\n<p>DBCP uses the Jakarta-Commons Database Connection Pool. It relies on number of Jakarta-Commons components:</p>\n\n<pre><code>* Jakarta-Commons DBCP\n* Jakarta-Commons Collections\n* Jakarta-Commons Pool\n</code></pre>\n\n<p>I'm using the same connection pooling stuff and I'm setting these properties to prevent the same thing it's just not configured through tomcat.\nBut if the first thing doesn't work try these.</p>\n\n<pre><code>testWhileIdle=true\ntimeBetweenEvictionRunsMillis=300000\n</code></pre>\n"
},
{
"answer_id": 58778,
"author": "Doug Miller",
"author_id": 3431280,
"author_profile": "https://Stackoverflow.com/users/3431280",
"pm_score": 2,
"selected": false,
"text": "<p>Ok I might have this sorted. I have changed the database config resource to the following:</p>\n\n<pre><code>*SNIP*\nmaxActive=\"10\"\nmaxIdle=\"5\"\nmaxWait=\"7000\"\nremoveAbandoned=\"true\"\nlogAbandoned=\"false\"\nremoveAbandonedTimeout=\"3\"\n*SNIP*\n</code></pre>\n\n<p>This works well enough for now. What is happening, afaik, is that once I reach the ten connections then Tomcat is checking for abandoned connections (idle time > 3). It does this in a batch job each time that max connections is reached. The potential issue with this is if i need more than 10 queries run at the same time (not unique to me). The important thing is that removeAbandonedTimeout is less than maxWait.</p>\n\n<p>Is this what should be happening? ie Is this the way that the pool should operate? If it is is seems, at least to me, that you would wait until something (the connection) is broken before fixing rather than not letting it 'break' in the first place. Maybe I am still not getting it.</p>\n"
},
{
"answer_id": 1085473,
"author": "Igor Zelaya",
"author_id": 22769,
"author_profile": "https://Stackoverflow.com/users/22769",
"pm_score": 0,
"selected": false,
"text": "<p>I am using the same configuration as you are. If the connection in mysql administrator(windows) shows that it is in sleep mode it only means that is pooled but not in use. I checked this running a test program program with multiple threads making random queries to Mysql. if it helps here is my configuration:</p>\n\n<pre><code> defaultAutoCommit=\"false\"\n defaultTransactionIsolation=\"REPEATABLE_READ\"\n auth=\"Container\"\n type=\"javax.sql.DataSource\"\n logAbandoned=\"true\" \n removeAbandoned=\"true\"\n removeAbandonedTimeout=\"300\" \n maxActive=\"-1\"\n initialSize=\"15\"\n maxIdle=\"10\"\n maxWait=\"10000\" \n username=\"youruser\"\n password=\"youruserpassword\"\n driverClassName=\"com.mysql.jdbc.Driver\"\n url=\"jdbc:mysql://yourhost/yourdatabase\"/>\n</code></pre>\n"
},
{
"answer_id": 4121987,
"author": "Doug Miller",
"author_id": 3431280,
"author_profile": "https://Stackoverflow.com/users/3431280",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n <p>The issue us that the connection does not close properly and is stuck in the 'sleep' mode</p>\n</blockquote>\n\n<p>This was actually only half right.</p>\n\n<p>The problem I ran into was actually that each app was defining a new connection to the database sever. So each time I closed all the connections App A would make a bunch of new connections as per it's WEB.xml config file and run happily. App B would do the same. The problem is that they are <em>independent pools</em> which try to grab up to the server defined limit. It is a kind of race condition I guess. So when App A has finished with the connections it sits waiting to to use them again until the timeout has passed while App B who needs the connection now is denied the resources even though App A has finished with the and should be back in the pool. Once the timeout has passed, the connection is freed up and B (or C etc) can get at it again.</p>\n\n<p>e.g. if the limit is 10 (mySQL profile limit) and each app has been configured to use a max of 10 the there will be 20 attempts at connections. Obviously this is a bad situation.</p>\n\n<p>The solution is to RTFM and put the <a href=\"http://tomcat.apache.org/tomcat-5.5-doc/config/context.html\" rel=\"nofollow\">connection details in the right place</a>. This does make shared posting a pain but there are ways around it (such as linking to other xml files from the context).</p>\n\n<p>Just to be explicit: I put the connection details in the WEB.xml for each app and the had a fight about it.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/53128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3431280/"
] | I have a webapp that uses JNDI lookups to get a connection to the database.
The connection works fine and returns the query no problems. The issue us that the connection does not close properly and is stuck in the 'sleep' mode (according to mysql administrator). This means that they become unusable nad then I run out of connections.
Can someone give me a few pointers as to what I can do to make the connection return to the pool successfully.
```
public class DatabaseBean {
private static final Logger logger = Logger.getLogger(DatabaseBean.class);
private Connection conn;
private PreparedStatement prepStmt;
/**
* Zero argument constructor
* Setup generic databse connection in here to avoid redundancy
* The connection details are in /META-INF/context.xml
*/
public DatabaseBean() {
try {
InitialContext initContext = new InitialContext();
DataSource ds = (DataSource) initContext.lookup("java:/comp/env/jdbc/mysite");
conn = ds.getConnection();
}
catch (SQLException SQLEx) {
logger.fatal("There was a problem with the database connection.");
logger.fatal(SQLEx);
logger.fatal(SQLEx.getCause());
}
catch (NamingException nameEx) {
logger.fatal("There was a naming exception");
logger.fatal(nameEx);
logger.fatal(nameEx.getCause());
}
}
/**
* Execute a query. Do not use for statements (update delete insert etc).
*
* @return A ResultSet of the execute query. A set of size zero if no results were returned. It is never null.
* @see #executeUpdate() for running update, insert delete etc.
*/
public ResultSet executeQuery() {
ResultSet result = null;
try {
result = prepStmt.executeQuery();
logger.debug(prepStmt.toString());
}
catch (SQLException SQLEx) {
logger.fatal("There was an error running a query");
logger.fatal(SQLEx);
}
return result;
}
```
*SNIP*
```
public void close() {
try {
prepStmt.close();
prepStmt = null;
conn.close();
conn = null;
} catch (SQLException SQLEx) {
logger.warn("There was an error closing the database connection.");
}
}
}
```
This is inside a javabean that uses the database connection.
```
public LinkedList<ImportantNoticeBean> getImportantNotices() {
DatabaseBean noticesDBBean = new DatabaseBean();
LinkedList<ImportantNoticeBean> listOfNotices = new LinkedList<ImportantNoticeBean>();
try {
PreparedStatement preStmt = noticesDBBean.getConn().prepareStatement("SELECT pseudonym, message, date_to, date_from " +
"FROM importantnotices, users " +
"WHERE importantnotices.username = users.username " +
"AND NOW() >= date_from AND NOW() <= date_to;");
noticesDBBean.setPrepStmt(preStmt);
ResultSet result = noticesDBBean.executeQuery();
while (result.next()) {
ImportantNoticeBean noticeBean = new ImportantNoticeBean();
noticeBean.setAuthor(result.getString("pseudonym"));
noticeBean.setMessage(result.getString("message"));
noticeBean.setDateTo(result.getDate("date_to"));
noticeBean.setDateFrom(result.getDate("date_from"));
listOfNotices.add(noticeBean);
}
result.close();
} catch (SQLException SQLEx) {
logger.error("There was an error in ImportantNoticesBean.getImportantNotices()");
logger.error(SQLEx);
} finally {
noticesDBBean.close();
}
return listOfNotices;
}
<Context reloadable="true">
<Resource name="jdbc/mysite"
auth="Container"
type="javax.sql.DataSource"
username="user"
password="password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mysite"
maxActive="10"
maxIdle="5"
maxWait="6000"
removeAbandoned="true"
logAbandoned="false"
removeAbandonedTimeout="20"
/>
</Context>
``` | >
> The issue us that the connection does not close properly and is stuck in the 'sleep' mode
>
>
>
This was actually only half right.
The problem I ran into was actually that each app was defining a new connection to the database sever. So each time I closed all the connections App A would make a bunch of new connections as per it's WEB.xml config file and run happily. App B would do the same. The problem is that they are *independent pools* which try to grab up to the server defined limit. It is a kind of race condition I guess. So when App A has finished with the connections it sits waiting to to use them again until the timeout has passed while App B who needs the connection now is denied the resources even though App A has finished with the and should be back in the pool. Once the timeout has passed, the connection is freed up and B (or C etc) can get at it again.
e.g. if the limit is 10 (mySQL profile limit) and each app has been configured to use a max of 10 the there will be 20 attempts at connections. Obviously this is a bad situation.
The solution is to RTFM and put the [connection details in the right place](http://tomcat.apache.org/tomcat-5.5-doc/config/context.html). This does make shared posting a pain but there are ways around it (such as linking to other xml files from the context).
Just to be explicit: I put the connection details in the WEB.xml for each app and the had a fight about it. |
53,161 | <p>what I'm after is something I can feed a number into and it will return the highest order bit. I'm sure there's a simple way. Below is an example output (left is the input)</p>
<pre>1 -> 1
2 -> 2
3 -> 2
4 -> 4
5 -> 4
6 -> 4
7 -> 4
8 -> 8
9 -> 8
...
63 -> 32</pre>
| [
{
"answer_id": 53174,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 3,
"selected": false,
"text": "<p>Continually remove the low order bit comes to mind...</p>\n\n<pre><code>int highest_order_bit( int x )\n{\n int y = x;\n do { \n x = y;\n y = x & (x-1); //remove low order bit\n }\n while( y != 0 );\n return x;\n}\n</code></pre>\n"
},
{
"answer_id": 53175,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 6,
"selected": true,
"text": "<p>This should do the trick.</p>\n\n<pre><code>int hob (int num)\n{\n if (!num)\n return 0;\n\n int ret = 1;\n\n while (num >>= 1)\n ret <<= 1;\n\n return ret;\n}\n</code></pre>\n\n<p>hob(1234) returns 1024<br>\nhob(1024) returns 1024<br>\nhob(1023) returns 512</p>\n"
},
{
"answer_id": 53184,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 7,
"selected": false,
"text": "<p>From Hacker's Delight:</p>\n\n<pre><code>int hibit(unsigned int n) {\n n |= (n >> 1);\n n |= (n >> 2);\n n |= (n >> 4);\n n |= (n >> 8);\n n |= (n >> 16);\n return n - (n >> 1);\n}\n</code></pre>\n\n<p>This version is for 32-bit ints, but the logic can be extended for 64-bits or higher.</p>\n"
},
{
"answer_id": 53229,
"author": "theorbtwo",
"author_id": 4839,
"author_profile": "https://Stackoverflow.com/users/4839",
"pm_score": 3,
"selected": false,
"text": "<p>The linux kernel has a number of handy bitops like this, coded in the most efficient way for a number of architectures. You can find generic versions in <a href=\"http://lxr.linux.no/linux+v2.6.26.5/include/asm-generic/bitops/fls.h\" rel=\"nofollow noreferrer\">include/asm-generic/bitops/fls.h</a> (and friends), but see also <a href=\"http://lxr.linux.no/linux+v2.6.26.5/include/asm-x86/bitops.h\" rel=\"nofollow noreferrer\">include/asm-x86/bitops.h</a> for a definition using inline assembly if speed is of the essence, and portability is not.</p>\n"
},
{
"answer_id": 53298,
"author": "Ben Lever",
"author_id": 2045,
"author_profile": "https://Stackoverflow.com/users/2045",
"pm_score": 2,
"selected": false,
"text": "<p>A fast way to do this is via a look-up table. For a 32-bit input, and an 8-bit look-up table, in only requires 4 iterations:</p>\n\n<pre><code>int highest_order_bit(int x)\n{\n static const int msb_lut[256] =\n {\n 0, 0, 1, 1, 2, 2, 2, 2, // 0000_0000 - 0000_0111\n 3, 3, 3, 3, 3, 3, 3, 3, // 0000_1000 - 0000_1111\n 4, 4, 4, 4, 4, 4, 4, 4, // 0001_0000 - 0001_0111\n 4, 4, 4, 4, 4, 4, 4, 4, // 0001_1000 - 0001_1111\n 5, 5, 5, 5, 5, 5, 5, 5, // 0010_0000 - 0010_0111\n 5, 5, 5, 5, 5, 5, 5, 5, // 0010_1000 - 0010_1111\n 5, 5, 5, 5, 5, 5, 5, 5, // 0011_0000 - 0011_0111\n 5, 5, 5, 5, 5, 5, 5, 5, // 0011_1000 - 0011_1111\n\n 6, 6, 6, 6, 6, 6, 6, 6, // 0100_0000 - 0100_0111\n 6, 6, 6, 6, 6, 6, 6, 6, // 0100_1000 - 0100_1111\n 6, 6, 6, 6, 6, 6, 6, 6, // 0101_0000 - 0101_0111\n 6, 6, 6, 6, 6, 6, 6, 6, // 0101_1000 - 0101_1111\n 6, 6, 6, 6, 6, 6, 6, 6, // 0110_0000 - 0110_0111\n 6, 6, 6, 6, 6, 6, 6, 6, // 0110_1000 - 0110_1111\n 6, 6, 6, 6, 6, 6, 6, 6, // 0111_0000 - 0111_0111\n 6, 6, 6, 6, 6, 6, 6, 6, // 0111_1000 - 0111_1111\n\n 7, 7, 7, 7, 7, 7, 7, 7, // 1000_0000 - 1000_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1000_1000 - 1000_1111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1001_0000 - 1001_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1001_1000 - 1001_1111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1010_0000 - 1010_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1010_1000 - 1010_1111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1011_0000 - 1011_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1011_1000 - 1011_1111\n\n 7, 7, 7, 7, 7, 7, 7, 7, // 1100_0000 - 1100_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1100_1000 - 1100_1111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1101_0000 - 1101_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1101_1000 - 1101_1111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1110_0000 - 1110_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1110_1000 - 1110_1111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1111_0000 - 1111_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1111_1000 - 1111_1111\n };\n\n int byte;\n int byte_cnt;\n\n for (byte_cnt = 3; byte_cnt >= 0; byte_cnt--)\n {\n byte = (x >> (byte_cnt * 8)) & 0xff;\n if (byte != 0)\n {\n return msb_lut[byte] + (byte_cnt * 8);\n }\n }\n\n return -1;\n}\n</code></pre>\n"
},
{
"answer_id": 53509,
"author": "dmityugov",
"author_id": 3232,
"author_profile": "https://Stackoverflow.com/users/3232",
"pm_score": 5,
"selected": false,
"text": "<p>like obfuscated code? Try this:</p>\n\n<p>1 << ( int) log2( x)</p>\n"
},
{
"answer_id": 1454990,
"author": "dharga",
"author_id": 176554,
"author_profile": "https://Stackoverflow.com/users/176554",
"pm_score": 2,
"selected": false,
"text": "<p>This can easily be solved with existing library calls.</p>\n\n<pre><code>int highestBit(int v){\n return fls(v) << 1;\n}\n</code></pre>\n\n<p>The Linux man page gives more details on this function and its counterparts for other input types.</p>\n"
},
{
"answer_id": 12376351,
"author": "bobobobo",
"author_id": 111307,
"author_profile": "https://Stackoverflow.com/users/111307",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// Note doesn't cover the case of 0 (0 returns 1)\ninline unsigned int hibit( unsigned int x )\n{\n unsigned int log2Val = 0 ;\n while( x>>=1 ) log2Val++; // eg x=63 (111111), log2Val=5\n return 1 << log2Val ; // finds 2^5=32\n}\n</code></pre>\n"
},
{
"answer_id": 14085901,
"author": "Fabian",
"author_id": 343664,
"author_profile": "https://Stackoverflow.com/users/343664",
"pm_score": 5,
"selected": false,
"text": "<p><code>fls</code> bottoms out to a hardware instruction on many architectures. I suspect this is probably the simplest, fastest way of doing it. </p>\n\n<pre><code>1<<(fls(input)-1)\n</code></pre>\n"
},
{
"answer_id": 30143805,
"author": "Gavin Sellers",
"author_id": 1123590,
"author_profile": "https://Stackoverflow.com/users/1123590",
"pm_score": 0,
"selected": false,
"text": "<p>A nifty solution I came up with is to binary search the bits.</p>\n\n<pre><code>uint64_t highestBit(uint64_t a, uint64_t bit_min, uint64_t bit_max, uint16_t bit_shift){\n if(a == 0) return 0;\n if(bit_min >= bit_max){\n if((a & bit_min) != 0)\n return bit_min;\n return 0;\n }\n uint64_t bit_mid = bit_max >> bit_shift;\n bit_shift >>= 1;\n if((a >= bit_mid) && (a < (bit_mid << 1)))\n return bit_mid;\n else if(a > bit_mid)\n return highestBit(a, bit_mid, bit_max, bit_shift);\n else\n return highestBit(a, bit_min, bit_mid, bit_shift);\n\n}\n</code></pre>\n\n<p>Bit max is the highest power of 2, so for a 64 bit number it would be 2^63. Bit shift should be initialized to half the number of bits, so for 64 bits, it would be 32.</p>\n"
},
{
"answer_id": 30619464,
"author": "Igor Levicki",
"author_id": 1778190,
"author_profile": "https://Stackoverflow.com/users/1778190",
"pm_score": 2,
"selected": false,
"text": "<p>If you do not need a portable solution and your code is executing on an x86 compatible CPU you can use _BitScanReverse() intrinsic function provided by Microsoft Visual C/C++ compiler. It maps to BSR CPU instruction which returns the highest bit set.</p>\n"
},
{
"answer_id": 42030874,
"author": "Kean",
"author_id": 849635,
"author_profile": "https://Stackoverflow.com/users/849635",
"pm_score": 3,
"selected": false,
"text": "<p>Little bit late to this party but the simplest solution I found, given a modern GCC as a compiler is simply:</p>\n\n<pre><code>static inline int_t get_msb32 (register unsigned int val)\n{\n return 32 - __builtin_clz(val);\n}\n\nstatic inline int get_msb64 (register unsigned long long val)\n{\n return 64 - __builtin_clzll(val);\n}\n</code></pre>\n\n<p>It's even relatively portable (at the very least it will work on any GCC platform).</p>\n"
},
{
"answer_id": 62509101,
"author": "Анатолий",
"author_id": 13789999,
"author_profile": "https://Stackoverflow.com/users/13789999",
"pm_score": 2,
"selected": false,
"text": "<p>The best algorithm I like very much is:</p>\n<pre><code>unsigned hibit(unsigned n) {\n n |= (n >> 1u);\n n |= (n >> 2u);\n n |= (n >> 4u);\n n |= (n >> 8u);\n n |= (n >> 16u);\n return n - (n >> 1);\n}\n</code></pre>\n<p>And it's easily extended for uint64_t like that:</p>\n<pre><code>uint64_t hibit(uint64_t n) {\n n |= (n >> 1u);\n n |= (n >> 2u);\n n |= (n >> 4u);\n n |= (n >> 8u);\n n |= (n >> 16u);\n n |= (n >> 32u);\n return n - (n >> 1);\n}\n</code></pre>\n<p>or even to __int128</p>\n<pre><code>__int128 hibit(__int128 n) {\n n |= (n >> 1u);\n n |= (n >> 2u);\n n |= (n >> 4u);\n n |= (n >> 8u);\n n |= (n >> 16u);\n n |= (n >> 32u);\n n |= (n >> 64u);\n return n - (n >> 1);\n}\n</code></pre>\n<p>In addition is crossplatphorm solution independend of using compilator</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/53161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1057/"
] | what I'm after is something I can feed a number into and it will return the highest order bit. I'm sure there's a simple way. Below is an example output (left is the input)
```
1 -> 1
2 -> 2
3 -> 2
4 -> 4
5 -> 4
6 -> 4
7 -> 4
8 -> 8
9 -> 8
...
63 -> 32
``` | This should do the trick.
```
int hob (int num)
{
if (!num)
return 0;
int ret = 1;
while (num >>= 1)
ret <<= 1;
return ret;
}
```
hob(1234) returns 1024
hob(1024) returns 1024
hob(1023) returns 512 |
53,162 | <p>Given:</p>
<pre><code>e = 'a' + 'b' + 'c' + 'd'
</code></pre>
<p>How do I write the above in two lines?</p>
<pre><code>e = 'a' + 'b' +
'c' + 'd'
</code></pre>
| [
{
"answer_id": 53173,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 5,
"selected": false,
"text": "<p>Put a <code>\\</code> at the end of your line or enclose the statement in parens <code>( .. )</code>. From <a href=\"http://www.ibm.com/developerworks/opensource/library/os-python5/\" rel=\"noreferrer\">IBM</a>:</p>\n\n<pre><code>b = ((i1 < 20) and\n (i2 < 30) and\n (i3 < 40))\n</code></pre>\n\n<p>or</p>\n\n<pre><code>b = (i1 < 20) and \\\n (i2 < 30) and \\\n (i3 < 40)\n</code></pre>\n"
},
{
"answer_id": 53180,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 12,
"selected": true,
"text": "<p>What is the line? You can just have arguments on the next line without any problems:</p>\n<pre><code>a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5, \n blahblah6, blahblah7)\n</code></pre>\n<p>Otherwise you can do something like this:</p>\n<pre><code>if (a == True and\n b == False):\n</code></pre>\n<p>or with explicit line break:</p>\n<pre><code>if a == True and \\\n b == False:\n</code></pre>\n<p>Check the <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">style guide</a> for more information.</p>\n<p>Using parentheses, your example can be written over multiple lines:</p>\n<pre><code>a = ('1' + '2' + '3' +\n '4' + '5')\n</code></pre>\n<p>The same effect can be obtained using explicit line break:</p>\n<pre><code>a = '1' + '2' + '3' + \\\n '4' + '5'\n</code></pre>\n<p>Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.</p>\n"
},
{
"answer_id": 53182,
"author": "Jason Navarrete",
"author_id": 3920,
"author_profile": "https://Stackoverflow.com/users/3920",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>From the horse's mouth: <a href=\"https://docs.python.org/2.5/ref/explicit-joining.html\" rel=\"noreferrer\">Explicit line\n joining </a></p>\n \n <p>Two or more physical lines may be\n joined into logical lines using\n backslash characters (<code>\\</code>), as follows:\n when a physical line ends in a\n backslash that is not part of a string\n literal or comment, it is joined with\n the following forming a single logical\n line, deleting the backslash and the\n following end-of-line character. For\n example:</p>\n\n<pre><code>if 1900 < year < 2100 and 1 <= month <= 12 \\\n and 1 <= day <= 31 and 0 <= hour < 24 \\\n and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date\n return 1\n</code></pre>\n \n <p>A line ending in a backslash cannot\n carry a comment. A backslash does not\n continue a comment. A backslash does\n not continue a token except for string\n literals (i.e., tokens other than\n string literals cannot be split across\n physical lines using a backslash). A\n backslash is illegal elsewhere on a\n line outside a string literal. </p>\n</blockquote>\n"
},
{
"answer_id": 53200,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 8,
"selected": false,
"text": "<p>From <em><a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8 -- Style Guide for Python Code</a></em>:</p>\n<blockquote>\n<p><strong>The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces.</strong> Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.</p>\n</blockquote>\n<blockquote>\n<p>Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable:</p>\n</blockquote>\n<blockquote>\n<pre><code>with open('/path/to/some/file/you/want/to/read') as file_1, \\\n open('/path/to/some/file/being/written', 'w') as file_2:\n file_2.write(file_1.read())\n</code></pre>\n<p>Another such case is with assert statements.</p>\n</blockquote>\n<blockquote>\n<p>Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is <strong>after</strong> the operator, not before it. Some examples:</p>\n</blockquote>\n<blockquote>\n<pre><code>class Rectangle(Blob):\n\n def __init__(self, width, height,\n color='black', emphasis=None, highlight=0):\n if (width == 0 and height == 0 and\n color == 'red' and emphasis == 'strong' or\n highlight > 100):\n raise ValueError("sorry, you lose")\n if width == 0 and height == 0 and (color == 'red' or\n emphasis is None):\n raise ValueError("I don't think so -- values are %s, %s" %\n (width, height))\n Blob.__init__(self, width, height,\n color, emphasis, highlight)file_2.write(file_1.read())\n</code></pre>\n</blockquote>\n<p>PEP8 now recommends the <em>opposite convention</em> (for breaking at binary operations) used by mathematicians and their publishers to improve readability.</p>\n<p>Donald Knuth's style of breaking <strong>before</strong> a binary operator aligns operators vertically, thus reducing the eye's workload when determining which items are added and subtracted.</p>\n<p>From <a href=\"http://legacy.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator\" rel=\"noreferrer\">PEP8: <em>Should a line break before or after a binary operator?</em></a>:</p>\n<blockquote>\n<p>Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations"[3].</p>\n</blockquote>\n<blockquote>\n<p>Following the tradition from mathematics usually results in more readable code:</p>\n</blockquote>\n<blockquote>\n<pre><code># Yes: easy to match operators with operands\n</code></pre>\n</blockquote>\n<pre><code>income = (gross_wages\n + taxable_interest\n + (dividends - qualified_dividends)\n - ira_deduction\n - student_loan_interest)\n</code></pre>\n<blockquote>\n<p>In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style is suggested.</p>\n</blockquote>\n<p>[3]: Donald Knuth's The TeXBook, pages 195 and 196</p>\n"
},
{
"answer_id": 61933,
"author": "George V. Reilly",
"author_id": 6364,
"author_profile": "https://Stackoverflow.com/users/6364",
"pm_score": 6,
"selected": false,
"text": "<p>The danger in using a backslash to end a line is that if whitespace is added after the backslash (which, of course, is very hard to see), the backslash is no longer doing what you thought it was.</p>\n\n<p>See Python Idioms and Anti-Idioms (for <a href=\"https://docs.python.org/2/howto/doanddont.html#using-backslash-to-continue-statements\" rel=\"noreferrer\">Python 2</a> or <a href=\"https://docs.python.org/3.1/howto/doanddont.html#using-backslash-to-continue-statements\" rel=\"noreferrer\">Python 3</a>) for more.</p>\n"
},
{
"answer_id": 110882,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<p>You can break lines in between parenthesises and braces. Additionally, you can append the backslash character <code>\\</code> to a line to explicitly break it:</p>\n\n<pre><code>x = (tuples_first_value,\n second_value)\ny = 1 + \\\n 2\n</code></pre>\n"
},
{
"answer_id": 53117661,
"author": "Hardik Sondagar",
"author_id": 2553366,
"author_profile": "https://Stackoverflow.com/users/2553366",
"pm_score": 3,
"selected": false,
"text": "<p>It may not be the Pythonic way, but I generally use a list with the join function for writing a long string, like SQL queries:</p>\n\n<pre><code>query = \" \".join([\n 'SELECT * FROM \"TableName\"',\n 'WHERE \"SomeColumn1\"=VALUE',\n 'ORDER BY \"SomeColumn2\"',\n 'LIMIT 5;'\n])\n</code></pre>\n"
},
{
"answer_id": 53657814,
"author": "ivanleoncz",
"author_id": 5780109,
"author_profile": "https://Stackoverflow.com/users/5780109",
"pm_score": 2,
"selected": false,
"text": "<p>Taken from The Hitchhiker's Guide to Python (<a href=\"https://docs.python-guide.org/writing/style/#line-continuations\" rel=\"nofollow noreferrer\">Line Continuation</a>):</p>\n<blockquote>\n<p>When a logical line of code is longer than the accepted limit, you need to split it over multiple physical lines. The Python interpreter will join consecutive lines if the last character of the line is a backslash. This is helpful in some cases, but should usually be avoided because of its fragility: a white space added to the end of the line, after the backslash, will break the code and may have unexpected results.</p>\n<p><strong>A better solution is to use parentheses around your elements.</strong> Left with an unclosed parenthesis on an end-of-line the Python interpreter will join the next line until the parentheses are closed. The same behaviour holds for curly and square braces.</p>\n<p><strong>However</strong>, more often than not, having to split a long logical line is a sign that you are trying to do too many things at the same time, which may hinder readability.</p>\n</blockquote>\n<p>Having that said, here's an example considering multiple imports (when exceeding <a href=\"https://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"nofollow noreferrer\">line limits, defined on PEP-8</a>), also applied to strings in general:</p>\n<pre><code>from app import (\n app, abort, make_response, redirect, render_template, request, session\n)\n</code></pre>\n"
},
{
"answer_id": 60844786,
"author": "jlaurens",
"author_id": 4858081,
"author_profile": "https://Stackoverflow.com/users/4858081",
"pm_score": 4,
"selected": false,
"text": "<p>If you want to break your line because of a long literal string, you can break that string into pieces:</p>\n<pre><code>long_string = "a very long string"\nprint("a very long string")\n</code></pre>\n<p>will be replaced by</p>\n<pre><code>long_string = (\n "a "\n "very "\n "long "\n "string"\n)\nprint(\n "a "\n "very "\n "long "\n "string"\n)\n</code></pre>\n<p>Output for both print statements:</p>\n<p><code>a very long string</code></p>\n<p>Notice the parenthesis in the affectation.</p>\n<p>Notice also that breaking literal strings into pieces allows to use the literal prefix only on parts of the string and mix the delimiters:</p>\n<pre><code>s = (\n '''2+2='''\n f"{2+2}"\n)\n</code></pre>\n"
},
{
"answer_id": 64812795,
"author": "Brandt",
"author_id": 687896,
"author_profile": "https://Stackoverflow.com/users/687896",
"pm_score": 4,
"selected": false,
"text": "<p>One can also break the call of methods (<code>obj.method()</code>) in multiple lines.</p>\n<p>Enclose the command in parenthesis "<code>()</code>" and span multiple lines:</p>\n<pre><code>> res = (some_object\n .apply(args)\n .filter()\n .values)\n</code></pre>\n<p>For instance, I find it useful on chain calling Pandas/Holoviews objects methods.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/53162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | Given:
```
e = 'a' + 'b' + 'c' + 'd'
```
How do I write the above in two lines?
```
e = 'a' + 'b' +
'c' + 'd'
``` | What is the line? You can just have arguments on the next line without any problems:
```
a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5,
blahblah6, blahblah7)
```
Otherwise you can do something like this:
```
if (a == True and
b == False):
```
or with explicit line break:
```
if a == True and \
b == False:
```
Check the [style guide](http://www.python.org/dev/peps/pep-0008/) for more information.
Using parentheses, your example can be written over multiple lines:
```
a = ('1' + '2' + '3' +
'4' + '5')
```
The same effect can be obtained using explicit line break:
```
a = '1' + '2' + '3' + \
'4' + '5'
```
Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go. |
53,208 | <p>In C++ Windows app, I launch several long running child processes (currently I use CreateProcess(...) to do this. </p>
<p>I want the child processes to be automatically closed <strong>if my main processes crashes</strong> or is closed.</p>
<p>Because of the requirement that this needs to work for a crash of the "parent", I believe this would need to be done using some API/feature of the operating system. So that all the "child" processes are cleaned up.</p>
<p>How do I do this?</p>
| [
{
"answer_id": 53212,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": -1,
"selected": false,
"text": "<p>You'd probably have to keep a list of the processes you start, and kill them off one by one when you exit your program. I'm not sure of the specifics of doing this in C++ but it shouldn't be hard. The difficult part would probably be ensuring that child processes are shutdown in the case of an application crash. .Net has the ability to add a function that get's called when an unhandled exception occurs. I'm not sure if C++ offers the same capabilities.</p>\n"
},
{
"answer_id": 53214,
"author": "jm.",
"author_id": 814,
"author_profile": "https://Stackoverflow.com/users/814",
"pm_score": 7,
"selected": true,
"text": "<p>The Windows API supports objects called \"Job Objects\". The following code will create a \"job\" that is configured to shut down all processes when the main application ends (when its handles are cleaned up). This code should only be run once.:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>HANDLE ghJob = CreateJobObject( NULL, NULL); // GLOBAL\nif( ghJob == NULL)\n{\n ::MessageBox( 0, \"Could not create job object\", \"TEST\", MB_OK);\n}\nelse\n{\n JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };\n\n // Configure all child processes associated with the job to terminate when the\n jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;\n if( 0 == SetInformationJobObject( ghJob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli)))\n {\n ::MessageBox( 0, \"Could not SetInformationJobObject\", \"TEST\", MB_OK);\n }\n}\n</code></pre>\n\n<p>Then when each child process is created, execute the following code to launch each child each process and add it to the job object:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>STARTUPINFO info={sizeof(info)};\nPROCESS_INFORMATION processInfo;\n\n// Launch child process - example is notepad.exe\nif (::CreateProcess( NULL, \"notepad.exe\", NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))\n{\n ::MessageBox( 0, \"CreateProcess succeeded.\", \"TEST\", MB_OK);\n if(ghJob)\n {\n if(0 == AssignProcessToJobObject( ghJob, processInfo.hProcess))\n {\n ::MessageBox( 0, \"Could not AssignProcessToObject\", \"TEST\", MB_OK);\n }\n }\n\n // Can we free handles now? Not sure about this.\n //CloseHandle(processInfo.hProcess); \n CloseHandle(processInfo.hThread);\n}\n</code></pre>\n\n<p>VISTA NOTE: See <a href=\"http://social.msdn.microsoft.com/Forums/en-US/windowssecurity/thread/71c9599e-a3d5-4b79-bfc1-1800565c5b8a\" rel=\"noreferrer\">AssignProcessToJobObject always return \"access denied\" on Vista</a> if you encounter access-denied issues with AssignProcessToObject() on vista.</p>\n"
},
{
"answer_id": 53216,
"author": "Pedro",
"author_id": 5488,
"author_profile": "https://Stackoverflow.com/users/5488",
"pm_score": 1,
"selected": false,
"text": "<p>You can keep a separate watchdog process running. Its only task is watching the current process space to spot situations like you describe. It could even re-launch the original application after a crash or provide different options to the user, collect debug information, etc. Just try to keep it simple enough so that you don't need a second watchdog to watch the first one.</p>\n"
},
{
"answer_id": 53218,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 3,
"selected": false,
"text": "<p>One somewhat hackish solution would be for the parent process to attach to each child as a debugger (use <a href=\"http://msdn.microsoft.com/en-us/library/ms679295(VS.85).aspx\" rel=\"noreferrer\">DebugActiveProcess</a>). When a debugger terminates all its debuggee processes are terminated as well.</p>\n\n<p>A better solution (assuming you wrote the child processes as well) would be to have the child processes monitor the parent and exit if it goes away.</p>\n"
},
{
"answer_id": 53227,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": -1,
"selected": false,
"text": "<p>You could encapsulate each process in a C++ object and keep a list of them in global scope. The destructors can shut down each process. That will work fine if the program exits normally but it it crashes, all bets are off.</p>\n\n<p>Here is a rough example:</p>\n\n<pre><code>class myprocess\n{\npublic:\n myprocess(HANDLE hProcess)\n : _hProcess(hProcess)\n { }\n\n ~myprocess()\n {\n TerminateProcess(_hProcess, 0);\n }\n\nprivate:\n HANDLE _hProcess;\n};\n\nstd::list<myprocess> allprocesses;\n</code></pre>\n\n<p>Then whenever you launch one, call allprocessess.push_back(hProcess);</p>\n"
},
{
"answer_id": 53518,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 2,
"selected": false,
"text": "<p>Windows Job Objects sounds like a good place to start. The name of the Job Object would have to be well-known, or passed to the children (or inherit the handle). The children would need to be notice when the parent dies, either through a failed IPC \"heartbeat\" or just WFMO/WFSO on the parent's process handle. At that point any child process could TermianteJobObject to bring down the whole group.</p>\n"
},
{
"answer_id": 69243480,
"author": "Kohill Yang",
"author_id": 14881537,
"author_profile": "https://Stackoverflow.com/users/14881537",
"pm_score": 0,
"selected": false,
"text": "<p>You can assign a job to the parent process before creating processes:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>static HANDLE hjob_kill_on_job_close=INVALID_HANDLE_VALUE;\nvoid init(){\n hjob_kill_on_job_close = CreateJobObject(NULL, NULL);\n if (hjob_kill_on_job_close){\n JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobli = { 0 };\n jobli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;\n SetInformationJobObject(hjob_kill_on_job_close,\n JobObjectExtendedLimitInformation,\n &jobli, sizeof(jobli));\n AssignProcessToJobObject(hjob_kill_on_job_close, GetCurrentProcess());\n }\n}\nvoid deinit(){\n if (hjob_kill_on_job_close) {\n CloseHandle(hjob_kill_on_job_close);\n }\n}\n</code></pre>\n<p><code>JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE</code> causes all processes associated with the job to terminate when the last handle to the job is closed. By default, all child processes will be assigned to the job automatically, unless you passed <code>CREATE_BREAKAWAY_FROM_JOB</code> when calling <code>CreateProcess</code>. See <a href=\"https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags</a> for more information about <code>CREATE_BREAKAWAY_FROM_JOB</code>.</p>\n<p>You can use process explorer from Sysinternals to make sure all processes are assigned to the job. Just like this:\n<a href=\"https://i.stack.imgur.com/DLERd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DLERd.png\" alt=\"enter image description here\" /></a></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
] | In C++ Windows app, I launch several long running child processes (currently I use CreateProcess(...) to do this.
I want the child processes to be automatically closed **if my main processes crashes** or is closed.
Because of the requirement that this needs to work for a crash of the "parent", I believe this would need to be done using some API/feature of the operating system. So that all the "child" processes are cleaned up.
How do I do this? | The Windows API supports objects called "Job Objects". The following code will create a "job" that is configured to shut down all processes when the main application ends (when its handles are cleaned up). This code should only be run once.:
```cpp
HANDLE ghJob = CreateJobObject( NULL, NULL); // GLOBAL
if( ghJob == NULL)
{
::MessageBox( 0, "Could not create job object", "TEST", MB_OK);
}
else
{
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
// Configure all child processes associated with the job to terminate when the
jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if( 0 == SetInformationJobObject( ghJob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli)))
{
::MessageBox( 0, "Could not SetInformationJobObject", "TEST", MB_OK);
}
}
```
Then when each child process is created, execute the following code to launch each child each process and add it to the job object:
```cpp
STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
// Launch child process - example is notepad.exe
if (::CreateProcess( NULL, "notepad.exe", NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
::MessageBox( 0, "CreateProcess succeeded.", "TEST", MB_OK);
if(ghJob)
{
if(0 == AssignProcessToJobObject( ghJob, processInfo.hProcess))
{
::MessageBox( 0, "Could not AssignProcessToObject", "TEST", MB_OK);
}
}
// Can we free handles now? Not sure about this.
//CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
```
VISTA NOTE: See [AssignProcessToJobObject always return "access denied" on Vista](http://social.msdn.microsoft.com/Forums/en-US/windowssecurity/thread/71c9599e-a3d5-4b79-bfc1-1800565c5b8a) if you encounter access-denied issues with AssignProcessToObject() on vista. |
53,224 | <p>I want to scrape some information off a football (soccer) web page using simple python regexp's. The problem is that players such as the first chap, ÄÄRITALO, comes out as &#196;&#196;RITALO!<br>
That is, html uses escaped markup for the special characters, such as &#196;</p>
<p>Is there a simple way of reading the html into the correct python string? If it was XML/XHTML it would be easy, the parser would do it.</p>
| [
{
"answer_id": 53226,
"author": "Nick Fortescue",
"author_id": 5346,
"author_profile": "https://Stackoverflow.com/users/5346",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't tried it myself, but have you tried</p>\n\n<p><a href=\"http://zesty.ca/python/scrape.html\" rel=\"nofollow noreferrer\">http://zesty.ca/python/scrape.html</a> ?</p>\n\n<p>It seems to have a method htmldecode(text) which would do what you want.</p>\n"
},
{
"answer_id": 53245,
"author": "Jacob Rigby",
"author_id": 5357,
"author_profile": "https://Stackoverflow.com/users/5357",
"pm_score": 2,
"selected": false,
"text": "<p>Try using <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">BeautifulSoup</a>. It should do the trick and give you a nicely formatted DOM to work with as well.</p>\n\n<p><a href=\"http://channel3b.wordpress.com/2007/07/04/how-to-convert-html-entities-to-real-unicode-in-python/\" rel=\"nofollow noreferrer\">This blog</a> entry seems to have had some success with it.</p>\n"
},
{
"answer_id": 53246,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 4,
"selected": true,
"text": "<p>I would recommend <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">BeautifulSoup</a> for HTML scraping. You also need to tell it to convert HTML entities to the corresponding Unicode characters, like so:</p>\n\n<pre><code>>>> from BeautifulSoup import BeautifulSoup \n>>> html = \"<html>&#196;&#196;RITALO!</html>\"\n>>> soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)\n>>> print soup.contents[0].string\nÄÄRITALO!\n</code></pre>\n\n<p>(It would be nice if the standard <a href=\"http://docs.python.org/lib/module-codecs.html\" rel=\"nofollow noreferrer\">codecs</a> module included a codec for this, such that you could do <code>\"some_string\".decode('html_entities')</code> but unfortunately it doesn't!)</p>\n\n<p><strong>EDIT:</strong>\nAnother solution:\nPython developer Fredrik Lundh (author of elementtree, among other things) has <a href=\"http://docs.python.org/lib/module-codecs.html\" rel=\"nofollow noreferrer\">a function to unsecape HTML entities</a> on his website, which works with decimal, hex and named entities (BeautifulSoup will not work with the hex ones).</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5346/"
] | I want to scrape some information off a football (soccer) web page using simple python regexp's. The problem is that players such as the first chap, ÄÄRITALO, comes out as ÄÄRITALO!
That is, html uses escaped markup for the special characters, such as Ä
Is there a simple way of reading the html into the correct python string? If it was XML/XHTML it would be easy, the parser would do it. | I would recommend [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) for HTML scraping. You also need to tell it to convert HTML entities to the corresponding Unicode characters, like so:
```
>>> from BeautifulSoup import BeautifulSoup
>>> html = "<html>ÄÄRITALO!</html>"
>>> soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
>>> print soup.contents[0].string
ÄÄRITALO!
```
(It would be nice if the standard [codecs](http://docs.python.org/lib/module-codecs.html) module included a codec for this, such that you could do `"some_string".decode('html_entities')` but unfortunately it doesn't!)
**EDIT:**
Another solution:
Python developer Fredrik Lundh (author of elementtree, among other things) has [a function to unsecape HTML entities](http://docs.python.org/lib/module-codecs.html) on his website, which works with decimal, hex and named entities (BeautifulSoup will not work with the hex ones). |
53,225 | <p>Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?</p>
| [
{
"answer_id": 53237,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://docs.python.org/2/reference/datamodel.html?highlight=im_self\" rel=\"nofollow noreferrer\"><strong>im_self</strong> attribute</a> (only Python 2)</p>\n"
},
{
"answer_id": 53322,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 7,
"selected": true,
"text": "<pre class=\"lang-py prettyprint-override\"><code>def isbound(method):\n return method.im_self is not None\n \ndef instance(bounded_method):\n return bounded_method.im_self\n</code></pre>\n<p><a href=\"https://docs.python.org/2.7/reference/datamodel.html#index-40\" rel=\"nofollow noreferrer\">User-defined methods:</a></p>\n<blockquote>\n<p>When a user-defined method object is\ncreated by retrieving a user-defined\nfunction object from a class, its\n<code>im_self</code> attribute is <code>None</code> and the\nmethod object is said to be unbound.\nWhen one is created by retrieving a\nuser-defined function object from a\nclass via one of its instances, its\n<code>im_self</code> attribute is the instance, and\nthe method object is said to be bound.\nIn either case, the new method's\n<code>im_class</code> attribute is the class from\nwhich the retrieval takes place, and\nits <code>im_func</code> attribute is the original\nfunction object.</p>\n</blockquote>\n<p>In Python <a href=\"https://docs.python.org/2.7/whatsnew/2.6.html\" rel=\"nofollow noreferrer\">2.6 and 3.0</a>:</p>\n<blockquote>\n<p>Instance method objects have new\nattributes for the object and function\ncomprising the method; the new synonym\nfor <code>im_self</code> is <code>__self__</code>, and <code>im_func</code>\nis also available as <code>__func__</code>. The old\nnames are still supported in Python\n2.6, but are gone in 3.0.</p>\n</blockquote>\n"
},
{
"answer_id": 18955425,
"author": "Rob Agar",
"author_id": 494373,
"author_profile": "https://Stackoverflow.com/users/494373",
"pm_score": 5,
"selected": false,
"text": "<p>In python 3 the <code>__self__</code> attribute is <em>only</em> set on bound methods. It's not set to <code>None</code> on plain functions (or unbound methods, which are just plain functions in python 3). </p>\n\n<p>Use something like this:</p>\n\n<pre><code>def is_bound(m):\n return hasattr(m, '__self__')\n</code></pre>\n"
},
{
"answer_id": 50074581,
"author": "Klaus",
"author_id": 1479700,
"author_profile": "https://Stackoverflow.com/users/1479700",
"pm_score": 4,
"selected": false,
"text": "<p>The chosen answer is valid in almost all cases. However when checking if a method is bound in a decorator using chosen answer, the check will fail. Consider this example decorator and method:</p>\n\n<pre><code>def my_decorator(*decorator_args, **decorator_kwargs):\n def decorate(f):\n print(hasattr(f, '__self__'))\n @wraps(f)\n def wrap(*args, **kwargs):\n return f(*args, **kwargs)\n return wrap\n return decorate\n\nclass test_class(object):\n @my_decorator()\n def test_method(self, *some_params):\n pass\n</code></pre>\n\n<p>The <code>print</code> statement in decorator will print <code>False</code>.\nIn this case I can't find any other way but to check function parameters using their argument names and look for one named <code>self</code>. This is also <strong>not</strong> guarantied to work flawlessly because the first argument of a method is not forced to be named <code>self</code> and can have any other name.</p>\n\n<pre><code>import inspect\n\ndef is_bounded(function):\n params = inspect.signature(function).parameters\n return params.get('self', None) is not None\n</code></pre>\n"
},
{
"answer_id": 65276709,
"author": "Anakhand",
"author_id": 6117426,
"author_profile": "https://Stackoverflow.com/users/6117426",
"pm_score": 0,
"selected": false,
"text": "<p>A solution that works for both Python 2 and 3 is tricky.</p>\n<p>Using the package <a href=\"https://six.readthedocs.io/\" rel=\"nofollow noreferrer\"><code>six</code></a>, one solution could be:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_bound_method(f):\n """Whether f is a bound method"""\n try:\n return six.get_method_self(f) is not None\n except AttributeError:\n return False\n</code></pre>\n<p>In Python 2:</p>\n<ul>\n<li>A regular function won't have the <code>im_self</code> attribute so <code>six.get_method_self()</code> will raise an <code>AttributeError</code> and this will return <code>False</code></li>\n<li>An unbound method will have the <code>im_self</code> attribute set to <code>None</code> so this will return <code>False</code></li>\n<li>An bound method will have the <code>im_self</code> attribute set to non-<code>None</code> so this will return <code>True</code></li>\n</ul>\n<p>In Python 3:</p>\n<ul>\n<li>A regular function won't have the <code>__self__</code> attribute so <code>six.get_method_self()</code> will raise an <code>AttributeError</code> and this will return <code>False</code></li>\n<li>An unbound method is the same as a regular function so this will return <code>False</code></li>\n<li>An bound method will have the <code>__self__</code> attribute set (to non-<code>None</code>) so this will return <code>True</code></li>\n</ul>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to? | ```py
def isbound(method):
return method.im_self is not None
def instance(bounded_method):
return bounded_method.im_self
```
[User-defined methods:](https://docs.python.org/2.7/reference/datamodel.html#index-40)
>
> When a user-defined method object is
> created by retrieving a user-defined
> function object from a class, its
> `im_self` attribute is `None` and the
> method object is said to be unbound.
> When one is created by retrieving a
> user-defined function object from a
> class via one of its instances, its
> `im_self` attribute is the instance, and
> the method object is said to be bound.
> In either case, the new method's
> `im_class` attribute is the class from
> which the retrieval takes place, and
> its `im_func` attribute is the original
> function object.
>
>
>
In Python [2.6 and 3.0](https://docs.python.org/2.7/whatsnew/2.6.html):
>
> Instance method objects have new
> attributes for the object and function
> comprising the method; the new synonym
> for `im_self` is `__self__`, and `im_func`
> is also available as `__func__`. The old
> names are still supported in Python
> 2.6, but are gone in 3.0.
>
>
> |
53,256 | <p>I have two elements:</p>
<pre><code><input a>
<input b onclick="...">
</code></pre>
<p>When b is clicked, I want to access a and manipulate some of its data. A does not have a globally unique name, so <code>document.getElementsByName</code> is out. Looking into the event object, I thought <code>event.target.parentNode</code> would have some function like <code>getElementsByName</code>, but this does not seem to be the case with <td>s. Is there any simple way to do this?</p>
| [
{
"answer_id": 53261,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 4,
"selected": true,
"text": "<p>If <code>a</code> and <code>b</code> are next to each other and have the same parent, you can use the <code>prevSibling</code> property of <code>b</code> to find <code>a</code>.</p>\n"
},
{
"answer_id": 53262,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li><p>You should be able to find the element that was clicked from the <a href=\"http://www.w3schools.com/htmldom/dom_obj_event.asp\" rel=\"nofollow noreferrer\">event object</a>. Depending on your browser you might want <code>e.target</code> or <code>e.srcElement</code>. The code below is from this <a href=\"http://www.w3schools.com/js/tryit.asp?filename=try_dom_event_srcelement\" rel=\"nofollow noreferrer\">w3schools example</a>:</p>\n\n<pre><code>function whichElement(e) {\n var targ;\n if (!e) var e = window.event;\n if (e.target) {\n targ=e.target;\n } else if (e.srcElement) {\n targ = e.srcElement;\n }\n\n if (targ.nodeType==3) { // defeat Safari bug \n targ = targ.parentNode;\n }\n\n var tname;\n tname = targ.tagName;\n alert(\"You clicked on a \" + tname + \" element.\");\n}\n</code></pre></li>\n<li><p>You may then use the <code>nextSibling</code> and <code>prevSibling</code> DOM traversal functions. <a href=\"http://www.newearthonline.co.uk/index.php?page=article&article=284\" rel=\"nofollow noreferrer\">Some more information here</a>. And yet again a w3schools reference for <a href=\"http://www.w3schools.com/DOM/dom_node.asp\" rel=\"nofollow noreferrer\">XML DOM Nodes</a>.</p></li>\n</ol>\n"
},
{
"answer_id": 53274,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 0,
"selected": false,
"text": "<p>Leave your plain vanilla JavaScript behind. Get JQuery--it will save you a ton of time.</p>\n\n<p><a href=\"http://docs.jquery.com/Selectors\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Selectors</a></p>\n"
},
{
"answer_id": 53536,
"author": "ujh",
"author_id": 4936,
"author_profile": "https://Stackoverflow.com/users/4936",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.prototypejs.org/\" rel=\"nofollow noreferrer\">Prototype</a> also has nice functions to move around in the DOM. In your example something like the following would do the trick:</p>\n\n<pre><code>b.up().down('a')\n</code></pre>\n\n<p>And if there are is more than one a element at that level you have the power of CSS selectors at your hand to specify exactly which element you want</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/429/"
] | I have two elements:
```
<input a>
<input b onclick="...">
```
When b is clicked, I want to access a and manipulate some of its data. A does not have a globally unique name, so `document.getElementsByName` is out. Looking into the event object, I thought `event.target.parentNode` would have some function like `getElementsByName`, but this does not seem to be the case with <td>s. Is there any simple way to do this? | If `a` and `b` are next to each other and have the same parent, you can use the `prevSibling` property of `b` to find `a`. |
53,260 | <p>Say a user is browsing a website, and then performs some action which changes the database (let's say they add a comment). When the request to actually add the comment comes in, however, we find we need to force them to login before they can continue.</p>
<p>Assume the login page asks for a username and password, and redirects the user back to the URL they were going to when the login was required. That redirect works find for a URL with only GET parameters, but if the request originally contained some HTTP POST data, that is now lost.</p>
<p>Can anyone recommend a way to handle this scenario when HTTP POST data is involved?</p>
<p>Obviously, if necessary, the login page could dynamically generate a form with all the POST parameters to pass them along (though that seems messy), but even then, I don't know of any way for the login page to redirect the user on to their intended page while keeping the POST data in the request.</p>
<hr>
<p><strong>Edit</strong> : One extra constraint I should have made clear - Imagine we don't know if a login will be required until the user submits their comment. For example, their cookie might have expired between when they loaded the form and actually submitted the comment.</p>
| [
{
"answer_id": 53267,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 4,
"selected": false,
"text": "<p>This is one good place where Ajax techniques might be helpful. When the user clicks the submit button, show the login dialog on client side and validate with the server before you actually submit the page.</p>\n\n<p>Another way I can think of is showing or hiding the login controls in a DIV tag dynamically in the main page itself.</p>\n"
},
{
"answer_id": 53270,
"author": "castaway",
"author_id": 4840,
"author_profile": "https://Stackoverflow.com/users/4840",
"pm_score": 1,
"selected": false,
"text": "<p>Collect the data on the page they submitted it, and store it in your backend (database?) while they go off through the login sequence, hide a transaction id or similar on the page with the login form. When they're done, return them to the page they asked for by looking it up using the transaction id on the backend, and dump all the data they posted into the form for previewing again, or just run whatever code that page would run.</p>\n\n<p>Note that many systems, eg blogs, get around this by having login fields in the same form as the one for posting comments, if the user needs to be logged in to comment and isn't yet.</p>\n"
},
{
"answer_id": 53289,
"author": "Robert Swisher",
"author_id": 1852,
"author_profile": "https://Stackoverflow.com/users/1852",
"pm_score": 2,
"selected": false,
"text": "<p>Just store all the necessary data from the POST in the session until after the login process is completed. Or have some sort of temp table in the db to store in and then retrieve it. Obviously this is pseudo-code but:</p>\n\n<pre><code>if ( !loggedIn ) {\n StorePostInSession();\n ShowLoginForm();\n}\n\nif ( postIsStored ) {\n RetrievePostFromSession();\n}\n</code></pre>\n\n<p>Or something along those lines.</p>\n"
},
{
"answer_id": 53315,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 3,
"selected": true,
"text": "<p>2 choices:</p>\n\n<ol>\n<li>Write out the messy form from the login page, and JavaScript form.submit() it to the page.</li>\n<li>Have the login page itself POST to the requesting page (with the previous values), and have that page's controller perform the login verification. Roll this into whatever logic you already have for detecting the not logged in user (frameworks vary on how they do this). In pseudo-MVC:</li>\n</ol>\n\n<pre><code>\n CommentController {\n void AddComment() {\n if (!Request.User.IsAuthenticated && !AuthenticateUser()) {\n return;\n }\n // add comment to database\n }\n\n bool AuthenticateUser() {\n if (Request.Form[\"username\"] == \"\") {\n // show login page\n foreach (Key key in Request.Form) {\n // copy form values\n ViewData.Form.Add(\"hidden\", key, Request.Form[key]);\n }\n ViewData.Form.Action = Request.Url;\n\n ShowLoginView();\n return false;\n } else {\n // validate login\n return TryLogin(Request.Form[\"username\"], Request.Form[\"password\"]);\n } \n }\n }\n</code></pre>\n"
},
{
"answer_id": 53330,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I know it says language-agnostic, but why not take advantage of the conventions provided by the server-side language you are using? If it were Java, the data could persist by setting a Request attribute. You would use a controller to process the form, detect the login, and then forward through. If the attributes are set, then just prepopulate the form with that data?</p>\n\n<p><strong>Edit:</strong> You could also use a Session as pointed out, but I'm pretty sure if you use a forward in Java back to the login page, that the Request attribute will persist.</p>\n"
},
{
"answer_id": 53342,
"author": "Jacob Rigby",
"author_id": 5357,
"author_profile": "https://Stackoverflow.com/users/5357",
"pm_score": 2,
"selected": false,
"text": "<p>You might want to investigate why Django <a href=\"http://www.djangoproject.com/weblog/2008/sep/02/security/\" rel=\"nofollow noreferrer\">removed this feature</a> before implementing it yourself. It doesn't seem like a Django specific problem, but rather yet another cross site forgery attack.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | Say a user is browsing a website, and then performs some action which changes the database (let's say they add a comment). When the request to actually add the comment comes in, however, we find we need to force them to login before they can continue.
Assume the login page asks for a username and password, and redirects the user back to the URL they were going to when the login was required. That redirect works find for a URL with only GET parameters, but if the request originally contained some HTTP POST data, that is now lost.
Can anyone recommend a way to handle this scenario when HTTP POST data is involved?
Obviously, if necessary, the login page could dynamically generate a form with all the POST parameters to pass them along (though that seems messy), but even then, I don't know of any way for the login page to redirect the user on to their intended page while keeping the POST data in the request.
---
**Edit** : One extra constraint I should have made clear - Imagine we don't know if a login will be required until the user submits their comment. For example, their cookie might have expired between when they loaded the form and actually submitted the comment. | 2 choices:
1. Write out the messy form from the login page, and JavaScript form.submit() it to the page.
2. Have the login page itself POST to the requesting page (with the previous values), and have that page's controller perform the login verification. Roll this into whatever logic you already have for detecting the not logged in user (frameworks vary on how they do this). In pseudo-MVC:
```
CommentController {
void AddComment() {
if (!Request.User.IsAuthenticated && !AuthenticateUser()) {
return;
}
// add comment to database
}
bool AuthenticateUser() {
if (Request.Form["username"] == "") {
// show login page
foreach (Key key in Request.Form) {
// copy form values
ViewData.Form.Add("hidden", key, Request.Form[key]);
}
ViewData.Form.Action = Request.Url;
ShowLoginView();
return false;
} else {
// validate login
return TryLogin(Request.Form["username"], Request.Form["password"]);
}
}
}
``` |
53,292 | <p>I'm trying to use the <a href="http://optiflag.rubyforge.org/discussion.html" rel="nofollow noreferrer">Optiflag</a> package in my Ruby code and whenever I try to do the necessary <code>require optiflag.rb</code>, my program fails with the standard <code>no such file to load -- optiflag</code> message. I added the directory with that library to my $PATH variable, but it's still not working. Any ideas?</p>
| [
{
"answer_id": 53313,
"author": "Purfideas",
"author_id": 4615,
"author_profile": "https://Stackoverflow.com/users/4615",
"pm_score": 3,
"selected": true,
"text": "<p>is it a gem? Are you doing </p>\n\n<pre><code>require 'rubygems'\nrequire 'optiflag'\n</code></pre>\n\n<p>or equivalent?</p>\n"
},
{
"answer_id": 53390,
"author": "Dominik Grabiec",
"author_id": 3719,
"author_profile": "https://Stackoverflow.com/users/3719",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like it's a gem, so you need to enable ruby gems before requiring it.</p>\n\n<p><a href=\"http://www.rubygems.org/read/chapter/3#page70\" rel=\"nofollow noreferrer\">This site</a> explains many ways of how to do it. But to have the cheat sheet here these are:</p>\n\n<p>1) Require the rubygems package before using a gem.</p>\n\n<pre><code>require \"rubygems\"\nrequire \"optiflag\" # etc\n</code></pre>\n\n<p>2) Add the -rubygems flag to wherever you execute ruby. I.e:</p>\n\n<pre><code>ruby -rubygems Something.rb\n</code></pre>\n\n<p>3) Add an environment variable called RUBYOPT, giving it an option of rubygems. I.e:</p>\n\n<pre><code>RUBYOPT=rubygems\n</code></pre>\n"
},
{
"answer_id": 8727718,
"author": "MrFox",
"author_id": 351025,
"author_profile": "https://Stackoverflow.com/users/351025",
"pm_score": 0,
"selected": false,
"text": "<p>I also keep having this problem with RubyXL, tried to use single and double quotes. Is there something else that needs to be done? Maybe putting a file somewhere? I already succesfully installed the gem with sudo gem install rubyXL (RubyXL actually din't work).</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] | I'm trying to use the [Optiflag](http://optiflag.rubyforge.org/discussion.html) package in my Ruby code and whenever I try to do the necessary `require optiflag.rb`, my program fails with the standard `no such file to load -- optiflag` message. I added the directory with that library to my $PATH variable, but it's still not working. Any ideas? | is it a gem? Are you doing
```
require 'rubygems'
require 'optiflag'
```
or equivalent? |
53,316 | <p>I have a one to many relationship between two tables. The many table contains a clob column. The clob column looks like this in hibernate:</p>
<pre><code>@CollectionOfElements(fetch = EAGER)
@JoinTable(name = NOTE_JOIN_TABLE, joinColumns = @JoinColumn(name = "note"))
@Column(name = "substitution")
@IndexColumn(name = "listIndex", base = 0)
@Lob
private List<String> substitutions;
</code></pre>
<p>So basically I may have a Note with some subsitutions, say <code>"foo"</code> and <code>"fizzbuzz"</code>. So in my main table I could have a Note with id 4 and in my <code>NOTE_JOIN_TABLE</code> I would have two rows, <code>"foo"</code> and <code>"fizzbuzz"</code> that both have a relationship to the Note.</p>
<p>However, when one of these is inserted into the DB <strong>the larger substitution values are cropped to be as long as the shortest.</strong> So in this case I would have <code>"foo"</code> and <code>"fiz"</code> in the DB instead of <code>"foo"</code> and <code>"fizzbuzz"</code>.</p>
<p>Do you have any idea why this is happening? I have checked and confirmed they aren't being cropped anywhere in our code, it's defintely hibernate.</p>
| [
{
"answer_id": 53308,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 0,
"selected": false,
"text": "<p>Are you trying to implement a client to a web service hosted somewhere else? If so, Java's not necessary. You can do web service clients in <a href=\"http://www.dotnetjunkies.ddj.com/Tutorial/4D13CEFA-D0FD-44BE-8749-8D17B5757564.dcik\" rel=\"nofollow noreferrer\">.NET</a>, <a href=\"http://sourceforge.net/projects/nusoap/\" rel=\"nofollow noreferrer\">PHP</a>, <a href=\"http://raa.ruby-lang.org/project/soap4r\" rel=\"nofollow noreferrer\">Ruby</a>, or pretty much any modern web technology out there. All you need is a WSDL document to provide metadata about how to invoke the services.</p>\n"
},
{
"answer_id": 53314,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>To follow up with jodonnell's comment, a Web service connection can be made in just about any server-side language. It is just that the API example they provided was in Java probably because PlanPlusOnline is written in Java. If you have a URL for the service, and an access key, then all you really need to do is figure out how to traverse the XML returned. If you can't do Java, then I suggest PHP because it could be already installed, and have the proper modules loaded. This link might be helpful:</p>\n\n<p><a href=\"http://www.onlamp.com/pub/a/php/2007/07/26/php-web-services.html\" rel=\"nofollow noreferrer\">http://www.onlamp.com/pub/a/php/2007/07/26/php-web-services.html</a></p>\n"
},
{
"answer_id": 53360,
"author": "Jacob Schoen",
"author_id": 3340,
"author_profile": "https://Stackoverflow.com/users/3340",
"pm_score": 0,
"selected": false,
"text": "<p>If I am understanding your question correctly, you only need to connect to an existing web service and not create your own web service. If that is a case, and maybe I am missing something, I do not believe you will need Tomcat at all. If you are using Netbeans you can create a new Desktop or Web application, and then right click the project name. Select New and then other, and select Web Client. Enter the information for where to find the WSDL (usually a URL) and the other required information.</p>\n\n<p>Once you added the WebClient create a new class that actually makes your calls to the webservice. If the web service name was PlanPlusOnline then you could have something like:</p>\n\n<pre><code>public final class PlanPlusOnlineClient\n{\n //instance to this class so that we do not have to reinstantiate it every time\n private static PlanPlusOnlineClient _instance = new PlanPlusOnlineClient();\n\n //generated class by netbeans with information about the web service\n private PlanPlusOnlineService service = null;\n\n //another generated class by netbeans but this is a property of the service\n //that contains information about the individual methods available.\n private PlanPlusOnline port = null;\n\n private PlanPlusOnlineClient()\n {\n try\n {\n service = new PlanPlusOnlineService();\n port = service.getPlanPlusOnlinePort();\n }\n catch (MalformedURLException ex)\n {\n MessageLog.error(this, ex.getClass().getName(), ex);\n }\n }\n\n public static PlanPlusOnlineClient getInstance()\n {\n return _instance;\n }\n\n public static String getSomethingInteresting(String param)\n {\n //this will call one of the actual methods the web \n //service provides.\n return port.getSomethingIntersting(param);\n } \n\n}\n</code></pre>\n\n<p>I hope this helps you along your way with this. You should also check out <a href=\"http://www.netbeans.org/kb/60/websvc/\" rel=\"nofollow noreferrer\">http://www.netbeans.org/kb/60/websvc/</a>\nfor some more information about Netbeans and web services. I am sure it is similar in other IDEs.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] | I have a one to many relationship between two tables. The many table contains a clob column. The clob column looks like this in hibernate:
```
@CollectionOfElements(fetch = EAGER)
@JoinTable(name = NOTE_JOIN_TABLE, joinColumns = @JoinColumn(name = "note"))
@Column(name = "substitution")
@IndexColumn(name = "listIndex", base = 0)
@Lob
private List<String> substitutions;
```
So basically I may have a Note with some subsitutions, say `"foo"` and `"fizzbuzz"`. So in my main table I could have a Note with id 4 and in my `NOTE_JOIN_TABLE` I would have two rows, `"foo"` and `"fizzbuzz"` that both have a relationship to the Note.
However, when one of these is inserted into the DB **the larger substitution values are cropped to be as long as the shortest.** So in this case I would have `"foo"` and `"fiz"` in the DB instead of `"foo"` and `"fizzbuzz"`.
Do you have any idea why this is happening? I have checked and confirmed they aren't being cropped anywhere in our code, it's defintely hibernate. | To follow up with jodonnell's comment, a Web service connection can be made in just about any server-side language. It is just that the API example they provided was in Java probably because PlanPlusOnline is written in Java. If you have a URL for the service, and an access key, then all you really need to do is figure out how to traverse the XML returned. If you can't do Java, then I suggest PHP because it could be already installed, and have the proper modules loaded. This link might be helpful:
<http://www.onlamp.com/pub/a/php/2007/07/26/php-web-services.html> |
53,353 | <p>Below I present three options for simplifying my database access when only a single connection is involved (this is often the case for the web apps I work on).</p>
<p>The general idea is to make the DB connection transparent, such that it connects the first time my script executes a query, and then it remains connected until the script terminates.</p>
<p>I'd like to know which one you think is the best and why. I don't know the names of any design patterns that these might fit so sorry for not using them. And if there's any <em>better</em> way of doing this with PHP5, please share.</p>
<p>To give a brief introduction: there is a DB_Connection class containing a query method. This is a third-party class which is out of my control and whose interface I've simplified for the purpose of this example. In each option I've also provided an example model for an imaginary DB "items" table to give some context.</p>
<p>Option 3 is the one that provides me with the interface I like most, but I don't think it's practical unfortunately.</p>
<p>I've described the pros and cons (that I can see) of each in the comment blocks below.</p>
<p>At the moment I lean towards Option 1 since the burden is put on my DB wrapper class instead of on the models.</p>
<p>All comments appreciated!</p>
<p>Note: For some reason, the Stack Overflow preview is showing an encoded HTML entity instead of underscores. If the post comes through like that, please take this into account.</p>
<pre><code><?php
/**
* This is the 3rd-party DB interface I'm trying to wrap.
* I've simplified the interface to one method for this example.
*
* This class is used in each option below.
*/
class DB_Connection {
public function &query($sql) { }
}
/**
* OPTION 1
*
* Cons: Have to wrap every public DB_Connection method.
* Pros: The model code is simple.
*/
class DB {
private static $connection;
private static function &getConnection() {
if (!self::$connection) {
self::$connection = new DB_Connection();
}
return self::$connection;
}
public static function &query($sql) {
$dbh = self::getConnection();
return $dbh->query($sql);
}
}
class Item {
public static function &getList() {
return DB::query("SELECT * FROM items");
}
}
/**
* OPTION 2
*
* Pros: Don't have to wrap every DB_Connection function like in Option 1
* Cons: Every function in the model is responsible for checking the connection
*/
class DB {
protected static $connection = null;
public function connect() {
self::$connection = new DB_Connection();
}
}
class Item extends DB {
public static function &getList() {
if (!self::$connection) $this->connect();
return self::$connection->query("SELECT * FROM items");
}
}
/**
* OPTION 3
*
* Use magic methods
*
* Pros: Simple model code AND don't have to reimplement the DB_Connection interface
* Cons: __callStatic requires PHP 5.3.0 and its args can't be passed-by-reference.
*/
class DB {
private static $connection = null;
public static function &getConnection() {
if (!self::$connection) {
self::$connection = new DB_Connection();
}
return self::$connection;
}
public static function __callStatic($name, $args) {
if (in_array($name, get_class_methods('DB_Connection'))) {
return call_user_func_array(
array(self::getConnection(), $name), $args);
}
}
}
</code></pre>
| [
{
"answer_id": 53399,
"author": "Dhaust",
"author_id": 242,
"author_profile": "https://Stackoverflow.com/users/242",
"pm_score": 4,
"selected": true,
"text": "<p>Doh! Someone else here at work figured this out. It was really simple and I should have been able to sort it, but hey, that's how it goes sometimes.</p>\n\n<p>Here the fix:<br>\nOn the web server, copy the 'aspnet_client' folder from 'C:\\Inetpub\\wwwroot' to 'C:\\Inetpub\\wwwroot\\your-website-name'. </p>\n\n<p>That's all we did and it's now working. </p>\n\n<p>Hope this saves someone from all the fuss I just went through.</p>\n"
},
{
"answer_id": 997321,
"author": "Emad Gabriel",
"author_id": 120885,
"author_profile": "https://Stackoverflow.com/users/120885",
"pm_score": 2,
"selected": false,
"text": "<p>Another solution is to simply create a new virtual directory in your web site and point it to \"C:/Inetpub/wwwroot/aspnet_client\"</p>\n"
},
{
"answer_id": 1887814,
"author": "shine jose",
"author_id": 229618,
"author_profile": "https://Stackoverflow.com/users/229618",
"pm_score": 2,
"selected": false,
"text": "<p>Try this<br>\nOn the web server, copy the 'aspnet_client' folder from 'C:\\Inetpub\\wwwroot' and past inside your website folder.(where form folder,app_data folder etc will be there)</p>\n"
},
{
"answer_id": 2735773,
"author": "Zappos",
"author_id": 328654,
"author_profile": "https://Stackoverflow.com/users/328654",
"pm_score": 0,
"selected": false,
"text": "<p>I took over maintaining some code produced by another developer who had left and suffered this issue too. In my case the compiled report was looking for the images in the crystalreportview115 folder which existed in my local development path and therefore worked locally. The only folder on on the target server was the CrystalReportWebFormViewer4 (I assume from a previous server installation or site deployment). Simply adding the ...115 folder sorted the problem out for me. </p>\n\n<p>The root cause for us would appear to be the version of Crystal installed on the developers machine. Not sure that helps anyone but thought I'd mention it!</p>\n"
},
{
"answer_id": 3873935,
"author": "Syed Nasir Abbas",
"author_id": 468116,
"author_profile": "https://Stackoverflow.com/users/468116",
"pm_score": 0,
"selected": false,
"text": "<p>Upload aspnet_client folder from c:\\inetpub\\wwwroot folder of your local computer to the httpdocs folder of your web hosting server. Good Luck!!!</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Below I present three options for simplifying my database access when only a single connection is involved (this is often the case for the web apps I work on).
The general idea is to make the DB connection transparent, such that it connects the first time my script executes a query, and then it remains connected until the script terminates.
I'd like to know which one you think is the best and why. I don't know the names of any design patterns that these might fit so sorry for not using them. And if there's any *better* way of doing this with PHP5, please share.
To give a brief introduction: there is a DB\_Connection class containing a query method. This is a third-party class which is out of my control and whose interface I've simplified for the purpose of this example. In each option I've also provided an example model for an imaginary DB "items" table to give some context.
Option 3 is the one that provides me with the interface I like most, but I don't think it's practical unfortunately.
I've described the pros and cons (that I can see) of each in the comment blocks below.
At the moment I lean towards Option 1 since the burden is put on my DB wrapper class instead of on the models.
All comments appreciated!
Note: For some reason, the Stack Overflow preview is showing an encoded HTML entity instead of underscores. If the post comes through like that, please take this into account.
```
<?php
/**
* This is the 3rd-party DB interface I'm trying to wrap.
* I've simplified the interface to one method for this example.
*
* This class is used in each option below.
*/
class DB_Connection {
public function &query($sql) { }
}
/**
* OPTION 1
*
* Cons: Have to wrap every public DB_Connection method.
* Pros: The model code is simple.
*/
class DB {
private static $connection;
private static function &getConnection() {
if (!self::$connection) {
self::$connection = new DB_Connection();
}
return self::$connection;
}
public static function &query($sql) {
$dbh = self::getConnection();
return $dbh->query($sql);
}
}
class Item {
public static function &getList() {
return DB::query("SELECT * FROM items");
}
}
/**
* OPTION 2
*
* Pros: Don't have to wrap every DB_Connection function like in Option 1
* Cons: Every function in the model is responsible for checking the connection
*/
class DB {
protected static $connection = null;
public function connect() {
self::$connection = new DB_Connection();
}
}
class Item extends DB {
public static function &getList() {
if (!self::$connection) $this->connect();
return self::$connection->query("SELECT * FROM items");
}
}
/**
* OPTION 3
*
* Use magic methods
*
* Pros: Simple model code AND don't have to reimplement the DB_Connection interface
* Cons: __callStatic requires PHP 5.3.0 and its args can't be passed-by-reference.
*/
class DB {
private static $connection = null;
public static function &getConnection() {
if (!self::$connection) {
self::$connection = new DB_Connection();
}
return self::$connection;
}
public static function __callStatic($name, $args) {
if (in_array($name, get_class_methods('DB_Connection'))) {
return call_user_func_array(
array(self::getConnection(), $name), $args);
}
}
}
``` | Doh! Someone else here at work figured this out. It was really simple and I should have been able to sort it, but hey, that's how it goes sometimes.
Here the fix:
On the web server, copy the 'aspnet\_client' folder from 'C:\Inetpub\wwwroot' to 'C:\Inetpub\wwwroot\your-website-name'.
That's all we did and it's now working.
Hope this saves someone from all the fuss I just went through. |
53,365 | <p><em>(see <a href="https://stackoverflow.com/questions/53316/hibernate-crops-clob-values-oddly">here</a> for the problem I'm trying to solve)</em></p>
<p>How do you get hibernate to log clob values it's going to insert. It is logging other value types, such as Integer etc.</p>
<p>I have the following in my log4j config:</p>
<pre><code>log4j.logger.net.sf.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.net.sf.hibernate.type=DEBUG
log4j.logger.org.hibernate.type=DEBUG
</code></pre>
<p>Which produces output such as:</p>
<pre><code>(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '0' to parameter: 2
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '1' to parameter: 2
</code></pre>
<p>However you'll note that it never displays <code>parameter: 3</code> which is our clob.</p>
<p>What I would really want is something like:</p>
<pre><code>(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '0' to parameter: 2
(org.hibernate.type.ClobType) binding 'something' to parameter: 3
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '1' to parameter: 2
(org.hibernate.type.ClobType) binding 'something else' to parameter: 3
</code></pre>
<p>How do I get it to show this in the log?</p>
| [
{
"answer_id": 53419,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 2,
"selected": true,
"text": "<p>Try using:</p>\n\n<pre><code>log4j.logger.net.sf.hibernate=DEBUG\nlog4j.logger.org.hibernate=DEBUG\n</code></pre>\n\n<p>That's the finest level you'll get. If it does not show the information you want, then it's not possible.</p>\n"
},
{
"answer_id": 55810,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 1,
"selected": false,
"text": "<p>Well, it looks like you can't. <em>(Thanks <a href=\"https://stackoverflow.com/questions/53365/getting-hibernate-to-log-clob-parameters#53419\">Marcio</a> for the suggestion, but sadly that didn't add anything useful)</em></p>\n"
},
{
"answer_id": 61728,
"author": "talg",
"author_id": 3332,
"author_profile": "https://Stackoverflow.com/users/3332",
"pm_score": 0,
"selected": false,
"text": "<p>Try to set log4j.logger.org.hibernate.type=TRACE and see if that helps.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] | *(see [here](https://stackoverflow.com/questions/53316/hibernate-crops-clob-values-oddly) for the problem I'm trying to solve)*
How do you get hibernate to log clob values it's going to insert. It is logging other value types, such as Integer etc.
I have the following in my log4j config:
```
log4j.logger.net.sf.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.net.sf.hibernate.type=DEBUG
log4j.logger.org.hibernate.type=DEBUG
```
Which produces output such as:
```
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '0' to parameter: 2
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '1' to parameter: 2
```
However you'll note that it never displays `parameter: 3` which is our clob.
What I would really want is something like:
```
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '0' to parameter: 2
(org.hibernate.type.ClobType) binding 'something' to parameter: 3
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '1' to parameter: 2
(org.hibernate.type.ClobType) binding 'something else' to parameter: 3
```
How do I get it to show this in the log? | Try using:
```
log4j.logger.net.sf.hibernate=DEBUG
log4j.logger.org.hibernate=DEBUG
```
That's the finest level you'll get. If it does not show the information you want, then it's not possible. |
53,379 | <p>Does anyone have examples of how to use <a href="http://www.oracle-base.com/articles/8i/DBMS_APPLICATION_INFO.php" rel="nofollow noreferrer">DBMS_APPLICATION_INFO</a> package with JBOSS? </p>
<p>We have a various applications which run within JBOSS and share db pools. I would like, at the start of each session these applications to identify themselves to the database using DBMS_APPLICATION_INFO so I can more easily track which sections of the application is causing database issues.</p>
<p>I'm not too familiar with session life cycles in JBOSS, but at the end of the day, what needs to happen is at the start and end of a transaction, this package needs to be called.</p>
<p>Has anyone done this before?</p>
| [
{
"answer_id": 53449,
"author": "Tony BenBrahim",
"author_id": 80075,
"author_profile": "https://Stackoverflow.com/users/80075",
"pm_score": 2,
"selected": true,
"text": "<p>yes, you can write a wrapper class around your connection pool, and a wraper around the connection\nso lets say you have:</p>\n\n<pre>\nOracleConnection conn=connectionPool.getConnection(\"java:scott@mydb\");\n</pre>\n\n<p>Change it to:</p>\n\n<pre>\npublic class LoggingConnectionPool extends ConnectionPool{\n public OracleConnection getConnection(String datasourceName, String module, String action){\n OracleConnection conn=getConnection(datasourceName);\n CallableStatement call=conn.preparedCall(\"begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;\");\n try{\n call.setString(1,module);\n call.setString(2,action);\n call.execute();\n finally{\n call.close();\n }\n return new WrappedOracleConnection(conn);\n }\n</pre>\n\n<p>Note the use of WrappedOracleConnection above. You need this because you need to trap the close call</p>\n\n<pre>\npublic class WrappedOracleConnection extends OracleConnection{\n public void close(){\n CallableStatement call=this.preparedCall(\"begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;\");\n try{\n call.setNull(1,Types.VARCHAR);\n call.setNull(2,Types.VARCHAR);\n call.execute();\n finally{\n call.close();\n }\n }\n\n // and you need to implement every other method\n //for example\n public CallableStatement prepareCall(String command){\n return super.prepareCall(command);\n }\n ...\n}\n</pre>\n\n<p>Hope this helps, I do something similar on a development server to catch connections that are not closed (not returned to the pool).</p>\n"
},
{
"answer_id": 378045,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using JBoss, you can use a \"valid-connection-checker\".\nThis class is normaly used to check the validity of the Connection.\nBut, as it will be invoked every time the Connection pool gives the user a Connection, you can use it to set the DBMS_ APPLICATION _INFO.</p>\n\n<p>You declare such a class in the oracle-ds.xml like this:</p>\n\n<pre><code><local-tx-datasource>\n <jndi-name>jdbc/myDS</jndi-name>\n <connection-url>jdbc:oracle:thin:@10.10.1.15:1521:SID</connection-url>\n <driver-class>oracle.jdbc.driver.OracleDriver</driver-class>\n <security-domain>MyEncryptDBPassword</security-domain>\n <valid-connection-checker-class-name>test.MyValidConn</valid-connection-checker-class-name>\n <metadata>\n <type-mapping>Oracle9i</type-mapping>\n </metadata>\n</local-tx-datasource>\n</code></pre>\n\n<p>Your class must implement the org.jboss.resource.adapter.jdbc.ValidConnectionChecker interface.\nIf you use Maven, you can include this interface with the following dependency:</p>\n\n<pre><code><dependency>\n <groupId>jboss</groupId>\n <artifactId>jboss-common-jdbc-wrapper</artifactId>\n <version>3.2.3</version>\n <scope>provided</scope>\n</dependency>\n</code></pre>\n\n<p>This interface has only one method: isValidConnection.\nI copy my implementation:</p>\n\n<pre><code>public SQLException isValidConnection(Connection arg0) {\n CallableStatement statement;\n try {\n statement = arg0.prepareCall(\"call dbms_application_info.set_client_info('\"+getInfos()+\"')\");\n statement.execute();\n } catch (SQLException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n return null;\n}\n</code></pre>\n\n<p>Hope it helps !</p>\n\n<p>Benoît</p>\n"
},
{
"answer_id": 9675451,
"author": "Nicholas",
"author_id": 43786,
"author_profile": "https://Stackoverflow.com/users/43786",
"pm_score": 0,
"selected": false,
"text": "<p>In your <em>-ds.xml</em>, you can set a connection property called <strong>v$session.program</strong> and the value of that property will populate the <strong>PROGRAM</strong> column of each session in the <strong>V$SESSION</strong> view created for connections originating from your connection pool. I usually set it to the <em>jboss.server.name</em> property.</p>\n\n<p>See <a href=\"http://www.magpiebrain.com/2006/05/09/specifying-a-program-name-in-oracle-jdbc-connections/\" rel=\"nofollow\">here</a> for an example.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3839/"
] | Does anyone have examples of how to use [DBMS\_APPLICATION\_INFO](http://www.oracle-base.com/articles/8i/DBMS_APPLICATION_INFO.php) package with JBOSS?
We have a various applications which run within JBOSS and share db pools. I would like, at the start of each session these applications to identify themselves to the database using DBMS\_APPLICATION\_INFO so I can more easily track which sections of the application is causing database issues.
I'm not too familiar with session life cycles in JBOSS, but at the end of the day, what needs to happen is at the start and end of a transaction, this package needs to be called.
Has anyone done this before? | yes, you can write a wrapper class around your connection pool, and a wraper around the connection
so lets say you have:
```
OracleConnection conn=connectionPool.getConnection("java:scott@mydb");
```
Change it to:
```
public class LoggingConnectionPool extends ConnectionPool{
public OracleConnection getConnection(String datasourceName, String module, String action){
OracleConnection conn=getConnection(datasourceName);
CallableStatement call=conn.preparedCall("begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;");
try{
call.setString(1,module);
call.setString(2,action);
call.execute();
finally{
call.close();
}
return new WrappedOracleConnection(conn);
}
```
Note the use of WrappedOracleConnection above. You need this because you need to trap the close call
```
public class WrappedOracleConnection extends OracleConnection{
public void close(){
CallableStatement call=this.preparedCall("begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;");
try{
call.setNull(1,Types.VARCHAR);
call.setNull(2,Types.VARCHAR);
call.execute();
finally{
call.close();
}
}
// and you need to implement every other method
//for example
public CallableStatement prepareCall(String command){
return super.prepareCall(command);
}
...
}
```
Hope this helps, I do something similar on a development server to catch connections that are not closed (not returned to the pool). |
53,395 | <p>I know the answer is not going to be simple, and I already use a couple of (I think ugly) cludges. I am simply looking for some elegant answers.</p>
<p>Abstract class:</p>
<pre><code>public interface IOtherObjects;
public abstract class MyObjects<T> where T : IOtherObjects
{
...
public List<T> ToList()
{
...
}
}
</code></pre>
<p>Children:</p>
<pre><code>public class MyObjectsA : MyObjects<OtherObjectA> //(where OtherObjectA implements IOtherObjects)
{
}
public class MyObjectsB : MyObjects<OtherObjectB> //(where OtherObjectB implements IOtherObjects)
{
}
</code></pre>
<p>Is it possible, looping through a collection of MyObjects (or other similar grouping, generic or otherwise) to then utilise to <em>ToList</em> method of the <em>MyObjects</em> base class, as we do not specifically know the type of T at this point. </p>
<p><strong>EDIT</strong>
As for specific examples, whenever this has come up, I've thought about it for a while, and done something different instead, so there is no current requirement. but as it has come up quite frequently, I thought I would float it.</p>
<p><strong>EDIT</strong>
@Sara, it's not the specific type of the collection I care about, it could be a List, but still the ToList method of each instance is relatively unusable, without an anonymous type)</p>
<p>@aku, true, and this question may be relatively hypothetical, however being able to retrieve, and work with a list of T of objects, knowing only their base type would be very useful. Having the ToList returning a List Of BaseType has been one of my workarounds</p>
<p><strong>EDIT</strong> @ all: So far, this has been the sort of discussion I was hoping for, though it largely confirms all I suspected. Thanks all so far, but anyone else, feel free to input.</p>
<p><strong>EDIT</strong>@Rob, Yes it works for a defined type, but not when the type is only known as a List of IOtherObjects. </p>
<p>@Rob <strong>Again</strong> Thanks. That has usually been my cludgy workaround (no disrespect :) ). Either that or using the ConvertAll function to Downcast through a delegate. Thanks for taking the time to understand the problem.</p>
<p><strong>QUALIFYING EDIT</strong> in case I have been a little confusing</p>
<p>To be more precise, (I may have let my latest implementation of this get it too complex):</p>
<p>lets say I have 2 object types, B and C inheriting from object A.</p>
<p>Many scenarios have presented themselves where, from a List of B or a List of C, or in other cases a List of either - but I don't know which if I am at a base class, I have needed a less specific List of A. </p>
<p>The above example was a watered-down example of the <em>List Of Less Specific</em> problem's latest incarnation.</p>
<p>Usually it has presented itself, as I think through possible scenarios that limit the amount of code that needs writing and seems a little more elegant than other options. I really wanted a discussion of possibilities and other points of view, which I have more or less got. I am surprised no one has mentioned ConvertAll() so far, as that is another workaround I have used, but a little too verbose for the scenarios at hand</p>
<p>@Rob <strong>Yet Again</strong> and Sara</p>
<p>Thanks, however I do feel I understand generics in all their static contexted glory, and did understand the issues at play here.</p>
<p>The actual design of our system and usage of generics it (and I can say this without only a touch of bias, as I was only one of the players in the design), has been done well. It is when I have been working with the core API, I have found situations when I have been in the wrong scope for doing something simply, instead I had to deal with them with a little less elegant than I like (trying either to be clever or perhaps lazy - I'll accept either of those labels).</p>
<p>My distaste for what I termed a cludge is largely that we require to do a loop through our record set simply to convert the objects to their base value which may be a performance hit.</p>
<p>I guess I was wondering if anyone else had come across this in their coding before, and if anyone had been cleverer, or at least more elegant, than me in dealing with it.</p>
| [
{
"answer_id": 53402,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>In your case MyObjectsA and MyObjectsB don't have common predecessor. Generic class is template for <em>different</em> classes not a common base class. If you want to have common properties in different classes use interfaces. You can't call <em>ToList</em> in a loop cause it has different signature in different classes. You can create ToList that returns <em>objects</em> rather than specific type.</p>\n"
},
{
"answer_id": 53403,
"author": "Sara Chipps",
"author_id": 4140,
"author_profile": "https://Stackoverflow.com/users/4140",
"pm_score": 2,
"selected": false,
"text": "<p>why do you have a collection of MyObjects? Is there a specific reason you don't have a List?</p>\n"
},
{
"answer_id": 53406,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 1,
"selected": false,
"text": "<p>You can still probably access the ToList() method, but since you are unsure of the type, won't this work?</p>\n\n<pre><code>foreach(var myObject in myObjectsList)\n foreach(var obj in myObject.ToList())\n //do something\n</code></pre>\n\n<p>Of course this will only work on C# 3.0.</p>\n\n<p>Note that the use of var is merely to remove the requirement of knowing what type the lists contain; as opposed to Frank's comments that I have delusions that var will make typing dynamic.</p>\n"
},
{
"answer_id": 53418,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": -1,
"selected": false,
"text": "<p>Generics are used for static time type checks <strong>not</strong> runtime dispatch. Use inheritance/interfaces for runtime dispatch, use generics for compile-time type guarantees.</p>\n\n<pre><code>interface IMyObjects : IEnumerable<IOtherObjects> {}\nabstract class MyObjects<T> : IMyObjects where T : IOtherObjects {}\n\nIEnumerable<IMyObjects> objs = ...;\nforeach (IMyObjects mo in objs) {\n foreach (IOtherObjects oo in mo) {\n Console.WriteLine(oo);\n }\n}\n</code></pre>\n\n<p>(Obviously, I prefer Enumerables over Lists.)</p>\n\n<p><strong>OR</strong> Just use a proper dynamic language like VB. :-)</p>\n"
},
{
"answer_id": 53446,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "<p>OK, I am confused, the following code works fine for me (curiosity got the better of me!):</p>\n\n<pre><code>// Original Code Snipped for Brevity - See Edit History if Req'd\n</code></pre>\n\n<p>Or have I missed something?</p>\n\n<h2>Update Following Response from OP</h2>\n\n<p>OK now I am really confused..\nWhat you are saying is that you want to get a List of <em>Typed</em> values from a generic/abstract List? (the child classes therefore become irrelevant).</p>\n\n<p>You cannot return a Typed List if the Types are children/interface implementors - they do not match! You can of course get a List of items that are of a specific type from the abstract List like so:</p>\n\n<pre><code> public List<OfType> TypedList<OfType>() where OfType : IOtherObjects\n {\n List<OfType> rtn = new List<OfType>();\n\n foreach (IOtherObjects o in _objects)\n {\n Type objType = o.GetType();\n Type reqType = typeof(OfType);\n\n if (objType == reqType)\n rtn.Add((OfType)o);\n }\n\n return rtn;\n }\n</code></pre>\n\n<p>If I am still off-base here can you please reword your question?! (It doesn't seem like I am the only one unsure of what you are driving at). I am trying to establish if there is a misunderstanding of generics on your part.</p>\n\n<h2>Another Update :D</h2>\n\n<p>Right, so it looks like you want/need the option to get the typed List, or the base list yes?</p>\n\n<p>This would make your abstract class look like this - you can use ToList to get the concrete type, or ToBaseList() to get a List of the interface type. This should work in any scenarios you have. Does that help?</p>\n\n<pre><code>public abstract class MyObjects<T> where T : IOtherObjects\n{\n List<T> _objects = new List<T>();\n\n public List<T> ToList()\n {\n return _objects;\n }\n\n public List<IOtherObjects> ToBaseList()\n {\n List<IOtherObjects> rtn = new List<IOtherObjects>();\n foreach (IOtherObjects o in _objects)\n {\n rtn.Add(o);\n }\n return rtn;\n }\n}\n</code></pre>\n\n<h2>Update #3</h2>\n\n<p>It's not really a \"cludgy\" workaround (no disrespect taken) - thats the only way to do it.. I think the bigger issue here is a design/grok problem. You said you had a problem, this code solves it. But if you were expecting to do something like:</p>\n\n<pre><code>public abstract class MyObjects<T> where T : IOtherObjects\n{\n List<T> _objects = new List<T>();\n\n public List<IOtherObjects> Objects\n { get { return _objects; } }\n}\n#warning This won't compile, its for demo's sake.\n</code></pre>\n\n<p>And be able to pick-and-choose the types that come out of it, how else <em>could</em> you do it?! I get the feeling you do not really understand what the point of generics are, and you are trying to get them to do something they are not designed for!?</p>\n"
},
{
"answer_id": 84484,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": true,
"text": "<p>If you have</p>\n\n<pre><code>class B : A\nclass C : A\n</code></pre>\n\n<p>And you have</p>\n\n<pre><code>List<B> listB;\nList<C> listC;\n</code></pre>\n\n<p>that you wish to treat as a List of the parent type</p>\n\n<p>Then you should use</p>\n\n<pre><code>List<A> listA = listB.Cast<A>().Concat(listC.Cast<A>()).ToList()\n</code></pre>\n"
},
{
"answer_id": 98008,
"author": "johnc",
"author_id": 5302,
"author_profile": "https://Stackoverflow.com/users/5302",
"pm_score": 0,
"selected": false,
"text": "<p>I have recently found the </p>\n\n<pre><code>List<A>.Cast<B>().ToList<B>()\n</code></pre>\n\n<p>pattern. </p>\n\n<p>It does exactly what I was looking for,</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] | I know the answer is not going to be simple, and I already use a couple of (I think ugly) cludges. I am simply looking for some elegant answers.
Abstract class:
```
public interface IOtherObjects;
public abstract class MyObjects<T> where T : IOtherObjects
{
...
public List<T> ToList()
{
...
}
}
```
Children:
```
public class MyObjectsA : MyObjects<OtherObjectA> //(where OtherObjectA implements IOtherObjects)
{
}
public class MyObjectsB : MyObjects<OtherObjectB> //(where OtherObjectB implements IOtherObjects)
{
}
```
Is it possible, looping through a collection of MyObjects (or other similar grouping, generic or otherwise) to then utilise to *ToList* method of the *MyObjects* base class, as we do not specifically know the type of T at this point.
**EDIT**
As for specific examples, whenever this has come up, I've thought about it for a while, and done something different instead, so there is no current requirement. but as it has come up quite frequently, I thought I would float it.
**EDIT**
@Sara, it's not the specific type of the collection I care about, it could be a List, but still the ToList method of each instance is relatively unusable, without an anonymous type)
@aku, true, and this question may be relatively hypothetical, however being able to retrieve, and work with a list of T of objects, knowing only their base type would be very useful. Having the ToList returning a List Of BaseType has been one of my workarounds
**EDIT** @ all: So far, this has been the sort of discussion I was hoping for, though it largely confirms all I suspected. Thanks all so far, but anyone else, feel free to input.
**EDIT**@Rob, Yes it works for a defined type, but not when the type is only known as a List of IOtherObjects.
@Rob **Again** Thanks. That has usually been my cludgy workaround (no disrespect :) ). Either that or using the ConvertAll function to Downcast through a delegate. Thanks for taking the time to understand the problem.
**QUALIFYING EDIT** in case I have been a little confusing
To be more precise, (I may have let my latest implementation of this get it too complex):
lets say I have 2 object types, B and C inheriting from object A.
Many scenarios have presented themselves where, from a List of B or a List of C, or in other cases a List of either - but I don't know which if I am at a base class, I have needed a less specific List of A.
The above example was a watered-down example of the *List Of Less Specific* problem's latest incarnation.
Usually it has presented itself, as I think through possible scenarios that limit the amount of code that needs writing and seems a little more elegant than other options. I really wanted a discussion of possibilities and other points of view, which I have more or less got. I am surprised no one has mentioned ConvertAll() so far, as that is another workaround I have used, but a little too verbose for the scenarios at hand
@Rob **Yet Again** and Sara
Thanks, however I do feel I understand generics in all their static contexted glory, and did understand the issues at play here.
The actual design of our system and usage of generics it (and I can say this without only a touch of bias, as I was only one of the players in the design), has been done well. It is when I have been working with the core API, I have found situations when I have been in the wrong scope for doing something simply, instead I had to deal with them with a little less elegant than I like (trying either to be clever or perhaps lazy - I'll accept either of those labels).
My distaste for what I termed a cludge is largely that we require to do a loop through our record set simply to convert the objects to their base value which may be a performance hit.
I guess I was wondering if anyone else had come across this in their coding before, and if anyone had been cleverer, or at least more elegant, than me in dealing with it. | If you have
```
class B : A
class C : A
```
And you have
```
List<B> listB;
List<C> listC;
```
that you wish to treat as a List of the parent type
Then you should use
```
List<A> listA = listB.Cast<A>().Concat(listC.Cast<A>()).ToList()
``` |
53,435 | <p>I'm doing something bad in my ASP.NET app. It could be the any number of CTP libraries I'm using or I'm just not disposing something properly. But when I redeploy my ASP.NET to my Vista IIS7 install or my server's IIS6 install I crash an IIS worker process.</p>
<p>I've narrowed the problem down to my HTTP crawler, which is a multithreaded beast that crawls sites for useful information when asked to. After I start a crawler and redeploy the app over the top, rather than gracefully unloading the appDomain and reloading, an IIS worker process will crash (popping up a crash message) and continue reloading the app domain.</p>
<p>When this crash happens, where can I find the crash dump for analysis?</p>
| [
{
"answer_id": 53457,
"author": "Gareth Jenkins",
"author_id": 1521,
"author_profile": "https://Stackoverflow.com/users/1521",
"pm_score": 1,
"selected": false,
"text": "<p>A quick search found <a href=\"http://www.iisfaq.com/default.aspx?view=P197\" rel=\"nofollow noreferrer\">IISState</a> - it relies on the <a href=\"http://www.microsoft.com/whdc/devtools/debugging/default.mspx\" rel=\"nofollow noreferrer\">Windows debugging tools</a> and needs to be running when a crash occurs, but given the circumstances you've described, this shouldn't be a problem,</p>\n"
},
{
"answer_id": 66625,
"author": "sachaa",
"author_id": 1152057,
"author_profile": "https://Stackoverflow.com/users/1152057",
"pm_score": 5,
"selected": true,
"text": "<p>Download Debugging tools for Windows:\n<a href=\"http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx\" rel=\"noreferrer\">http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx</a></p>\n\n<p>Debugging Tools for Windows has has a script (ADPLUS) that allows you to create dumps when a process CRASHES:\n<a href=\"http://support.microsoft.com/kb/286350\" rel=\"noreferrer\">http://support.microsoft.com/kb/286350</a></p>\n\n<p>The command should be something like (if you are using IIS6):</p>\n\n<pre><code>cscript adplus.vbs -crash -pn w3wp.exe\n</code></pre>\n\n<p>This command will attach the debugger to the worker process. When the crash occurs it will generate a dump (a *.DMP file).</p>\n\n<p>You can open it in WinDBG (also included in the Debugging Tools for Windows). File > Open Crash dump...</p>\n\n<p>By default, WinDBG will show you (next to the command line) the thread were the process crashed.</p>\n\n<p>The first thing you need to do in WinDBG is to load the .NET Framework extensions:</p>\n\n<pre><code>.loadby sos mscorwks\n</code></pre>\n\n<p>then, you will display the managed callstack:</p>\n\n<pre><code>!clrstack\n</code></pre>\n\n<p>if the thread was not running managed code, then you'll need to check the native stack:</p>\n\n<pre><code>kpn 200\n</code></pre>\n\n<p>This should give you some ideas. To continue troubleshooting I recommend you read the following article:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ee817663.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ee817663.aspx</a></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/209/"
] | I'm doing something bad in my ASP.NET app. It could be the any number of CTP libraries I'm using or I'm just not disposing something properly. But when I redeploy my ASP.NET to my Vista IIS7 install or my server's IIS6 install I crash an IIS worker process.
I've narrowed the problem down to my HTTP crawler, which is a multithreaded beast that crawls sites for useful information when asked to. After I start a crawler and redeploy the app over the top, rather than gracefully unloading the appDomain and reloading, an IIS worker process will crash (popping up a crash message) and continue reloading the app domain.
When this crash happens, where can I find the crash dump for analysis? | Download Debugging tools for Windows:
<http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx>
Debugging Tools for Windows has has a script (ADPLUS) that allows you to create dumps when a process CRASHES:
<http://support.microsoft.com/kb/286350>
The command should be something like (if you are using IIS6):
```
cscript adplus.vbs -crash -pn w3wp.exe
```
This command will attach the debugger to the worker process. When the crash occurs it will generate a dump (a \*.DMP file).
You can open it in WinDBG (also included in the Debugging Tools for Windows). File > Open Crash dump...
By default, WinDBG will show you (next to the command line) the thread were the process crashed.
The first thing you need to do in WinDBG is to load the .NET Framework extensions:
```
.loadby sos mscorwks
```
then, you will display the managed callstack:
```
!clrstack
```
if the thread was not running managed code, then you'll need to check the native stack:
```
kpn 200
```
This should give you some ideas. To continue troubleshooting I recommend you read the following article:
<http://msdn.microsoft.com/en-us/library/ee817663.aspx> |
53,472 | <p>I have some Ruby code which takes dates on the command line in the format:</p>
<pre><code>-d 20080101,20080201..20080229,20080301
</code></pre>
<p>I want to run for all dates between <code>20080201</code> and <code>20080229</code> inclusive and the other dates present in the list.</p>
<p>I can get the string <code>20080201..20080229</code>, so is the best way to convert this to a Range instance? Currently, I am using <code>eval</code>, but it feels like there should be a better way.</p>
<hr>
<p>@Purfideas I was kind of looking for a more general answer for converting any string of type <code>int..int</code> to a Range I guess.</p>
| [
{
"answer_id": 53504,
"author": "Purfideas",
"author_id": 4615,
"author_profile": "https://Stackoverflow.com/users/4615",
"pm_score": 2,
"selected": false,
"text": "<p>assuming you want the range to iterate properly through months etc, try</p>\n\n<pre><code>require 'date'\n\nends = '20080201..20080229'.split('..').map{|d| Date.parse(d)}\n(ends[0]..ends[1]).each do |d|\n p d.day\nend\n</code></pre>\n"
},
{
"answer_id": 53588,
"author": "Purfideas",
"author_id": 4615,
"author_profile": "https://Stackoverflow.com/users/4615",
"pm_score": 5,
"selected": true,
"text": "<p>But then just do </p>\n\n<pre><code>ends = '20080201..20080229'.split('..').map{|d| Integer(d)}\nends[0]..ends[1]\n</code></pre>\n\n<p>anyway I don't recommend eval, for security reasons</p>\n"
},
{
"answer_id": 54647,
"author": "theschmitzer",
"author_id": 2167252,
"author_profile": "https://Stackoverflow.com/users/2167252",
"pm_score": 3,
"selected": false,
"text": "<p>Inject with no args works well for two element arrays:</p>\n\n<pre><code>rng='20080201..20080229'.split('..').inject { |s,e| s.to_i..e.to_i }\n</code></pre>\n\n<p>Of course, this can be made generic</p>\n\n<pre><code>class Range\n def self.from_ary(a)\n a.inject{|s,e| s..e }\n end\nend\n\nrng = Range.from_ary('20080201..20080229'.split('..').map{|s| s.to_i})\nrng.class # => Range\n</code></pre>\n"
},
{
"answer_id": 3243732,
"author": "ujifgc",
"author_id": 391229,
"author_profile": "https://Stackoverflow.com/users/391229",
"pm_score": 5,
"selected": false,
"text": "<pre><code>Range.new(*self.split(\"..\").map(&:to_i))\n</code></pre>\n"
},
{
"answer_id": 21399899,
"author": "MetalArend",
"author_id": 1945685,
"author_profile": "https://Stackoverflow.com/users/1945685",
"pm_score": 0,
"selected": false,
"text": "<p>Combining @Purfideas answer with another answer somewhere on StackOverflow, I solved this by also surrounding the code with an input check, so the only thing used is a valid enumerable </p>\n\n<pre><code>if !value[/^[0-9]+\\.\\.[0-9]+$/].nil?\n ends = value.split('..').map{|d| Integer(d)}\n value = ends[0]..ends[1]\nend\n</code></pre>\n\n<p>It essentially rewrites your string value to a enumerable value. This comes in handy if you add a enumerable field in a yaml config file.</p>\n\n<p>If you need it for your application, you could extend the regex with an optional third literal dot, that could be optional.</p>\n"
},
{
"answer_id": 26996959,
"author": "nurettin",
"author_id": 227755,
"author_profile": "https://Stackoverflow.com/users/227755",
"pm_score": 0,
"selected": false,
"text": "<p>If we do it like</p>\n\n<pre><code>v= \"20140101..20150101\"\nraise \"Error: invalid format: #{v}\" if /\\d{8}\\.\\.\\d{8}/ !~ v\nr= eval(v)\n</code></pre>\n\n<p>and the attacker has a way of bypassing the raise check (simply by means of manipulating the runtime to disable exceptions) then we can get a dangerous eval which will potentially destroy the universe.</p>\n\n<p>So for the sake of reducing attack vectors, we check the format, and then do the parsing manually, then check the results</p>\n\n<pre><code>v= \"20140101..20150101\"\nraise \"Error: invalid format: #{v}\" if /\\d{8}\\.\\.\\d{8}/ !~ v\nr= Range.new(*v.split(/\\.\\./).map(&:to_i))\nraise \"Error: invalid range: #{v}\" if r.first> r.last\n</code></pre>\n"
},
{
"answer_id": 29943562,
"author": "Epigene",
"author_id": 3319298,
"author_profile": "https://Stackoverflow.com/users/3319298",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://github.com/Epigene/ranger\" rel=\"nofollow noreferrer\">Ranger</a> uses regex to validate strings with no SQL injection fear, and then <code>eval</code>.</p>\n"
},
{
"answer_id": 48169090,
"author": "shubham mishra",
"author_id": 7516788,
"author_profile": "https://Stackoverflow.com/users/7516788",
"pm_score": 0,
"selected": false,
"text": "<p>Here suppose you want to store the hash as a system constant value and fetch it in any model. The hash key will be a range value.</p>\n\n<pre><code>hash_1 = {1..5 => 'a', 6..12 => 'b', 13..67 => 'c', 68..9999999 => 'd'}\n</code></pre>\n\n<p>Then create the system constant with value as hash_1.to_json.\n.to_json will convert your hash object to JSON object.\nNow inside the code create a new hash hash_2,</p>\n\n<pre><code>JSON.parse(SystemConstant.get('Constant_name')).each{|key,val| temp_k=key.split('..').map{|d| Integer(d)}; hash_2[temp_k[0]..temp_k[1]] = val}\n</code></pre>\n\n<p>The new hash_2 will be the required hash_1</p>\n"
},
{
"answer_id": 65895545,
"author": "Matthew",
"author_id": 145725,
"author_profile": "https://Stackoverflow.com/users/145725",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar requirement although in my case the strings were in two possible formats, occasionally they were single number strings such as "7", other times they were ranges such as "10-14". Either way I wanted to turn the string into an Enumerable collection of numbers.</p>\n<p>My approach (inspired by the <a href=\"https://stackoverflow.com/a/3243732/145725\">highest voted answer</a>) was:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>def numbers(from_string:)\n if from_string.include?('-')\n return Range.new(*from_string.split('-').map(&:to_i))\n else\n return [from_string.to_i] # put number in an array so we can enumerate over it\n end\nend\n</code></pre>\n<p>It can also be done as a (long) one-liner if you think that's more readable:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>from_string.include?('-') ? Range.new(*from_string.split('-').map(&:to_i)) : [from_string.to_i]\n</code></pre>\n<p>I was processing a long list of known strings, not dealing with arbitrary user input so this doesn't guard against malicious input.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4121/"
] | I have some Ruby code which takes dates on the command line in the format:
```
-d 20080101,20080201..20080229,20080301
```
I want to run for all dates between `20080201` and `20080229` inclusive and the other dates present in the list.
I can get the string `20080201..20080229`, so is the best way to convert this to a Range instance? Currently, I am using `eval`, but it feels like there should be a better way.
---
@Purfideas I was kind of looking for a more general answer for converting any string of type `int..int` to a Range I guess. | But then just do
```
ends = '20080201..20080229'.split('..').map{|d| Integer(d)}
ends[0]..ends[1]
```
anyway I don't recommend eval, for security reasons |
53,473 | <p>I am trying to apply styles to HTML tags dynamically by reading in the value of certain HTML attributes and applying a class name based on their values. For instance, if I have:</p>
<pre><code><p height="30">
</code></pre>
<p>I want to apply a <code>class="h30"</code> to that paragraph so that I can style it in my style sheet. I can't find any information on getting the value of an attribute that is not an <code>id</code> or <code>class</code>. Help?</p>
| [
{
"answer_id": 53475,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 0,
"selected": false,
"text": "<p>Attributes are just properties (usually). So just try:</p>\n\n<pre><code>for (e in ...) {\n if (e.height == 30) {\n e.className = \"h30\";\n }\n}\n</code></pre>\n\n<p>Or use something like jquery to simplify this kind of stuff.</p>\n"
},
{
"answer_id": 53485,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 2,
"selected": false,
"text": "<p>See: <a href=\"http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-666EE0F9\" rel=\"nofollow noreferrer\">getAttribute()</a>. Parameter is the name of the attribute (case insensitive). Return value is the value of the attribute (a string). </p>\n\n<p>Be sure to see the <a href=\"http://msdn.microsoft.com/en-us/library/ms536429(VS.85).aspx\" rel=\"nofollow noreferrer\">Remarks</a> in MSDN before dealing with IE...</p>\n"
},
{
"answer_id": 53593,
"author": "SeanDowney",
"author_id": 5261,
"author_profile": "https://Stackoverflow.com/users/5261",
"pm_score": 4,
"selected": true,
"text": "<p>I would highly recommend using something like jquery where adding classes is trivial:</p>\n\n<pre><code>$(\"#someId\").addClass(\"newClass\");\n</code></pre>\n\n<p>so in your case:</p>\n\n<pre><code>$(\"p[height='30']\").addClass(\"h30\");\n</code></pre>\n\n<p>so this selects all paragraph tags where the height attribute is 30 and adds the class h30 to it.</p>\n"
},
{
"answer_id": 324566,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 2,
"selected": false,
"text": "<p>It's better to separate layout and presentation. </p>\n\n<p>Despite using CSS, you're tying these two together. <a href=\"http://www.w3.org/QA/Tips/goodclassnames\" rel=\"nofollow noreferrer\">Use better class names</a> (why does it have to have 30px height? Is it menubar? footer? banner?)</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5512/"
] | I am trying to apply styles to HTML tags dynamically by reading in the value of certain HTML attributes and applying a class name based on their values. For instance, if I have:
```
<p height="30">
```
I want to apply a `class="h30"` to that paragraph so that I can style it in my style sheet. I can't find any information on getting the value of an attribute that is not an `id` or `class`. Help? | I would highly recommend using something like jquery where adding classes is trivial:
```
$("#someId").addClass("newClass");
```
so in your case:
```
$("p[height='30']").addClass("h30");
```
so this selects all paragraph tags where the height attribute is 30 and adds the class h30 to it. |
53,480 | <p>Hey, I'm using <a href="http://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow noreferrer">Levenshteins</a> algorithm to get distance between source and target string.</p>
<p>also I have method which returns value from 0 to 1:</p>
<pre><code>/// <summary>
/// Gets the similarity between two strings.
/// All relation scores are in the [0, 1] range,
/// which means that if the score gets a maximum value (equal to 1)
/// then the two string are absolutely similar
/// </summary>
/// <param name="string1">The string1.</param>
/// <param name="string2">The string2.</param>
/// <returns></returns>
public static float CalculateSimilarity(String s1, String s2)
{
if ((s1 == null) || (s2 == null)) return 0.0f;
float dis = LevenshteinDistance.Compute(s1, s2);
float maxLen = s1.Length;
if (maxLen < s2.Length)
maxLen = s2.Length;
if (maxLen == 0.0F)
return 1.0F;
else return 1.0F - dis / maxLen;
}
</code></pre>
<p>but this for me is not enough. Because I need more complex way to match two sentences.</p>
<p>For example I want automatically tag some music, I have original song names, and i have songs with trash, like <em>super, quality,</em> years like <em>2007, 2008,</em> etc..etc.. also some files have just <a href="http://trash..thash..song_name_mp3.mp3" rel="nofollow noreferrer">http://trash..thash..song_name_mp3.mp3</a>, other are normal. I want to create an algorithm which will work just more perfect than mine now.. Maybe anyone can help me?</p>
<p>here is my current algo:</p>
<pre><code>/// <summary>
/// if we need to ignore this target.
/// </summary>
/// <param name="targetString">The target string.</param>
/// <returns></returns>
private bool doIgnore(String targetString)
{
if ((targetString != null) && (targetString != String.Empty))
{
for (int i = 0; i < ignoreWordsList.Length; ++i)
{
//* if we found ignore word or target string matching some some special cases like years (Regex).
if (targetString == ignoreWordsList[i] || (isMatchInSpecialCases(targetString))) return true;
}
}
return false;
}
/// <summary>
/// Removes the duplicates.
/// </summary>
/// <param name="list">The list.</param>
private void removeDuplicates(List<String> list)
{
if ((list != null) && (list.Count > 0))
{
for (int i = 0; i < list.Count - 1; ++i)
{
if (list[i] == list[i + 1])
{
list.RemoveAt(i);
--i;
}
}
}
}
/// <summary>
/// Does the fuzzy match.
/// </summary>
/// <param name="targetTitle">The target title.</param>
/// <returns></returns>
private TitleMatchResult doFuzzyMatch(String targetTitle)
{
TitleMatchResult matchResult = null;
if (targetTitle != null && targetTitle != String.Empty)
{
try
{
//* change target title (string) to lower case.
targetTitle = targetTitle.ToLower();
//* scores, we will select higher score at the end.
Dictionary<Title, float> scores = new Dictionary<Title, float>();
//* do split special chars: '-', ' ', '.', ',', '?', '/', ':', ';', '%', '(', ')', '#', '\"', '\'', '!', '|', '^', '*', '[', ']', '{', '}', '=', '!', '+', '_'
List<String> targetKeywords = new List<string>(targetTitle.Split(ignoreCharsList, StringSplitOptions.RemoveEmptyEntries));
//* remove all trash from keywords, like super, quality, etc..
targetKeywords.RemoveAll(delegate(String x) { return doIgnore(x); });
//* sort keywords.
targetKeywords.Sort();
//* remove some duplicates.
removeDuplicates(targetKeywords);
//* go through all original titles.
foreach (Title sourceTitle in titles)
{
float tempScore = 0f;
//* split orig. title to keywords list.
List<String> sourceKeywords = new List<string>(sourceTitle.Name.Split(ignoreCharsList, StringSplitOptions.RemoveEmptyEntries));
sourceKeywords.Sort();
removeDuplicates(sourceKeywords);
//* go through all source ttl keywords.
foreach (String keyw1 in sourceKeywords)
{
float max = float.MinValue;
foreach (String keyw2 in targetKeywords)
{
float currentScore = StringMatching.StringMatching.CalculateSimilarity(keyw1.ToLower(), keyw2);
if (currentScore > max)
{
max = currentScore;
}
}
tempScore += max;
}
//* calculate average score.
float averageScore = (tempScore / Math.Max(targetKeywords.Count, sourceKeywords.Count));
//* if average score is bigger than minimal score and target title is not in this source title ignore list.
if (averageScore >= minimalScore && !sourceTitle.doIgnore(targetTitle))
{
//* add score.
scores.Add(sourceTitle, averageScore);
}
}
//* choose biggest score.
float maxi = float.MinValue;
foreach (KeyValuePair<Title, float> kvp in scores)
{
if (kvp.Value > maxi)
{
maxi = kvp.Value;
matchResult = new TitleMatchResult(maxi, kvp.Key, MatchTechnique.FuzzyLogic);
}
}
}
catch { }
}
//* return result.
return matchResult;
}
</code></pre>
<p>This works normally but just in some cases, a lot of titles which should match, does not match... I think I need some kind of formula to play with weights and etc, but i can't think of one.. </p>
<p>Ideas? Suggestions? Algos?</p>
<p>by the way I already know this topic (My colleague already posted it but we cannot come with a proper solution for this problem.):
<a href="https://stackoverflow.com/questions/49263/approximate-string-matching-algorithms">Approximate string matching algorithms</a></p>
| [
{
"answer_id": 53531,
"author": "Greg",
"author_id": 4123,
"author_profile": "https://Stackoverflow.com/users/4123",
"pm_score": 3,
"selected": false,
"text": "<p>It sounds like what you want may be a longest substring match. That is, in your example, two files like</p>\n\n<p>trash..thash..song_name_mp3.mp3\nand\ngarbage..spotch..song_name_mp3.mp3</p>\n\n<p>would end up looking the same.</p>\n\n<p>You'd need some heuristics there, of course. One thing you might try is putting the string through a soundex converter. Soundex is the \"codec\" used to see if things \"sound\" the same (as you might tell a telephone operator). It's more or less a rough phonetic and mispronunciation semi-proof transliteration. It is definitely poorer than edit distance, but much, much cheaper. (The official use is for names, and only uses three characters. There's no reason to stop there, though, just use the mapping for every character in the string. See <a href=\"http://en.wikipedia.org/wiki/Soundex\" rel=\"noreferrer\">wikipedia</a> for details)</p>\n\n<p>So my suggestion would be to soundex your strings, chop each one into a few length tranches (say 5, 10, 20) and then just look at clusters. Within clusters you can use something more expensive like edit distance or max substring.</p>\n"
},
{
"answer_id": 53539,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": true,
"text": "<p>Your problem here may be distinguishing between noise words and useful data:</p>\n\n<ul>\n<li>Rolling_Stones.Best_of_2003.Wild_Horses.mp3</li>\n<li>Super.Quality.Wild_Horses.mp3</li>\n<li>Tori_Amos.Wild_Horses.mp3</li>\n</ul>\n\n<p>You may need to produce a dictionary of noise words to ignore. That seems clunky, but I'm not sure there's an algorithm that can distinguish between band/album names and noise.</p>\n"
},
{
"answer_id": 55913,
"author": "ima",
"author_id": 5733,
"author_profile": "https://Stackoverflow.com/users/5733",
"pm_score": 2,
"selected": false,
"text": "<p>There's a lot of work done on somewhat related problem of DNA sequence alignment (search for \"local sequence alignment\") - classic algorithm being \"Needleman-Wunsch\" and more complex modern ones also easy to find. The idea is - similar to Greg's answer - instead of identifying and comparing keywords try to find longest loosely matching substrings within long strings. </p>\n\n<p>That being sad, if the only goal is sorting music, a number of regular expressions to cover possible naming schemes would probably work better than any generic algorithm.</p>\n"
},
{
"answer_id": 10079256,
"author": "Alain",
"author_id": 529618,
"author_profile": "https://Stackoverflow.com/users/529618",
"pm_score": 4,
"selected": false,
"text": "<p>Kind of old, but It might be useful to future visitors. If you're already using the Levenshtein algorithm and you need to go a little better, I describe some very effective heuristics in this solution:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/5859561/getting-the-closest-string-match/5859823#5859823\">Getting the closest string match</a></p>\n\n<p>The key is that you come up with 3 or 4 (or <a href=\"http://en.wikipedia.org/wiki/String_metric\" rel=\"nofollow noreferrer\">more</a>) methods of gauging the similarity between your phrases (Levenshtein distance is just one method) - and then using real examples of strings you want to match as similar, you adjust the weightings and combinations of those heuristics until you get something that maximizes the number of positive matches. Then you use that formula for all future matches and you should see great results.</p>\n\n<p>If a user is involved in the process, it's also best if you provide an interface which allows the user to see additional matches that rank highly in similarity in case they disagree with the first choice.</p>\n\n<p>Here's an excerpt from the linked answer. If you end up wanting to use any of this code as is, I apologize in advance for having to convert VBA into C#.</p>\n\n<hr>\n\n<p>Simple, speedy, and a very useful metric. Using this, I created two separate metrics for evaluating the similarity of two strings. One I call \"valuePhrase\" and one I call \"valueWords\". valuePhrase is just the Levenshtein distance between the two phrases, and valueWords splits the string into individual words, based on delimiters such as spaces, dashes, and anything else you'd like, and compares each word to each other word, summing up the shortest Levenshtein distance connecting any two words. Essentially, it measures whether the information in one 'phrase' is really contained in another, just as a word-wise permutation. I spent a few days as a side project coming up with the most efficient way possible of splitting a string based on delimiters.</p>\n\n<p>valueWords, valuePhrase, and Split function:</p>\n\n<pre><code>Public Function valuePhrase#(ByRef S1$, ByRef S2$)\n valuePhrase = LevenshteinDistance(S1, S2)\nEnd Function\n\nPublic Function valueWords#(ByRef S1$, ByRef S2$)\n Dim wordsS1$(), wordsS2$()\n wordsS1 = SplitMultiDelims(S1, \" _-\")\n wordsS2 = SplitMultiDelims(S2, \" _-\")\n Dim word1%, word2%, thisD#, wordbest#\n Dim wordsTotal#\n For word1 = LBound(wordsS1) To UBound(wordsS1)\n wordbest = Len(S2)\n For word2 = LBound(wordsS2) To UBound(wordsS2)\n thisD = LevenshteinDistance(wordsS1(word1), wordsS2(word2))\n If thisD < wordbest Then wordbest = thisD\n If thisD = 0 Then GoTo foundbest\n Next word2\nfoundbest:\n wordsTotal = wordsTotal + wordbest\n Next word1\n valueWords = wordsTotal\nEnd Function\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' SplitMultiDelims\n' This function splits Text into an array of substrings, each substring\n' delimited by any character in DelimChars. Only a single character\n' may be a delimiter between two substrings, but DelimChars may\n' contain any number of delimiter characters. It returns a single element\n' array containing all of text if DelimChars is empty, or a 1 or greater\n' element array if the Text is successfully split into substrings.\n' If IgnoreConsecutiveDelimiters is true, empty array elements will not occur.\n' If Limit greater than 0, the function will only split Text into 'Limit'\n' array elements or less. The last element will contain the rest of Text.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction SplitMultiDelims(ByRef Text As String, ByRef DelimChars As String, _\n Optional ByVal IgnoreConsecutiveDelimiters As Boolean = False, _\n Optional ByVal Limit As Long = -1) As String()\n Dim ElemStart As Long, N As Long, M As Long, Elements As Long\n Dim lDelims As Long, lText As Long\n Dim Arr() As String\n\n lText = Len(Text)\n lDelims = Len(DelimChars)\n If lDelims = 0 Or lText = 0 Or Limit = 1 Then\n ReDim Arr(0 To 0)\n Arr(0) = Text\n SplitMultiDelims = Arr\n Exit Function\n End If\n ReDim Arr(0 To IIf(Limit = -1, lText - 1, Limit))\n\n Elements = 0: ElemStart = 1\n For N = 1 To lText\n If InStr(DelimChars, Mid(Text, N, 1)) Then\n Arr(Elements) = Mid(Text, ElemStart, N - ElemStart)\n If IgnoreConsecutiveDelimiters Then\n If Len(Arr(Elements)) > 0 Then Elements = Elements + 1\n Else\n Elements = Elements + 1\n End If\n ElemStart = N + 1\n If Elements + 1 = Limit Then Exit For\n End If\n Next N\n 'Get the last token terminated by the end of the string into the array\n If ElemStart <= lText Then Arr(Elements) = Mid(Text, ElemStart)\n 'Since the end of string counts as the terminating delimiter, if the last character\n 'was also a delimiter, we treat the two as consecutive, and so ignore the last elemnent\n If IgnoreConsecutiveDelimiters Then If Len(Arr(Elements)) = 0 Then Elements = Elements - 1\n\n ReDim Preserve Arr(0 To Elements) 'Chop off unused array elements\n SplitMultiDelims = Arr\nEnd Function\n</code></pre>\n\n<p><strong>Measures of Similarity</strong></p>\n\n<p>Using these two metrics, and a third which simply computes the distance between two strings, I have a series of variables which I can run an optimization algorithm to achieve the greatest number of matches. Fuzzy string matching is, itself, a fuzzy science, and so by creating linearly independent metrics for measuring string similarity, and having a known set of strings we wish to match to each other, we can find the parameters that, for our specific styles of strings, give the best fuzzy match results.</p>\n\n<p>Initially, the goal of the metric was to have a low search value for for an exact match, and increasing search values for increasingly permuted measures. In an impractical case, this was fairly easy to define using a set of well defined permutations, and engineering the final formula such that they had increasing search values results as desired.</p>\n\n<p><img src=\"https://i.stack.imgur.com/eGCtC.png\" alt=\"enter image description here\"></p>\n\n<p>As you can see, the last two metrics, which are fuzzy string matching metrics, already have a natural tendency to give low scores to strings that are meant to match (down the diagonal). This is very good. </p>\n\n<p><strong>Application</strong>\nTo allow the optimization of fuzzy matching, I weight each metric. As such, every application of fuzzy string match can weight the parameters differently. The formula that defines the final score is a simply combination of the metrics and their weights:</p>\n\n<pre><code>value = Min(phraseWeight*phraseValue, wordsWeight*wordsValue)*minWeight + \n Max(phraseWeight*phraseValue, wordsWeight*wordsValue)*maxWeight + lengthWeight*lengthValue\n</code></pre>\n\n<p>Using an optimization algorithm (neural network is best here because it is a discrete, multi-dimentional problem), the goal is now to maximize the number of matches. I created a function that detects the number of correct matches of each set to each other, as can be seen in this final screenshot. A column or row gets a point if the lowest score is assigned the the string that was meant to be matched, and partial points are given if there is a tie for the lowest score, and the correct match is among the tied matched strings. I then optimized it. You can see that a green cell is the column that best matches the current row, and a blue square around the cell is the row that best matches the current column. The score in the bottom corner is roughly the number of successful matches and this is what we tell our optimization problem to maximize. </p>\n\n<p><img src=\"https://i.stack.imgur.com/hsMtp.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 55732425,
"author": "Ricardo stands with Ukraine",
"author_id": 364568,
"author_profile": "https://Stackoverflow.com/users/364568",
"pm_score": 0,
"selected": false,
"text": "<p>There is a <a href=\"https://github.com/kdjones/fuzzystring\" rel=\"nofollow noreferrer\">GitHub repo</a> implementing several methods.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5369/"
] | Hey, I'm using [Levenshteins](http://en.wikipedia.org/wiki/Levenshtein_distance) algorithm to get distance between source and target string.
also I have method which returns value from 0 to 1:
```
/// <summary>
/// Gets the similarity between two strings.
/// All relation scores are in the [0, 1] range,
/// which means that if the score gets a maximum value (equal to 1)
/// then the two string are absolutely similar
/// </summary>
/// <param name="string1">The string1.</param>
/// <param name="string2">The string2.</param>
/// <returns></returns>
public static float CalculateSimilarity(String s1, String s2)
{
if ((s1 == null) || (s2 == null)) return 0.0f;
float dis = LevenshteinDistance.Compute(s1, s2);
float maxLen = s1.Length;
if (maxLen < s2.Length)
maxLen = s2.Length;
if (maxLen == 0.0F)
return 1.0F;
else return 1.0F - dis / maxLen;
}
```
but this for me is not enough. Because I need more complex way to match two sentences.
For example I want automatically tag some music, I have original song names, and i have songs with trash, like *super, quality,* years like *2007, 2008,* etc..etc.. also some files have just <http://trash..thash..song_name_mp3.mp3>, other are normal. I want to create an algorithm which will work just more perfect than mine now.. Maybe anyone can help me?
here is my current algo:
```
/// <summary>
/// if we need to ignore this target.
/// </summary>
/// <param name="targetString">The target string.</param>
/// <returns></returns>
private bool doIgnore(String targetString)
{
if ((targetString != null) && (targetString != String.Empty))
{
for (int i = 0; i < ignoreWordsList.Length; ++i)
{
//* if we found ignore word or target string matching some some special cases like years (Regex).
if (targetString == ignoreWordsList[i] || (isMatchInSpecialCases(targetString))) return true;
}
}
return false;
}
/// <summary>
/// Removes the duplicates.
/// </summary>
/// <param name="list">The list.</param>
private void removeDuplicates(List<String> list)
{
if ((list != null) && (list.Count > 0))
{
for (int i = 0; i < list.Count - 1; ++i)
{
if (list[i] == list[i + 1])
{
list.RemoveAt(i);
--i;
}
}
}
}
/// <summary>
/// Does the fuzzy match.
/// </summary>
/// <param name="targetTitle">The target title.</param>
/// <returns></returns>
private TitleMatchResult doFuzzyMatch(String targetTitle)
{
TitleMatchResult matchResult = null;
if (targetTitle != null && targetTitle != String.Empty)
{
try
{
//* change target title (string) to lower case.
targetTitle = targetTitle.ToLower();
//* scores, we will select higher score at the end.
Dictionary<Title, float> scores = new Dictionary<Title, float>();
//* do split special chars: '-', ' ', '.', ',', '?', '/', ':', ';', '%', '(', ')', '#', '\"', '\'', '!', '|', '^', '*', '[', ']', '{', '}', '=', '!', '+', '_'
List<String> targetKeywords = new List<string>(targetTitle.Split(ignoreCharsList, StringSplitOptions.RemoveEmptyEntries));
//* remove all trash from keywords, like super, quality, etc..
targetKeywords.RemoveAll(delegate(String x) { return doIgnore(x); });
//* sort keywords.
targetKeywords.Sort();
//* remove some duplicates.
removeDuplicates(targetKeywords);
//* go through all original titles.
foreach (Title sourceTitle in titles)
{
float tempScore = 0f;
//* split orig. title to keywords list.
List<String> sourceKeywords = new List<string>(sourceTitle.Name.Split(ignoreCharsList, StringSplitOptions.RemoveEmptyEntries));
sourceKeywords.Sort();
removeDuplicates(sourceKeywords);
//* go through all source ttl keywords.
foreach (String keyw1 in sourceKeywords)
{
float max = float.MinValue;
foreach (String keyw2 in targetKeywords)
{
float currentScore = StringMatching.StringMatching.CalculateSimilarity(keyw1.ToLower(), keyw2);
if (currentScore > max)
{
max = currentScore;
}
}
tempScore += max;
}
//* calculate average score.
float averageScore = (tempScore / Math.Max(targetKeywords.Count, sourceKeywords.Count));
//* if average score is bigger than minimal score and target title is not in this source title ignore list.
if (averageScore >= minimalScore && !sourceTitle.doIgnore(targetTitle))
{
//* add score.
scores.Add(sourceTitle, averageScore);
}
}
//* choose biggest score.
float maxi = float.MinValue;
foreach (KeyValuePair<Title, float> kvp in scores)
{
if (kvp.Value > maxi)
{
maxi = kvp.Value;
matchResult = new TitleMatchResult(maxi, kvp.Key, MatchTechnique.FuzzyLogic);
}
}
}
catch { }
}
//* return result.
return matchResult;
}
```
This works normally but just in some cases, a lot of titles which should match, does not match... I think I need some kind of formula to play with weights and etc, but i can't think of one..
Ideas? Suggestions? Algos?
by the way I already know this topic (My colleague already posted it but we cannot come with a proper solution for this problem.):
[Approximate string matching algorithms](https://stackoverflow.com/questions/49263/approximate-string-matching-algorithms) | Your problem here may be distinguishing between noise words and useful data:
* Rolling\_Stones.Best\_of\_2003.Wild\_Horses.mp3
* Super.Quality.Wild\_Horses.mp3
* Tori\_Amos.Wild\_Horses.mp3
You may need to produce a dictionary of noise words to ignore. That seems clunky, but I'm not sure there's an algorithm that can distinguish between band/album names and noise. |
53,482 | <p>I have long since forgotten the password for the root user on one of my boxes. Is there a way I can change it without having to log in to the instance, or will I have to reinstall?</p>
| [
{
"answer_id": 53483,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": 2,
"selected": false,
"text": "<p>A quick Google resulted in this answer. In the root shell type:</p>\n\n<pre><code>mysqladmin -u root password <password>\n</code></pre>\n"
},
{
"answer_id": 53567,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 3,
"selected": true,
"text": "<p><strong>Step 1</strong></p>\n\n<p>Stop database:</p>\n\n<pre><code>shell> /etc/init.d/mysql stop\n</code></pre>\n\n<p><strong>Step 2</strong></p>\n\n<p>Restart database</p>\n\n<ul>\n<li>without password autentification</li>\n<li>without connection to the network</li>\n</ul>\n\n<p>Access to database is only possible through it's sock file '/var/lib/mysql/mysql.sock'.</p>\n\n<pre><code>shell> mysqld --user=mysql --pid-file=/var/lib/mysql/mysqld.pid \\\n --socket=/var/lib/mysql/mysql.sock --datadir=/var/lib/mysql \\\n --skip-grant-tables --skip-networking &\n</code></pre>\n\n<p><strong>Step 3</strong></p>\n\n<p>Connect to the database and change password:</p>\n\n<pre><code>shell> mysql --database mysql --socket=/var/lib/mysql/mysql.sock\n</code></pre>\n\n<p>If you want to, show all users:</p>\n\n<pre><code>mysql> select User, password from user;\n</code></pre>\n\n<p>Set new password:</p>\n\n<pre><code>mysql> update user set password=password('NEW PASS') WHERE User='USERNAME';\n</code></pre>\n\n<p>Leave database connection:</p>\n\n<pre><code>mysql> exit\n</code></pre>\n\n<p><strong>Step 4</strong></p>\n\n<p>Restart database server \"normally\".</p>\n\n<pre><code>shell> kill `cat /var/lib/mysql/mysqld.pid`\nshell> /etc/init.d/mysql start\n</code></pre>\n"
},
{
"answer_id": 22678039,
"author": "user12345",
"author_id": 1048805,
"author_profile": "https://Stackoverflow.com/users/1048805",
"pm_score": 0,
"selected": false,
"text": "<p>If you are running an Ubuntu server (possibly also Debian?) you can easily reset. </p>\n\n<p>If you are on 12.04:</p>\n\n<pre><code>sudo dpkg-reconfigure mysql-server-5.5\n</code></pre>\n\n<p>If you are on 10.04:</p>\n\n<pre><code>sudo dpkg-reconfigure mysql-server-5.1\n</code></pre>\n\n<p>If you are not sure which mysql-server version is installed you can try: </p>\n\n<pre><code>dpkg --get-selections | grep mysql-server\n</code></pre>\n\n<p>See for more info:</p>\n\n<p><a href=\"https://help.ubuntu.com/12.04/serverguide/mysql.html\" rel=\"nofollow\">https://help.ubuntu.com/12.04/serverguide/mysql.html</a>\n<a href=\"https://help.ubuntu.com/10.04/serverguide/mysql.html\" rel=\"nofollow\">https://help.ubuntu.com/10.04/serverguide/mysql.html</a></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960/"
] | I have long since forgotten the password for the root user on one of my boxes. Is there a way I can change it without having to log in to the instance, or will I have to reinstall? | **Step 1**
Stop database:
```
shell> /etc/init.d/mysql stop
```
**Step 2**
Restart database
* without password autentification
* without connection to the network
Access to database is only possible through it's sock file '/var/lib/mysql/mysql.sock'.
```
shell> mysqld --user=mysql --pid-file=/var/lib/mysql/mysqld.pid \
--socket=/var/lib/mysql/mysql.sock --datadir=/var/lib/mysql \
--skip-grant-tables --skip-networking &
```
**Step 3**
Connect to the database and change password:
```
shell> mysql --database mysql --socket=/var/lib/mysql/mysql.sock
```
If you want to, show all users:
```
mysql> select User, password from user;
```
Set new password:
```
mysql> update user set password=password('NEW PASS') WHERE User='USERNAME';
```
Leave database connection:
```
mysql> exit
```
**Step 4**
Restart database server "normally".
```
shell> kill `cat /var/lib/mysql/mysqld.pid`
shell> /etc/init.d/mysql start
``` |
53,491 | <p>How do I enable external access to MySQL Server? I can connect locally but I cannot connect from another box on the network.</p>
<p>I just tried</p>
<pre><code>grant all privileges on *.* to root@'%' identified by '*****' with grant option;
</code></pre>
<p>And restarted MySQL Server with no success.</p>
| [
{
"answer_id": 53512,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 6,
"selected": true,
"text": "<p>You probably have to edit the configuration file (usually my.cnf) to listen in the external interface instead of on localhost only.</p>\n\n<p>Change the <code>bind-address</code> parameter to your machine's IP address.</p>\n\n<p>If this is an old MySQL installation, you should comment out the skip-networking parameter.</p>\n\n<p>Afterwards, restart MySQL and you'll be set</p>\n"
},
{
"answer_id": 53517,
"author": "Craig Day",
"author_id": 5193,
"author_profile": "https://Stackoverflow.com/users/5193",
"pm_score": 2,
"selected": false,
"text": "<p>Command and syntax looks fine. Have you checked the server is listening on an interface other than 127.0.0.1? By default Im pretty sure it only listens on the localhost address (127.0.0.1)</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960/"
] | How do I enable external access to MySQL Server? I can connect locally but I cannot connect from another box on the network.
I just tried
```
grant all privileges on *.* to root@'%' identified by '*****' with grant option;
```
And restarted MySQL Server with no success. | You probably have to edit the configuration file (usually my.cnf) to listen in the external interface instead of on localhost only.
Change the `bind-address` parameter to your machine's IP address.
If this is an old MySQL installation, you should comment out the skip-networking parameter.
Afterwards, restart MySQL and you'll be set |
53,497 | <p>I'm having trouble writing a regular expression that matches valid IPv6 addresses, including those in their compressed form (with <code>::</code> or leading zeros omitted from each byte pair). </p>
<p>Can someone suggest a regular expression that would fulfill the requirement?</p>
<p>I'm considering expanding each byte pair and matching the result with a simpler regex.</p>
| [
{
"answer_id": 53499,
"author": "Factor Mystic",
"author_id": 1569,
"author_profile": "https://Stackoverflow.com/users/1569",
"pm_score": 5,
"selected": false,
"text": "<p>From \"<a href=\"http://vernon.mauery.com/content/projects/linux/ipv6_regex\" rel=\"noreferrer\">IPv6 regex</a>\": </p>\n\n<pre><code>(\\A([0-9a-f]{1,4}:){1,1}(:[0-9a-f]{1,4}){1,6}\\Z)|\n(\\A([0-9a-f]{1,4}:){1,2}(:[0-9a-f]{1,4}){1,5}\\Z)|\n(\\A([0-9a-f]{1,4}:){1,3}(:[0-9a-f]{1,4}){1,4}\\Z)|\n(\\A([0-9a-f]{1,4}:){1,4}(:[0-9a-f]{1,4}){1,3}\\Z)|\n(\\A([0-9a-f]{1,4}:){1,5}(:[0-9a-f]{1,4}){1,2}\\Z)|\n(\\A([0-9a-f]{1,4}:){1,6}(:[0-9a-f]{1,4}){1,1}\\Z)|\n(\\A(([0-9a-f]{1,4}:){1,7}|:):\\Z)|\n(\\A:(:[0-9a-f]{1,4}){1,7}\\Z)|\n(\\A((([0-9a-f]{1,4}:){6})(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3})\\Z)|\n(\\A(([0-9a-f]{1,4}:){5}[0-9a-f]{1,4}:(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3})\\Z)|\n(\\A([0-9a-f]{1,4}:){5}:[0-9a-f]{1,4}:(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\Z)|\n(\\A([0-9a-f]{1,4}:){1,1}(:[0-9a-f]{1,4}){1,4}:(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\Z)|\n(\\A([0-9a-f]{1,4}:){1,2}(:[0-9a-f]{1,4}){1,3}:(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\Z)|\n(\\A([0-9a-f]{1,4}:){1,3}(:[0-9a-f]{1,4}){1,2}:(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\Z)|\n(\\A([0-9a-f]{1,4}:){1,4}(:[0-9a-f]{1,4}){1,1}:(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\Z)|\n(\\A(([0-9a-f]{1,4}:){1,5}|:):(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\Z)|\n(\\A:(:[0-9a-f]{1,4}){1,5}:(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\Z)\n</code></pre>\n"
},
{
"answer_id": 53578,
"author": "Jon Cram",
"author_id": 5343,
"author_profile": "https://Stackoverflow.com/users/5343",
"pm_score": 4,
"selected": false,
"text": "<p>I'd have to strongly second the answer from <a href=\"/users/338/frank-krueger\">Frank Krueger</a>.</p>\n\n<p>Whilst you say you need a regular expression to match an IPv6 address, I'm assuming what you really need is to be able to check if a given string is a valid IPv6 address. There is a subtle but important distinction here.</p>\n\n<p>There is more than one way to check if a given string is a valid IPv6 address and regular expression matching is only one solution.</p>\n\n<p>Use an existing library if you can. The library will have fewer bugs and its use will result in less code for you to maintain.</p>\n\n<p>The regular expression suggested by <a href=\"/users/1569/factor-mystic\">Factor Mystic</a> is long and complex. It most likely works, but you should also consider how you'd cope if it unexpectedly fails. The point I'm trying to make here is that if you can't form a required regular expression yourself you won't be able to easily debug it.</p>\n\n<p>If you have no suitable library it may be better to write your own IPv6 validation routine that doesn't depend on regular expressions. If you write it you understand it and if you understand it you can add comments to explain it so that others can also understand and subsequently maintain it.</p>\n\n<p>Act with caution when using a regular expression whose functionality you can't explain to someone else.</p>\n"
},
{
"answer_id": 60946,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 3,
"selected": false,
"text": "<p>If you use Perl try <a href=\"https://metacpan.org/module/Net::IPv6Addr\" rel=\"nofollow noreferrer\">Net::IPv6Addr</a></p>\n\n<pre><code>use Net::IPv6Addr;\n\nif( defined Net::IPv6Addr::is_ipv6($ip_address) ){\n print \"Looks like an ipv6 address\\n\";\n}\n</code></pre>\n\n<p><a href=\"https://metacpan.org/module/NetAddr::IP\" rel=\"nofollow noreferrer\">NetAddr::IP</a></p>\n\n<pre><code>use NetAddr::IP;\n\nmy $obj = NetAddr::IP->new6($ip_address);\n</code></pre>\n\n<p><a href=\"https://metacpan.org/module/Data::Validate::IP\" rel=\"nofollow noreferrer\">Validate::IP</a></p>\n\n<pre><code>use Validate::IP qw'is_ipv6';\n\nif( is_ipv6($ip_address) ){\n print \"Looks like an ipv6 address\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 81899,
"author": "Joe Hildebrand",
"author_id": 8388,
"author_profile": "https://Stackoverflow.com/users/8388",
"pm_score": 5,
"selected": false,
"text": "<p>It sounds like you may be using Python. If so, you can use something like this:</p>\n\n<pre><code>import socket\n\ndef check_ipv6(n):\n try:\n socket.inet_pton(socket.AF_INET6, n)\n return True\n except socket.error:\n return False\n\nprint check_ipv6('::1') # True\nprint check_ipv6('foo') # False\nprint check_ipv6(5) # TypeError exception\nprint check_ipv6(None) # TypeError exception\n</code></pre>\n\n<p>I don't think you have to have IPv6 compiled in to Python to get <a href=\"http://docs.python.org/2/library/socket.html#socket.inet_pton\" rel=\"noreferrer\"><code>inet_pton</code></a>, which can also parse IPv4 addresses if you pass in <code>socket.AF_INET</code> as the first parameter. Note: this may not work on non-Unix systems.</p>\n"
},
{
"answer_id": 1572953,
"author": "Aeron",
"author_id": 190680,
"author_profile": "https://Stackoverflow.com/users/190680",
"pm_score": -1,
"selected": false,
"text": "<p>The regex allows the use of leading zeros in the IPv4 parts.</p>\n\n<p>Some Unix and Mac distros convert those segments into octals.</p>\n\n<p>I suggest using <code>25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d</code> as an IPv4 segment.</p>\n"
},
{
"answer_id": 1934546,
"author": "Michael",
"author_id": 215384,
"author_profile": "https://Stackoverflow.com/users/215384",
"pm_score": 6,
"selected": false,
"text": "<p>The following will validate IPv4, IPv6 (full and compressed), and IPv6v4 (full and compressed) addresses:</p>\n\n<pre><code>'/^(?>(?>([a-f0-9]{1,4})(?>:(?1)){7}|(?!(?:.*[a-f0-9](?>:|$)){8,})((?1)(?>:(?1)){0,6})?::(?2)?)|(?>(?>(?1)(?>:(?1)){5}:|(?!(?:.*[a-f0-9]:){6,})(?3)?::(?>((?1)(?>:(?1)){0,4}):)?)?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\\.(?4)){3}))$/iD'\n</code></pre>\n"
},
{
"answer_id": 3837430,
"author": "user463639",
"author_id": 463639,
"author_profile": "https://Stackoverflow.com/users/463639",
"pm_score": 1,
"selected": false,
"text": "<p>In Java, you can use the library class <code>sun.net.util.IPAddressUtil</code>:</p>\n\n<pre><code>IPAddressUtil.isIPv6LiteralAddress(iPaddress);\n</code></pre>\n"
},
{
"answer_id": 5567938,
"author": "janCoffee",
"author_id": 513481,
"author_profile": "https://Stackoverflow.com/users/513481",
"pm_score": 3,
"selected": false,
"text": "<p>This regular expression will match valid IPv6 and IPv4 addresses in accordance with GNU C++ implementation of regex with REGULAR EXTENDED mode used:</p>\n\n<pre><code>\"^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:)))(%.+)?\\s*$\"\n</code></pre>\n"
},
{
"answer_id": 14365005,
"author": "Ahamx",
"author_id": 1984714,
"author_profile": "https://Stackoverflow.com/users/1984714",
"pm_score": 1,
"selected": false,
"text": "<p>Using Ruby? Try this:</p>\n\n<pre><code>/^(((?=.*(::))(?!.*\\3.+\\3))\\3?|[\\dA-F]{1,4}:)([\\dA-F]{1,4}(\\3|:\\b)|\\2){5}(([\\dA-F]{1,4}(\\3|:\\b|$)|\\2){2}|(((2[0-4]|1\\d|[1-9])?\\d|25[0-5])\\.?\\b){4})\\z/i\n</code></pre>\n"
},
{
"answer_id": 14960927,
"author": "Remi Morin",
"author_id": 2087666,
"author_profile": "https://Stackoverflow.com/users/2087666",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not an Ipv6 expert but I think you can get a pretty good result more easily with this one:</p>\n\n<pre><code>^([0-9A-Fa-f]{0,4}:){2,7}([0-9A-Fa-f]{1,4}$|((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4})$\n</code></pre>\n\n<p>to answer \"is a valid ipv6\" it look like ok to me. To break it down in parts... forget it. I've omitted the unspecified one (::) since there is no use to have \"unpecified adress\" in my database. </p>\n\n<p>the beginning:\n<code>^([0-9A-Fa-f]{0,4}:){2,7}</code> <-- match the compressible part, we can translate this as: between 2 and 7 colon who may have heaxadecimal number between them.</p>\n\n<p>followed by:\n<code>[0-9A-Fa-f]{1,4}$</code> <-- an hexadecimal number (leading 0 omitted)\nOR\n<code>((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}</code> <-- an Ipv4 adress</p>\n"
},
{
"answer_id": 15988275,
"author": "JinnKo",
"author_id": 506757,
"author_profile": "https://Stackoverflow.com/users/506757",
"pm_score": 3,
"selected": false,
"text": "<p>A simple regex that will match, but I wouldn't recommend for validation of any sort is this:</p>\n\n<pre><code>([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4}\n</code></pre>\n\n<p>Note this matches compression anywhere in the address, though it won't match the loopback address ::1. I find this a reasonable compromise in order to keep the regex simple.</p>\n\n<p>I successfully use this in iTerm2 <em>smart selection rules</em> to quad-click IPv6 addresses.</p>\n"
},
{
"answer_id": 17836822,
"author": "Harry",
"author_id": 126537,
"author_profile": "https://Stackoverflow.com/users/126537",
"pm_score": -1,
"selected": false,
"text": "<p>If you want only normal IP-s (no slashes), here:</p>\n\n<pre><code>^(?:[0-9a-f]{1,4}(?:::)?){0,7}::[0-9a-f]+$\n</code></pre>\n\n<p>I use it for my syntax highlighter in hosts file editor application. Works as charm.</p>\n"
},
{
"answer_id": 17871737,
"author": "David M. Syzdek",
"author_id": 903194,
"author_profile": "https://Stackoverflow.com/users/903194",
"pm_score": 8,
"selected": false,
"text": "<p>I was unable to get @Factor Mystic's answer to work with POSIX regular expressions, so I wrote one that works with POSIX regular expressions and PERL regular expressions.</p>\n<p>It should match:</p>\n<ul>\n<li>IPv6 addresses</li>\n<li>zero compressed IPv6 addresses (<a href=\"https://www.rfc-editor.org/rfc/rfc5952#section-2.2\" rel=\"noreferrer\">section 2.2 of rfc5952</a>)</li>\n<li>link-local IPv6 addresses with zone index (<a href=\"https://www.rfc-editor.org/rfc/rfc4007#section-11\" rel=\"noreferrer\">section 11 of rfc4007</a>)</li>\n<li>IPv4-Embedded IPv6 Address (<a href=\"https://www.rfc-editor.org/rfc/rfc6052#section-2\" rel=\"noreferrer\">section 2 of rfc6052</a>)</li>\n<li>IPv4-mapped IPv6 addresses (<a href=\"https://www.rfc-editor.org/rfc/rfc2765#section-2.1\" rel=\"noreferrer\">section 2.1 of rfc2765</a>)</li>\n<li>IPv4-translated addresses (<a href=\"https://www.rfc-editor.org/rfc/rfc2765#section-2.1\" rel=\"noreferrer\">section 2.1 of rfc2765</a>)</li>\n</ul>\n<p>IPv6 Regular Expression:</p>\n<pre><code>(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\n</code></pre>\n<p>For ease of reading, the following is the above regular expression split at major OR points into separate lines:</p>\n<pre><code># IPv6 RegEx\n(\n([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}| # 1:2:3:4:5:6:7:8\n([0-9a-fA-F]{1,4}:){1,7}:| # 1:: 1:2:3:4:5:6:7::\n([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}| # 1::8 1:2:3:4:5:6::8 1:2:3:4:5:6::8\n([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}| # 1::7:8 1:2:3:4:5::7:8 1:2:3:4:5::8\n([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}| # 1::6:7:8 1:2:3:4::6:7:8 1:2:3:4::8\n([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}| # 1::5:6:7:8 1:2:3::5:6:7:8 1:2:3::8\n([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}| # 1::4:5:6:7:8 1:2::4:5:6:7:8 1:2::8\n[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})| # 1::3:4:5:6:7:8 1::3:4:5:6:7:8 1::8 \n:((:[0-9a-fA-F]{1,4}){1,7}|:)| # ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 :: \nfe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}| # fe80::7:8%eth0 fe80::7:8%1 (link-local IPv6 addresses with zone index)\n::(ffff(:0{1,4}){0,1}:){0,1}\n((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}\n(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])| # ::255.255.255.255 ::ffff:255.255.255.255 ::ffff:0:255.255.255.255 (IPv4-mapped IPv6 addresses and IPv4-translated addresses)\n([0-9a-fA-F]{1,4}:){1,4}:\n((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}\n(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]) # 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33 (IPv4-Embedded IPv6 Address)\n)\n\n# IPv4 RegEx\n((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\n</code></pre>\n<p>To make the above easier to understand, the following "pseudo" code replicates the above:</p>\n<pre><code>IPV4SEG = (25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\nIPV4ADDR = (IPV4SEG\\.){3,3}IPV4SEG\nIPV6SEG = [0-9a-fA-F]{1,4}\nIPV6ADDR = (\n (IPV6SEG:){7,7}IPV6SEG| # 1:2:3:4:5:6:7:8\n (IPV6SEG:){1,7}:| # 1:: 1:2:3:4:5:6:7::\n (IPV6SEG:){1,6}:IPV6SEG| # 1::8 1:2:3:4:5:6::8 1:2:3:4:5:6::8\n (IPV6SEG:){1,5}(:IPV6SEG){1,2}| # 1::7:8 1:2:3:4:5::7:8 1:2:3:4:5::8\n (IPV6SEG:){1,4}(:IPV6SEG){1,3}| # 1::6:7:8 1:2:3:4::6:7:8 1:2:3:4::8\n (IPV6SEG:){1,3}(:IPV6SEG){1,4}| # 1::5:6:7:8 1:2:3::5:6:7:8 1:2:3::8\n (IPV6SEG:){1,2}(:IPV6SEG){1,5}| # 1::4:5:6:7:8 1:2::4:5:6:7:8 1:2::8\n IPV6SEG:((:IPV6SEG){1,6})| # 1::3:4:5:6:7:8 1::3:4:5:6:7:8 1::8\n :((:IPV6SEG){1,7}|:)| # ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 :: \n fe80:(:IPV6SEG){0,4}%[0-9a-zA-Z]{1,}| # fe80::7:8%eth0 fe80::7:8%1 (link-local IPv6 addresses with zone index)\n ::(ffff(:0{1,4}){0,1}:){0,1}IPV4ADDR| # ::255.255.255.255 ::ffff:255.255.255.255 ::ffff:0:255.255.255.255 (IPv4-mapped IPv6 addresses and IPv4-translated addresses)\n (IPV6SEG:){1,4}:IPV4ADDR # 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33 (IPv4-Embedded IPv6 Address)\n )\n</code></pre>\n<p>I posted a script on GitHub which tests the regular expression: <a href=\"https://gist.github.com/syzdek/6086792\" rel=\"noreferrer\">https://gist.github.com/syzdek/6086792</a></p>\n"
},
{
"answer_id": 17895611,
"author": "user2623580",
"author_id": 2623580,
"author_profile": "https://Stackoverflow.com/users/2623580",
"pm_score": 3,
"selected": false,
"text": "<p>Beware! <strong>In Java, the use of InetAddress and related classes (Inet4Address, Inet6Address, URL) may involve network trafic!</strong> E.g. DNS resolving (URL.equals, InetAddress from string!). This call may take long and is blocking!</p>\n\n<p>For IPv6 I have something like this. This of course does not handle the very subtle details of IPv6 like that zone indices are allowed only on some classes of IPv6 addresses. And this regex is not written for group capturing, it is only a \"matches\" kind of regexp.</p>\n\n<p><code>S</code> - IPv6 segment = <code>[0-9a-f]{1,4}</code></p>\n\n<p><code>I</code> - IPv4 = <code>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})</code></p>\n\n<p>Schematic (first part matches IPv6 addresses with IPv4 suffix, second part matches IPv6 addresses, last patrt the zone index):</p>\n\n<pre><code>(\n(\n::(S:){0,5}|\nS::(S:){0,4}|\n(S:){2}:(S:){0,3}|\n(S:){3}:(S:){0,2}|\n(S:){4}:(S:)?|\n(S:){5}:|\n(S:){6}\n)\nI\n\n|\n\n:(:|(:S){1,7})|\nS:(:|(:S){1,6})|\n(S:){2}(:|(:S){1,5})|\n(S:){3}(:|(:S){1,4})|\n(S:){4}(:|(:S){1,3})|\n(S:){5}(:|(:S){1,2})|\n(S:){6}(:|(:S))|\n(S:){7}:|\n(S:){7}S\n)\n\n(?:%[0-9a-z]+)?\n</code></pre>\n\n<p>And here the might regex (case insensitive, surround with what ever needed like beginning/end of line, etc.):</p>\n\n<pre><code>(?:\n(?:\n::(?:[0-9a-f]{1,4}:){0,5}|\n[0-9a-f]{1,4}::(?:[0-9a-f]{1,4}:){0,4}|\n(?:[0-9a-f]{1,4}:){2}:(?:[0-9a-f]{1,4}:){0,3}|\n(?:[0-9a-f]{1,4}:){3}:(?:[0-9a-f]{1,4}:){0,2}|\n(?:[0-9a-f]{1,4}:){4}:(?:[0-9a-f]{1,4}:)?|\n(?:[0-9a-f]{1,4}:){5}:|\n(?:[0-9a-f]{1,4}:){6}\n)\n(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})\\.){3}\n(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})|\n\n:(?::|(?::[0-9a-f]{1,4}){1,7})|\n[0-9a-f]{1,4}:(?::|(?::[0-9a-f]{1,4}){1,6})|\n(?:[0-9a-f]{1,4}:){2}(?::|(?::[0-9a-f]{1,4}){1,5})|\n(?:[0-9a-f]{1,4}:){3}(?::|(?::[0-9a-f]{1,4}){1,4})|\n(?:[0-9a-f]{1,4}:){4}(?::|(?::[0-9a-f]{1,4}){1,3})|\n(?:[0-9a-f]{1,4}:){5}(?::|(?::[0-9a-f]{1,4}){1,2})|\n(?:[0-9a-f]{1,4}:){6}(?::|(?::[0-9a-f]{1,4}))|\n(?:[0-9a-f]{1,4}:){7}:|\n(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}\n)\n\n(?:%[0-9a-z]+)?\n</code></pre>\n"
},
{
"answer_id": 20059655,
"author": "Wireblue",
"author_id": 367806,
"author_profile": "https://Stackoverflow.com/users/367806",
"pm_score": 0,
"selected": false,
"text": "<p>For PHP 5.2+ users <code>filter_var</code> works great.</p>\n\n<p>I know this doesn't answer the original question (specifically a regex solution), but I post this in the hope it may help someone else in the future.</p>\n\n<pre><code>$is_ip4address = (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== FALSE);\n$is_ip6address = (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== FALSE);\n</code></pre>\n"
},
{
"answer_id": 20423004,
"author": "Chris",
"author_id": 3074256,
"author_profile": "https://Stackoverflow.com/users/3074256",
"pm_score": -1,
"selected": false,
"text": "<p>This will work for IPv4 and IPv6:</p>\n\n<pre><code>^(([0-9a-f]{0,4}:){1,7}[0-9a-f]{1,4}|([0-9]{1,3}\\.){3}[0-9]{1,3})$\n</code></pre>\n"
},
{
"answer_id": 21962114,
"author": "Phil L.",
"author_id": 3024786,
"author_profile": "https://Stackoverflow.com/users/3024786",
"pm_score": -1,
"selected": false,
"text": "<p>You can use <a href=\"https://github.com/philpraxis/ipextract\" rel=\"nofollow\">the ipextract shell tools</a> I made for this purpose. They are based on regexp and grep.</p>\n\n<p>Usage:</p>\n\n<pre><code>$ ifconfig | ipextract6\nfe80::1%lo0\n::1\nfe80::7ed1:c3ff:feec:dee1%en0\n</code></pre>\n"
},
{
"answer_id": 22329731,
"author": "Steve Buzonas",
"author_id": 816584,
"author_profile": "https://Stackoverflow.com/users/816584",
"pm_score": 2,
"selected": false,
"text": "<p>Looking at the patterns included in the other answers there are a number of good patterns that can be improved by referencing groups and utilizing lookaheads. Here is an example of a pattern that is self referencing that I would utilize in PHP if I had to:</p>\n\n<pre><code>^(?<hgroup>(?<hex>[[:xdigit:]]{0,4}) # grab a sequence of up to 4 hex digits\n # and name this pattern for usage later\n (?<!:::):{1,2}) # match 1 or 2 ':' characters\n # as long as we can't match 3\n (?&hgroup){1,6} # match our hex group 1 to 6 more times\n (?:(?:\n # match an ipv4 address or\n (?<dgroup>2[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3}(?&dgroup)\n # match our hex group one last time\n |(?&hex))$\n</code></pre>\n\n<p><strong>Note:</strong> PHP has a built in filter for this which would be a better solution than this \npattern.</p>\n\n<p><a href=\"http://regex101.com/r/qZ5wF3\" rel=\"nofollow\">Regex101 Analysis</a></p>\n"
},
{
"answer_id": 26105334,
"author": "user1977022",
"author_id": 1977022,
"author_profile": "https://Stackoverflow.com/users/1977022",
"pm_score": 0,
"selected": false,
"text": "<p>Here's what I came up with, using a bit of lookahead and named groups. This is of course just IPv6, but it shouldn't interfere with additional patterns if you want to add IPv4:</p>\n\n<pre><code>(?=([0-9a-f]+(:[0-9a-f])*)?(?P<wild>::)(?!([0-9a-f]+:)*:))(::)?([0-9a-f]{1,4}:{1,2}){0,6}(?(wild)[0-9a-f]{0,4}|[0-9a-f]{1,4}:[0-9a-f]{1,4})\n</code></pre>\n"
},
{
"answer_id": 28289439,
"author": "Nuh Metin Güler",
"author_id": 4506317,
"author_profile": "https://Stackoverflow.com/users/4506317",
"pm_score": 1,
"selected": false,
"text": "<p>It is difficult to find a regular expression which works for all IPv6 cases. They are usually hard to maintain, not easily readable and may cause performance problems. Hence, I want to share an alternative solution which I have developed: <a href=\"https://stackoverflow.com/questions/21631669/regular-expression-regex-for-ipv6-separate-from-ipv4/28289229#28289229\">Regular Expression (RegEx) for IPv6 Separate from IPv4</a> </p>\n\n<p>Now you may ask that \"This method only finds IPv6, how can I find IPv6 in a text or file?\" Here are methods for this issue too.</p>\n\n<p><strong>Note</strong>: If you do not want to use IPAddress class in .NET, you can also replace it with <a href=\"https://stackoverflow.com/questions/21631669/regular-expression-regex-for-ipv6-separate-from-ipv4/28289229#28289229\">my method</a>. It also covers mapped IPv4 and special cases too, while IPAddress does not cover. </p>\n\n<pre><code>class IPv6\n{\n public List<string> FindIPv6InFile(string filePath)\n {\n Char ch;\n StringBuilder sbIPv6 = new StringBuilder();\n List<string> listIPv6 = new List<string>();\n StreamReader reader = new StreamReader(filePath);\n do\n {\n bool hasColon = false;\n int length = 0;\n\n do\n {\n ch = (char)reader.Read();\n\n if (IsEscapeChar(ch))\n break;\n\n //Check the first 5 chars, if it has colon, then continue appending to stringbuilder\n if (!hasColon && length < 5)\n {\n if (ch == ':')\n {\n hasColon = true;\n }\n sbIPv6.Append(ch.ToString());\n }\n else if (hasColon) //if no colon in first 5 chars, then dont append to stringbuilder\n {\n sbIPv6.Append(ch.ToString());\n }\n\n length++;\n\n } while (!reader.EndOfStream);\n\n if (hasColon && !listIPv6.Contains(sbIPv6.ToString()) && IsIPv6(sbIPv6.ToString()))\n {\n listIPv6.Add(sbIPv6.ToString());\n }\n\n sbIPv6.Clear();\n\n } while (!reader.EndOfStream);\n reader.Close();\n reader.Dispose();\n\n return listIPv6;\n }\n\n public List<string> FindIPv6InText(string text)\n {\n StringBuilder sbIPv6 = new StringBuilder();\n List<string> listIPv6 = new List<string>();\n\n for (int i = 0; i < text.Length; i++)\n {\n bool hasColon = false;\n int length = 0;\n\n do\n {\n if (IsEscapeChar(text[length + i]))\n break;\n\n //Check the first 5 chars, if it has colon, then continue appending to stringbuilder\n if (!hasColon && length < 5)\n {\n if (text[length + i] == ':')\n {\n hasColon = true;\n }\n sbIPv6.Append(text[length + i].ToString());\n }\n else if (hasColon) //if no colon in first 5 chars, then dont append to stringbuilder\n {\n sbIPv6.Append(text[length + i].ToString());\n }\n\n length++;\n\n } while (i + length != text.Length);\n\n if (hasColon && !listIPv6.Contains(sbIPv6.ToString()) && IsIPv6(sbIPv6.ToString()))\n {\n listIPv6.Add(sbIPv6.ToString());\n }\n\n i += length;\n sbIPv6.Clear();\n }\n\n return listIPv6;\n }\n\n bool IsEscapeChar(char ch)\n {\n if (ch != ' ' && ch != '\\r' && ch != '\\n' && ch!='\\t')\n {\n return false;\n }\n\n return true;\n }\n\n bool IsIPv6(string maybeIPv6)\n {\n IPAddress ip;\n if (IPAddress.TryParse(maybeIPv6, out ip))\n {\n return ip.AddressFamily == AddressFamily.InterNetworkV6;\n }\n else\n {\n return false;\n }\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 28711926,
"author": "user4604205",
"author_id": 4604205,
"author_profile": "https://Stackoverflow.com/users/4604205",
"pm_score": 1,
"selected": false,
"text": "<p><code>InetAddressUtils</code> has all the patterns defined. I ended-up using their pattern directly, and am pasting it here for reference:</p>\n\n<pre><code>private static final String IPV4_BASIC_PATTERN_STRING =\n \"(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\\\.){3}\" + // initial 3 fields, 0-255 followed by .\n \"([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\"; // final field, 0-255\n\nprivate static final Pattern IPV4_PATTERN =\n Pattern.compile(\"^\" + IPV4_BASIC_PATTERN_STRING + \"$\");\n\nprivate static final Pattern IPV4_MAPPED_IPV6_PATTERN = // TODO does not allow for redundant leading zeros\n Pattern.compile(\"^::[fF]{4}:\" + IPV4_BASIC_PATTERN_STRING + \"$\");\n\nprivate static final Pattern IPV6_STD_PATTERN =\n Pattern.compile(\n \"^[0-9a-fA-F]{1,4}(:[0-9a-fA-F]{1,4}){7}$\");\n\nprivate static final Pattern IPV6_HEX_COMPRESSED_PATTERN =\n Pattern.compile(\n \"^(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)\" + // 0-6 hex fields\n \"::\" +\n \"(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)$\"); // 0-6 hex fields \n</code></pre>\n"
},
{
"answer_id": 32970482,
"author": "OliverKK",
"author_id": 2717428,
"author_profile": "https://Stackoverflow.com/users/2717428",
"pm_score": 2,
"selected": false,
"text": "<p>In <strong>Scala</strong> use the well known Apache Commons validators.</p>\n\n<p><a href=\"http://mvnrepository.com/artifact/commons-validator/commons-validator/1.4.1\" rel=\"nofollow\">http://mvnrepository.com/artifact/commons-validator/commons-validator/1.4.1</a> </p>\n\n<pre><code>libraryDependencies += \"commons-validator\" % \"commons-validator\" % \"1.4.1\"\n\n\nimport org.apache.commons.validator.routines._\n\n/**\n * Validates if the passed ip is a valid IPv4 or IPv6 address.\n *\n * @param ip The IP address to validate.\n * @return True if the passed IP address is valid, false otherwise.\n */ \n def ip(ip: String) = InetAddressValidator.getInstance().isValid(ip)\n</code></pre>\n\n<p>Following the test's of the method <code>ip(ip: String)</code>:</p>\n\n<pre><code>\"The `ip` validator\" should {\n \"return false if the IPv4 is invalid\" in {\n ip(\"123\") must beFalse\n ip(\"255.255.255.256\") must beFalse\n ip(\"127.1\") must beFalse\n ip(\"30.168.1.255.1\") must beFalse\n ip(\"-1.2.3.4\") must beFalse\n }\n\n \"return true if the IPv4 is valid\" in {\n ip(\"255.255.255.255\") must beTrue\n ip(\"127.0.0.1\") must beTrue\n ip(\"0.0.0.0\") must beTrue\n }\n\n //IPv6\n //@see: http://www.ronnutter.com/ipv6-cheatsheet-on-identifying-valid-ipv6-addresses/\n \"return false if the IPv6 is invalid\" in {\n ip(\"1200::AB00:1234::2552:7777:1313\") must beFalse\n }\n\n \"return true if the IPv6 is valid\" in {\n ip(\"1200:0000:AB00:1234:0000:2552:7777:1313\") must beTrue\n ip(\"21DA:D3:0:2F3B:2AA:FF:FE28:9C5A\") must beTrue\n }\n}\n</code></pre>\n"
},
{
"answer_id": 37355379,
"author": "Rohit Malgaonkar",
"author_id": 6336249,
"author_profile": "https://Stackoverflow.com/users/6336249",
"pm_score": 4,
"selected": false,
"text": "<p>This catches the loopback(::1) as well and ipv6 addresses.\n changed {} to + and put : inside the first square bracket.</p>\n\n<pre><code>([a-f0-9:]+:+)+[a-f0-9]+\n</code></pre>\n\n<p>tested on with ifconfig -a output\n<a href=\"http://regexr.com/\" rel=\"noreferrer\">http://regexr.com/</a></p>\n\n<p>Unix or Mac OSx terminal o option returns only the matching output(ipv6) including ::1</p>\n\n<pre><code>ifconfig -a | egrep -o '([a-f0-9:]+:+)+[a-f0-9]+'\n</code></pre>\n\n<p>Get All IP addresses (IPv4 OR IPv6) and print match on unix OSx term</p>\n\n<pre><code>ifconfig -a | egrep -o '([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}) | (([a-f0-9:]+:+)+[a-f0-9]+)'\n</code></pre>\n"
},
{
"answer_id": 37903336,
"author": "Carlos Velazquez",
"author_id": 6484333,
"author_profile": "https://Stackoverflow.com/users/6484333",
"pm_score": -1,
"selected": false,
"text": "<p>Try this small one-liner. It should only match valid uncompressed/compressed IPv6 addresses (no IPv4 hybrids)</p>\n\n<pre><code>/(?!.*::.*::)(?!.*:::.*)(?!:[a-f0-9])((([a-f0-9]{1,4})?[:](?!:)){7}|(?=(.*:[:a-f0-9]{1,4}::|^([:a-f0-9]{1,4})?::))(([a-f0-9]{1,4})?[:]{1,2}){1,6})[a-f0-9]{1,4}/\n</code></pre>\n"
},
{
"answer_id": 39237544,
"author": "Bill Lipa",
"author_id": 1825318,
"author_profile": "https://Stackoverflow.com/users/1825318",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on your needs, an approximation like:</p>\n\n<pre><code>[0-9a-f:]+\n</code></pre>\n\n<p>may be enough (as with simple log file grepping, for example.)</p>\n"
},
{
"answer_id": 39841307,
"author": "Mike Wilmes",
"author_id": 5140523,
"author_profile": "https://Stackoverflow.com/users/5140523",
"pm_score": 2,
"selected": false,
"text": "<p>I generated the following using python and works with the re module. The look-ahead assertions ensure that the correct number of dots or colons appear in the address. It does not support IPv4 in IPv6 notation.</p>\n\n<pre><code>pattern = '^(?=\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$)(?:(?:25[0-5]|[12][0-4][0-9]|1[5-9][0-9]|[1-9]?[0-9])\\.?){4}$|(?=^(?:[0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}$)(?![^:]*::.+::[^:]*$)(?:(?=.*::.*)|(?=\\w+:\\w+:\\w+:\\w+:\\w+:\\w+:\\w+:\\w+))(?:(?:^|:)(?:[0-9a-f]{4}|[1-9a-f][0-9a-f]{0,3})){0,8}(?:::(?:[0-9a-f]{1,4}(?:$|:)){0,6})?$'\nresult = re.match(pattern, ip)\nif result: result.group(0)\n</code></pre>\n"
},
{
"answer_id": 43307289,
"author": "Master James",
"author_id": 4928388,
"author_profile": "https://Stackoverflow.com/users/4928388",
"pm_score": 0,
"selected": false,
"text": "<p>Just matching local ones from an origin with square brackets included. I know it's not as comprehensive but in javascript the other ones had difficult to trace issues primarily that of not working, so this seems to get me what I needed for now. extra capitals A-F aren't needed either.</p>\n\n<pre><code>^\\[([0-9a-fA-F]{1,4})(\\:{1,2})([0-9a-fA-F]{1,4})(\\:{1,2})([0-9a-fA-F]{1,4})(\\:{1,2})([0-9a-fA-F]{1,4})(\\:{1,2})([0-9a-fA-F]{1,4})\\]\n</code></pre>\n\n<p>Jinnko's version is simplified and better I see.</p>\n"
},
{
"answer_id": 45271143,
"author": "Alexandre Fenyo",
"author_id": 8334991,
"author_profile": "https://Stackoverflow.com/users/8334991",
"pm_score": 0,
"selected": false,
"text": "<p>As stated above, another way to get an IPv6 textual representation <strong>validating</strong> parser is to use programming. Here is one that is fully compliant with RFC-4291 and RFC-5952. I've written this code in ANSI C (works with GCC, passed tests on Linux - works with clang, passed tests on FreeBSD). Thus, it does only rely on the ANSI C standard library, so it can be compiled everywhere (I've used it for IPv6 parsing inside a kernel module with FreeBSD).</p>\n\n<pre><code>// IPv6 textual representation validating parser fully compliant with RFC-4291 and RFC-5952\n// BSD-licensed / Copyright 2015-2017 Alexandre Fenyo\n\n#include <string.h>\n#include <netinet/in.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <ctype.h>\n\ntypedef enum { false, true } bool;\n\nstatic const char hexdigits[] = \"0123456789abcdef\";\nstatic int digit2int(const char digit) {\n return strchr(hexdigits, digit) - hexdigits;\n}\n\n// This IPv6 address parser handles any valid textual representation according to RFC-4291 and RFC-5952.\n// Other representations will return -1.\n//\n// note that str input parameter has been modified when the function call returns\n//\n// parse_ipv6(char *str, struct in6_addr *retaddr)\n// parse textual representation of IPv6 addresses\n// str: input arg\n// retaddr: output arg\nint parse_ipv6(char *str, struct in6_addr *retaddr) {\n bool compressed_field_found = false;\n unsigned char *_retaddr = (unsigned char *) retaddr;\n char *_str = str;\n char *delim;\n\n bzero((void *) retaddr, sizeof(struct in6_addr));\n if (!strlen(str) || strchr(str, ':') == NULL || (str[0] == ':' && str[1] != ':') ||\n (strlen(str) >= 2 && str[strlen(str) - 1] == ':' && str[strlen(str) - 2] != ':')) return -1;\n\n // convert transitional to standard textual representation\n if (strchr(str, '.')) {\n int ipv4bytes[4];\n char *curp = strrchr(str, ':');\n if (curp == NULL) return -1;\n char *_curp = ++curp;\n int i;\n for (i = 0; i < 4; i++) {\n char *nextsep = strchr(_curp, '.');\n if (_curp[0] == '0' || (i < 3 && nextsep == NULL) || (i == 3 && nextsep != NULL)) return -1;\n if (nextsep != NULL) *nextsep = 0;\n int j;\n for (j = 0; j < strlen(_curp); j++) if (_curp[j] < '0' || _curp[j] > '9') return -1;\n if (strlen(_curp) > 3) return -1;\n const long val = strtol(_curp, NULL, 10);\n if (val < 0 || val > 255) return -1;\n ipv4bytes[i] = val;\n _curp = nextsep + 1;\n }\n sprintf(curp, \"%x%02x:%x%02x\", ipv4bytes[0], ipv4bytes[1], ipv4bytes[2], ipv4bytes[3]);\n }\n\n // parse standard textual representation\n do {\n if ((delim = strchr(_str, ':')) == _str || (delim == NULL && !strlen(_str))) {\n if (delim == str) _str++;\n else if (delim == NULL) return 0;\n else {\n if (compressed_field_found == true) return -1;\n if (delim == str + strlen(str) - 1 && _retaddr != (unsigned char *) (retaddr + 1)) return 0;\n compressed_field_found = true;\n _str++;\n int cnt = 0;\n char *__str;\n for (__str = _str; *__str; ) if (*(__str++) == ':') cnt++;\n unsigned char *__retaddr = - 2 * ++cnt + (unsigned char *) (retaddr + 1);\n if (__retaddr <= _retaddr) return -1;\n _retaddr = __retaddr;\n }\n } else {\n char hexnum[4] = \"0000\";\n if (delim == NULL) delim = str + strlen(str);\n if (delim - _str > 4) return -1;\n int i;\n for (i = 0; i < delim - _str; i++)\n if (!isxdigit(_str[i])) return -1;\n else hexnum[4 - (delim - _str) + i] = tolower(_str[i]);\n _str = delim + 1;\n *(_retaddr++) = (digit2int(hexnum[0]) << 4) + digit2int(hexnum[1]);\n *(_retaddr++) = (digit2int(hexnum[2]) << 4) + digit2int(hexnum[3]);\n }\n } while (_str < str + strlen(str));\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 47861266,
"author": "Sean F",
"author_id": 6801443,
"author_profile": "https://Stackoverflow.com/users/6801443",
"pm_score": 2,
"selected": false,
"text": "<p>Regexes for ipv6 can get really tricky when you consider addresses with embedded ipv4 and addresses that are compressed, as you can see from some of these answers.</p>\n\n<p><a href=\"https://seancfoley.github.io/IPAddress/\" rel=\"nofollow noreferrer\">The open-source IPAddress Java library</a> will validate all standard representations of IPv6 and IPv4 and also supports prefix-length (and validation of such). Disclaimer: I am the project manager of that library.</p>\n\n<p>Code example:</p>\n\n<pre><code> try {\n IPAddressString str = new IPAddressString(\"::1\");\n IPAddress addr = str.toAddress();\n if(addr.isIPv6() || addr.isIPv6Convertible()) {\n IPv6Address ipv6Addr = addr.toIPv6();\n }\n //use address\n } catch(AddressStringException e) {\n //e.getMessage has validation error\n }\n</code></pre>\n"
},
{
"answer_id": 50385461,
"author": "Jitendra Gosavi",
"author_id": 5725705,
"author_profile": "https://Stackoverflow.com/users/5725705",
"pm_score": 3,
"selected": false,
"text": "<p>Following regex is for IPv6 only. Group 1 matches with the IP.</p>\n\n<pre><code>(([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4})\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | I'm having trouble writing a regular expression that matches valid IPv6 addresses, including those in their compressed form (with `::` or leading zeros omitted from each byte pair).
Can someone suggest a regular expression that would fulfill the requirement?
I'm considering expanding each byte pair and matching the result with a simpler regex. | I was unable to get @Factor Mystic's answer to work with POSIX regular expressions, so I wrote one that works with POSIX regular expressions and PERL regular expressions.
It should match:
* IPv6 addresses
* zero compressed IPv6 addresses ([section 2.2 of rfc5952](https://www.rfc-editor.org/rfc/rfc5952#section-2.2))
* link-local IPv6 addresses with zone index ([section 11 of rfc4007](https://www.rfc-editor.org/rfc/rfc4007#section-11))
* IPv4-Embedded IPv6 Address ([section 2 of rfc6052](https://www.rfc-editor.org/rfc/rfc6052#section-2))
* IPv4-mapped IPv6 addresses ([section 2.1 of rfc2765](https://www.rfc-editor.org/rfc/rfc2765#section-2.1))
* IPv4-translated addresses ([section 2.1 of rfc2765](https://www.rfc-editor.org/rfc/rfc2765#section-2.1))
IPv6 Regular Expression:
```
(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))
```
For ease of reading, the following is the above regular expression split at major OR points into separate lines:
```
# IPv6 RegEx
(
([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}| # 1:2:3:4:5:6:7:8
([0-9a-fA-F]{1,4}:){1,7}:| # 1:: 1:2:3:4:5:6:7::
([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}| # 1::8 1:2:3:4:5:6::8 1:2:3:4:5:6::8
([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}| # 1::7:8 1:2:3:4:5::7:8 1:2:3:4:5::8
([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}| # 1::6:7:8 1:2:3:4::6:7:8 1:2:3:4::8
([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}| # 1::5:6:7:8 1:2:3::5:6:7:8 1:2:3::8
([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}| # 1::4:5:6:7:8 1:2::4:5:6:7:8 1:2::8
[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})| # 1::3:4:5:6:7:8 1::3:4:5:6:7:8 1::8
:((:[0-9a-fA-F]{1,4}){1,7}|:)| # ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::
fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}| # fe80::7:8%eth0 fe80::7:8%1 (link-local IPv6 addresses with zone index)
::(ffff(:0{1,4}){0,1}:){0,1}
((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}
(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])| # ::255.255.255.255 ::ffff:255.255.255.255 ::ffff:0:255.255.255.255 (IPv4-mapped IPv6 addresses and IPv4-translated addresses)
([0-9a-fA-F]{1,4}:){1,4}:
((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}
(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]) # 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33 (IPv4-Embedded IPv6 Address)
)
# IPv4 RegEx
((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])
```
To make the above easier to understand, the following "pseudo" code replicates the above:
```
IPV4SEG = (25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])
IPV4ADDR = (IPV4SEG\.){3,3}IPV4SEG
IPV6SEG = [0-9a-fA-F]{1,4}
IPV6ADDR = (
(IPV6SEG:){7,7}IPV6SEG| # 1:2:3:4:5:6:7:8
(IPV6SEG:){1,7}:| # 1:: 1:2:3:4:5:6:7::
(IPV6SEG:){1,6}:IPV6SEG| # 1::8 1:2:3:4:5:6::8 1:2:3:4:5:6::8
(IPV6SEG:){1,5}(:IPV6SEG){1,2}| # 1::7:8 1:2:3:4:5::7:8 1:2:3:4:5::8
(IPV6SEG:){1,4}(:IPV6SEG){1,3}| # 1::6:7:8 1:2:3:4::6:7:8 1:2:3:4::8
(IPV6SEG:){1,3}(:IPV6SEG){1,4}| # 1::5:6:7:8 1:2:3::5:6:7:8 1:2:3::8
(IPV6SEG:){1,2}(:IPV6SEG){1,5}| # 1::4:5:6:7:8 1:2::4:5:6:7:8 1:2::8
IPV6SEG:((:IPV6SEG){1,6})| # 1::3:4:5:6:7:8 1::3:4:5:6:7:8 1::8
:((:IPV6SEG){1,7}|:)| # ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::
fe80:(:IPV6SEG){0,4}%[0-9a-zA-Z]{1,}| # fe80::7:8%eth0 fe80::7:8%1 (link-local IPv6 addresses with zone index)
::(ffff(:0{1,4}){0,1}:){0,1}IPV4ADDR| # ::255.255.255.255 ::ffff:255.255.255.255 ::ffff:0:255.255.255.255 (IPv4-mapped IPv6 addresses and IPv4-translated addresses)
(IPV6SEG:){1,4}:IPV4ADDR # 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33 (IPv4-Embedded IPv6 Address)
)
```
I posted a script on GitHub which tests the regular expression: <https://gist.github.com/syzdek/6086792> |
53,501 | <p>I am developing console application in .Net and I want to change a behavior a little based on information that application was started from cmd.exe or from explorer.exe. Is it possible?</p>
| [
{
"answer_id": 53508,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/ms682489(VS.85).aspx\" rel=\"nofollow noreferrer\">CreateToolhelp32Snapshot Function</a> has a Process32First method that will allow you to read a <a href=\"http://msdn.microsoft.com/en-us/library/ms684839(VS.85).aspx\" rel=\"nofollow noreferrer\">PROCESSENTRY32 Structure</a>. The structure has a property that will get you the information you want:</p>\n\n<blockquote>\n <p><strong>th32ParentProcessID</strong> - The identifier\n of the process that created this\n process (its parent process).</p>\n</blockquote>\n\n<p>This article will help you get started using the ToolHelpSnapshot function:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/IsApplicationRunning.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/IsApplicationRunning.aspx</a></p>\n"
},
{
"answer_id": 53526,
"author": "Factor Mystic",
"author_id": 1569,
"author_profile": "https://Stackoverflow.com/users/1569",
"pm_score": 4,
"selected": true,
"text": "<pre><code>Process this_process = Process.GetCurrentProcess();\nint parent_pid = 0;\nusing (ManagementObject MgmtObj = new ManagementObject(\"win32_process.handle='\" + this_process.Id.ToString() + \"'\"))\n{\n MgmtObj.Get();\n parent_pid = Convert.ToInt32(MgmtObj[\"ParentProcessId\"]);\n}\nstring parent_process_name = Process.GetProcessById(parent_pid).ProcessName;\n</code></pre>\n"
},
{
"answer_id": 53565,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 2,
"selected": false,
"text": "<p>One issue with the ToolHelp/ManagementObject approaches is that the parent process could already have exited.</p>\n\n<p>The GetStartupInfo Win32 function (use PInvoke if there's no .NET equivalent) fills in a structure that includes the window title. For a Win32 console application \"app.exe\", this title string is \"app\" when started from cmd and \"c:\\full\\path\\to\\app.exe\" when started from explorer (or the VS debugger).</p>\n\n<p>Of course this is a hack (subject to change in other versions, etc.).</p>\n\n<pre><code>#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\nint main()\n{\n STARTUPINFO si;\n GetStartupInfo(&si);\n MessageBox(NULL, si.lpTitle, NULL, MB_OK);\n return 0;\n}\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
] | I am developing console application in .Net and I want to change a behavior a little based on information that application was started from cmd.exe or from explorer.exe. Is it possible? | ```
Process this_process = Process.GetCurrentProcess();
int parent_pid = 0;
using (ManagementObject MgmtObj = new ManagementObject("win32_process.handle='" + this_process.Id.ToString() + "'"))
{
MgmtObj.Get();
parent_pid = Convert.ToInt32(MgmtObj["ParentProcessId"]);
}
string parent_process_name = Process.GetProcessById(parent_pid).ProcessName;
``` |
53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| [
{
"answer_id": 53522,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 14,
"selected": true,
"text": "<pre><code>if not a:\n print("List is empty")\n</code></pre>\n<p>Using the <a href=\"https://docs.python.org/library/stdtypes.html#truth-value-testing\" rel=\"noreferrer\">implicit booleanness</a> of the empty <code>list</code> is quite Pythonic.</p>\n"
},
{
"answer_id": 53525,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 7,
"selected": false,
"text": "<p>An empty list is itself considered false in true value testing (see <a href=\"https://docs.python.org/2/library/stdtypes.html#truth-value-testing\" rel=\"nofollow noreferrer\">python documentation</a>):</p>\n<pre><code>a = []\nif a:\n print("not empty")\n</code></pre>\n<p>To <a href=\"https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty/53530#53530\">Daren Thomas's answer</a>:</p>\n<blockquote>\n<p>EDIT: Another point against testing\nthe empty list as False: What about\npolymorphism? You shouldn't depend on\na list being a list. It should just\nquack like a duck - how are you going\nto get your duckCollection to quack\n''False'' when it has no elements?</p>\n</blockquote>\n<p>Your duckCollection should implement <code>__nonzero__</code> or <code>__len__</code> so the if a: will work without problems.</p>\n"
},
{
"answer_id": 53533,
"author": "verix",
"author_id": 5342,
"author_profile": "https://Stackoverflow.com/users/5342",
"pm_score": 5,
"selected": false,
"text": "<p>I prefer the following:</p>\n\n<pre><code>if a == []:\n print \"The list is empty.\"\n</code></pre>\n"
},
{
"answer_id": 53752,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 10,
"selected": false,
"text": "<p>The Pythonic way to do it is from the <a href=\"https://www.python.org/dev/peps/pep-0008\" rel=\"noreferrer\">PEP 8 style guide</a>.</p>\n<blockquote>\n<p>For sequences, (strings, lists, tuples), use the fact that empty sequences are false:</p>\n<pre class=\"lang-python prettyprint-override\"><code># Correct:\nif not seq:\nif seq:\n\n# Wrong:\nif len(seq):\nif not len(seq):\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 61918,
"author": "George V. Reilly",
"author_id": 6364,
"author_profile": "https://Stackoverflow.com/users/6364",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://books.google.com/books?id=vpTAq4dnmuAC&pg=RA1-PA479&lpg=RA1-PA479&dq=Python+len+big+O&source=web&ots=AOM6A1K9Fy&sig=iQo8mV6Xf9KdzuNSa-Jkr8wDEuw&hl=en&sa=X&oi=book_result&resnum=4&ct=result\" rel=\"noreferrer\"><code>len()</code> is an O(1) operation</a> for Python lists, strings, dicts, and sets. Python internally keeps track of the number of elements in these containers.</p>\n\n<p>JavaScript <a href=\"http://www.isolani.co.uk/blog/javascript/TruthyFalsyAndTypeCasting\" rel=\"noreferrer\">has a similar notion of truthy/falsy</a>.</p>\n"
},
{
"answer_id": 7302987,
"author": "Jabba",
"author_id": 232485,
"author_profile": "https://Stackoverflow.com/users/232485",
"pm_score": 10,
"selected": false,
"text": "<p>I prefer it explicitly:</p>\n\n<pre><code>if len(li) == 0:\n print('the list is empty')\n</code></pre>\n\n<p>This way it's 100% clear that <code>li</code> is a sequence (list) and we want to test its size. My problem with <code>if not li: ...</code> is that it gives the false impression that <code>li</code> is a boolean variable.</p>\n"
},
{
"answer_id": 9381545,
"author": "Mike",
"author_id": 1194883,
"author_profile": "https://Stackoverflow.com/users/1194883",
"pm_score": 9,
"selected": false,
"text": "<p><sub>This is the first google hit for "python test empty array" and similar queries, and other people are generalizing the question beyond just lists, so here's a caveat for a different type of sequence that a lot of people use.</sub></p>\n<h1>Other methods don't work for NumPy arrays</h1>\n<p>You need to be careful with NumPy arrays, because other methods that work fine for <code>list</code>s or other standard containers fail for NumPy arrays. I explain why below, but in short, the <a href=\"http://www.scipy.org/scipylib/faq.html#what-is-the-preferred-way-to-check-for-an-empty-zero-element-array\" rel=\"nofollow noreferrer\">preferred method</a> is to use <code>size</code>.</p>\n<h2>The "pythonic" way doesn't work: Part 1</h2>\n<p>The "pythonic" way fails with NumPy arrays because NumPy tries to cast the array to an array of <code>bool</code>s, and <code>if x</code> tries to evaluate all of those <code>bool</code>s at once for some kind of aggregate truth value. But this doesn't make any sense, so you get a <code>ValueError</code>:</p>\n<pre><code>>>> x = numpy.array([0,1])\n>>> if x: print("x")\nValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()\n</code></pre>\n<h2>The "pythonic" way doesn't work: Part 2</h2>\n<p>But at least the case above tells you that it failed. If you happen to have a NumPy array with exactly one element, the <code>if</code> statement will "work", in the sense that you don't get an error. However, if that one element happens to be <code>0</code> (or <code>0.0</code>, or <code>False</code>, ...), the <code>if</code> statement will incorrectly result in <code>False</code>:</p>\n<pre><code>>>> x = numpy.array([0,])\n>>> if x: print("x")\n... else: print("No x")\nNo x\n</code></pre>\n<p>But clearly <code>x</code> exists and is not empty! This result is not what you wanted.</p>\n<h2>Using <code>len</code> can give unexpected results</h2>\n<p>For example,</p>\n<pre><code>len( numpy.zeros((1,0)) )\n</code></pre>\n<p>returns 1, even though the array has zero elements.</p>\n<h2>The numpythonic way</h2>\n<p>As explained in the <a href=\"http://www.scipy.org/scipylib/faq.html#what-is-the-preferred-way-to-check-for-an-empty-zero-element-array\" rel=\"nofollow noreferrer\">SciPy FAQ</a>, the correct method in all cases where you know you have a NumPy array is to use <code>if x.size</code>:</p>\n<pre><code>>>> x = numpy.array([0,1])\n>>> if x.size: print("x")\nx\n\n>>> x = numpy.array([0,])\n>>> if x.size: print("x")\n... else: print("No x")\nx\n\n>>> x = numpy.zeros((1,0))\n>>> if x.size: print("x")\n... else: print("No x")\nNo x\n</code></pre>\n<p>If you're not sure whether it might be a <code>list</code>, a NumPy array, or something else, you could combine this approach with <a href=\"https://stackoverflow.com/a/10835703/1194883\">the answer @dubiousjim gives</a> to make sure the right test is used for each type. Not very "pythonic", but it turns out that NumPy intentionally broke pythonicity in at least this sense.</p>\n<p>If you need to do more than just check if the input is empty, and you're using other NumPy features like indexing or math operations, it's probably more efficient (and certainly more common) to force the input <em>to be</em> a NumPy array. There are a few nice functions for doing this quickly — most importantly <a href=\"https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.asarray.html\" rel=\"nofollow noreferrer\"><code>numpy.asarray</code></a>. This takes your input, does nothing if it's already an array, or wraps your input into an array if it's a list, tuple, etc., and optionally converts it to your chosen <code>dtype</code>. So it's very quick whenever it can be, and it ensures that you just get to assume the input is a NumPy array. We usually even just use the same name, as the conversion to an array won't make it back outside of the current <a href=\"http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html\" rel=\"nofollow noreferrer\">scope</a>:</p>\n<pre><code>x = numpy.asarray(x, dtype=numpy.double)\n</code></pre>\n<p>This will make the <code>x.size</code> check work in all cases I see on this page.</p>\n"
},
{
"answer_id": 10835703,
"author": "dubiousjim",
"author_id": 272427,
"author_profile": "https://Stackoverflow.com/users/272427",
"pm_score": 6,
"selected": false,
"text": "<p>I had written:</p>\n\n<pre><code>if isinstance(a, (list, some, other, types, i, accept)) and not a:\n do_stuff\n</code></pre>\n\n<p>which was voted -1. I'm not sure if that's because readers objected to the strategy or thought the answer wasn't helpful as presented. I'll pretend it was the latter, since---whatever counts as \"pythonic\"---this is the correct strategy. Unless you've already ruled out, or are prepared to handle cases where <code>a</code> is, for example, <code>False</code>, you need a test more restrictive than just <code>if not a:</code>. You could use something like this:</p>\n\n<pre><code>if isinstance(a, numpy.ndarray) and not a.size:\n do_stuff\nelif isinstance(a, collections.Sized) and not a:\n do_stuff\n</code></pre>\n\n<p>the first test is in response to @Mike's answer, above. The third line could also be replaced with:</p>\n\n<pre><code>elif isinstance(a, (list, tuple)) and not a:\n</code></pre>\n\n<p>if you only want to accept instances of particular types (and their subtypes), or with:</p>\n\n<pre><code>elif isinstance(a, (list, tuple)) and not len(a):\n</code></pre>\n\n<p>You can get away without the explicit type check, but only if the surrounding context already assures you that <code>a</code> is a value of the types you're prepared to handle, or if you're sure that types you're not prepared to handle are going to raise errors (e.g., a <code>TypeError</code> if you call <code>len</code> on a value for which it's undefined) that you're prepared to handle. In general, the \"pythonic\" conventions seem to go this last way. Squeeze it like a duck and let it raise a DuckError if it doesn't know how to quack. You still have to <em>think</em> about what type assumptions you're making, though, and whether the cases you're not prepared to handle properly really are going to error out in the right places. The Numpy arrays are a good example where just blindly relying on <code>len</code> or the boolean typecast may not do precisely what you're expecting.</p>\n"
},
{
"answer_id": 27262598,
"author": "abarnert",
"author_id": 908494,
"author_profile": "https://Stackoverflow.com/users/908494",
"pm_score": 7,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/53522/908494\">Patrick's (accepted) answer</a> is right: <code>if not a:</code> is the right way to do it. <a href=\"https://stackoverflow.com/a/53752/908494\">Harley Holcombe's answer</a> is right that this is in the PEP 8 style guide. But what none of the answers explain is why it's a good idea to follow the idiom—even if you personally find it's not explicit enough or confusing to Ruby users or whatever.</p>\n\n<p>Python code, and the Python community, has very strong idioms. Following those idioms makes your code easier to read for anyone experienced in Python. And when you violate those idioms, that's a strong signal.</p>\n\n<p>It's true that <code>if not a:</code> doesn't distinguish empty lists from <code>None</code>, or numeric 0, or empty tuples, or empty user-created collection types, or empty user-created not-quite-collection types, or single-element NumPy array acting as scalars with falsey values, etc. And sometimes it's important to be explicit about that. And in that case, you know <em>what</em> you want to be explicit about, so you can test for exactly that. For example, <code>if not a and a is not None:</code> means \"anything falsey except None\", while <code>if len(a) != 0:</code> means \"only empty sequences—and anything besides a sequence is an error here\", and so on. Besides testing for exactly what you want to test, this also signals to the reader that this test is important.</p>\n\n<p>But when you don't have anything to be explicit about, anything other than <code>if not a:</code> is misleading the reader. You're signaling something as important when it isn't. (You may also be making the code less flexible, or slower, or whatever, but that's all less important.) And if you <em>habitually</em> mislead the reader like this, then when you <em>do</em> need to make a distinction, it's going to pass unnoticed because you've been \"crying wolf\" all over your code.</p>\n"
},
{
"answer_id": 32978062,
"author": "MrWonderful",
"author_id": 2069807,
"author_profile": "https://Stackoverflow.com/users/2069807",
"pm_score": 7,
"selected": false,
"text": "<h1>Why check at all?</h1>\n<p>No one seems to have addressed questioning your <em>need</em> to test the list in the first place. Because you provided no additional context, I can imagine that you may not need to do this check in the first place, but are unfamiliar with list processing in Python.</p>\n<p>I would argue that the <em>most Pythonic</em> way is to not check at all, but rather to just process the list. That way it will do the right thing whether empty or full.</p>\n<pre><code>a = []\n\nfor item in a:\n # <Do something with item>\n\n# <The rest of code>\n</code></pre>\n<p>This has the benefit of handling any contents of <strong>a</strong>, while not requiring a specific check for emptiness. If <strong>a</strong> is empty, the dependent block will not execute and the interpreter will fall through to the next line.</p>\n<p>If you do actually need to check the array for emptiness:</p>\n<pre><code>a = []\n\nif not a:\n # <React to empty list>\n\n# <The rest of code>\n</code></pre>\n<p>is sufficient.</p>\n"
},
{
"answer_id": 34558732,
"author": "Sнаđошƒаӽ",
"author_id": 3375713,
"author_profile": "https://Stackoverflow.com/users/3375713",
"pm_score": 5,
"selected": false,
"text": "<p>From <a href=\"https://docs.python.org/3.5/library/stdtypes.html#truth-value-testing\">documentation</a> on truth value testing:</p>\n\n<p>All values other than what is listed here are considered <code>True</code></p>\n\n<ul>\n<li><code>None</code></li>\n<li><code>False</code></li>\n<li>zero of any numeric type, for example, <code>0</code>, <code>0.0</code>, <code>0j</code>.</li>\n<li>any empty sequence, for example, <code>''</code>, <code>()</code>, <code>[]</code>.</li>\n<li>any empty mapping, for example, <code>{}</code>.</li>\n<li>instances of user-defined classes, if the class defines a <code>__bool__()</code> or <code>__len__()</code> method, when that method returns the integer zero or bool value <code>False</code>.</li>\n</ul>\n\n<p>As can be seen, empty list <code>[]</code> is <em>falsy</em>, so doing what would be done to a boolean value sounds most efficient:</p>\n\n<pre><code>if not a:\n print('\"a\" is empty!')\n</code></pre>\n"
},
{
"answer_id": 36610301,
"author": "Tagar",
"author_id": 470583,
"author_profile": "https://Stackoverflow.com/users/470583",
"pm_score": 4,
"selected": false,
"text": "<pre><code>def list_test (L):\n if L is None : print('list is None')\n elif not L : print('list is empty')\n else: print('list has %d elements' % len(L))\n\nlist_test(None)\nlist_test([])\nlist_test([1,2,3])\n</code></pre>\n\n<p>It is sometimes good to test for <code>None</code> and for emptiness separately as those are two different states. The code above produces the following output:</p>\n\n<pre><code>list is None \nlist is empty \nlist has 3 elements\n</code></pre>\n\n<p>Although it's worth nothing that <code>None</code> is falsy. So if you don't want to separate test for <code>None</code>-ness, you don't have to do that. </p>\n\n<pre><code>def list_test2 (L):\n if not L : print('list is empty')\n else: print('list has %d elements' % len(L))\n\nlist_test2(None)\nlist_test2([])\nlist_test2([1,2,3])\n</code></pre>\n\n<p>produces expected</p>\n\n<pre><code>list is empty\nlist is empty\nlist has 3 elements\n</code></pre>\n"
},
{
"answer_id": 39469420,
"author": "Sunil Lulla",
"author_id": 5267848,
"author_profile": "https://Stackoverflow.com/users/5267848",
"pm_score": 5,
"selected": false,
"text": "<p>You can even try using <code>bool()</code> like this. Although it is less readable surely it's a concise way to perform this.</p>\n<pre><code> a = [1,2,3];\n print bool(a); # it will return True\n a = [];\n print bool(a); # it will return False\n</code></pre>\n<p>I love this way for the checking list is empty or not.</p>\n<p>Very handy and useful.</p>\n"
},
{
"answer_id": 40846473,
"author": "Taufiq Rahman",
"author_id": 5401681,
"author_profile": "https://Stackoverflow.com/users/5401681",
"pm_score": 5,
"selected": false,
"text": "<p>Here are a few ways you can check if a list is empty:</p>\n\n<pre><code>a = [] #the list\n</code></pre>\n\n<p><strong>1)</strong> The pretty simple pythonic way:</p>\n\n<pre><code>if not a:\n print(\"a is empty\")\n</code></pre>\n\n<p>In Python, <strong>empty containers</strong> such as lists,tuples,sets,dicts,variables etc are seen as <code>False</code>. One could simply treat the list as a predicate (<em>returning a Boolean value</em>). And a <code>True</code> value would indicate that it's non-empty.</p>\n\n<p><strong>2)</strong> A much explicit way: using the <code>len()</code> to find the length and check if it equals to <code>0</code>:</p>\n\n<pre><code>if len(a) == 0:\n print(\"a is empty\")\n</code></pre>\n\n<p><strong>3)</strong> Or comparing it to an anonymous empty list:</p>\n\n<pre><code>if a == []:\n print(\"a is empty\")\n</code></pre>\n\n<p><strong>4)</strong> Another yet <em>silly</em> way to do is using <code>exception</code> and <code>iter()</code>:</p>\n\n<pre><code>try:\n next(iter(a))\n # list has elements\nexcept StopIteration:\n print(\"Error: a is empty\")\n</code></pre>\n"
},
{
"answer_id": 43083496,
"author": "AndreyS Scherbakov",
"author_id": 4819357,
"author_profile": "https://Stackoverflow.com/users/4819357",
"pm_score": 4,
"selected": false,
"text": "<p>Being inspired by <a href=\"https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty/10835703#10835703\">dubiousjim's solution</a>, I propose to use an additional general check of whether is it something iterable:</p>\n<pre><code>import collections\ndef is_empty(a):\n return not a and isinstance(a, collections.Iterable)\n</code></pre>\n<p>Note: a string is considered to be iterable—add <code>and not isinstance(a,(str,unicode))</code> if you want the empty string to be excluded</p>\n<p>Test:</p>\n<pre><code>>>> is_empty('sss')\nFalse\n>>> is_empty(555)\nFalse\n>>> is_empty(0)\nFalse\n>>> is_empty('')\nTrue\n>>> is_empty([3])\nFalse\n>>> is_empty([])\nTrue\n>>> is_empty({})\nTrue\n>>> is_empty(())\nTrue\n</code></pre>\n"
},
{
"answer_id": 45778282,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 8,
"selected": false,
"text": "<blockquote>\n <h2>Best way to check if a list is empty</h2>\n \n <p>For example, if passed the following:</p>\n\n<pre><code>a = []\n</code></pre>\n \n <p>How do I check to see if a is empty?</p>\n</blockquote>\n\n<h2>Short Answer:</h2>\n\n<p>Place the list in a boolean context (for example, with an <code>if</code> or <code>while</code> statement). It will test <code>False</code> if it is empty, and <code>True</code> otherwise. For example:</p>\n\n<pre><code>if not a: # do this!\n print('a is an empty list')\n</code></pre>\n\n<h2>PEP 8</h2>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"noreferrer\">PEP 8</a>, the official Python style guide for Python code in Python's standard library, asserts:</p>\n\n<blockquote>\n <p>For sequences, (strings, lists, tuples), use the fact that empty sequences are false.</p>\n\n<pre><code>Yes: if not seq:\n if seq:\n\nNo: if len(seq):\n if not len(seq):\n</code></pre>\n</blockquote>\n\n<p>We should expect that standard library code should be as performant and correct as possible. But why is that the case, and why do we need this guidance?</p>\n\n<h2>Explanation</h2>\n\n<p>I frequently see code like this from experienced programmers new to Python:</p>\n\n<pre><code>if len(a) == 0: # Don't do this!\n print('a is an empty list')\n</code></pre>\n\n<p>And users of lazy languages may be tempted to do this:</p>\n\n<pre><code>if a == []: # Don't do this!\n print('a is an empty list')\n</code></pre>\n\n<p>These are correct in their respective other languages. And this is even semantically correct in Python. </p>\n\n<p>But we consider it un-Pythonic because Python supports these semantics directly in the list object's interface via boolean coercion.</p>\n\n<p>From the <a href=\"https://docs.python.org/3/library/stdtypes.html#truth-value-testing\" rel=\"noreferrer\">docs</a> (and note specifically the inclusion of the empty list, <code>[]</code>):</p>\n\n<blockquote>\n <p>By default, an object is considered true unless its class defines\n either a <code>__bool__()</code> method that returns <code>False</code> or a <code>__len__()</code> method\n that returns zero, when called with the object. Here are most of the built-in objects considered false:</p>\n \n <ul>\n <li>constants defined to be false: <code>None</code> and <code>False</code>.</li>\n <li>zero of any numeric type: <code>0</code>, <code>0.0</code>, <code>0j</code>, <code>Decimal(0)</code>, <code>Fraction(0, 1)</code></li>\n <li>empty sequences and collections: <code>''</code>, <code>()</code>, <code>[]</code>, <code>{}</code>, <code>set()</code>, <code>range(0)</code></li>\n </ul>\n</blockquote>\n\n<p>And the datamodel documentation:</p>\n\n<blockquote>\n <p><a href=\"https://docs.python.org/3/reference/datamodel.html#object.__bool__\" rel=\"noreferrer\"><code>object.__bool__(self)</code></a></p>\n \n <p>Called to implement truth value testing and the built-in operation <code>bool()</code>; should return <code>False</code> or <code>True</code>. When this method is not defined,\n <code>__len__()</code> is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither <code>__len__()</code>\n nor <code>__bool__()</code>, all its instances are considered true.</p>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n <p><a href=\"https://docs.python.org/3/reference/datamodel.html#object.__len__\" rel=\"noreferrer\"><code>object.__len__(self)</code></a></p>\n \n <p>Called to implement the built-in function <code>len()</code>. Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a <code>__bool__()</code> method and whose <code>__len__()</code> method returns zero is considered to be false in a Boolean context.</p>\n</blockquote>\n\n<p>So instead of this:</p>\n\n<pre><code>if len(a) == 0: # Don't do this!\n print('a is an empty list')\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>if a == []: # Don't do this!\n print('a is an empty list')\n</code></pre>\n\n<p>Do this:</p>\n\n<pre><code>if not a:\n print('a is an empty list')\n</code></pre>\n\n<h2>Doing what's Pythonic usually pays off in performance:</h2>\n\n<p>Does it pay off? (Note that less time to perform an equivalent operation is better:)</p>\n\n<pre><code>>>> import timeit\n>>> min(timeit.repeat(lambda: len([]) == 0, repeat=100))\n0.13775854044661884\n>>> min(timeit.repeat(lambda: [] == [], repeat=100))\n0.0984637276455409\n>>> min(timeit.repeat(lambda: not [], repeat=100))\n0.07878462291455435\n</code></pre>\n\n<p>For scale, here's the cost of calling the function and constructing and returning an empty list, which you might subtract from the costs of the emptiness checks used above:</p>\n\n<pre><code>>>> min(timeit.repeat(lambda: [], repeat=100))\n0.07074015751817342\n</code></pre>\n\n<p>We see that <em>either</em> checking for length with the builtin function <code>len</code> compared to <code>0</code> <em>or</em> checking against an empty list is <strong>much</strong> less performant than using the builtin syntax of the language as documented.</p>\n\n<p>Why?</p>\n\n<p>For the <code>len(a) == 0</code> check:</p>\n\n<p>First Python has to check the globals to see if <code>len</code> is shadowed. </p>\n\n<p>Then it must call the function, load <code>0</code>, and do the equality comparison in Python (instead of with C):</p>\n\n<pre><code>>>> import dis\n>>> dis.dis(lambda: len([]) == 0)\n 1 0 LOAD_GLOBAL 0 (len)\n 2 BUILD_LIST 0\n 4 CALL_FUNCTION 1\n 6 LOAD_CONST 1 (0)\n 8 COMPARE_OP 2 (==)\n 10 RETURN_VALUE\n</code></pre>\n\n<p>And for the <code>[] == []</code> it has to build an unnecessary list and then, again, do the comparison operation in Python's virtual machine (as opposed to C)</p>\n\n<pre><code>>>> dis.dis(lambda: [] == [])\n 1 0 BUILD_LIST 0\n 2 BUILD_LIST 0\n 4 COMPARE_OP 2 (==)\n 6 RETURN_VALUE\n</code></pre>\n\n<p>The \"Pythonic\" way is a much simpler and faster check since the length of the list is cached in the object instance header:</p>\n\n<pre><code>>>> dis.dis(lambda: not [])\n 1 0 BUILD_LIST 0\n 2 UNARY_NOT\n 4 RETURN_VALUE\n</code></pre>\n\n<h2>Evidence from the C source and documentation</h2>\n\n<blockquote>\n <p><a href=\"https://docs.python.org/2/c-api/structures.html#c.PyVarObject\" rel=\"noreferrer\"><code>PyVarObject</code></a></p>\n \n <p>This is an extension of <code>PyObject</code> that adds the <code>ob_size</code> field. This is only used for objects that have some notion of length. This type does not often appear in the Python/C API. It corresponds to the fields defined by the expansion of the <code>PyObject_VAR_HEAD</code> macro.</p>\n</blockquote>\n\n<p>From the c source in <a href=\"https://github.com/python/cpython/blob/master/Include/listobject.h\" rel=\"noreferrer\">Include/listobject.h</a>:</p>\n\n<pre><code>typedef struct {\n PyObject_VAR_HEAD\n /* Vector of pointers to list elements. list[0] is ob_item[0], etc. */\n PyObject **ob_item;\n\n /* ob_item contains space for 'allocated' elements. The number\n * currently in use is ob_size.\n * Invariants:\n * 0 <= ob_size <= allocated\n * len(list) == ob_size\n</code></pre>\n\n<h2>Response to comments:</h2>\n\n<blockquote>\n <p>I would point out that this is also true for the non-empty case though its pretty ugly as with <code>l=[]</code> then <code>%timeit len(l) != 0</code> 90.6 ns ± 8.3 ns, <code>%timeit l != []</code> 55.6 ns ± 3.09, <code>%timeit not not l</code> 38.5 ns ± 0.372. But there is no way anyone is going to enjoy <code>not not l</code> despite triple the speed. It looks ridiculous. But the speed wins out<br>\n I suppose the problem is testing with timeit since just <code>if l:</code> is sufficient but surprisingly <code>%timeit bool(l)</code> yields 101 ns ± 2.64 ns. Interesting there is no way to coerce to bool without this penalty. <code>%timeit l</code> is useless since no conversion would occur.</p>\n</blockquote>\n\n<p>IPython magic, <code>%timeit</code>, is not entirely useless here:</p>\n\n<pre><code>In [1]: l = [] \n\nIn [2]: %timeit l \n20 ns ± 0.155 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)\n\nIn [3]: %timeit not l \n24.4 ns ± 1.58 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n\nIn [4]: %timeit not not l \n30.1 ns ± 2.16 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n</code></pre>\n\n<p>We can see there's a bit of linear cost for each additional <code>not</code> here. We want to see the costs, <em>ceteris paribus</em>, that is, all else equal - where all else is minimized as far as possible:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>In [5]: %timeit if l: pass \n22.6 ns ± 0.963 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n\nIn [6]: %timeit if not l: pass \n24.4 ns ± 0.796 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n\nIn [7]: %timeit if not not l: pass \n23.4 ns ± 0.793 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n</code></pre>\n\n<p>Now let's look at the case for an unempty list:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>In [8]: l = [1] \n\nIn [9]: %timeit if l: pass \n23.7 ns ± 1.06 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n\nIn [10]: %timeit if not l: pass \n23.6 ns ± 1.64 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n\nIn [11]: %timeit if not not l: pass \n26.3 ns ± 1 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n</code></pre>\n\n<p>What we can see here is that it makes little difference whether you pass in an actual <code>bool</code> to the condition check or the list itself, and if anything, giving the list, as is, is faster.</p>\n\n<p>Python is written in C; it uses its logic at the C level. Anything you write in Python will be slower. And it will likely be orders of magnitude slower unless you're using the mechanisms built into Python directly.</p>\n"
},
{
"answer_id": 45898755,
"author": "Vineet Jain",
"author_id": 6761181,
"author_profile": "https://Stackoverflow.com/users/6761181",
"pm_score": 3,
"selected": false,
"text": "<p>Simply use is_empty() or make function like:- </p>\n\n<pre><code>def is_empty(any_structure):\n if any_structure:\n print('Structure is not empty.')\n return True\n else:\n print('Structure is empty.')\n return False \n</code></pre>\n\n<p>It can be used for any data_structure like a list,tuples, dictionary and many more. By these, you can call it many times using just <code>is_empty(any_structure)</code>. </p>\n"
},
{
"answer_id": 49109480,
"author": "Rahul",
"author_id": 5452365,
"author_profile": "https://Stackoverflow.com/users/5452365",
"pm_score": 4,
"selected": false,
"text": "<p>If you want to check if a list is empty:</p>\n\n<pre><code>l = []\nif l:\n # do your stuff.\n</code></pre>\n\n<p>If you want to check whether all the values in list is empty. However it will be <code>True</code> for an empty list:</p>\n\n<pre><code>l = [\"\", False, 0, '', [], {}, ()]\nif all(bool(x) for x in l):\n # do your stuff.\n</code></pre>\n\n<p>If you want to use both cases together:</p>\n\n<pre><code>def empty_list(lst):\n if len(lst) == 0:\n return False\n else:\n return all(bool(x) for x in l)\n</code></pre>\n\n<p>Now you can use:</p>\n\n<pre><code>if empty_list(lst):\n # do your stuff.\n</code></pre>\n"
},
{
"answer_id": 50362360,
"author": "Nitin Siwach",
"author_id": 6546694,
"author_profile": "https://Stackoverflow.com/users/6546694",
"pm_score": 3,
"selected": false,
"text": "<p>The truth value of an empty list is <code>False</code> whereas for a non-empty list it is <code>True</code>.</p>\n"
},
{
"answer_id": 52771578,
"author": "Ashiq Imran",
"author_id": 7032887,
"author_profile": "https://Stackoverflow.com/users/7032887",
"pm_score": 3,
"selected": false,
"text": "<p>Simple way is checking the length is equal zero.</p>\n\n<pre><code>if len(a) == 0:\n print(\"a is empty\")\n</code></pre>\n"
},
{
"answer_id": 52772082,
"author": "HackerBoss",
"author_id": 3081198,
"author_profile": "https://Stackoverflow.com/users/3081198",
"pm_score": 4,
"selected": false,
"text": "<p>Many answers have been given, and a lot of them are pretty good. I just wanted to add that the check</p>\n\n<pre><code>not a\n</code></pre>\n\n<p>will also pass for <code>None</code> and other types of empty structures. If you truly want to check for an empty list, you can do this:</p>\n\n<pre><code>if isinstance(a, list) and len(a)==0:\n print(\"Received an empty list\")\n</code></pre>\n"
},
{
"answer_id": 53127845,
"author": "Andrey Topoleov",
"author_id": 7306511,
"author_profile": "https://Stackoverflow.com/users/7306511",
"pm_score": 4,
"selected": false,
"text": "<pre><code>print('not empty' if a else 'empty')\n</code></pre>\n<p>a little more practical:</p>\n<pre><code>a.pop() if a else None\n</code></pre>\n<p>and the shortest version:</p>\n<pre><code>if a: a.pop() \n</code></pre>\n"
},
{
"answer_id": 53169502,
"author": "Trect",
"author_id": 9789097,
"author_profile": "https://Stackoverflow.com/users/9789097",
"pm_score": 3,
"selected": false,
"text": "<p>From python3 onwards you can use</p>\n\n<pre><code>a == []\n</code></pre>\n\n<p>to check if the list is empty</p>\n\n<p>EDIT : This works with python2.7 too.. </p>\n\n<p>I am not sure why there are so many complicated answers.\nIt's pretty clear and straightforward</p>\n"
},
{
"answer_id": 53926417,
"author": "Andy Jazz",
"author_id": 6599590,
"author_profile": "https://Stackoverflow.com/users/6599590",
"pm_score": 4,
"selected": false,
"text": "<p>To check whether a list is empty or not you can use two following ways. But remember, we should avoid the way of explicitly checking for a type of sequence (it's a <strong>less Pythonic</strong> way):</p>\n<pre><code>def enquiry(list1):\n return len(list1) == 0\n\n# ––––––––––––––––––––––––––––––––\n\nlist1 = []\n\nif enquiry(list1):\n print("The list isn't empty")\nelse:\n print("The list is Empty")\n\n# Result: "The list is Empty".\n</code></pre>\n<p>The second way is a <strong>more Pythonic</strong> one. This method is an implicit way of checking and much more preferable than the previous one.</p>\n<pre><code>def enquiry(list1):\n return not list1\n\n# ––––––––––––––––––––––––––––––––\n\nlist1 = []\n\nif enquiry(list1):\n print("The list is Empty")\nelse:\n print("The list isn't empty")\n\n# Result: "The list is Empty"\n</code></pre>\n"
},
{
"answer_id": 54065002,
"author": "l. zhang",
"author_id": 10874195,
"author_profile": "https://Stackoverflow.com/users/10874195",
"pm_score": 4,
"selected": false,
"text": "<p>We could use a simple <em>if else</em>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>item_list=[]\nif len(item_list) == 0:\n print("list is empty")\nelse:\n print("list is not empty")\n</code></pre>\n"
},
{
"answer_id": 54612063,
"author": "Vikrant",
"author_id": 1302617,
"author_profile": "https://Stackoverflow.com/users/1302617",
"pm_score": 5,
"selected": false,
"text": "<p>Method 1 (preferred):</p>\n<pre><code>if not a:\n print ("Empty")\n</code></pre>\n<p>Method 2:</p>\n<pre><code>if len(a) == 0:\n print("Empty")\n</code></pre>\n<p>Method 3:</p>\n<pre><code>if a == []:\n print ("Empty")\n</code></pre>\n"
},
{
"answer_id": 55833259,
"author": "Vedran Šego",
"author_id": 1667018,
"author_profile": "https://Stackoverflow.com/users/1667018",
"pm_score": 3,
"selected": false,
"text": "<p>What brought me here is a special use-case: I actually wanted a <em>function</em> to tell me if a list is empty or not. I wanted to avoid writing my own function or using a lambda-expression here (because it seemed like it should be simple enough):</p>\n\n<pre><code>foo = itertools.takewhile(is_not_empty, (f(x) for x in itertools.count(1)))\n</code></pre>\n\n<p>And, of course, there is a very natural way to do it:</p>\n\n<pre><code>foo = itertools.takewhile(bool, (f(x) for x in itertools.count(1)))\n</code></pre>\n\n<p>Of course, do <strong>not</strong> use <code>bool</code> in <code>if</code> (i.e., <code>if bool(L):</code>) because it's implied. But, for the cases when \"is not empty\" is explicitly needed as a function, <code>bool</code> is the best choice.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | For example, if passed the following:
```
a = []
```
How do I check to see if `a` is empty? | ```
if not a:
print("List is empty")
```
Using the [implicit booleanness](https://docs.python.org/library/stdtypes.html#truth-value-testing) of the empty `list` is quite Pythonic. |
53,543 | <p>Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation?</p>
| [
{
"answer_id": 53549,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 4,
"selected": false,
"text": "<p>If you <em>do</em> find you need to write unique code for an environment, use pythons </p>\n\n<pre><code>import mymodule_jython as mymodule\n\nimport mymodule_cpython as mymodule\n</code></pre>\n\n<p>have this stuff in a simple module (''module_importer''?) and write your code like this:</p>\n\n<pre><code>from module_importer import mymodule\n</code></pre>\n\n<p>This way, all you need to do is alter <code>module_importer.py</code> per platform.</p>\n"
},
{
"answer_id": 55312,
"author": "cdleary",
"author_id": 3594,
"author_profile": "https://Stackoverflow.com/users/3594",
"pm_score": 3,
"selected": false,
"text": "<p>@Daren Thomas: I agree, but you should use the <a href=\"http://docs.python.org/dev/library/platform.html#platform.python_implementation\" rel=\"nofollow noreferrer\">platform module</a> to determine which interpreter you're running.</p>\n"
},
{
"answer_id": 199275,
"author": "CyberFonic",
"author_id": 23999,
"author_profile": "https://Stackoverflow.com/users/23999",
"pm_score": 2,
"selected": false,
"text": "<p>I write code for CPython and IronPython but tip should work for Jython as well.</p>\n\n<p>Basically, I write all the platform specific code in separate modules/packages and then import the appropriate one based on platform I'm running on. (see cdleary's comment above)</p>\n\n<p>This is especially important when it comes to the differences between the SQLite implementations and if you are implementing any GUI code.</p>\n"
},
{
"answer_id": 342835,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 1,
"selected": false,
"text": "<p>The #1 thing IMO: <strong>Focus on thread safety</strong>. CPython's GIL makes writing threadsafe code easy because only one thread can access the interpreter at a time. IronPython and Jython are a little less hand-holding though.</p>\n"
},
{
"answer_id": 342845,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 0,
"selected": false,
"text": "<p>I'm pretty sure you already know this but unfortunately Jython <a href=\"http://www.jython.org/Project/userfaq.html#is-jython-the-same-language-as-python\" rel=\"nofollow noreferrer\">can't load c extension modules.</a></p>\n"
},
{
"answer_id": 637549,
"author": "Arafangion",
"author_id": 52273,
"author_profile": "https://Stackoverflow.com/users/52273",
"pm_score": 0,
"selected": false,
"text": "<p>There are two <em>major</em> issues at play here...</p>\n\n<p>Firstly, to my knowledge, only CPython has RAII - you have to close your own resources in Jython, Ironpython, etc.</p>\n\n<p>And Secondly, as has been mentioned, is thread safety.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] | Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation? | If you *do* find you need to write unique code for an environment, use pythons
```
import mymodule_jython as mymodule
import mymodule_cpython as mymodule
```
have this stuff in a simple module (''module\_importer''?) and write your code like this:
```
from module_importer import mymodule
```
This way, all you need to do is alter `module_importer.py` per platform. |
53,545 | <p>I have an exe with an <code>App.Config</code> file. Now I want to create a wrapper dll around the exe in order to consume some of the functionalities.</p>
<p>The question is how can I access the app.config property in the exe from the wrapper dll?</p>
<p>Maybe I should be a little bit more in my questions, I have the following app.config content with the exe:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="myKey" value="myValue"/>
</appSettings>
</configuration>
</code></pre>
<p>The question is how to how to get "myValue" out from the wrapper dll?</p>
<hr>
<p>thanks for your solution.</p>
<p>Actually my initial concept was to avoid XML file reading method or LINQ or whatever. My preferred solution was to use the <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx" rel="noreferrer">configuration manager libraries and the like</a>.</p>
<p>I'll appreciate any help that uses the classes that are normally associated with accessing app.config properties. </p>
| [
{
"answer_id": 53552,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": -1,
"selected": false,
"text": "<p>It's an xml file, you can use Linq-XML or DOM based approaches to parse out the relevant information.<br>\n(that said I'd question if there isn't a better design for whatever it is.. you're trying to achieve.)</p>\n"
},
{
"answer_id": 53553,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 5,
"selected": false,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openmappedexeconfiguration(VS.80).aspx\" rel=\"noreferrer\">ConfigurationManager.OpenMappedExeConfiguration Method</a> will allow you to do this.</p>\n\n<p>Sample from the MSDN page:</p>\n\n<pre><code>static void GetMappedExeConfigurationSections()\n{\n // Get the machine.config file.\n ExeConfigurationFileMap fileMap =\n new ExeConfigurationFileMap();\n // You may want to map to your own exe.comfig file here.\n fileMap.ExeConfigFilename = \n @\"C:\\test\\ConfigurationManager.exe.config\";\n System.Configuration.Configuration config =\n ConfigurationManager.OpenMappedExeConfiguration(fileMap, \n ConfigurationUserLevel.None);\n\n // Loop to get the sections. Display basic information.\n Console.WriteLine(\"Name, Allow Definition\");\n int i = 0;\n foreach (ConfigurationSection section in config.Sections)\n {\n Console.WriteLine(\n section.SectionInformation.Name + \"\\t\" +\n section.SectionInformation.AllowExeDefinition);\n i += 1;\n\n }\n Console.WriteLine(\"[Total number of sections: {0}]\", i);\n\n // Display machine.config path.\n Console.WriteLine(\"[File path: {0}]\", config.FilePath);\n}\n</code></pre>\n\n<hr>\n\n<p>EDIT: This should output the \"myKey\" value:</p>\n\n<pre><code>ExeConfigurationFileMap fileMap =\n new ExeConfigurationFileMap();\nfileMap.ExeConfigFilename = \n @\"C:\\test\\ConfigurationManager.exe.config\";\nSystem.Configuration.Configuration config =\n ConfigurationManager.OpenMappedExeConfiguration(fileMap, \n ConfigurationUserLevel.None);\nConsole.WriteLine(config.AppSettings.Settings[\"MyKey\"].Value);\n</code></pre>\n"
},
{
"answer_id": 53557,
"author": "alastairs",
"author_id": 5296,
"author_profile": "https://Stackoverflow.com/users/5296",
"pm_score": 0,
"selected": false,
"text": "<p>I'd second Gishu's point that there's another way. Wouldn't it be better to abstact the common/\"public\" part of the EXE out into DLL create a wrapper EXE to run it? This is certainly the more usual pattern of development. Only the stuff that you wish to consume would go into the DLL, and the EXE would do all the stuff it currently does, minus what's gone into the DLL. </p>\n"
},
{
"answer_id": 53642,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 2,
"selected": false,
"text": "<p>I think what you're looking for is:</p>\n\n<pre><code>System.Configuration.ConfigurationManager.OpenExeConfiguration(string path)\n</code></pre>\n"
},
{
"answer_id": 53776,
"author": "Graviton",
"author_id": 3834,
"author_profile": "https://Stackoverflow.com/users/3834",
"pm_score": 4,
"selected": true,
"text": "<p>After some testing, I found a way to do this.</p>\n\n<ol>\n<li>Add the App.Config file to the test project. Use \"Add as a link\" option.</li>\n<li>Use <code>System.Configuration.ConfigurationManager.AppSettings[\"myKey\"]</code> to access the value.</li>\n</ol>\n"
},
{
"answer_id": 53784,
"author": "tkrehbiel",
"author_id": 4925,
"author_profile": "https://Stackoverflow.com/users/4925",
"pm_score": -1,
"selected": false,
"text": "<p>Adding a link in the IDE would only help during development. I think lomaxx has the right idea: <code>System.Configuration.ConfigurationManager.OpenExeConfiguration.</code></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] | I have an exe with an `App.Config` file. Now I want to create a wrapper dll around the exe in order to consume some of the functionalities.
The question is how can I access the app.config property in the exe from the wrapper dll?
Maybe I should be a little bit more in my questions, I have the following app.config content with the exe:
```
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="myKey" value="myValue"/>
</appSettings>
</configuration>
```
The question is how to how to get "myValue" out from the wrapper dll?
---
thanks for your solution.
Actually my initial concept was to avoid XML file reading method or LINQ or whatever. My preferred solution was to use the [configuration manager libraries and the like](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx).
I'll appreciate any help that uses the classes that are normally associated with accessing app.config properties. | After some testing, I found a way to do this.
1. Add the App.Config file to the test project. Use "Add as a link" option.
2. Use `System.Configuration.ConfigurationManager.AppSettings["myKey"]` to access the value. |
53,562 | <p>What are the steps required to enable Hibernate's second-level cache, when using the Java Persistence API (annotated entities)? How do I check that it's working? I'm using JBoss 4.2.2.GA.</p>
<p>From the Hibernate documentation, it seems that I need to enable the cache and specify a cache provider in <em>persistence.xml</em>, like:</p>
<pre><code><property name="hibernate.cache.use_second_level_cache"
value="true" />
<property name="hibernate.cache.provider_class"
value="org.hibernate.cache.HashtableCacheProvider" />
</code></pre>
<p>What else is required? Do I need to add <em>@Cache</em> annotations to my JPA entities?</p>
<p>How can I tell if the cache is working? I have tried accessing cache statistics after running a Query, but <em>Statistics.getSecondLevelCacheStatistics</em> returns null, perhaps because I don't know what 'region' name to use.</p>
| [
{
"answer_id": 53992,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 3,
"selected": true,
"text": "<p>I believe you need to add the cache annotations to tell hibernate how to use the second-level cache (read-only, read-write, etc). This was the case in my app (using spring / traditional hibernate and ehcache, so your mileage may vary). Once the caches were indicated, I started seeing messages that they were in use from hibernate.</p>\n"
},
{
"answer_id": 54415,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 2,
"selected": false,
"text": "<p>Follow-up: in the end, after adding annotations, I have it working with EhCache, i.e.</p>\n\n<pre><code><property name=\"hibernate.cache.provider_class\" \n value=\"net.sf.ehcache.hibernate.EhCacheProvider\" />\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2670/"
] | What are the steps required to enable Hibernate's second-level cache, when using the Java Persistence API (annotated entities)? How do I check that it's working? I'm using JBoss 4.2.2.GA.
From the Hibernate documentation, it seems that I need to enable the cache and specify a cache provider in *persistence.xml*, like:
```
<property name="hibernate.cache.use_second_level_cache"
value="true" />
<property name="hibernate.cache.provider_class"
value="org.hibernate.cache.HashtableCacheProvider" />
```
What else is required? Do I need to add *@Cache* annotations to my JPA entities?
How can I tell if the cache is working? I have tried accessing cache statistics after running a Query, but *Statistics.getSecondLevelCacheStatistics* returns null, perhaps because I don't know what 'region' name to use. | I believe you need to add the cache annotations to tell hibernate how to use the second-level cache (read-only, read-write, etc). This was the case in my app (using spring / traditional hibernate and ehcache, so your mileage may vary). Once the caches were indicated, I started seeing messages that they were in use from hibernate. |
53,569 | <p>What is the best way to get a log of commits on a branch since the time it was branched from the current branch? My solution so far is:</p>
<pre><code>git log $(git merge-base HEAD branch)..branch
</code></pre>
<p>The documentation for <a href="http://git-scm.com/docs/git-diff" rel="noreferrer">git-diff</a> indicates that <code>git diff A...B</code> is equivalent to <code>git diff $(git-merge-base A B) B</code>. On the other hand, the documentation for <a href="http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html" rel="noreferrer">git-rev-parse</a> indicates that <code>r1...r2</code> is defined as <code>r1 r2 --not $(git merge-base --all r1 r2)</code>.</p>
<p>Why are these different? Note that <code>git diff HEAD...branch</code> gives me the diffs I want, but the corresponding git log command gives me more than what I want.</p>
<p>In pictures, suppose this:</p>
<pre>
x---y---z---branch
/
---a---b---c---d---e---HEAD
</pre>
<p>I would like to get a log containing commits x, y, z.</p>
<ul>
<li><code>git diff HEAD...branch</code> gives these commits</li>
<li>however, <code>git log HEAD...branch</code> gives x, y, z, c, d, e.</li>
</ul>
| [
{
"answer_id": 53573,
"author": "Lily Ballard",
"author_id": 582,
"author_profile": "https://Stackoverflow.com/users/582",
"pm_score": 9,
"selected": true,
"text": "<p>In the context of a revision list, <code>A...B</code> is how <code>git-rev-parse</code> defines it. git-log takes a revision list. <code>git-diff</code> does not take a list of revisions - it takes one or two revisions, and has defined the <code>A...B</code> syntax to mean how it's defined in the <code>git-diff</code> manpage. If <code>git-diff</code> did not explicitly define <code>A...B</code>, then that syntax would be invalid. Note that the <code>git-rev-parse</code> manpage describes <code>A...B</code> in the \"Specifying Ranges\" section, and everything in that section is only valid in situations where a revision range is valid (i.e. when a revision list is desired).</p>\n\n<p>To get a log containing just x, y, and z, try <code>git log HEAD..branch</code> (two dots, not three). This is identical to <code>git log branch --not HEAD</code>, and means all commits on branch that aren't on HEAD.</p>\n"
},
{
"answer_id": 273683,
"author": "skiphoppy",
"author_id": 18103,
"author_profile": "https://Stackoverflow.com/users/18103",
"pm_score": 6,
"selected": false,
"text": "<pre><code>git cherry branch [newbranch]\n</code></pre>\n\n<p>does exactly what you are asking, when you are in the <code>master</code> branch.</p>\n\n<p>I am also very fond of:</p>\n\n<pre><code>git diff --name-status branch [newbranch]\n</code></pre>\n\n<p>Which isn't exactly what you're asking, but is still very useful in the same context.</p>\n"
},
{
"answer_id": 2831173,
"author": "Clintm",
"author_id": 3384609,
"author_profile": "https://Stackoverflow.com/users/3384609",
"pm_score": 5,
"selected": false,
"text": "<p>This is similar to the answer I posted on: <a href=\"https://stackoverflow.com/questions/2176278/preview-a-git-push/2831135#2831135\">Preview a Git push</a></p>\n\n<p>Drop these functions into your Bash profile:</p>\n\n<ul>\n<li>gbout - git branch outgoing</li>\n<li>gbin - git branch incoming</li>\n</ul>\n\n<p>You can use this like:</p>\n\n<ul>\n<li>If on master: gbin branch1 <-- this\nwill show you what's in branch1 and\nnot in master</li>\n<li>If on master: gbout\nbranch1 <-- this will show you what's\nin master that's not in branch 1</li>\n</ul>\n\n<p>This will work with any branch.</p>\n\n<pre><code>function parse_git_branch {\n git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \\(.*\\)/\\1/'\n}\n\nfunction gbin {\n echo branch \\($1\\) has these commits and \\($(parse_git_branch)\\) does not\n git log ..$1 --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local\n}\n\nfunction gbout {\n echo branch \\($(parse_git_branch)\\) has these commits and \\($1\\) does not\n git log $1.. --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local\n}\n</code></pre>\n"
},
{
"answer_id": 11689964,
"author": "nopsoft",
"author_id": 1557959,
"author_profile": "https://Stackoverflow.com/users/1557959",
"pm_score": 2,
"selected": false,
"text": "<pre><code>git log --cherry-mark --oneline from_branch...to_branch\n</code></pre>\n\n<p>(3dots) but sometimes it shows '+' instead of '='</p>\n"
},
{
"answer_id": 13465814,
"author": "Debajit",
"author_id": 2288585,
"author_profile": "https://Stackoverflow.com/users/2288585",
"pm_score": 5,
"selected": false,
"text": "<p>What you want to see is the list of outgoing commits. You can do this using</p>\n\n<pre><code>git log master..branchName \n</code></pre>\n\n<p>or </p>\n\n<pre><code>git log master..branchName --oneline\n</code></pre>\n\n<p>Where I assume that \"branchName\" was created as a tracking branch of \"master\".</p>\n\n<p>Similarly, to see the incoming changes you can use:</p>\n\n<pre><code>git log branchName..master\n</code></pre>\n"
},
{
"answer_id": 18241536,
"author": "Alex V",
"author_id": 327934,
"author_profile": "https://Stackoverflow.com/users/327934",
"pm_score": 3,
"selected": false,
"text": "<p>Throw a -p in there to see some FILE CHANGES</p>\n\n<pre><code>git log -p master..branch\n</code></pre>\n\n<p>Make some aliases:</p>\n\n<pre><code>alias gbc=\"git branch --no-color | sed -e '/^[^\\*]/d' -e 's/* \\\\(.*\\\\)/\\1/'\"\n\nalias gbl='git log -p master..\\`gbc\\`'\n</code></pre>\n\n<p>See a branch's unique commits:</p>\n\n<pre><code>gbl\n</code></pre>\n"
},
{
"answer_id": 19315225,
"author": "Dominik Ehrenberg",
"author_id": 2410151,
"author_profile": "https://Stackoverflow.com/users/2410151",
"pm_score": 2,
"selected": false,
"text": "<p>I found</p>\n\n<pre><code>git diff <branch_with_changes> <branch_to_compare_to>\n</code></pre>\n\n<p>more useful, since you don't only get the commit messages but the whole diff. If you are already on the branch you want to see the changes of and (for instance) want to see what has changed to the master, you can use:</p>\n\n<pre><code>git diff HEAD master\n</code></pre>\n"
},
{
"answer_id": 33091430,
"author": "NDavis",
"author_id": 1457295,
"author_profile": "https://Stackoverflow.com/users/1457295",
"pm_score": 3,
"selected": false,
"text": "<p>To see the log of the current branch since branching off master:</p>\n\n<p><code>git log master...</code></p>\n\n<p>If you are currently on master, to see the log of a different branch since it branched off master:</p>\n\n<p><code>git log ...other-branch</code></p>\n"
},
{
"answer_id": 37115352,
"author": "Michael Durrant",
"author_id": 631619,
"author_profile": "https://Stackoverflow.com/users/631619",
"pm_score": 4,
"selected": false,
"text": "<p>When already in the branch in question use</p>\n<pre><code>git diff master...\n</code></pre>\n<p>Which combines several features:</p>\n<ul>\n<li>it's super short</li>\n<li>shows the actual changes</li>\n<li>Allow for master having moved forward</li>\n</ul>\n"
},
{
"answer_id": 65117801,
"author": "Denton L",
"author_id": 4762298,
"author_profile": "https://Stackoverflow.com/users/4762298",
"pm_score": 0,
"selected": false,
"text": "<p>With Git 2.30 (Q1 2021), "git diff A...B(man)" learned "git diff --merge-base A B(man), which is a longer short-hand to say the same thing.</p>\n<p>Thus you can do this using <code>git diff --merge-base <branch> HEAD</code>. This should be equivalent to <code>git diff <branch>...HEAD</code> but without the confusion of having to use range-notation in a diff.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/893/"
] | What is the best way to get a log of commits on a branch since the time it was branched from the current branch? My solution so far is:
```
git log $(git merge-base HEAD branch)..branch
```
The documentation for [git-diff](http://git-scm.com/docs/git-diff) indicates that `git diff A...B` is equivalent to `git diff $(git-merge-base A B) B`. On the other hand, the documentation for [git-rev-parse](http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html) indicates that `r1...r2` is defined as `r1 r2 --not $(git merge-base --all r1 r2)`.
Why are these different? Note that `git diff HEAD...branch` gives me the diffs I want, but the corresponding git log command gives me more than what I want.
In pictures, suppose this:
```
x---y---z---branch
/
---a---b---c---d---e---HEAD
```
I would like to get a log containing commits x, y, z.
* `git diff HEAD...branch` gives these commits
* however, `git log HEAD...branch` gives x, y, z, c, d, e. | In the context of a revision list, `A...B` is how `git-rev-parse` defines it. git-log takes a revision list. `git-diff` does not take a list of revisions - it takes one or two revisions, and has defined the `A...B` syntax to mean how it's defined in the `git-diff` manpage. If `git-diff` did not explicitly define `A...B`, then that syntax would be invalid. Note that the `git-rev-parse` manpage describes `A...B` in the "Specifying Ranges" section, and everything in that section is only valid in situations where a revision range is valid (i.e. when a revision list is desired).
To get a log containing just x, y, and z, try `git log HEAD..branch` (two dots, not three). This is identical to `git log branch --not HEAD`, and means all commits on branch that aren't on HEAD. |
53,599 | <p>Ulimately I just wanted to extract strings from the .rc file so I could translate them, but anything that goes with .rc files works for me.</p>
| [
{
"answer_id": 53697,
"author": "Thomas",
"author_id": 4980,
"author_profile": "https://Stackoverflow.com/users/4980",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe this helps? (<a href=\"http://social.msdn.microsoft.com/forums/en-US/regexp/thread/5e87fce9-ec73-42eb-b2eb-c821e95e0d31/\" rel=\"nofollow noreferrer\">http://social.msdn.microsoft.com/forums/en-US/regexp/thread/5e87fce9-ec73-42eb-b2eb-c821e95e0d31/</a>)</p>\n\n<p>They are using the following regex to find the stringtable in the rc source:</p>\n\n<p>(?<=\\bSTRINGTABLE\\s+BEGIN\\s+).*?(?=\\s+END\\b)</p>\n\n<p>Edit - And you can read the key values pairs with the following statement with the MultiLine option:</p>\n\n<p>@\"\\s+(.*?)\\s+\"\"(.*)\"\"\";</p>\n"
},
{
"answer_id": 98442,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 0,
"selected": false,
"text": "<p>This sounds like a job for a <a href=\"http://www.zeusedit.com/forum/viewtopic.php?t=1229\" rel=\"nofollow noreferrer\">SED</a> script.</p>\n\n<p>By running this command line: <strong>sed.exe -n -f sed.txt test.rc</strong></p>\n\n<p>The following <a href=\"http://www.zeusedit.com/forum/viewtopic.php?t=1229\" rel=\"nofollow noreferrer\">SED</a> script will extract all the <em>quoted strings</em> from the input <strong>test.rc</strong> file:</p>\n\n<pre><code># Run Script Using This Command Line\n#\n# sed.exe -n -f sed.txt test.rc\n#\n\n# Check for lines that contain strings\n/\\\".*\\\"/ {\n # print the string part of the line only\n s/\\(.*\\)\\(\\\".*\\\"\\)\\(.*\\)/\\2/ p\n}\n</code></pre>\n"
},
{
"answer_id": 109370,
"author": "Serge Wautier",
"author_id": 12379,
"author_profile": "https://Stackoverflow.com/users/12379",
"pm_score": 1,
"selected": false,
"text": "<p>Although rc files seems an obvious starting point for translation, it's not. \nThe job of developers is to make sure the app is translatable. It's not to manage translations. Starting translations from the exe, although somewhat counter-intuitive, is a way better idea.\nRead more about it here: <a href=\"http://www.apptranslator.com/misconceptions.html\" rel=\"nofollow noreferrer\">http://www.apptranslator.com/misconceptions.html</a></p>\n"
},
{
"answer_id": 666447,
"author": "Germstorm",
"author_id": 18631,
"author_profile": "https://Stackoverflow.com/users/18631",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"http://resxcrunch.com\" rel=\"nofollow noreferrer\">ResxCrunch</a> will be out sometimes soon. \nIt will edit multiple resource files in multiple languages in one single table.</p>\n"
},
{
"answer_id": 13627025,
"author": "blackbada_cpp",
"author_id": 1220715,
"author_profile": "https://Stackoverflow.com/users/1220715",
"pm_score": 2,
"selected": false,
"text": "<p>I'd consider usage of <a href=\"http://en.wikipedia.org/wiki/Gettext\" rel=\"nofollow\">gettext</a> and <a href=\"http://gnu.cs.pu.edu.tw/software/gettext/manual/html_node/PO-Files.html\" rel=\"nofollow\">.PO files</a>, if your program fits GNU license</p>\n\n<p>1) I'd suggest extracting from .rc files using state machine algorithm.</p>\n\n<pre><code>void ProcessLine(const char * str)\n{\n if (strstr(str, \" DIALOG\"))\n state = Scan;\n else if (strstr(str, \" MENU\"))\n state = Scan;\n else if (strstr(str, \" STRINGTABLE\"))\n state = Scan;\n else if (strstr(str, \"END\"))\n state = DontScan;\n\n if (state == Scan)\n {\n const char * cur = sLine;\n string hdr = ...// for example \"# file.rc:453\"\n string msgid;\n string msgid = \"\";\n while (ExtractString(sLine, cur, msgid))\n {\n if (msgid.empty())\n continue;\n if (IsPredefined(msgid))\n continue;\n if (msgid.find(\"IDB_\") == 0 || msgid.find(\"IDC_\") == 0)\n continue;\n WritePoString(hdr, msgid, msgstr);\n }\n }\n}\n</code></pre>\n\n<p>2) When extracting string inside ExtractString() you should consider that char \" is represented as \"\", and there are also chars like \\t \\n \\r. So state machine is also a good option here.</p>\n\n<p>The following string:</p>\n\n<pre><code>LTEXT \"Mother has washed \"\"Sony\"\", then \\taquarium\\\\shelves\\r\\nand probably floors\",IDC_TEXT1,24,14,224,19\n</code></pre>\n\n<p>represents such label on a dialog:</p>\n\n<pre><code>Mother has washed \"Sony\", then aquarium\\shelves\nand probably floors\n</code></pre>\n\n<p>3) Then on program startup you should load .po file via gettext and for each dialog translate its string on startup using a function like this:</p>\n\n<pre><code>int TranslateDialog(CWnd& wnd)\n{\n int i = 0;\n CWnd *pChild;\n CString text;\n\n //Translate Title\nwnd.GetWindowText(text);\nLPCTSTR translation = Translate(text);\n window.SetWindowText(translation);\n\n //Translate child windows\n pChild=wnd.GetWindow(GW_CHILD);\n while(pChild)\n {\n i++;\n Child->GetWindowText(Text);//including NULL\n translation = Translate(Text);\n pChild->SetWindowText(translation);\n pChild = pChild->GetWindow(GW_HWNDNEXT);\n }\n return i;\n}\n</code></pre>\n"
},
{
"answer_id": 26954495,
"author": "Maxim Kapitonov",
"author_id": 645806,
"author_profile": "https://Stackoverflow.com/users/645806",
"pm_score": 0,
"selected": false,
"text": "<p>In case rc, better use advanced parser like <a href=\"http://www.soft-gems.net/index.php/java/windows-resource-file-parser-and-converter\" rel=\"nofollow\">http://www.soft-gems.net/index.php/java/windows-resource-file-parser-and-converter</a></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4880/"
] | Ulimately I just wanted to extract strings from the .rc file so I could translate them, but anything that goes with .rc files works for me. | I'd consider usage of [gettext](http://en.wikipedia.org/wiki/Gettext) and [.PO files](http://gnu.cs.pu.edu.tw/software/gettext/manual/html_node/PO-Files.html), if your program fits GNU license
1) I'd suggest extracting from .rc files using state machine algorithm.
```
void ProcessLine(const char * str)
{
if (strstr(str, " DIALOG"))
state = Scan;
else if (strstr(str, " MENU"))
state = Scan;
else if (strstr(str, " STRINGTABLE"))
state = Scan;
else if (strstr(str, "END"))
state = DontScan;
if (state == Scan)
{
const char * cur = sLine;
string hdr = ...// for example "# file.rc:453"
string msgid;
string msgid = "";
while (ExtractString(sLine, cur, msgid))
{
if (msgid.empty())
continue;
if (IsPredefined(msgid))
continue;
if (msgid.find("IDB_") == 0 || msgid.find("IDC_") == 0)
continue;
WritePoString(hdr, msgid, msgstr);
}
}
}
```
2) When extracting string inside ExtractString() you should consider that char " is represented as "", and there are also chars like \t \n \r. So state machine is also a good option here.
The following string:
```
LTEXT "Mother has washed ""Sony"", then \taquarium\\shelves\r\nand probably floors",IDC_TEXT1,24,14,224,19
```
represents such label on a dialog:
```
Mother has washed "Sony", then aquarium\shelves
and probably floors
```
3) Then on program startup you should load .po file via gettext and for each dialog translate its string on startup using a function like this:
```
int TranslateDialog(CWnd& wnd)
{
int i = 0;
CWnd *pChild;
CString text;
//Translate Title
wnd.GetWindowText(text);
LPCTSTR translation = Translate(text);
window.SetWindowText(translation);
//Translate child windows
pChild=wnd.GetWindow(GW_CHILD);
while(pChild)
{
i++;
Child->GetWindowText(Text);//including NULL
translation = Translate(Text);
pChild->SetWindowText(translation);
pChild = pChild->GetWindow(GW_HWNDNEXT);
}
return i;
}
``` |
53,623 | <p>I want to get whois information of a domain name from my c#/java programs. Is there a simple way to do this? </p>
| [
{
"answer_id": 53631,
"author": "Thomas",
"author_id": 4980,
"author_profile": "https://Stackoverflow.com/users/4980",
"pm_score": 2,
"selected": false,
"text": "<p>I think, the easiest way is a socket connection to a whois server on port 43. Send the domainname followed by a newline and read the response.</p>\n"
},
{
"answer_id": 53632,
"author": "Chris Bunch",
"author_id": 422,
"author_profile": "https://Stackoverflow.com/users/422",
"pm_score": -1,
"selected": false,
"text": "<p>Here's the Java solution, which just opens up a shell and runs <code>whois</code>:</p>\n\n<pre><code>import java.io.*;\nimport java.util.*;\n\npublic class ExecTest2 {\n public static void main(String[] args) throws IOException {\n Process result = Runtime.getRuntime().exec(\"whois stackoverflow.com\");\n\n BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));\n StringBuffer outputSB = new StringBuffer(40000);\n String s = null;\n\n while ((s = output.readLine()) != null) {\n outputSB.append(s + \"\\n\");\n System.out.println(s);\n }\n\n String whoisStr = output.toString();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 177758,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 2,
"selected": false,
"text": "<p>Thomas' answer will only work if you know <em>which</em> "whois" server to connect to.</p>\n<p>There are many different ways of finding that out, but none (AFAIK) that works uniformly for every domain registry.</p>\n<p>Some domain names support an <code>SRV</code> record for the <code>_nicname._tcp</code> service in the DNS, but there are issues with that because there's no accepted standard yet on how to prevent a subdomain from serving up <code>SRV</code> records which override those of the official registry (see <a href=\"https://datatracker.ietf.org/doc/html/draft-sanz-whois-srv-00\" rel=\"nofollow noreferrer\">https://datatracker.ietf.org/doc/html/draft-sanz-whois-srv-00</a>).</p>\n<p>For many TLDs it's possible to send your query to <code><tld>.whois-servers.net</code>. This actually works quite well, but beware that it won't work in all cases where there are officially delegated second level domains.</p>\n<p>For example in <code>.uk</code> there are several official sub-domains, but only some of them are run by the <code>.uk</code> registry and the others have their own WHOIS services and those aren't in the <code>whois-servers.net</code> database.</p>\n<p>Confusingly there are also "unofficial" registries, such as <code>.uk.com</code>, which <em>are</em> in the <code>whois-servers.net</code> database.</p>\n<p>p.s. the official End-Of-Line delimiter in WHOIS, as with most IETF protocols is <code>CRLF</code>, not just <code>LF</code>.</p>\n"
},
{
"answer_id": 923873,
"author": "Jeff",
"author_id": 105756,
"author_profile": "https://Stackoverflow.com/users/105756",
"pm_score": 2,
"selected": false,
"text": "<p>I found some web services that offer this information. This one is free and worked great for me. <a href=\"http://www.webservicex.net/whois.asmx?op=GetWhoIS\" rel=\"nofollow noreferrer\">http://www.webservicex.net/whois.asmx?op=GetWhoIS</a></p>\n"
},
{
"answer_id": 1067587,
"author": "Andrew Shepherd",
"author_id": 25216,
"author_profile": "https://Stackoverflow.com/users/25216",
"pm_score": 4,
"selected": true,
"text": "<p>I found a perfect C# example on dotnet-snippets.com (<em>which doesn't exist anymore</em>). </p>\n\n<p>It's 11 lines of code to copy and paste straight into your own application.</p>\n\n<pre><code>/// <summary>\n/// Gets the whois information.\n/// </summary>\n/// <param name=\"whoisServer\">The whois server.</param>\n/// <param name=\"url\">The URL.</param>\n/// <returns></returns>\nprivate string GetWhoisInformation(string whoisServer, string url)\n{\n StringBuilder stringBuilderResult = new StringBuilder();\n TcpClient tcpClinetWhois = new TcpClient(whoisServer, 43);\n NetworkStream networkStreamWhois = tcpClinetWhois.GetStream();\n BufferedStream bufferedStreamWhois = new BufferedStream(networkStreamWhois);\n StreamWriter streamWriter = new StreamWriter(bufferedStreamWhois);\n\n streamWriter.WriteLine(url);\n streamWriter.Flush();\n\n StreamReader streamReaderReceive = new StreamReader(bufferedStreamWhois);\n\n while (!streamReaderReceive.EndOfStream)\n stringBuilderResult.AppendLine(streamReaderReceive.ReadLine());\n\n return stringBuilderResult.ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 16179401,
"author": "user2313093",
"author_id": 2313093,
"author_profile": "https://Stackoverflow.com/users/2313093",
"pm_score": 2,
"selected": false,
"text": "<p>I found a perfect C# example here. It's 11 lines of code to copy and paste straight into your own application. BUT FIRST you should add some using statements to ensure that the dispose methods are properly called to prevent memory leaks:</p>\n\n<pre><code>StringBuilder stringBuilderResult = new StringBuilder();\nusing(TcpClient tcpClinetWhois = new TcpClient(whoIsServer, 43))\n{\n using(NetworkStream networkStreamWhois = tcpClinetWhois.GetStream())\n {\n using(BufferedStream bufferedStreamWhois = new BufferedStream(networkStreamWhois))\n {\n using(StreamWriter streamWriter = new StreamWriter(bufferedStreamWhois))\n {\n streamWriter.WriteLine(url);\n streamWriter.Flush();\n using (StreamReader streamReaderReceive = new StreamReader(bufferedStreamWhois))\n {\n while (!streamReaderReceive.EndOfStream) stringBuilderResult.AppendLine(streamReaderReceive.ReadLine());\n }\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 72093332,
"author": "Erman Çetin",
"author_id": 4819851,
"author_profile": "https://Stackoverflow.com/users/4819851",
"pm_score": 0,
"selected": false,
"text": "<p>if you add <code>leaveOpen: true</code> to the <code>StreamWriter</code> and <code>StreamReader</code> constructors. You will not get "Cannot access a closed stream" exception</p>\n<pre><code>var stringBuilderResult = new StringBuilder();\n\nusing (var tcpClinetWhois = new TcpClient(whoIsServer, 43))\nusing (var networkStreamWhois = tcpClinetWhois.GetStream())\nusing (var bufferedStreamWhois = new BufferedStream(networkStreamWhois))\nusing (var streamWriter = new StreamWriter(networkStreamWhois, leaveOpen: true))\n{\n streamWriter.WriteLine(url);\n streamWriter.Flush();\n\n using (var streamReaderReceive = new StreamReader(networkStreamWhois, leaveOpen: true))\n {\n while (!streamReaderReceive.EndOfStream)\n {\n stringBuilderResult.AppendLine(streamReaderReceive.ReadLine());\n }\n }\n}\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] | I want to get whois information of a domain name from my c#/java programs. Is there a simple way to do this? | I found a perfect C# example on dotnet-snippets.com (*which doesn't exist anymore*).
It's 11 lines of code to copy and paste straight into your own application.
```
/// <summary>
/// Gets the whois information.
/// </summary>
/// <param name="whoisServer">The whois server.</param>
/// <param name="url">The URL.</param>
/// <returns></returns>
private string GetWhoisInformation(string whoisServer, string url)
{
StringBuilder stringBuilderResult = new StringBuilder();
TcpClient tcpClinetWhois = new TcpClient(whoisServer, 43);
NetworkStream networkStreamWhois = tcpClinetWhois.GetStream();
BufferedStream bufferedStreamWhois = new BufferedStream(networkStreamWhois);
StreamWriter streamWriter = new StreamWriter(bufferedStreamWhois);
streamWriter.WriteLine(url);
streamWriter.Flush();
StreamReader streamReaderReceive = new StreamReader(bufferedStreamWhois);
while (!streamReaderReceive.EndOfStream)
stringBuilderResult.AppendLine(streamReaderReceive.ReadLine());
return stringBuilderResult.ToString();
}
``` |
53,629 | <p>Is it possible to see the history of changes to a particular line of code in a Subversion repository?</p>
<p>I'd like, for instance, to be able to see when a particular statement was added or when that statement was changed, even if its line number is not the same any more.</p>
| [
{
"answer_id": 53633,
"author": "Maximilian",
"author_id": 1733,
"author_profile": "https://Stackoverflow.com/users/1733",
"pm_score": 0,
"selected": false,
"text": "<p>svn blame shows you which checkin modified any line in a file the last time.</p>\n\n<p>This works on old revisions too.</p>\n"
},
{
"answer_id": 53634,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": -1,
"selected": false,
"text": "<p>The command you're looking for is <a href=\"http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.blame.html\" rel=\"nofollow noreferrer\"><code>svn blame</code></a>.</p>\n"
},
{
"answer_id": 53636,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 0,
"selected": false,
"text": "<p>A start is the command svn blame (or annotate,praise). It will show you when a line of code was last modified and by whom it was modified. e.g.:</p>\n\n<pre><code> 4564 wiemann # $Id$\n 4564 wiemann # Author: David Goodger <goodger@python.org>\n 778 goodger # Copyright: This module has been placed in the public domain.\n 217 goodger \n</code></pre>\n"
},
{
"answer_id": 53640,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 1,
"selected": false,
"text": "<pre><code>svn annotate\n</code></pre>\n\n<p>The AKA <em>SVN Blame</em> from <a href=\"http://en.wikipedia.org/wiki/TortoiseSVN\" rel=\"nofollow noreferrer\">TortoiseSVN</a>.</p>\n"
},
{
"answer_id": 53644,
"author": "morechilli",
"author_id": 5427,
"author_profile": "https://Stackoverflow.com/users/5427",
"pm_score": 7,
"selected": true,
"text": "<p>I don't know a method for tracking statements through time in Subversion.</p>\n\n<p>It is simple however to see when any particular line in a file was last changed using <code>svn blame</code>. Check the SVNBook: <a href=\"http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.blame.html\" rel=\"noreferrer\"><code>svn blame</code> reference</a>:</p>\n\n<p><strong>Synopsis</strong></p>\n\n<pre><code>svn blame TARGET[@REV]...\n</code></pre>\n\n<p><strong>Description</strong></p>\n\n<p>Show author and revision information in-line for the specified files or URLs. Each line of text is annotated at the beginning with the author (username) and the revision number for the last change to that line.</p>\n"
},
{
"answer_id": 197895,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 6,
"selected": false,
"text": "<p>In the <a href=\"http://tortoisesvn.tigris.org/\" rel=\"noreferrer\">TortoiseSVN</a> client there is a very nice feature that lets you:</p>\n\n<ul>\n<li>blame a file, displaying the last change for each line (this is standard)</li>\n<li>\"blame previous revision\", after clicking on a particular line in the above view (this is the good one)</li>\n</ul>\n\n<p>The second feature does what it says - it shows the annotated revision preceding the last modification to the line. By using this feature iteratively, you can trace back through the history of a particular line.</p>\n"
},
{
"answer_id": 9137338,
"author": "atedja",
"author_id": 1015188,
"author_profile": "https://Stackoverflow.com/users/1015188",
"pm_score": 4,
"selected": false,
"text": "<p>I'd usually:</p>\n\n<ol>\n<li>Run <code>svn blame FILE</code> first.</li>\n<li>Note the last revision of the particular line.</li>\n<li><p>Do another query with the <code>-r</code> argument:</p>\n\n<pre><code>svn blame FILE -r 1:REV\n</code></pre></li>\n<li>Trace manually from there.</li>\n</ol>\n"
},
{
"answer_id": 27187583,
"author": "Serge Kutny",
"author_id": 1766641,
"author_profile": "https://Stackoverflow.com/users/1766641",
"pm_score": 3,
"selected": false,
"text": "<p>This can be done in two stages:</p>\n\n<ol>\n<li><code>svn blame /path/to/your/file > blame.tmp</code></li>\n<li><code>grep \"your_line_of_text\" blame.tmp</code></li>\n</ol>\n\n<p>You can delete blame.tmp file afterwards if you don't need it.</p>\n\n<p>In principle, a simple script can be written in any scripting language that does roughly the same.</p>\n"
},
{
"answer_id": 32481771,
"author": "Youssef NAIT",
"author_id": 4782694,
"author_profile": "https://Stackoverflow.com/users/4782694",
"pm_score": 2,
"selected": false,
"text": "<p>In <a href=\"http://en.wikipedia.org/wiki/Eclipse_%28software%29\" rel=\"nofollow noreferrer\">Eclipse</a> you can know when each line of your code has been committed using the SVN annotate view, or right click on the file → <em>Team</em> → <em>Show annotation...</em>. </p>\n"
},
{
"answer_id": 37281937,
"author": "tniles",
"author_id": 1228878,
"author_profile": "https://Stackoverflow.com/users/1228878",
"pm_score": 2,
"selected": false,
"text": "<p>The key here is how much history is required. As others have pointed out, the short answer is: <code>svn blame</code> (see <code>svn help blame</code> for details). If you're reaching far back in history or dealing with significant changes, you will likely need more than just this one command.</p>\n\n<p>I just had to do this myself, and found this (ye ole) thread here on SO. Here's what I did to solve it with just the <code>CLI</code>, specifically for my case where an API had changed (e.g. while porting someone's far outdated work (not on a branch, <em>arrgh!</em>) back into a feature branch based off of an up-to-date trunk). E.g. function names had changed enough to where it wasn't apparent which function needed to be called.</p>\n\n<h1>Step One</h1>\n\n<p>The following command allowed me to page through commits where things had changed in the file \"fileName.h\" and to see the corresponding revision number (note: you may have to alter the '10' for more or less context per your svn log text).</p>\n\n<p><code>svn log | grep -C 10 \"fileName.h\" | less</code> </p>\n\n<p><em>This results in a list of revisions in which this file was modified.</em></p>\n\n<h1>Step Two</h1>\n\n<p>Then it was a simple matter of using <code>blame</code> (or as others have pointed out, <code>annotate</code>) to narrow down to the revisions of interest.</p>\n\n<pre><code>cd trunk\nsvn blame fileName.h@r35948 | less\n</code></pre>\n\n<p><em>E.g. found the revision of interest was 35948.</em></p>\n\n<h1>Step Three</h1>\n\n<p>Having found the revision(s) of interest via blame, a diff can be produced to leverage the SVN tool. </p>\n\n<pre><code>svn diff -r35948:PREV fileName.h\n</code></pre>\n\n<h1>Conclusion</h1>\n\n<p>Having a visual diff made it much easier to identify the old API names with the newer/updated API names.</p>\n"
},
{
"answer_id": 57630362,
"author": "Harrison Mc",
"author_id": 7343786,
"author_profile": "https://Stackoverflow.com/users/7343786",
"pm_score": 0,
"selected": false,
"text": "<p>If you use Emacs, the built-in package <code>vc</code> can do this. </p>\n\n<ol>\n<li>Navigate to the file in question.</li>\n<li>Run the command <code>vc-annotate</code> with either <kbd>M-x</kbd> <code>vc-annotate</code> or <kbd>C-x</kbd><kbd>v</kbd><kbd>g</kbd>.</li>\n<li>Each line will show up with its revision, like a normal <code>svn blame</code>.</li>\n<li>Pressing <kbd>a</kbd> (<code>vc-annotate-revision-previous-to-line</code>) will navigate to the revision before the revision at the line you're on.</li>\n</ol>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1428/"
] | Is it possible to see the history of changes to a particular line of code in a Subversion repository?
I'd like, for instance, to be able to see when a particular statement was added or when that statement was changed, even if its line number is not the same any more. | I don't know a method for tracking statements through time in Subversion.
It is simple however to see when any particular line in a file was last changed using `svn blame`. Check the SVNBook: [`svn blame` reference](http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.blame.html):
**Synopsis**
```
svn blame TARGET[@REV]...
```
**Description**
Show author and revision information in-line for the specified files or URLs. Each line of text is annotated at the beginning with the author (username) and the revision number for the last change to that line. |
53,664 | <p>I've started using Vim to develop Perl scripts and am starting to find it very powerful. </p>
<p>One thing I like is to be able to open multiple files at once with:</p>
<pre><code>vi main.pl maintenance.pl
</code></pre>
<p>and then hop between them with:</p>
<pre><code>:n
:prev
</code></pre>
<p>and see which file are open with:</p>
<pre><code>:args
</code></pre>
<p>And to add a file, I can say: </p>
<pre><code>:n test.pl
</code></pre>
<p>which I expect would then be added to my list of files, but instead it wipes out my current file list and when I type <code>:args</code> I only have <code>test.pl</code> open.</p>
<p>So how can I add and remove files in my args list?</p>
| [
{
"answer_id": 53667,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<p>Vim (but not the original Vi!) has tabs which I find (in many contexts) superior to buffers. You can say <code>:tabe [filename]</code> to open a file in a new tab. Cycling between tabs is done by clicking on the tab or by the key combinations [<em>n</em>]<code>gt</code> and <code>gT</code>. Graphical Vim even has graphical tabs.</p>\n"
},
{
"answer_id": 53668,
"author": "fijter",
"author_id": 3215,
"author_profile": "https://Stackoverflow.com/users/3215",
"pm_score": 11,
"selected": true,
"text": "<p>Why not use tabs (introduced in Vim 7)?\nYou can switch between tabs with <code>:tabn</code> and <code>:tabp</code>,\nWith <code>:tabe <filepath></code> you can add a new tab; and with a regular <code>:q</code> or <code>:wq</code> you close a tab.\nIf you map <code>:tabn</code> and <code>:tabp</code> to your <kbd>F7</kbd>/<kbd>F8</kbd> keys you can easily switch between files.</p>\n\n<p>If there are not that many files or you don't have Vim 7 you can also split your screen in multiple files: <code>:sp <filepath></code>. Then you can switch between splitscreens with <kbd>Ctrl</kbd>+<kbd>W</kbd> and then an arrow key in the direction you want to move (or instead of arrow keys, <kbd>w</kbd> for next and <kbd>W</kbd> for previous splitscreen)</p>\n"
},
{
"answer_id": 53701,
"author": "MarkB",
"author_id": 2996,
"author_profile": "https://Stackoverflow.com/users/2996",
"pm_score": 7,
"selected": false,
"text": "<p>To add to the <code>args</code> list:</p>\n\n<pre><code>:argadd\n</code></pre>\n\n<p>To delete from the <code>args</code> list:</p>\n\n<pre><code>:argdelete\n</code></pre>\n\n<p>In your example, you could use <code>:argedit</code> test.pl to add test.pl to the <code>args</code> list and edit the file in one step.</p>\n\n<p><code>:help args</code> gives much more detail and advanced usage</p>\n"
},
{
"answer_id": 53702,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 6,
"selected": false,
"text": "<p>I think you may be using the wrong command for looking at the list of files that you have open.</p>\n\n<p>Try doing an <code>:ls</code> to see the list of files that you have open and you'll see:</p>\n\n<pre><code> 1 %a \"./checkin.pl\" line 1\n 2 # \"./grabakamailogs.pl\" line 1\n 3 \"./grabwmlogs.pl\" line 0\n etc.\n</code></pre>\n\n<p>You can then bounce through the files by referring to them by the numbers listed, e.g.\n:3b</p>\n\n<p>or you can split your screen by entering the number but using sb instead of just b.</p>\n\n<p>As an aside % refers to the file currently visible and # refers to the alternate file.</p>\n\n<p>You can easily toggle between these two files by pressing <kbd>Ctrl</kbd> <kbd>Shift</kbd> <kbd>6</kbd></p>\n\n<p>Edit: like <code>:ls</code> you can use <code>:reg</code> to see the current contents of your registers including the 0-9 registers that contain what you've deleted. This is especially useful if you want to reuse some text that you've previously deleted.</p>\n"
},
{
"answer_id": 53709,
"author": "Andy Whitfield",
"author_id": 4805,
"author_profile": "https://Stackoverflow.com/users/4805",
"pm_score": 6,
"selected": false,
"text": "<p>I use buffer commands - <code>:bn</code> (next buffer), <code>:bp</code> (previous buffer) <code>:buffers</code> (list open buffers) <code>:b<n></code> (open buffer n) <code>:bd</code> (delete buffer). <code>:e <filename></code> will just open into a new buffer.</p>\n"
},
{
"answer_id": 53714,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 9,
"selected": false,
"text": "<h3>Listing</h3>\n\n<p>To see a list of current buffers, I use:</p>\n\n<pre><code>:ls\n</code></pre>\n\n<hr>\n\n<h3>Opening</h3>\n\n<p>To open a new file, I use</p>\n\n<pre><code>:e ../myFile.pl\n</code></pre>\n\n<p>with enhanced tab completion (put <code>set wildmenu</code> in your <code>.vimrc</code>).</p>\n\n<p>Note: you can also use <code>:find</code> which will search a set of paths for you, but you need to customize those paths first.</p>\n\n<hr>\n\n<h3>Switching</h3>\n\n<p>To switch between all open files, I use</p>\n\n<pre><code>:b myfile\n</code></pre>\n\n<p>with enhanced tab completion (still <code>set wildmenu</code>).</p>\n\n<p>Note: <code>:b#</code> chooses the last visited file, so you can use it to switch quickly between two files.</p>\n\n<hr>\n\n<h3>Using windows</h3>\n\n<p><code>Ctrl-W s</code> and <code>Ctrl-W v</code> to split the current window horizontally and vertically. You can also use <code>:split</code> and <code>:vertical split</code> (<code>:sp</code> and <code>:vs</code>)</p>\n\n<p><code>Ctrl-W w</code> to switch between open windows, and <code>Ctrl-W h</code> (or <code>j</code> or <code>k</code> or <code>l</code>) to navigate through open windows.</p>\n\n<p><code>Ctrl-W c</code> to close the current window, and <code>Ctrl-W o</code> to close all windows except the current one.</p>\n\n<p>Starting vim with a <code>-o</code> or <code>-O</code> flag opens each file in its own split.</p>\n\n<hr>\n\n<p>With all these I don't need tabs in Vim, and my fingers find my buffers, not my eyes.</p>\n\n<p>Note: if you want all files to go to the same instance of Vim, start Vim with the <code>--remote-silent</code> option.</p>\n"
},
{
"answer_id": 63489,
"author": "indentation",
"author_id": 7706,
"author_profile": "https://Stackoverflow.com/users/7706",
"pm_score": 3,
"selected": false,
"text": "<p>If you are going to use multiple buffers, I think the most important thing is to\nset hidden\nso that it will let you switch buffers even if you have unsaved changes in the one you are leaving.</p>\n"
},
{
"answer_id": 64829,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 4,
"selected": false,
"text": "<p>When using multiple files in vim, I use these commands mostly (with ~350 files open):</p>\n\n<ul>\n<li><code>:b <partial filename><tab></code> (jump to a buffer)</li>\n<li><code>:bw</code> (buffer wipe, remove a buffer)</li>\n<li><code>:e <file path></code> (edit, open a new buffer></li>\n<li><code>pltags</code> - enable jumping to subroutine/method definitions</li>\n</ul>\n"
},
{
"answer_id": 65732,
"author": "shyam",
"author_id": 7616,
"author_profile": "https://Stackoverflow.com/users/7616",
"pm_score": 8,
"selected": false,
"text": "<pre><code>:ls\n</code></pre>\n\n<p>for list of open buffers</p>\n\n<ul>\n<li><code>:bp</code> previous buffer</li>\n<li><code>:bn</code> next buffer</li>\n<li><code>:bn</code> (<code>n</code> a number) move to n'th buffer</li>\n<li><code>:b <filename-part></code> with tab-key providing auto-completion (awesome !!)</li>\n</ul>\n\n<p>In some versions of vim, <code>bn</code> and <code>bp</code> are actually <code>bnext</code> and <code>bprevious</code> respectively. Tab auto-complete is helpful in this case.</p>\n\n<p>Or when you are in normal mode, use <code>^</code> to switch to the last file you were working on.</p>\n\n<p>Plus, you can save sessions of vim</p>\n\n<pre><code>:mksession! ~/today.ses\n</code></pre>\n\n<p>The above command saves the current open file buffers and settings to <code>~/today.ses</code>. You can load that session by using</p>\n\n<pre><code>vim -S ~/today.ses\n</code></pre>\n\n<p>No hassle remembering where you left off yesterday. ;)</p>\n"
},
{
"answer_id": 75793,
"author": "projecktzero",
"author_id": 13380,
"author_profile": "https://Stackoverflow.com/users/13380",
"pm_score": 2,
"selected": false,
"text": "<p>I use multiple buffers that are set hidden in my <code>~/.vimrc</code> file.</p>\n\n<p>The mini-buffer explorer script is nice too to get a nice compact listing of your buffers. Then <code>:b1</code> or <code>:b2</code>... to go to the appropriate buffer or use the mini-buffer explorer and tab through the buffers.</p>\n"
},
{
"answer_id": 83984,
"author": "Max Cantor",
"author_id": 16034,
"author_profile": "https://Stackoverflow.com/users/16034",
"pm_score": 4,
"selected": false,
"text": "<p>I use the same .vimrc file for gVim and the command line Vim. I tend to use tabs in gVim and buffers in the command line Vim, so I have my .vimrc set up to make working with both of them easier:</p>\n\n<pre><code>\" Movement between tabs OR buffers\nnnoremap L :call MyNext()<CR>\nnnoremap H :call MyPrev()<CR>\n\n\" MyNext() and MyPrev(): Movement between tabs OR buffers\nfunction! MyNext()\n if exists( '*tabpagenr' ) && tabpagenr('$') != 1\n \" Tab support && tabs open\n normal gt\n else\n \" No tab support, or no tabs open\n execute \":bnext\"\n endif\nendfunction\nfunction! MyPrev()\n if exists( '*tabpagenr' ) && tabpagenr('$') != '1'\n \" Tab support && tabs open\n normal gT\n else\n \" No tab support, or no tabs open\n execute \":bprev\"\n endif\nendfunction\n</code></pre>\n\n<p>This clobbers the existing mappings for <kbd>H</kbd> and <kbd>L</kbd>, but it makes switching between files extremely fast and easy. Just hit <kbd>H</kbd> for next and <kbd>L</kbd> for previous; whether you're using tabs or buffers, you'll get the intended results.</p>\n"
},
{
"answer_id": 8436685,
"author": "puk",
"author_id": 654789,
"author_profile": "https://Stackoverflow.com/users/654789",
"pm_score": 5,
"selected": false,
"text": "<p>Things like <code>:e</code> and <code>:badd</code> will only accept ONE argument, therefore the following will fail</p>\n\n<pre><code>:e foo.txt bar.txt\n:e /foo/bar/*.txt\n:badd /foo/bar/*\n</code></pre>\n\n<p>If you want to add multiple files from within vim, use <code>arga[dd]</code></p>\n\n<pre><code>:arga foo.txt bar.txt\n:arga /foo/bar/*.txt\n:argadd /foo/bar/*\n</code></pre>\n"
},
{
"answer_id": 16854181,
"author": "Cpt. Senkfuss",
"author_id": 1823536,
"author_profile": "https://Stackoverflow.com/users/1823536",
"pm_score": 0,
"selected": false,
"text": "<p>if you're on osx and want to be able to click on your tabs, use MouseTerm and SIMBL (taken from <a href=\"http://ayaz.wordpress.com/2010/10/19/using-mouse-inside-vim-on-terminal-app/\" rel=\"nofollow noreferrer\">here</a>). Also, check out this <a href=\"https://stackoverflow.com/questions/1727261/scrolling-inside-vim-in-macs-terminal?rq=1\">related discussion</a>.</p>\n"
},
{
"answer_id": 17536403,
"author": "user2179522",
"author_id": 2179522,
"author_profile": "https://Stackoverflow.com/users/2179522",
"pm_score": 4,
"selected": false,
"text": "<p>You may want to use <a href=\"http://vim.wikia.com/wiki/Using_marks\" rel=\"noreferrer\">Vim global marks</a>.</p>\n\n<p>This way you can quickly bounce between files, and even to the marked location in the file. Also, the key commands are short:\n <code>'C</code> takes me to the code I'm working with,\n <code>'T</code> takes me to the unit test I'm working with.</p>\n\n<p>When you change places, resetting the marks is quick too:\n <code>mC</code> marks the new code spot,\n <code>mT</code> marks the new test spot.</p>\n"
},
{
"answer_id": 20964867,
"author": "user2663398",
"author_id": 2663398,
"author_profile": "https://Stackoverflow.com/users/2663398",
"pm_score": 2,
"selected": false,
"text": "<p>have a try following maps for convenience editing multiple files</p>\n\n<p>\" split windows</p>\n\n<p><code>nmap <leader>sh :leftabove vnew<CR></code></p>\n\n<p><code>nmap <leader>sl :rightbelow vnew<CR></code></p>\n\n<p><code>nmap <leader>sk :leftabove new<CR></code></p>\n\n<p><code>nmap <leader>sj :rightbelow new<CR></code></p>\n\n<p>\" moving around</p>\n\n<p><code>nmap <C-j> <C-w>j</code></p>\n\n<p><code>nmap <C-k> <C-w>k</code></p>\n\n<p><code>nmap <C-l> <C-w>l</code></p>\n\n<p><code>nmap <C-h> <C-w>h</code></p>\n"
},
{
"answer_id": 21220765,
"author": "Michael Durrant",
"author_id": 631619,
"author_profile": "https://Stackoverflow.com/users/631619",
"pm_score": 3,
"selected": false,
"text": "<p>My way to effectively work with multiple files is to use tmux.</p>\n\n<p>It allows you to split windows vertically and horizontally, as in:</p>\n\n<p><img src=\"https://i.stack.imgur.com/XDnTX.png\" alt=\"enter image description here\"></p>\n\n<p>I have it working this way on both my mac and linux machines and I find it better than the native window pane switching mechanism that's provided (on Macs). I find the switching easier and only with tmux have I been able to get the 'new page at the same current directory' working on my mac (despite the fact that there seems to be options to open new panes in the same directory) which is a surprisingly critical piece. An instant new pane at the current location is amazingly useful. A method that does new panes with the same key combos for both OS's is critical for me and a bonus for all for future personal compatibility.\nAside from multiple tmux panes, I've also tried using multiple tabs, e.g. <img src=\"https://i.stack.imgur.com/O0N8A.png\" alt=\"enter image description here\"> and multiple new windows, e.g. <img src=\"https://i.stack.imgur.com/TpErK.png\" alt=\"enter image description here\"> and ultimately I've found that multiple tmux panes to be the most useful for me. I am very 'visual' and like to keep my various contexts right in front of me, connected together as panes. </p>\n\n<p>tmux also support horizontal and vertical panes which the older <code>screen</code> didn't (though mac's iterm2 seems to support it, but again, the current directory setting didn't work for me). tmux 1.8 </p>\n"
},
{
"answer_id": 24555993,
"author": "Jens",
"author_id": 925649,
"author_profile": "https://Stackoverflow.com/users/925649",
"pm_score": 2,
"selected": false,
"text": "<p>I use the command line and git a lot, so I have this alias in my bashrc:</p>\n\n<pre><code>alias gvim=\"gvim --servername \\$(git rev-parse --show-toplevel || echo 'default') --remote-tab\"\n</code></pre>\n\n<p>This will open each new file in a new tab on an existing window and will create one window for each git repository.\nSo if you open two files from repo A, and 3 files from repo B, you will end up with two windows, one for repo A with two tabs and one for repo B with three tabs.</p>\n\n<p>If the file you are opening is not contained in a git repo it will go to a default window.</p>\n\n<p>To jump between tabs I use these mappings:</p>\n\n<pre><code>nmap <C-p> :tabprevious<CR>\nnmap <C-n> :tabnext<CR>\n</code></pre>\n\n<p>To open multiple files at once you should combine this with one of the other solutions.</p>\n"
},
{
"answer_id": 29597152,
"author": "superarts.org",
"author_id": 772295,
"author_profile": "https://Stackoverflow.com/users/772295",
"pm_score": 1,
"selected": false,
"text": "<p>When I started using VIM I didn't realize that tabs were supposed to be used as different window layouts, and buffer serves the role for multiple file editing / switching between each other. Actually in the beginning tabs are not even there before v7.0 and I just opened one VIM inside a terminal tab (I was using gnome-terminal at the moment), and switch between tabs using alt+numbers, since I thought using commands like :buffers, :bn and :bp were too much for me. When VIM 7.0 was released I find it's easier to manager a lot of files and switched to it, but recently I just realized that buffers should always be the way to go, unless one thing: you need to configure it to make it works right.</p>\n\n<p>So I tried vim-airline and enabled the visual on-top tab-like buffer bar, but graphic was having problem with my iTerm2, so I tried a couple of others and it seems that MBE works the best for me. I also set shift+h/l as shortcuts, since the original ones (moving to the head/tail of the current page) is not very useful to me.<br>\n<br>\n<code>map <S-h> :bprev<Return></code>\n<br>\n<code>map <S-l> :bnext<Return></code></p>\n\n<p>It seems to be even easier than gt and gT, and :e is easier than :tabnew too. I find :bd is not as convenient as :q though (MBE is having some problem with it) but I can live with all files in buffer I think.</p>\n"
},
{
"answer_id": 30915769,
"author": "Andrew",
"author_id": 1977609,
"author_profile": "https://Stackoverflow.com/users/1977609",
"pm_score": 5,
"selected": false,
"text": "<p>Some answers in this thread suggest using tabs and others suggest using buffer to accomplish the same thing. Tabs and Buffers are different. I strongly suggest you read this article \"<a href=\"https://joshldavis.com/2014/04/05/vim-tab-madness-buffers-vs-tabs/\" rel=\"noreferrer\">Vim Tab madness - Buffers vs Tabs</a>\".</p>\n\n<p>Here's a nice summary I pulled from the article:</p>\n\n<p>Summary:</p>\n\n<ul>\n<li>A buffer is the in-memory text of a file.</li>\n<li>A window is a viewport on a buffer.</li>\n<li>A tab page is a collection of windows.</li>\n</ul>\n"
},
{
"answer_id": 34109581,
"author": "fede1024",
"author_id": 1025899,
"author_profile": "https://Stackoverflow.com/users/1025899",
"pm_score": 2,
"selected": false,
"text": "<p>I made a <a href=\"https://www.youtube.com/watch?v=baNUGVAoX8M\" rel=\"nofollow\">very simple video</a> showing the workflow that I use. Basically I use the <a href=\"https://github.com/kien/ctrlp.vim\" rel=\"nofollow\">Ctrl-P</a> Vim plugin, and I mapped the buffer navigation to the Enter key.</p>\n\n<p>In this way I can press Enter in normal mode, look at the list of open files (that shows up in a small new window at the bottom of the screen), select the file I want to edit and press Enter again. To quickly search through multiple open files, just type part of the file name, select the file and press Enter.</p>\n\n<p>I don't have many files open in the video, but it becomes incredibly helpful when you start having a lot of them.</p>\n\n<p>Since the plugin sorts the buffers using a MRU ordering, you can just press Enter twice and jump to the most recent file you were editing.</p>\n\n<p>After the plugin is installed, the only configuration you need is:</p>\n\n<pre><code>nmap <CR> :CtrlPBuffer<CR>\n</code></pre>\n\n<p>Of course you can map it to a different key, but I find the mapping to enter to be very handy.</p>\n"
},
{
"answer_id": 35669509,
"author": "Dionysis",
"author_id": 1236333,
"author_profile": "https://Stackoverflow.com/users/1236333",
"pm_score": 1,
"selected": false,
"text": "<p>Most of the answers in this thread are using plain vim commands which is of course fine but I thought I would provide an extensive answer using a combination of plugins and functions that I find particularly useful (at least some of these tips came from <a href=\"https://www.destroyallsoftware.com/file-navigation-in-vim.html\" rel=\"nofollow\">Gary Bernhardt's file navigation tips</a>):</p>\n\n<ol>\n<li><p>To toggle between the last two file just press <code><leader></code> twice. I recommend assigning <code><leader></code> to the spacebar:</p>\n\n<pre><code>nnoremap <leader><leader> <c-^>\n</code></pre></li>\n<li><p>For quickly moving around a project the answer is a fuzzy matching solution such as <a href=\"https://github.com/ctrlpvim/ctrlp.vim\" rel=\"nofollow\">CtrlP</a>. I bind it to <code><leader>a</code> for quick access.</p></li>\n<li><p>In the case I want to see a visual representation of the currently open buffers I use <a href=\"https://github.com/jlanzarotta/bufexplorer\" rel=\"nofollow\">the BufExplorer plugin</a>. Simple but effective.</p></li>\n<li><p>If I want to browse around the file system I would use the command line or an external utility (Quicklsilver, Afred etc.) but to look at the current project structure <a href=\"https://github.com/scrooloose/nerdtree\" rel=\"nofollow\">NERD Tree</a> is a classic. Do not use this though in the place of <code>2</code> as your main file finding method. It will really slow you down. I use the binding <code><leader>ff</code>.</p></li>\n</ol>\n\n<p>These should be enough for finding and opening files. From there of course use horizontal and vertical splits. Concerning splits I find these functions particularly useful:</p>\n\n<ol>\n<li><p>Open new splits in smaller areas when there is not enough room and expand them on navigation. Refer <a href=\"https://www.destroyallsoftware.com/file-navigation-in-vim.html\" rel=\"nofollow\">here</a> for comments on what these do exactly:</p>\n\n<pre><code>set winwidth=84\nset winheight=5\nset winminheight=5\nset winheight=999\n\nnnoremap <C-w>v :111vs<CR>\nnnoremap <C-w>s :rightbelow split<CR>\nset splitright\n</code></pre></li>\n<li><p>Move from split to split easily:</p>\n\n<pre><code>nnoremap <C-J> <C-W><C-J>\nnnoremap <C-K> <C-W><C-K>\nnnoremap <C-L> <C-W><C-L>\nnnoremap <C-H> <C-W><C-H>\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 36332558,
"author": "Petur Subev",
"author_id": 332124,
"author_profile": "https://Stackoverflow.com/users/332124",
"pm_score": 5,
"selected": false,
"text": "<p>Many answers here! What I use without reinventing the wheel - the most famous plugins (that are not going to die any time soon and are used by many people) to be ultra fast and geeky.</p>\n\n<ul>\n<li><strong>ctrlpvim/ctrlp.vim</strong> - to find file by name fuzzy search by its location or just its name</li>\n<li><strong>jlanzarotta/bufexplorer</strong> - to browse opened buffers (when you do not remember how many files you opened and modified recently and you do not remember where they are, probably because you searched for them with Ag)</li>\n<li><strong>rking/ag.vim</strong> to search the files with respect to gitignore</li>\n<li><strong>scrooloose/nerdtree</strong> to see the directory structure, lookaround, add/delete/modify files</li>\n</ul>\n\n<p><strong>EDIT:</strong> Recently I have been using <strong>dyng/ctrlsf.vim</strong> to search with contextual view (like Sublime search) and I switched the engine from <strong>ag</strong> to <strong>ripgrep</strong>. The performance is outstanding.</p>\n\n<p><strong>EDIT2:</strong> Along with <strong>CtrlSF</strong> you can use <strong>mg979/vim-visual-multi</strong>, make changes to multiple files at once and then at the end save them in one go.</p>\n"
},
{
"answer_id": 44647932,
"author": "qeatzy",
"author_id": 3625404,
"author_profile": "https://Stackoverflow.com/users/3625404",
"pm_score": 4,
"selected": false,
"text": "<p>If <strong>using only vim built-in commands</strong>, the best one that I ever saw to switch among multiple buffers is this:</p>\n\n<pre><code>nnoremap <Leader>f :set nomore<Bar>:ls<Bar>:set more<CR>:b<Space>\n</code></pre>\n\n<p><strong>It perfectly combines both <code>:ls</code> and <code>:b</code> commands -- listing all opened buffers and waiting for you to input the command to switch buffer.</strong></p>\n\n<p>Given above mapping in vimrc, once you type <code><Leader>f</code>,</p>\n\n<ul>\n<li>All opened buffers are displayed</li>\n<li>You can:\n\n<ul>\n<li>Type <code>23</code> to go to buffer 23,</li>\n<li>Type <code>#</code> to go to the alternative/MRU buffer,</li>\n<li>Type partial name of file, then type <code><Tab></code>, or <code><C-i></code> to autocomplete,</li>\n<li>Or just <code><CR></code> or <code><Esc></code> to stay on current buffer</li>\n</ul></li>\n</ul>\n\n<p>A snapshot of output for the above key mapping is:</p>\n\n<pre><code>:set nomore|:ls|:set more\n 1 h \"script.py\" line 1\n 2 #h + \"file1.txt\" line 6 -- '#' for alternative buffer\n 3 %a \"README.md\" line 17 -- '%' for current buffer\n 4 \"file3.txt\" line 0 -- line 0 for hasn't switched to\n 5 + \"/etc/passwd\" line 42 -- '+' for modified\n:b '<Cursor> here'\n</code></pre>\n\n<p>In the above snapshot:</p>\n\n<ul>\n<li>Second column: <code>%a</code> for current, <code>h</code> for hidden, <code>#</code> for previous, empty for hasn't been switched to.</li>\n<li>Third column: <code>+</code> for modified.</li>\n</ul>\n\n<p>Also, I strongly suggest <code>set hidden</code>. See <code>:help 'hidden'</code>.</p>\n"
},
{
"answer_id": 44935024,
"author": "dlmeetei",
"author_id": 1389898,
"author_profile": "https://Stackoverflow.com/users/1389898",
"pm_score": 4,
"selected": false,
"text": "<p>To change all buffers to <code>tab</code> view.</p>\n<pre><code> :tab sball\n</code></pre>\n<p>will open all the buffers to tab view. Then we can use any tab related commands</p>\n<pre><code>gt or :tabn " go to next tab\ngT or :tabp or :tabN " go to previous tab\n</code></pre>\n<p>details at <code>:help tab-page-commands</code>.</p>\n<p>We can instruct vim to open ,as tab view, multiple files by <code>vim -p file1 file2</code>.\n<code>alias vim='vim -p'</code> will be useful.<br />\nThe same thing can also be achieved by having following autocommand in <code>~/.vimrc</code></p>\n<pre><code> au VimEnter * if !&diff | tab all | tabfirst | endif\n</code></pre>\n<hr />\n<p>Anyway to answer the question:\nTo add to arg list: <code>arga file</code>,</p>\n<p>To delete from arg list: <code>argd pattern</code></p>\n<p>More at <code>:help arglist</code></p>\n"
},
{
"answer_id": 45770452,
"author": "icc97",
"author_id": 327074,
"author_profile": "https://Stackoverflow.com/users/327074",
"pm_score": 3,
"selected": false,
"text": "<p>I use the following, this gives you lots of features that you'd expect to have in other editors such as Sublime Text / Textmate</p>\n\n<ol>\n<li>Use buffers not 'tab pages'. Buffers are the same concept as tabs in almost all other editors.</li>\n<li>If you want the same look of having tabs you can use the <a href=\"https://github.com/vim-airline/vim-airline\" rel=\"noreferrer\">vim-airline</a> plugin with the following setting in your <code>.vimrc</code>: <code>let g:airline#extensions#tabline#enabled = 1</code>. This automatically displays all the buffers as tab headers when you have no tab pages opened</li>\n<li>Use Tim Pope's <a href=\"https://github.com/tpope/vim-unimpaired\" rel=\"noreferrer\">vim-unimpaired</a> which gives <kbd>[</kbd><kbd>b</kbd> and <kbd>]</kbd><kbd>b</kbd> for moving to previous/next buffers respectively (plus a whole host of other goodies)</li>\n<li>Have <code>set wildmenu</code> in your <code>.vimrc</code> then when you type <code>:b <file part></code> + <kbd>Tab</kbd> for a buffer you will get a list of possible buffers that you can use left/right arrows to scroll through</li>\n<li>Use Tim Pope's <a href=\"https://github.com/tpope/vim-obsession\" rel=\"noreferrer\">vim-obsession</a> plugin to store sessions that play nicely with airline (I had <a href=\"https://github.com/vim-airline/vim-airline/issues/1505#issuecomment-316848122\" rel=\"noreferrer\">lots of pain with sessions and plugins</a>)</li>\n<li>Use Tim Pope's <a href=\"https://github.com/tpope/vim-vinegar\" rel=\"noreferrer\">vim-vinegar</a> plugin. This works with the native <code>:Explore</code> but makes it much easier to work with. You just type <code>-</code> to open the explorer, which is the same key as to go up a directory in the explorer. Makes navigating faster (however with fzf I rarely use this)</li>\n<li><a href=\"https://github.com/junegunn/fzf#as-vim-plugin\" rel=\"noreferrer\">fzf</a> (which can be installed as a vim plugin) is also a really powerful fuzzy finder that you can use for searching for files (and buffers too). fzf also <a href=\"https://github.com/junegunn/fzf#tips\" rel=\"noreferrer\">plays very nicely</a> with fd (a faster version of find)</li>\n<li>Use <a href=\"https://github.com/BurntSushi/ripgrep\" rel=\"noreferrer\">Ripgrep</a> with <a href=\"https://github.com/jremmen/vim-ripgrep\" rel=\"noreferrer\">vim-ripgrep</a> to search through your code base and then you can use <code>:cdo</code> on the results to do search and replace</li>\n</ol>\n"
},
{
"answer_id": 46858244,
"author": "npit",
"author_id": 3532255,
"author_profile": "https://Stackoverflow.com/users/3532255",
"pm_score": 0,
"selected": false,
"text": "<p>You can be an <em>absolute madman</em> and alias <code>vim</code> to <code>vim -p</code> by adding in your <code>.bashrc</code>:</p>\n<pre><code>alias vim="vim -p"\n</code></pre>\n<p>This will result in opening multiple files from the shell in tabs, without having to invoke <code>:tab ball</code> from within vim afterwards.</p>\n"
},
{
"answer_id": 50671995,
"author": "thenakulchawla",
"author_id": 4057016,
"author_profile": "https://Stackoverflow.com/users/4057016",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest using the plugin </p>\n\n<blockquote>\n <p>NERDtree</p>\n</blockquote>\n\n<p>Here is the github link with instructions.</p>\n\n<p><a href=\"https://github.com/scrooloose/nerdtree\" rel=\"nofollow noreferrer\">Nerdtree</a></p>\n\n<p>I use vim-plug as a plugin manager, but you can use Vundle as well.</p>\n\n<p><a href=\"https://github.com/junegunn/vim-plug\" rel=\"nofollow noreferrer\">vim-plug</a></p>\n\n<p><a href=\"https://github.com/VundleVim/Vundle.vim\" rel=\"nofollow noreferrer\">Vundle</a></p>\n"
},
{
"answer_id": 59810540,
"author": "Mou Sam Dahal",
"author_id": 10048518,
"author_profile": "https://Stackoverflow.com/users/10048518",
"pm_score": 3,
"selected": false,
"text": "<p>In my and other many vim users, the best option is to,</p>\n<ul>\n<li>Open the file using,</li>\n</ul>\n<blockquote>\n<p>:e file_name.extension</p>\n</blockquote>\n<p>And then just <kbd>Ctrl</kbd> + <kbd>6</kbd> to change to the last buffer. Or, you can always press</p>\n<blockquote>\n<p>:ls to list the buffer and then change the buffer using b followed by the buffer number.</p>\n</blockquote>\n<ul>\n<li>We make a vertical or horizontal split using</li>\n</ul>\n<blockquote>\n<p>:vsp for vertical split</p>\n<p>:sp for horizantal split</p>\n</blockquote>\n<p>And then <code><C-W><C-H/K/L/j></code> to change the working split.</p>\n<p><strong>You can ofcourse edit any file in any number of splits.</strong></p>\n"
},
{
"answer_id": 66870832,
"author": "Aram Simonyan",
"author_id": 14274837,
"author_profile": "https://Stackoverflow.com/users/14274837",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li><p>To open 2 or more files with vim type: <code>vim -p file1 file2</code></p>\n</li>\n<li><p>After that command to go threw that files you can use <kbd>CTRL</kbd>+<kbd>Shift</kbd>+<kbd>↑</kbd> or <kbd>↓</kbd> , it will change your files in vim.</p>\n</li>\n<li><p>If u want to add one more file vim and work on it use: <code>:tabnew file3</code></p>\n</li>\n<li><p>Also u can use which will not create a new tab and will open file on screen slicing your screen: <code>:new file3</code></p>\n</li>\n<li><p>If u want to use a plugin that will help u work with directories\nand files i suggest u <a href=\"https://github.com/scrooloose/nerdtree\" rel=\"nofollow noreferrer\">NERDTree</a>.</p>\n</li>\n<li><p>To download it u need to have vim-plug so to download other plugins also NERDTree to type this commands in your <code>~/.vimrc</code>.</p>\n</li>\n</ol>\n<pre><code> let data_dir = has('nvim') ? stdpath('data') . '/site' : '~/.vim'\n if empty(glob(data_dir . '/autoload/plug.vim'))\n silent execute '!curl -fLo '.data_dir.'/autoload/plug.vim --create-dirs \n https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'\n autocmd VimEnter * PlugInstall --sync | source $MYVIMRC\n endif\n\n call plug#begin('~/.vim/plugged')\n Plug 'scrooloose/nerdtree'\n call plug#end()\n</code></pre>\n<ol start=\"7\">\n<li>Then save .vimrc via command <code>:wq</code> , get back to it and type: <code>:PlugInstall</code></li>\n</ol>\n<p>After that the plugins will be installed and u could use your NERDTree with other plugins.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] | I've started using Vim to develop Perl scripts and am starting to find it very powerful.
One thing I like is to be able to open multiple files at once with:
```
vi main.pl maintenance.pl
```
and then hop between them with:
```
:n
:prev
```
and see which file are open with:
```
:args
```
And to add a file, I can say:
```
:n test.pl
```
which I expect would then be added to my list of files, but instead it wipes out my current file list and when I type `:args` I only have `test.pl` open.
So how can I add and remove files in my args list? | Why not use tabs (introduced in Vim 7)?
You can switch between tabs with `:tabn` and `:tabp`,
With `:tabe <filepath>` you can add a new tab; and with a regular `:q` or `:wq` you close a tab.
If you map `:tabn` and `:tabp` to your `F7`/`F8` keys you can easily switch between files.
If there are not that many files or you don't have Vim 7 you can also split your screen in multiple files: `:sp <filepath>`. Then you can switch between splitscreens with `Ctrl`+`W` and then an arrow key in the direction you want to move (or instead of arrow keys, `w` for next and `W` for previous splitscreen) |
53,676 | <p>When trying to connect to an <code>ORACLE</code> user via TOAD (Quest Software) or any other means (<code>Oracle Enterprise Manager</code>) I get this error:</p>
<blockquote>
<p><code>ORA-011033: ORACLE initialization or shutdown in progress</code></p>
</blockquote>
| [
{
"answer_id": 53684,
"author": "rohancragg",
"author_id": 5351,
"author_profile": "https://Stackoverflow.com/users/5351",
"pm_score": 8,
"selected": true,
"text": "<p>After some googling, I found the advice to do the following, and it worked:</p>\n\n<pre><code>SQL> startup mount\n\nORACLE Instance started\n\nSQL> recover database \n\nMedia recovery complete\n\nSQL> alter database open;\n\nDatabase altered\n</code></pre>\n"
},
{
"answer_id": 142790,
"author": "JoshL",
"author_id": 20625,
"author_profile": "https://Stackoverflow.com/users/20625",
"pm_score": 3,
"selected": false,
"text": "<p>This error can also occur in the normal situation when a database is starting or stopping. Normally on startup you can wait until the startup completes, then connect as usual. If the error persists, the <em>service</em> (on a Windows box) may be started without the <em>database</em> being started. This may be due to startup issues, or because the service is not configured to automatically start the database. In this case you will have to connect as sysdba and physically start the database using the \"startup\" command.</p>\n"
},
{
"answer_id": 21298642,
"author": "z atef",
"author_id": 2052097,
"author_profile": "https://Stackoverflow.com/users/2052097",
"pm_score": 5,
"selected": false,
"text": "<p>Here is my solution to this issue:</p>\n\n<pre><code>SQL> Startup mount\nORA-01081: cannot start already-running ORACLE - shut it down first\nSQL> shutdown abort\nORACLE instance shut down.\nSQL>\nSQL> startup mount\nORACLE instance started.\n\nTotal System Global Area 1904054272 bytes\nFixed Size 2404024 bytes\nVariable Size 570425672 bytes\nDatabase Buffers 1325400064 bytes\nRedo Buffers 5824512 bytes\nDatabase mounted.\nSQL> Show parameter control_files\n\nNAME TYPE VALUE\n------------------------------------ ----------- ------------------------------\ncontrol_files string C:\\APP\\USER\\ORADATA\\ORACLEDB\\C\n ONTROL01.CTL, C:\\APP\\USER\\FAST\n _RECOVERY_AREA\\ORACLEDB\\CONTRO\n L02.CTL\nSQL> select a.member,a.group#,b.status from v$logfile a ,v$log b where a.group#=\nb.group# and b.status='CURRENT'\n 2\nSQL> select a.member,a.group#,b.status from v$logfile a ,v$log b where a.group#=\nb.group# and b.status='CURRENT';\n\nMEMBER\n--------------------------------------------------------------------------------\n\n GROUP# STATUS\n---------- ----------------\nC:\\APP\\USER\\ORADATA\\ORACLEDB\\REDO03.LOG\n 3 CURRENT\n\n\nSQL> shutdown abort\nORACLE instance shut down.\nSQL> startup mount\nORACLE instance started.\n\nTotal System Global Area 1904054272 bytes\nFixed Size 2404024 bytes\nVariable Size 570425672 bytes\nDatabase Buffers 1325400064 bytes\nRedo Buffers 5824512 bytes\nDatabase mounted.\nSQL> recover database using backup controlfile until cancel;\nORA-00279: change 4234808 generated at 01/21/2014 18:31:05 needed for thread 1\nORA-00289: suggestion :\nC:\\APP\\USER\\FAST_RECOVERY_AREA\\ORACLEDB\\ARCHIVELOG\\2014_01_22\\O1_MF_1_108_%U_.AR\n\nC\nORA-00280: change 4234808 for thread 1 is in sequence #108\n\n\nSpecify log: {<RET>=suggested | filename | AUTO | CANCEL}\nC:\\APP\\USER\\ORADATA\\ORACLEDB\\REDO03.LOG\nLog applied.\nMedia recovery complete.\nSQL> alter database open resetlogs;\n\nDatabase altered.\n</code></pre>\n\n<p>And it worked:</p>\n\n<p><img src=\"https://i.stack.imgur.com/TXcoQ.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 35026997,
"author": "gadildafissh",
"author_id": 811058,
"author_profile": "https://Stackoverflow.com/users/811058",
"pm_score": 2,
"selected": false,
"text": "<p>I used a combination of the answers from rohancragg, Mukul Goel, and NullSoulException from above. However I had an additional error: </p>\n\n<p>ORA-01157: cannot identify/lock data file string - see DBWR trace file</p>\n\n<p>To which I found the answer here: <a href=\"http://nimishgarg.blogspot.com/2014/01/ora-01157-cannot-identifylock-data-file.html\" rel=\"nofollow\">http://nimishgarg.blogspot.com/2014/01/ora-01157-cannot-identifylock-data-file.html</a></p>\n\n<p>Incase the above post gets deleted I am including the commands here as well.</p>\n\n<pre><code>C:\\>sqlplus sys/sys as sysdba\nSQL*Plus: Release 11.2.0.3.0 Production on Tue Apr 30 19:07:16 2013\nCopyright (c) 1982, 2011, Oracle. All rights reserved.\nConnected to an idle instance.\n\nSQL> startup\nORACLE instance started.\nTotal System Global Area 778387456 bytes\nFixed Size 1384856 bytes\nVariable Size 520097384 bytes\nDatabase Buffers 251658240 bytes\nRedo Buffers 5246976 bytes\nDatabase mounted.\nORA-01157: cannot identify/lock data file 11 – see DBWR trace file\nORA-01110: data file 16: 'E:\\oracle\\app\\nimish.garg\\oradata\\orcl\\test_ts.dbf'\n\nSQL> select NAME from v$datafile where file#=16;\nNAME\n--------------------------------------------------------------------------------\nE:\\ORACLE\\APP\\NIMISH.GARG\\ORADATA\\ORCL\\TEST_TS.DBF\n\nSQL> alter database datafile 16 OFFLINE DROP;\nDatabase altered.\n\nSQL> alter database open;\nDatabase altered.\n</code></pre>\n\n<p>Thanks everyone you saved my day!</p>\n\n<p>Fissh</p>\n"
},
{
"answer_id": 43871217,
"author": "Witold Kaczurba",
"author_id": 6931119,
"author_profile": "https://Stackoverflow.com/users/6931119",
"pm_score": 5,
"selected": false,
"text": "<p>I had a similar problem when I had installed the 12c database as per <a href=\"http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/12c/r1/Windows_DB_Install_OBE/Installing_Oracle_Db12c_Windows.html\" rel=\"noreferrer\">Oracle's tutorial</a> . The instruction instructs reader to create a PLUGGABLE DATABASE (pdb). </p>\n\n<h2>The problem</h2>\n\n<p><code>sqlplus hr/hr@pdborcl</code> would result in <strong><code>ORACLE initialization or shutdown in progress</code></strong>.</p>\n\n<h2>The solution</h2>\n\n<ul>\n<li><ol>\n<li><p><strong>Login as <code>SYSDBA</code> to the dabase</strong> : </p>\n\n<pre><code>sqlplus SYS/Oracle_1@pdborcl AS SYSDBA\n</code></pre></li>\n</ol></li>\n<li><ol start=\"2\">\n<li><p><strong>Alter database</strong>: </p>\n\n<pre><code>alter pluggable database pdborcl open read write;\n</code></pre></li>\n</ol></li>\n<li><ol start=\"3\">\n<li><p><strong>Login again</strong>: </p>\n\n<pre><code>sqlplus hr/hr@pdborcl\n</code></pre></li>\n</ol></li>\n</ul>\n\n<p><em>That worked for me</em></p>\n\n<p>Some documentation <a href=\"https://docs.oracle.com/database/121/SQLRF/statements_2008.htm#SQLRF55667\" rel=\"noreferrer\">here</a></p>\n"
},
{
"answer_id": 45348175,
"author": "Alan Hollis",
"author_id": 346271,
"author_profile": "https://Stackoverflow.com/users/346271",
"pm_score": 2,
"selected": false,
"text": "<p>The issue can also be due to lack of hard drive space. The installation will succeed but on startup, oracle won't be able to create the required files and will fail with the same above error message.</p>\n"
},
{
"answer_id": 54326242,
"author": "Goku",
"author_id": 10631120,
"author_profile": "https://Stackoverflow.com/users/10631120",
"pm_score": 2,
"selected": false,
"text": "<p>I hope this will help somebody, I solved the problem like this</p>\n\n<p>There was a problem because the database was not open.\nCommand startup opens the database.</p>\n\n<p>This you can solve with command <code>alter database open</code> \nin some case with <code>alter database open resetlogs</code></p>\n\n<pre><code>$ sqlplus / sysdba\n\nSQL> startup\nORACLE instance started.\n\nTotal System Global Area 1073741824 bytes\nFixed Size 8628936 bytes\nVariable Size 624952632 bytes\nDatabase Buffers 436207616 bytes\nRedo Buffers 3952640 bytes\nDatabase mounted.\nDatabase opened.\n\nSQL> conn user/pass123\nConnected.\n</code></pre>\n"
},
{
"answer_id": 54340339,
"author": "Hari",
"author_id": 1619241,
"author_profile": "https://Stackoverflow.com/users/1619241",
"pm_score": 0,
"selected": false,
"text": "<p>I faced the same problem. I restarted the oracle service for that DB instance and the error is gone.</p>\n"
},
{
"answer_id": 64407006,
"author": "Ian Nato",
"author_id": 5841507,
"author_profile": "https://Stackoverflow.com/users/5841507",
"pm_score": 0,
"selected": false,
"text": "<p>What worked for me is that i hadn't set the local_listener, to see if the local listener is set login to <code>sqlplus / as sysdba</code>, make sure the database is open and run the following command\n<code>show parameter local_listener</code>, if the value is empty, then you will have to set the local_listener with the following SQL command <code>ALTER SYSTEM SET LOCAL_LISTENER='<LISTENER_NAME_GOES_HERE>'</code></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5351/"
] | When trying to connect to an `ORACLE` user via TOAD (Quest Software) or any other means (`Oracle Enterprise Manager`) I get this error:
>
> `ORA-011033: ORACLE initialization or shutdown in progress`
>
>
> | After some googling, I found the advice to do the following, and it worked:
```
SQL> startup mount
ORACLE Instance started
SQL> recover database
Media recovery complete
SQL> alter database open;
Database altered
``` |
53,728 | <p>I am not concerned about other kinds of attacks. Just want to know whether HTML Encode can prevent all kinds of XSS attacks.</p>
<p>Is there some way to do an XSS attack even if HTML Encode is used?</p>
| [
{
"answer_id": 53739,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": -1,
"selected": false,
"text": "<p>I don't believe so. Html Encode converts all functional characters (characters which could be interpreted by the browser as code) in to entity references which cannot be parsed by the browser and thus, cannot be executed.</p>\n\n<pre><code>&lt;script/&gt;\n</code></pre>\n\n<p>There is no way that the above can be executed by the browser.</p>\n\n<p>**Unless their is a bug in the browser ofcourse.*</p>\n"
},
{
"answer_id": 53741,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 2,
"selected": false,
"text": "<p>If you encode everything it will. (depending on your platform and the implementation of htmlencode) But any usefull web application is so complex that it's easy to forget to check every part of it. Or maybe a 3rd party component isn't safe. Or maybe some code path that you though did encoding didn't do it so you forgot it somewhere else. </p>\n\n<p>So you might want to check things on the input side too. And you might want to check stuff you read from the database.</p>\n"
},
{
"answer_id": 53755,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 3,
"selected": false,
"text": "<p>If you systematically encode all user input before displaying <s>then yes, you are safe</s> you are still not 100 % safe.<br>\n(See @Avid's post for more details)</p>\n\n<p>In addition problems arise when you need to let <strong>some</strong> tags go unencoded so that you allow users to post images or bold text or any feature that requires user's input be processed as (or converted to) un-encoded markup.</p>\n\n<p>You will have to set up a decision making system to decide which tags are allowed and which are not, and it is always possible that someone will figure out a way to let a non allowed tag to pass through.</p>\n\n<p>It helps if you follow Joel's advice of <a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"noreferrer\">Making Wrong Code Look Wrong</a> or if <a href=\"http://blog.moertel.com/articles/2006/10/18/a-type-based-solution-to-the-strings-problem\" rel=\"noreferrer\">your language helps you</a> by warning/not compiling when you are outputting unprocessed user data (static-typing).</p>\n"
},
{
"answer_id": 53816,
"author": "metavida",
"author_id": 5539,
"author_profile": "https://Stackoverflow.com/users/5539",
"pm_score": 1,
"selected": false,
"text": "<p>As mentioned by everyone else, you're safe as long as you encode <em>all</em> user input before displaying it. This includes all request parameters and data retrieved from the database that can be changed by user input.</p>\n\n<p>As <a href=\"https://stackoverflow.com/questions/53728/will-html-encoding-prevent-all-kinds-of-xss-attacks#53755\">mentioned by Pat</a> you'll sometimes want to display some tags, just not all tags. One common way to do this is to use a markup language like <a href=\"http://en.wikipedia.org/wiki/Textile_(markup_language)\" rel=\"nofollow noreferrer\">Textile</a>, <a href=\"http://en.wikipedia.org/wiki/Markdown\" rel=\"nofollow noreferrer\">Markdown</a>, or <a href=\"http://en.wikipedia.org/wiki/BBCode\" rel=\"nofollow noreferrer\">BBCode</a>. However, even markup languages can be vulnerable to XSS, just be aware.</p>\n\n<pre><code># Markup example\n[foo](javascript:alert\\('bar'\\);)\n</code></pre>\n\n<p>If you do decide to let \"safe\" tags through I would recommend finding some existing library to parse & sanitize your code before output. There are <a href=\"http://ha.ckers.org/xss.html\" rel=\"nofollow noreferrer\">a lot of XSS vectors</a> out there that you would have to detect before your sanitizer is fairly safe.</p>\n"
},
{
"answer_id": 57434,
"author": "tqbf",
"author_id": 5674,
"author_profile": "https://Stackoverflow.com/users/5674",
"pm_score": 1,
"selected": false,
"text": "<p>I second metavida's advice to find a third-party library to handle output filtering. Neutralizing HTML characters is a good approach to stopping XSS attacks. However, the code you use to transform metacharacters can be vulnerable to evasion attacks; for instance, if it doesn't properly handle Unicode and internationalization.</p>\n\n<p>A classic simple mistake homebrew output filters make is to catch only < and >, but miss things like \", which can break user-controlled output out into the attribute space of an HTML tag, where Javascript can be attached to the DOM.</p>\n"
},
{
"answer_id": 70222,
"author": "AviD",
"author_id": 10080,
"author_profile": "https://Stackoverflow.com/users/10080",
"pm_score": 8,
"selected": true,
"text": "<p>No.</p>\n\n<p>Putting aside the subject of allowing some tags (not really the point of the question), HtmlEncode simply does NOT cover all XSS attacks.</p>\n\n<p>For instance, consider server-generated client-side javascript - the server dynamically outputs htmlencoded values directly into the client-side javascript, htmlencode will <strong>not stop</strong> injected script from executing.</p>\n\n<p>Next, consider the following pseudocode:</p>\n\n<pre><code><input value=<%= HtmlEncode(somevar) %> id=textbox>\n</code></pre>\n\n<p>Now, in case its not immediately obvious, if somevar (sent by the user, of course) is set for example to</p>\n\n<pre><code>a onclick=alert(document.cookie)\n</code></pre>\n\n<p>the resulting output is</p>\n\n<pre><code><input value=a onclick=alert(document.cookie) id=textbox>\n</code></pre>\n\n<p>which would clearly work. Obviously, this can be (almost) any other script... and HtmlEncode would not help much.</p>\n\n<p>There are a few additional vectors to be considered... including the third flavor of XSS, called DOM-based XSS (wherein the malicious script is generated dynamically on the client, e.g. based on # values).</p>\n\n<p>Also don't forget about UTF-7 type attacks - where the attack looks like </p>\n\n<pre><code>+ADw-script+AD4-alert(document.cookie)+ADw-/script+AD4-\n</code></pre>\n\n<p>Nothing much to encode there...</p>\n\n<p>The solution, of course (in addition to proper and restrictive white-list input validation), is to perform <strong>context-sensitive</strong> encoding: HtmlEncoding is great IF you're output context IS HTML, or maybe you need JavaScriptEncoding, or VBScriptEncoding, or AttributeValueEncoding, or... etc.</p>\n\n<p>If you're using MS ASP.NET, you can use their Anti-XSS Library, which provides all of the necessary context-encoding methods.</p>\n\n<p>Note that all encoding should not be restricted to user input, but also stored values from the database, text files, etc.</p>\n\n<p>Oh, and don't forget to explicitly set the charset, both in the HTTP header AND the META tag, otherwise you'll still have UTF-7 vulnerabilities...</p>\n\n<p>Some more information, and a pretty definitive list (constantly updated), check out RSnake's Cheat Sheet: <a href=\"http://ha.ckers.org/xss.html\" rel=\"noreferrer\">http://ha.ckers.org/xss.html</a></p>\n"
},
{
"answer_id": 91509,
"author": "Buzz",
"author_id": 13113,
"author_profile": "https://Stackoverflow.com/users/13113",
"pm_score": 0,
"selected": false,
"text": "<p>I'd like to suggest HTML Purifier (<a href=\"http://htmlpurifier.org/\" rel=\"nofollow noreferrer\">http://htmlpurifier.org/</a>) It doesn't just filter the html, it basically tokenizes and re-compiles it. It is truly industrial-strength. </p>\n\n<p>It has the additional benefit of allowing you to ensure valid html/xhtml output. </p>\n\n<p>Also n'thing textile, its a great tool and I use it all the time, but I'd run it though html purifier too. </p>\n\n<p>I don't think you understood what I meant re tokens. HTML Purifier doesn't just 'filter', it actually reconstructs the html. <a href=\"http://htmlpurifier.org/comparison.html\" rel=\"nofollow noreferrer\">http://htmlpurifier.org/comparison.html</a></p>\n"
},
{
"answer_id": 94086,
"author": "Chris Kite",
"author_id": 9573,
"author_profile": "https://Stackoverflow.com/users/9573",
"pm_score": 1,
"selected": false,
"text": "<p>No, just encoding common HTML tokens DOES NOT completely protect your site from XSS attacks. See, for example, this XSS vulnerability found in google.com:</p>\n\n<p><a href=\"http://www.securiteam.com/securitynews/6Z00L0AEUE.html\" rel=\"nofollow noreferrer\">http://www.securiteam.com/securitynews/6Z00L0AEUE.html</a></p>\n\n<p>The important thing about this type of vulnerability is that the attacker is able to encode his XSS payload using UTF-7, and if you haven't specified a different character encoding on your page, a user's browser could interpret the UTF-7 payload and execute the attack script.</p>\n"
},
{
"answer_id": 100912,
"author": "Mladen Mihajlovic",
"author_id": 11421,
"author_profile": "https://Stackoverflow.com/users/11421",
"pm_score": 0,
"selected": false,
"text": "<p>One other thing you need to check is where your input comes from. You can use the referrer string (most of the time) to check that it's from your own page, but putting in a hidden random number or something in your form and then checking it (with a session set variable maybe) also helps knowing that the input is coming from your own site and not some phishing site.</p>\n"
},
{
"answer_id": 68540513,
"author": "NguyenPD_LoH",
"author_id": 16403867,
"author_profile": "https://Stackoverflow.com/users/16403867",
"pm_score": -1,
"selected": false,
"text": "<p>myString.replace(/<[^>]*>?/gm, '');</p>\n<p>I use it, then successfully.\n<a href=\"https://stackoverflow.com/questions/822452/strip-html-from-text-javascript\">Strip HTML from Text JavaScript</a></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] | I am not concerned about other kinds of attacks. Just want to know whether HTML Encode can prevent all kinds of XSS attacks.
Is there some way to do an XSS attack even if HTML Encode is used? | No.
Putting aside the subject of allowing some tags (not really the point of the question), HtmlEncode simply does NOT cover all XSS attacks.
For instance, consider server-generated client-side javascript - the server dynamically outputs htmlencoded values directly into the client-side javascript, htmlencode will **not stop** injected script from executing.
Next, consider the following pseudocode:
```
<input value=<%= HtmlEncode(somevar) %> id=textbox>
```
Now, in case its not immediately obvious, if somevar (sent by the user, of course) is set for example to
```
a onclick=alert(document.cookie)
```
the resulting output is
```
<input value=a onclick=alert(document.cookie) id=textbox>
```
which would clearly work. Obviously, this can be (almost) any other script... and HtmlEncode would not help much.
There are a few additional vectors to be considered... including the third flavor of XSS, called DOM-based XSS (wherein the malicious script is generated dynamically on the client, e.g. based on # values).
Also don't forget about UTF-7 type attacks - where the attack looks like
```
+ADw-script+AD4-alert(document.cookie)+ADw-/script+AD4-
```
Nothing much to encode there...
The solution, of course (in addition to proper and restrictive white-list input validation), is to perform **context-sensitive** encoding: HtmlEncoding is great IF you're output context IS HTML, or maybe you need JavaScriptEncoding, or VBScriptEncoding, or AttributeValueEncoding, or... etc.
If you're using MS ASP.NET, you can use their Anti-XSS Library, which provides all of the necessary context-encoding methods.
Note that all encoding should not be restricted to user input, but also stored values from the database, text files, etc.
Oh, and don't forget to explicitly set the charset, both in the HTTP header AND the META tag, otherwise you'll still have UTF-7 vulnerabilities...
Some more information, and a pretty definitive list (constantly updated), check out RSnake's Cheat Sheet: <http://ha.ckers.org/xss.html> |
53,734 | <p>If you're creating a temporary table within a stored procedure and want to add an index or two on it, to improve the performance of any additional statements made against it, what is the best approach? Sybase says <a href="http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc20020_1251/html/databases/databases644.htm" rel="noreferrer">this</a>:</p>
<p><em>"the table must contain data when the index is created. If you create the temporary table and create the index on an empty table, Adaptive Server does not create column statistics such as histograms and densities. If you insert data rows after creating the index, the optimizer has incomplete statistics."</em></p>
<p>but recently a colleague mentioned that if I create the temp table and indices in a different stored procedure to the one which actually uses the temporary table, then Adaptive Server optimiser <em>will</em> be able to make use of them.</p>
<p>On the whole, I'm not a big fan of wrapper procedures that add little value, so I've not actually got around to testing this, but I thought I'd put the question out there, to see if anyone had any other approaches or advice?</p>
| [
{
"answer_id": 53814,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 2,
"selected": false,
"text": "<p>What's the problem with adding the indexes after you put data into the temp table?</p>\n\n<p>One thing you need to be mindful of is the visibility of the index to other instances of the procedure that might be running at the same time.</p>\n\n<p>I like to add a guid to these kinds of temp tables (and to the indexes), to make sure there is never a conflict. The other benefit of this approach is that you could simply make the temp table a real table.</p>\n\n<p>Also, make sure that you will need to query the data in these temp tables <em>more than once</em> during the running of the stored procedure, otherwise the cost of index creation will outweigh the benefit to the select.</p>\n"
},
{
"answer_id": 66620,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>In Sybase if you create a temp table and then use it in one proc the plan for the select is built using an estimate of 100 rows in the table. (The plan is built when the procedure starts before the tables are populated.) This can result in the temp table being table scanned since it is only \"100 rows\". Calling a another proc causes Sybase to build the plan for the select with the actual number of rows, this allows the optimizer to pick a better index to use. I have seen significant improvedments using this approach but test on your database as sometimes there is no difference. </p>\n"
},
{
"answer_id": 153680,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 4,
"selected": true,
"text": "<p>A few thoughts: </p>\n\n<ul>\n<li>If your temporary table is so big that you have to index it, then is there a better way to solve the problem? </li>\n<li><p>You can force it to use the index (if you are sure that the index is the correct way to access the table) by giving an optimiser hint, of the form: </p>\n\n<pre><code>SELECT * \nFROM #table (index idIndex) \nWHERE id = @id\n</code></pre></li>\n</ul>\n\n<p>If you are interested in performance tips in general, I've answered a couple of other questions about that at some length here: </p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/18783/sql-what-are-your-favorite-performance-tricks#103176\">Favourite performance tuning tricks</a></li>\n<li><a href=\"https://stackoverflow.com/questions/137226/how-do-you-optimize-tables-for-specific-queries#138949\">How do you optimize tables for specific queries?</a></li>\n</ul>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | If you're creating a temporary table within a stored procedure and want to add an index or two on it, to improve the performance of any additional statements made against it, what is the best approach? Sybase says [this](http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc20020_1251/html/databases/databases644.htm):
*"the table must contain data when the index is created. If you create the temporary table and create the index on an empty table, Adaptive Server does not create column statistics such as histograms and densities. If you insert data rows after creating the index, the optimizer has incomplete statistics."*
but recently a colleague mentioned that if I create the temp table and indices in a different stored procedure to the one which actually uses the temporary table, then Adaptive Server optimiser *will* be able to make use of them.
On the whole, I'm not a big fan of wrapper procedures that add little value, so I've not actually got around to testing this, but I thought I'd put the question out there, to see if anyone had any other approaches or advice? | A few thoughts:
* If your temporary table is so big that you have to index it, then is there a better way to solve the problem?
* You can force it to use the index (if you are sure that the index is the correct way to access the table) by giving an optimiser hint, of the form:
```
SELECT *
FROM #table (index idIndex)
WHERE id = @id
```
If you are interested in performance tips in general, I've answered a couple of other questions about that at some length here:
* [Favourite performance tuning tricks](https://stackoverflow.com/questions/18783/sql-what-are-your-favorite-performance-tricks#103176)
* [How do you optimize tables for specific queries?](https://stackoverflow.com/questions/137226/how-do-you-optimize-tables-for-specific-queries#138949) |
53,744 | <p>I would like to know how can i escape a # in velocity. Backslash seems to escape it but it prints itself as well</p>
<p>This: </p>
<pre><code>\#\#
</code></pre>
<p>prints: </p>
<pre><code>\#\#
</code></pre>
<p>I would like: </p>
<pre><code>##
</code></pre>
| [
{
"answer_id": 53747,
"author": "Thomas",
"author_id": 4980,
"author_profile": "https://Stackoverflow.com/users/4980",
"pm_score": 3,
"selected": false,
"text": "<p>Maybe, the following site helps? <a href=\"http://velocity.apache.org/tools/1.4/generic/EscapeTool.html\" rel=\"nofollow noreferrer\">http://velocity.apache.org/tools/1.4/generic/EscapeTool.html</a></p>\n"
},
{
"answer_id": 58427,
"author": "Sergio del Amo",
"author_id": 2138,
"author_profile": "https://Stackoverflow.com/users/2138",
"pm_score": 2,
"selected": false,
"text": "<p>Add the esc tool to your toolbox and then you can use ${esc.hash}</p>\n"
},
{
"answer_id": 64246,
"author": "Nathan Bubna",
"author_id": 8131,
"author_profile": "https://Stackoverflow.com/users/8131",
"pm_score": 6,
"selected": false,
"text": "<p>If you don't want to bother with the EscapeTool, you can do this:</p>\n\n<pre><code>#set( $H = '#' )\n$H$H\n</code></pre>\n"
},
{
"answer_id": 7093929,
"author": "alvi",
"author_id": 644958,
"author_profile": "https://Stackoverflow.com/users/644958",
"pm_score": 6,
"selected": false,
"text": "<p>this:</p>\n\n<pre><code>#[[\n##\n]]#\n</code></pre>\n\n<p>will yield:</p>\n\n<pre><code>##\n</code></pre>\n\n<p>anything within #[[ ... ]]# is unparsed.</p>\n"
},
{
"answer_id": 11053895,
"author": "gregm",
"author_id": 108495,
"author_profile": "https://Stackoverflow.com/users/108495",
"pm_score": 0,
"selected": false,
"text": "<p>The set technique is a good way to get around any characters you need escaping, like if you want to have $name followed by \"_lastname\" then you can do:</p>\n\n<pre><code>set ($n = '_lastname)\n</code></pre>\n\n<p>and have this in your template: </p>\n\n<pre><code>$name$n\n</code></pre>\n\n<p>and it's all good.</p>\n"
},
{
"answer_id": 46972395,
"author": "Ankit Raonka",
"author_id": 5027628,
"author_profile": "https://Stackoverflow.com/users/5027628",
"pm_score": 2,
"selected": false,
"text": "<p>${esc.h} will output # as per </p>\n\n<p><a href=\"http://velocity.apache.org/tools/1.4/generic/EscapeTool.html\" rel=\"nofollow noreferrer\">this link</a></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] | I would like to know how can i escape a # in velocity. Backslash seems to escape it but it prints itself as well
This:
```
\#\#
```
prints:
```
\#\#
```
I would like:
```
##
``` | If you don't want to bother with the EscapeTool, you can do this:
```
#set( $H = '#' )
$H$H
``` |
53,757 | <p>Which compiles to faster code: "ans = n * 3" or "ans = n+(n*2)"?</p>
<p>Assuming that n is either an int or a long, and it is is running on a modern Win32 Intel box.</p>
<p>Would this be different if there was some dereferencing involved, that is, which of these would be faster?</p>
<pre>
long a;
long *pn;
long ans;
...
*pn = some_number;
ans = *pn * 3;
</pre>
<p>Or</p>
<pre>
ans = *pn+(*pn*2);
</pre>
<p>Or, is it something one need not worry about as optimizing compilers are likely to account for this in any case?</p>
| [
{
"answer_id": 53759,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 7,
"selected": true,
"text": "<p>IMO such micro-optimization is not necessary unless you work with some exotic compiler. I would put readability on the first place.</p>\n"
},
{
"answer_id": 53761,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "<p>It does depend on the compiler you are actually using, but very probably they translate to the same code. </p>\n\n<p>You can check it by yourself by creating a small test program and checking its disassembly.</p>\n"
},
{
"answer_id": 53762,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 1,
"selected": false,
"text": "<p>Most compilers are smart enough to decompose an integer multiplication into a series of bit shifts and adds. I don't know about Windows compilers, but at least with gcc you can get it to spit out the assembler, and if you look at that you can probably see identical assembler for both ways of writing it.</p>\n"
},
{
"answer_id": 53763,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>Compilers are good at optimising code such as yours. Any modern compiler would produce the same code for both cases and additionally replace <code>* 2</code> by a left shift.</p>\n"
},
{
"answer_id": 53765,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 2,
"selected": false,
"text": "<p>This would depend on the compiler, its configuration and the surrounding code.</p>\n\n<p>You should not try and guess whether things are 'faster' without taking measurements. </p>\n\n<p><em>In general</em> you should not worry about this kind of nanoscale optimisation stuff nowadays - it's almost always a complete irrelevance, and if you were genuinely working in a domain where it mattered, you would already be using a profiler and looking at the assembly language output of the compiler.</p>\n"
},
{
"answer_id": 53781,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 3,
"selected": false,
"text": "<p>As it's easy to measure it yourself, why don't do that? (Using <code>gcc</code> and <code>time</code> from cygwin)</p>\n\n<pre><code>/* test1.c */\nint main()\n{\n int result = 0;\n int times = 1000000000;\n while (--times)\n result = result * 3;\n return result;\n}\n\nmachine:~$ gcc -O2 test1.c -o test1\nmachine:~$ time ./test1.exe\n\nreal 0m0.673s\nuser 0m0.608s\nsys 0m0.000s\n</code></pre>\n\n<p>Do the test for a couple of times and repeat for the other case.</p>\n\n<p>If you want to peek at the assembly code, <code>gcc -S -O2 test1.c</code></p>\n"
},
{
"answer_id": 53797,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 4,
"selected": false,
"text": "<p>It doesn't matter. Modern processors can execute an integer MUL instruction in one clock cycle or less, unlike older processers which needed to perform a series of shifts and adds internally in order to perform the MUL, thereby using multiple cycles. I would bet that</p>\n\n<pre><code>MUL EAX,3\n</code></pre>\n\n<p>executes faster than</p>\n\n<pre><code>MOV EBX,EAX\nSHL EAX,1\nADD EAX,EBX\n</code></pre>\n\n<p>The last processor where this sort of optimization might have been useful was probably the 486. (yes, this is biased to intel processors, but is probably representative of other architectures as well).</p>\n\n<p>In any event, any reasonable compiler should be able to generate the smallest/fastest code. So always go with readability first.</p>\n"
},
{
"answer_id": 53815,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 2,
"selected": false,
"text": "<p>It's not difficult to find out what the compiler is doing with your code (I'm using DevStudio 2005 here). Write a simple program with the following code:</p>\n\n<pre><code>int i = 45, j, k;\nj = i * 3;\nk = i + (i * 2);\n</code></pre>\n\n<p>Place a breakpoint on the middle line and run the code using the debugger. When the breakpoint is triggered, right click on the source file and select \"Go To Disassembly\". You will now have a window with the code the CPU is executing. You will notice in this case that the last two lines produce exactly the same instructions, namely, \"lea eax,[ebx+ebx*2]\" (not bit shifting and adding in this particular case). On a modern IA32 CPU, it's probably more efficient to do a straight MUL rather than bit shifting due to pipelineing nature of the CPU which incurs a penalty when using a modified value too soon.</p>\n\n<p>This demonstrates what aku is talking about, namely, compilers are clever enough to pick the best instructions for your code.</p>\n"
},
{
"answer_id": 63220,
"author": "Mark D",
"author_id": 7452,
"author_profile": "https://Stackoverflow.com/users/7452",
"pm_score": 0,
"selected": false,
"text": "<p>Trust your compiler to optimize little pieces of code like that. Readability is much more important at the code level. True optimization should come at a higher level.</p>\n"
},
{
"answer_id": 304032,
"author": "Angel",
"author_id": 23285,
"author_profile": "https://Stackoverflow.com/users/23285",
"pm_score": 1,
"selected": false,
"text": "<p>It doesn't care. I think that there are more important things to optimize. How much time have you invested thinking and writing that question instead of coding and testing by yourself? </p>\n\n<p>:-)</p>\n"
},
{
"answer_id": 304053,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 1,
"selected": false,
"text": "<p>As long as you're using a decent optimising compiler, just <em>write code that's easy for the compiler to understand</em>. This makes it easier for the compiler to perform clever optimisations.</p>\n\n<p>You asking this question indicates that an optimising compiler knows more about optimisation than you do. So trust the compiler. Use <code>n * 3</code>.</p>\n\n<p>Have a look at <a href=\"https://stackoverflow.com/questions/288942/how-to-convert-last-3-digits-of-number-into-0#289034\">this answer</a> as well.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3137/"
] | Which compiles to faster code: "ans = n \* 3" or "ans = n+(n\*2)"?
Assuming that n is either an int or a long, and it is is running on a modern Win32 Intel box.
Would this be different if there was some dereferencing involved, that is, which of these would be faster?
```
long a;
long *pn;
long ans;
...
*pn = some_number;
ans = *pn * 3;
```
Or
```
ans = *pn+(*pn*2);
```
Or, is it something one need not worry about as optimizing compilers are likely to account for this in any case? | IMO such micro-optimization is not necessary unless you work with some exotic compiler. I would put readability on the first place. |
53,786 | <p>I am trying to automate functional testing of a server using a realistic frequency distribution of requests. (sort of load testing, sort of simulation)</p>
<p>I've chosen the <a href="http://en.wikipedia.org/wiki/Weibull_distribution" rel="nofollow noreferrer">Weibull</a> distribution as it "sort of" matches the distribution I've observed (ramps up quickly, drops off quickly but not instantly)</p>
<p>I use this distribution to generate the number of requests that should be sent each day between a given start and end date</p>
<p>I've hacked together an algorithm in Python that sort of works but it feels kludgy:</p>
<pre><code>how_many_days = (end_date - start_date).days
freqs = defaultdict(int)
for x in xrange(how_many_responses):
freqs[int(how_many_days * weibullvariate(0.5, 2))] += 1
timeline = []
day = start_date
for i,freq in sorted(freqs.iteritems()):
timeline.append((day, freq))
day += timedelta(days=1)
return timeline
</code></pre>
<p>What better ways are there to do this? </p>
| [
{
"answer_id": 53791,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "<p>Why don't you try <a href=\"http://grinder.sourceforge.net\" rel=\"nofollow noreferrer\">The Grinder 3</a> to load test your server, it comes with all this and more prebuilt, and it supports python as a scripting language</p>\n"
},
{
"answer_id": 56032,
"author": "Kai",
"author_id": 2963,
"author_profile": "https://Stackoverflow.com/users/2963",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of giving the number of requests as a fixed value, why not use a scaling factor instead? At the moment, you're treating requests as a limited quantity, and randomising the days on which those requests fall. It would seem more reasonable to treat your requests-per-day as independent.</p>\n\n<pre><code>from datetime import *\nfrom random import *\n\ntimeline = []\nscaling = 10\nstart_date = date(2008, 5, 1)\nend_date = date(2008, 6, 1)\n\nnum_days = (end_date - start_date).days + 1\ndays = [start_date + timedelta(i) for i in range(num_days)]\nrequests = [int(scaling * weibullvariate(0.5, 2)) for i in range(num_days)]\ntimeline = zip(days, requests)\ntimeline\n</code></pre>\n"
},
{
"answer_id": 56102,
"author": "Jacob Rigby",
"author_id": 5357,
"author_profile": "https://Stackoverflow.com/users/5357",
"pm_score": 0,
"selected": false,
"text": "<p>I rewrote the code above to be shorter (but maybe it's too obfuscated now?)</p>\n\n<pre><code>timeline = (start_date + timedelta(days=days) for days in count(0))\nhow_many_days = (end_date - start_date).days\npick_a_day = lambda _:int(how_many_days * weibullvariate(0.5, 2))\ndays = sorted(imap(pick_a_day, xrange(how_many_responses)))\nhistogram = zip(timeline, (len(list(responses)) for day, responses in groupby(days)))\nprint '\\n'.join((d.strftime('%Y-%m-%d ') + \"*\" * c) for d,c in histogram)\n</code></pre>\n"
},
{
"answer_id": 56247,
"author": "Kai",
"author_id": 2963,
"author_profile": "https://Stackoverflow.com/users/2963",
"pm_score": 1,
"selected": false,
"text": "<p>Slightly longer but probably more readable rework of your last four lines:</p>\n\n<pre><code>samples = [0 for i in xrange(how_many_days + 1)]\nfor s in xrange(how_many_responses):\n samples[min(int(how_many_days * weibullvariate(0.5, 2)), how_many_days)] += 1\nhistogram = zip(timeline, samples)\nprint '\\n'.join((d.strftime('%Y-%m-%d ') + \"*\" * c) for d,c in histogram)\n</code></pre>\n\n<p>This always drops the samples within the date range, but you get a corresponding bump at the end of the timeline from all of the samples that are above the [0, 1] range.</p>\n"
},
{
"answer_id": 56548,
"author": "Kai",
"author_id": 2963,
"author_profile": "https://Stackoverflow.com/users/2963",
"pm_score": 2,
"selected": true,
"text": "<p>This is quick and probably not that accurate, but if you calculate the PDF yourself, then at least you make it easier to lay several smaller/larger ones on a single timeline. <code>dev</code> is the std deviation in the Guassian noise, which controls the roughness. Note that this is <em>not</em> the 'right' way to generate what you want, but it's easy.</p>\n\n<pre><code>import math\nfrom datetime import datetime, timedelta, date\nfrom random import gauss\n\nhow_many_responses = 1000\nstart_date = date(2008, 5, 1)\nend_date = date(2008, 6, 1)\nnum_days = (end_date - start_date).days + 1\ntimeline = [start_date + timedelta(i) for i in xrange(num_days)]\n\ndef weibull(x, k, l):\n return (k / l) * (x / l)**(k-1) * math.e**(-(x/l)**k)\n\ndev = 0.1\nsamples = [i * 1.25/(num_days-1) for i in range(num_days)]\nprobs = [weibull(i, 2, 0.5) for i in samples]\nnoise = [gauss(0, dev) for i in samples]\nsimdata = [max(0., e + n) for (e, n) in zip(probs, noise)]\nevents = [int(p * (how_many_responses / sum(probs))) for p in simdata]\n\nhistogram = zip(timeline, events)\n\nprint '\\n'.join((d.strftime('%Y-%m-%d ') + \"*\" * c) for d,c in histogram)\n</code></pre>\n"
},
{
"answer_id": 89140,
"author": "Gregg Lind",
"author_id": 15842,
"author_profile": "https://Stackoverflow.com/users/15842",
"pm_score": 0,
"selected": false,
"text": "<p>Another solution is to use <a href=\"http://rpy.sourceforge.net/\" rel=\"nofollow noreferrer\">Rpy</a>, which puts all of the power of R (including lots of tools for distributions), easily into Python. </p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5357/"
] | I am trying to automate functional testing of a server using a realistic frequency distribution of requests. (sort of load testing, sort of simulation)
I've chosen the [Weibull](http://en.wikipedia.org/wiki/Weibull_distribution) distribution as it "sort of" matches the distribution I've observed (ramps up quickly, drops off quickly but not instantly)
I use this distribution to generate the number of requests that should be sent each day between a given start and end date
I've hacked together an algorithm in Python that sort of works but it feels kludgy:
```
how_many_days = (end_date - start_date).days
freqs = defaultdict(int)
for x in xrange(how_many_responses):
freqs[int(how_many_days * weibullvariate(0.5, 2))] += 1
timeline = []
day = start_date
for i,freq in sorted(freqs.iteritems()):
timeline.append((day, freq))
day += timedelta(days=1)
return timeline
```
What better ways are there to do this? | This is quick and probably not that accurate, but if you calculate the PDF yourself, then at least you make it easier to lay several smaller/larger ones on a single timeline. `dev` is the std deviation in the Guassian noise, which controls the roughness. Note that this is *not* the 'right' way to generate what you want, but it's easy.
```
import math
from datetime import datetime, timedelta, date
from random import gauss
how_many_responses = 1000
start_date = date(2008, 5, 1)
end_date = date(2008, 6, 1)
num_days = (end_date - start_date).days + 1
timeline = [start_date + timedelta(i) for i in xrange(num_days)]
def weibull(x, k, l):
return (k / l) * (x / l)**(k-1) * math.e**(-(x/l)**k)
dev = 0.1
samples = [i * 1.25/(num_days-1) for i in range(num_days)]
probs = [weibull(i, 2, 0.5) for i in samples]
noise = [gauss(0, dev) for i in samples]
simdata = [max(0., e + n) for (e, n) in zip(probs, noise)]
events = [int(p * (how_many_responses / sum(probs))) for p in simdata]
histogram = zip(timeline, events)
print '\n'.join((d.strftime('%Y-%m-%d ') + "*" * c) for d,c in histogram)
``` |
53,811 | <p>Do you normally set your compiler to optimize for maximum speed or smallest code size? or do you manually configure individual optimization settings? Why?</p>
<p>I notice most of the time people tend to just leave compiler optimization settings to their default state, which with visual c++ means max speed.
I've always felt that the default settings had more to do with looking good on benchmarks, which tend to be small programs that will fit entirely within the L2 cache than what's best for overall performance, so I normally set it optimize for smallest size.</p>
| [
{
"answer_id": 53819,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>We always use maximize for optimal speed but then, all the code I write in C++ is somehow related to bioinformatics algorithms and speed is crucial while the code size is relatively small.</p>\n"
},
{
"answer_id": 53823,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>Memory is cheap now days :) So it can be meaningful to set compiler settings to max speed unless you work with embedded systems. Of course answer depends on concrete situation.</p>\n"
},
{
"answer_id": 53825,
"author": "Mike McQuaid",
"author_id": 5355,
"author_profile": "https://Stackoverflow.com/users/5355",
"pm_score": 1,
"selected": false,
"text": "<p>For me it depends on what platform I'm using. For some embedded platforms or when I worked on the Cell processor you have restraints such as a very small cache or minimal space provided for code.</p>\n\n<p>I use GCC and tend to leave it on \"-O2\" which is the \"safest\" level of optimisation and favours speed over a minimal size.</p>\n\n<p>I'd say it probably doesn't make a huge difference unless you are developing for a very high-performance application in which case you should probably be benchmarking the various options for your particular use-case.</p>\n"
},
{
"answer_id": 53826,
"author": "Claes Mogren",
"author_id": 4992,
"author_profile": "https://Stackoverflow.com/users/4992",
"pm_score": 4,
"selected": true,
"text": "<p>As a Gentoo user I have tried quite a few optimizations on the complete OS and there have been endless discussions on the <a href=\"http://forums.gentoo.org/\" rel=\"noreferrer\">Gentoo forums</a> about it. Some good flags for GCC can be found in the <a href=\"http://gentoo-wiki.com/Safe_Cflags\" rel=\"noreferrer\">wiki</a>.</p>\n\n<p>In short, optimizing for size worked best on an old Pentium3 laptop with limited ram, but on my main desktop machine with a Core2Duo, -O2 gave better results over all.</p>\n\n<p>There's also a <a href=\"http://www.pixelbeat.org/scripts/gcccpuopt\" rel=\"noreferrer\">small script</a> if you are interested in the x86 (32 bit) specific flags that are the most optimized.</p>\n\n<p>If you use gcc and really want to optimize a specific application, try <a href=\"http://www.coyotegulch.com/products/acovea/\" rel=\"noreferrer\">ACOVEA</a>. It runs a set of benchmarks, then recompile them with all possible combinations of compile flags. There's an example using Huffman encoding on the site (lower is better):</p>\n\n<pre><code>A relative graph of fitnesses:\n\n Acovea Best-of-the-Best: ************************************** (2.55366)\n Acovea Common Options: ******************************************* (2.86788)\n -O1: ********************************************** (3.0752)\n -O2: *********************************************** (3.12343)\n -O3: *********************************************** (3.1277)\n -O3 -ffast-math: ************************************************** (3.31539)\n -Os: ************************************************* (3.30573)\n</code></pre>\n\n<p>(Note that it found -Os to be the slowest on this Opteron system.)</p>\n"
},
{
"answer_id": 53833,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer to use minimal size. Memory may be cheap, <b>cache is not</b>.</p>\n"
},
{
"answer_id": 53871,
"author": "On Freund",
"author_id": 2150,
"author_profile": "https://Stackoverflow.com/users/2150",
"pm_score": 1,
"selected": false,
"text": "<p>Microsoft ships all its C/C++ software optimized for size. After benchmarking they discovered that it actually gives better speed (due to cache locality).</p>\n"
},
{
"answer_id": 54181,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 2,
"selected": false,
"text": "<p>Besides the fact that cache locality matters (as On Freund said), one other things Microsoft does is to profile their application and find out which code paths are executed during the first few seconds of startup. After that they feed this data back to the compiler and ask it to put the parts which are executed during startup close together. This results in faster startup time.</p>\n\n<p>I do believe that this technique is available publicly in VS, but I'm not 100% sure.</p>\n"
},
{
"answer_id": 57005,
"author": "botismarius",
"author_id": 4528,
"author_profile": "https://Stackoverflow.com/users/4528",
"pm_score": 1,
"selected": false,
"text": "<p>There are many types of optimization, maximum speed versus small code is just one. In this case, I'd choose maximum speed, as the executable will be just a bit bigger.\nOn the other hand, you could optimize your application for a specific type of processor. In some cases this is a good idea (if you intend to run the program only on your station), but in this case it is probable that the program will not work on other architecture (eg: you compile your program to work on a Pentium 4 machine -> it will probably not work on a Pentium 3).</p>\n"
},
{
"answer_id": 61945,
"author": "ima",
"author_id": 5733,
"author_profile": "https://Stackoverflow.com/users/5733",
"pm_score": 1,
"selected": false,
"text": "<p>Build both, profile, choose which works better on specific project and hardware.</p>\n\n<p>For performance critical code, that is - otherwise choose any and don't bother.</p>\n"
},
{
"answer_id": 63195,
"author": "Mark D",
"author_id": 7452,
"author_profile": "https://Stackoverflow.com/users/7452",
"pm_score": 0,
"selected": false,
"text": "<p>This depends on the application of your program. When programming an application to control a fast industrial process, optimize for speed would make sense. When programming an application that only needs to react to a user's input, optimization for size could make sense. That is, if you are concerned about the size of your executable.</p>\n"
},
{
"answer_id": 238097,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 0,
"selected": false,
"text": "<p>Tweaking compiler settings like that is an optimization. On the principle that \"premature optimization is the root of all evil,\" I don't bother with it until the program is near its final shipping state and I've discovered that it's not fast enough -- i.e. almost never.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
] | Do you normally set your compiler to optimize for maximum speed or smallest code size? or do you manually configure individual optimization settings? Why?
I notice most of the time people tend to just leave compiler optimization settings to their default state, which with visual c++ means max speed.
I've always felt that the default settings had more to do with looking good on benchmarks, which tend to be small programs that will fit entirely within the L2 cache than what's best for overall performance, so I normally set it optimize for smallest size. | As a Gentoo user I have tried quite a few optimizations on the complete OS and there have been endless discussions on the [Gentoo forums](http://forums.gentoo.org/) about it. Some good flags for GCC can be found in the [wiki](http://gentoo-wiki.com/Safe_Cflags).
In short, optimizing for size worked best on an old Pentium3 laptop with limited ram, but on my main desktop machine with a Core2Duo, -O2 gave better results over all.
There's also a [small script](http://www.pixelbeat.org/scripts/gcccpuopt) if you are interested in the x86 (32 bit) specific flags that are the most optimized.
If you use gcc and really want to optimize a specific application, try [ACOVEA](http://www.coyotegulch.com/products/acovea/). It runs a set of benchmarks, then recompile them with all possible combinations of compile flags. There's an example using Huffman encoding on the site (lower is better):
```
A relative graph of fitnesses:
Acovea Best-of-the-Best: ************************************** (2.55366)
Acovea Common Options: ******************************************* (2.86788)
-O1: ********************************************** (3.0752)
-O2: *********************************************** (3.12343)
-O3: *********************************************** (3.1277)
-O3 -ffast-math: ************************************************** (3.31539)
-Os: ************************************************* (3.30573)
```
(Note that it found -Os to be the slowest on this Opteron system.) |
53,820 | <p>In the application I'm developping (in Java/swing), I have to show a full screen window on the <em>second</em> screen of the user.
I did this using a code similar to the one you'll find below...
Be, as soon as I click in a window opened by windows explorer, or as soon as I open windows explorer (i'm using windows XP), the full screen window is minimized...</p>
<p>Do you know any way or workaround to fix this problem, or is there something important I did not understand with full screen windows?</p>
<p>Thanks for the help,</p>
<pre><code>import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JWindow;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Window;
import javax.swing.JButton;
import javax.swing.JToggleButton;
import java.awt.Rectangle;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
public class FullScreenTest {
private JFrame jFrame = null; // @jve:decl-index=0:visual-constraint="94,35"
private JPanel jContentPane = null;
private JToggleButton jToggleButton = null;
private JPanel jFSPanel = null; // @jve:decl-index=0:visual-constraint="392,37"
private JLabel jLabel = null;
private Window window;
/**
* This method initializes jFrame
*
* @return javax.swing.JFrame
*/
private JFrame getJFrame() {
if (jFrame == null) {
jFrame = new JFrame();
jFrame.setSize(new Dimension(474, 105));
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setContentPane(getJContentPane());
}
return jFrame;
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getJToggleButton(), null);
}
return jContentPane;
}
/**
* This method initializes jToggleButton
*
* @return javax.swing.JToggleButton
*/
private JToggleButton getJToggleButton() {
if (jToggleButton == null) {
jToggleButton = new JToggleButton();
jToggleButton.setBounds(new Rectangle(50, 23, 360, 28));
jToggleButton.setText("Show Full Screen Window on 2nd screen");
jToggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
showFullScreenWindow(jToggleButton.isSelected());
}
});
}
return jToggleButton;
}
protected void showFullScreenWindow(boolean b) {
if(window==null){
window = initFullScreenWindow();
}
window.setVisible(b);
}
private Window initFullScreenWindow() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gds = ge.getScreenDevices();
GraphicsDevice gd = gds[1];
JWindow window = new JWindow(gd.getDefaultConfiguration());
window.setContentPane(getJFSPanel());
gd.setFullScreenWindow(window);
return window;
}
/**
* This method initializes jFSPanel
*
* @return javax.swing.JPanel
*/
private JPanel getJFSPanel() {
if (jFSPanel == null) {
jLabel = new JLabel();
jLabel.setBounds(new Rectangle(18, 19, 500, 66));
jLabel.setText("Hello ! Now, juste open windows explorer and see what happens...");
jFSPanel = new JPanel();
jFSPanel.setLayout(null);
jFSPanel.setSize(new Dimension(500, 107));
jFSPanel.add(jLabel, null);
}
return jFSPanel;
}
/**
* @param args
*/
public static void main(String[] args) {
FullScreenTest me = new FullScreenTest();
me.getJFrame().setVisible(true);
}
}
</code></pre>
| [
{
"answer_id": 53831,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 2,
"selected": true,
"text": "<p>Usually when an application is in \"full screen\" mode it will take over the entire desktop. For a user to get to another window they would have to alt-tab to it. At that point windows would minimize the full screen app so that the other application could come to the front. </p>\n\n<p>This sounds like it may be a bug (undocumented feature...) in windows. It should probably not be doing this for a dual screen setup. </p>\n\n<p>One option to fix this is rather than setting it to be \"full screen\" just make the window the same size as the screen with location (0,0). You can get screen information from the <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/awt/GraphicsDevice.html#getConfigurations%28%29\" rel=\"nofollow noreferrer\">GraphicsConfigurations on the GraphicsDevice</a>. </p>\n"
},
{
"answer_id": 56166,
"author": "Laurent K",
"author_id": 2965,
"author_profile": "https://Stackoverflow.com/users/2965",
"pm_score": 0,
"selected": false,
"text": "<p>The following code works (thank you John). With no full screen and a large \"always on top\" window.\nBut I still don't know why windows caused this stranged behavior...</p>\n\n<pre><code>private Window initFullScreenWindow() {\n GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();\n GraphicsDevice[] gds = ge.getScreenDevices();\n GraphicsDevice gd = gds[1];\n JWindow window = new JWindow(gd.getDefaultConfiguration());\n window.setContentPane(getJFSPanel());\n window.setLocation(1280, 0);\n window.setSize(gd.getDisplayMode().getWidth(), gd.getDisplayMode().getHeight());\n window.setAlwaysOnTop(true);\n //gd.setFullScreenWindow(window);\n return window;\n}\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2965/"
] | In the application I'm developping (in Java/swing), I have to show a full screen window on the *second* screen of the user.
I did this using a code similar to the one you'll find below...
Be, as soon as I click in a window opened by windows explorer, or as soon as I open windows explorer (i'm using windows XP), the full screen window is minimized...
Do you know any way or workaround to fix this problem, or is there something important I did not understand with full screen windows?
Thanks for the help,
```
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JWindow;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Window;
import javax.swing.JButton;
import javax.swing.JToggleButton;
import java.awt.Rectangle;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
public class FullScreenTest {
private JFrame jFrame = null; // @jve:decl-index=0:visual-constraint="94,35"
private JPanel jContentPane = null;
private JToggleButton jToggleButton = null;
private JPanel jFSPanel = null; // @jve:decl-index=0:visual-constraint="392,37"
private JLabel jLabel = null;
private Window window;
/**
* This method initializes jFrame
*
* @return javax.swing.JFrame
*/
private JFrame getJFrame() {
if (jFrame == null) {
jFrame = new JFrame();
jFrame.setSize(new Dimension(474, 105));
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setContentPane(getJContentPane());
}
return jFrame;
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getJToggleButton(), null);
}
return jContentPane;
}
/**
* This method initializes jToggleButton
*
* @return javax.swing.JToggleButton
*/
private JToggleButton getJToggleButton() {
if (jToggleButton == null) {
jToggleButton = new JToggleButton();
jToggleButton.setBounds(new Rectangle(50, 23, 360, 28));
jToggleButton.setText("Show Full Screen Window on 2nd screen");
jToggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
showFullScreenWindow(jToggleButton.isSelected());
}
});
}
return jToggleButton;
}
protected void showFullScreenWindow(boolean b) {
if(window==null){
window = initFullScreenWindow();
}
window.setVisible(b);
}
private Window initFullScreenWindow() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gds = ge.getScreenDevices();
GraphicsDevice gd = gds[1];
JWindow window = new JWindow(gd.getDefaultConfiguration());
window.setContentPane(getJFSPanel());
gd.setFullScreenWindow(window);
return window;
}
/**
* This method initializes jFSPanel
*
* @return javax.swing.JPanel
*/
private JPanel getJFSPanel() {
if (jFSPanel == null) {
jLabel = new JLabel();
jLabel.setBounds(new Rectangle(18, 19, 500, 66));
jLabel.setText("Hello ! Now, juste open windows explorer and see what happens...");
jFSPanel = new JPanel();
jFSPanel.setLayout(null);
jFSPanel.setSize(new Dimension(500, 107));
jFSPanel.add(jLabel, null);
}
return jFSPanel;
}
/**
* @param args
*/
public static void main(String[] args) {
FullScreenTest me = new FullScreenTest();
me.getJFrame().setVisible(true);
}
}
``` | Usually when an application is in "full screen" mode it will take over the entire desktop. For a user to get to another window they would have to alt-tab to it. At that point windows would minimize the full screen app so that the other application could come to the front.
This sounds like it may be a bug (undocumented feature...) in windows. It should probably not be doing this for a dual screen setup.
One option to fix this is rather than setting it to be "full screen" just make the window the same size as the screen with location (0,0). You can get screen information from the [GraphicsConfigurations on the GraphicsDevice](http://java.sun.com/j2se/1.4.2/docs/api/java/awt/GraphicsDevice.html#getConfigurations%28%29). |
53,824 | <p>I am attempting to use the .Net System.Security.SslStream class to process the server side of a SSL/TLS stream with client authentication.</p>
<p>To perform the handshake, I am using this code:</p>
<pre><code>SslStream sslStream = new SslStream(innerStream, false, RemoteCertificateValidation, LocalCertificateSelectionCallback);
sslStream.AuthenticateAsServer(serverCertificate, true, SslProtocols.Default, false);
</code></pre>
<p>Unfortunately, this results in the SslStream transmitting a CertificateRequest containing the subjectnames of all certificates in my CryptoAPI Trusted Root Store.</p>
<p>I would like to be able to override this. It is not an option for me to require the user to install or remove certificates from the Trusted Root Store.</p>
<p>It looks like the SslStream uses SSPI/SecureChannel underneath, so if anyone knows how to do the equivalent with that API, that would be helpful, too.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 54321,
"author": "Peter Ritchie",
"author_id": 5620,
"author_profile": "https://Stackoverflow.com/users/5620",
"pm_score": 2,
"selected": false,
"text": "<p>What the certificate validation is doing is validating all certificates in the chain. In order to truely do that it just contact the root store of each of those cerficates.</p>\n\n<p>If that's not something you want to happen you can deploy your own root store locally.</p>\n"
},
{
"answer_id": 54749,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 1,
"selected": false,
"text": "<p>It is not the validation part I want to change. The problem is in the initial handshake, the server transmits the message informing the client that client authentication is required (that is the CertificateRequest message). As part of this message, the server sends the names of CAs that it will accept as issuers of the client certificate. It is that list which per default contains all the Trusted Roots in the store.</p>\n\n<p>But if is possible to override the certificate root store for a single application, that would probably fix the problem. Is that what you mean? And if so, how do I do that?</p>\n"
},
{
"answer_id": 62274,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 3,
"selected": true,
"text": "<p>It does not look like this is currently possible using the .NET libraries. </p>\n\n<p>I solved it by using the Mono class library implementation of System.Security.SslStream, which gives better access to overriding the servers behavior during the handshake.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5542/"
] | I am attempting to use the .Net System.Security.SslStream class to process the server side of a SSL/TLS stream with client authentication.
To perform the handshake, I am using this code:
```
SslStream sslStream = new SslStream(innerStream, false, RemoteCertificateValidation, LocalCertificateSelectionCallback);
sslStream.AuthenticateAsServer(serverCertificate, true, SslProtocols.Default, false);
```
Unfortunately, this results in the SslStream transmitting a CertificateRequest containing the subjectnames of all certificates in my CryptoAPI Trusted Root Store.
I would like to be able to override this. It is not an option for me to require the user to install or remove certificates from the Trusted Root Store.
It looks like the SslStream uses SSPI/SecureChannel underneath, so if anyone knows how to do the equivalent with that API, that would be helpful, too.
Any ideas? | It does not look like this is currently possible using the .NET libraries.
I solved it by using the Mono class library implementation of System.Security.SslStream, which gives better access to overriding the servers behavior during the handshake. |
53,844 | <p>I would like to do the equivalent of:</p>
<pre><code>object result = Eval("1 + 3");
string now = Eval("System.DateTime.Now().ToString()") as string
</code></pre>
<p>Following Biri s <a href="http://www.codeproject.com/KB/cs/evalcscode.aspx" rel="noreferrer">link</a>, I got this snippet (modified to remove obsolete method <code>ICodeCompiler.CreateCompiler()</code>:</p>
<pre><code>private object Eval(string sExpression)
{
CSharpCodeProvider c = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.CompilerOptions = "/t:library";
cp.GenerateInMemory = true;
StringBuilder sb = new StringBuilder("");
sb.Append("using System;\n");
sb.Append("namespace CSCodeEvaler{ \n");
sb.Append("public class CSCodeEvaler{ \n");
sb.Append("public object EvalCode(){\n");
sb.Append("return " + sExpression + "; \n");
sb.Append("} \n");
sb.Append("} \n");
sb.Append("}\n");
CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());
if (cr.Errors.Count > 0)
{
throw new InvalidExpressionException(
string.Format("Error ({0}) evaluating: {1}",
cr.Errors[0].ErrorText, sExpression));
}
System.Reflection.Assembly a = cr.CompiledAssembly;
object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");
Type t = o.GetType();
MethodInfo mi = t.GetMethod("EvalCode");
object s = mi.Invoke(o, null);
return s;
}
</code></pre>
| [
{
"answer_id": 54339,
"author": "JJJ",
"author_id": 5547,
"author_profile": "https://Stackoverflow.com/users/5547",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>What are the performance implications of doing this?</p>\n</blockquote>\n\n<p>We use a system based on something like the above mentioned, where each C# script is compiled to an in-memory assembly and executed in a separate AppDomain. There's no caching system yet, so the scripts are recompiled every time they run. I've done some simple testing and a very simple \"Hello World\" script compiles in about 0.7 seconds on my machine, including loading the script from disk. 0.7 seconds is fine for a scripting system, but might be too slow for responding to user input, in that case a dedicated parser/compiler like Flee might be better.</p>\n\n<pre><code>using System;\npublic class Test\n{\n static public void DoStuff( Scripting.IJob Job)\n {\n Console.WriteLine( \"Heps\" );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 286189,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like there is also a way of doing it using RegEx and XPathNavigator to evaluate the expression. I did not have the chance to test it yet but I kind of liked it because it did not require to compile code at runtime or use libraries that could not be available.</p>\n\n<p><a href=\"http://www.webtips.co.in/c/evaluate-function-in-c-net-as-eval-function-in-javascript.aspx\" rel=\"nofollow noreferrer\">http://www.webtips.co.in/c/evaluate-function-in-c-net-as-eval-function-in-javascript.aspx</a></p>\n\n<p>I'll try it and tell later if it worked. I also intend to try it in Silverlight, but it is too late and I'm almost asleep to do it now.</p>\n"
},
{
"answer_id": 4050198,
"author": "Rudolf_Abel",
"author_id": 491038,
"author_profile": "https://Stackoverflow.com/users/491038",
"pm_score": 2,
"selected": false,
"text": "<pre><code>using System;\nusing Microsoft.JScript;\nusing Microsoft.JScript.Vsa;\nusing Convert = Microsoft.JScript.Convert;\n\nnamespace System\n{\n public class MathEvaluator : INeedEngine\n {\n private VsaEngine vsaEngine;\n\n public virtual String Evaluate(string expr)\n {\n var engine = (INeedEngine)this;\n var result = Eval.JScriptEvaluate(expr, engine.GetEngine());\n\n return Convert.ToString(result, true);\n }\n\n VsaEngine INeedEngine.GetEngine()\n {\n vsaEngine = vsaEngine ?? VsaEngine.CreateEngineWithType(this.GetType().TypeHandle);\n return vsaEngine;\n }\n\n void INeedEngine.SetEngine(VsaEngine engine)\n {\n vsaEngine = engine;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6301451,
"author": "xnaterm",
"author_id": 445334,
"author_profile": "https://Stackoverflow.com/users/445334",
"pm_score": 0,
"selected": false,
"text": "<p>While C# doesn't have any support for an Eval method natively, I have a C# eval program that does allow for evaluating C# code. It provides for evaluating C# code at runtime and supports many C# statements. In fact, this code is usable within any .NET project, however, it is limited to using C# syntax. Have a look at my website, <a href=\"http://csharp-eval.com\" rel=\"nofollow\">http://csharp-eval.com</a>, for additional details.</p>\n"
},
{
"answer_id": 14761604,
"author": "Davide Icardi",
"author_id": 209727,
"author_profile": "https://Stackoverflow.com/users/209727",
"pm_score": 5,
"selected": false,
"text": "<p>I have written an open source project, <a href=\"https://github.com/davideicardi/DynamicExpresso/\" rel=\"noreferrer\">Dynamic Expresso</a>, that can convert text expression written using a C# syntax into delegates (or expression tree). Text expressions are parsed and transformed into <a href=\"http://msdn.microsoft.com/en-us/library/bb397951.aspx\" rel=\"noreferrer\">Expression Trees</a> without using compilation or reflection.</p>\n\n<p>You can write something like:</p>\n\n<pre><code>var interpreter = new Interpreter();\nvar result = interpreter.Eval(\"8 / 2 + 2\");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var interpreter = new Interpreter()\n .SetVariable(\"service\", new ServiceExample());\n\nstring expression = \"x > 4 ? service.aMethod() : service.AnotherMethod()\";\n\nLambda parsedExpression = interpreter.Parse(expression, \n new Parameter(\"x\", typeof(int)));\n\nparsedExpression.Invoke(5);\n</code></pre>\n\n<p>My work is based on Scott Gu article <a href=\"http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx\" rel=\"noreferrer\">http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx</a> .</p>\n"
},
{
"answer_id": 43630318,
"author": "Ridkuma",
"author_id": 5466644,
"author_profile": "https://Stackoverflow.com/users/5466644",
"pm_score": 5,
"selected": false,
"text": "<p>Old topic, but considering this is one of the first threads showing up when googling, here is an updated solution.</p>\n\n<p>You can use <a href=\"https://github.com/dotnet/roslyn/wiki/Scripting-API-Samples\" rel=\"noreferrer\">Roslyn's new Scripting API to evaluate expressions</a>.</p>\n\n<p>If you are using NuGet, just add a dependency to <a href=\"https://www.nuget.org/packages/Microsoft.CodeAnalysis.CSharp.Scripting/\" rel=\"noreferrer\">Microsoft.CodeAnalysis.CSharp.Scripting</a>.\nTo evaluate the examples you provided, it is as simple as:</p>\n\n<pre><code>var result = CSharpScript.EvaluateAsync(\"1 + 3\").Result;\n</code></pre>\n\n<p>This obviously does not make use of the scripting engine's async capabilities. </p>\n\n<p>You can also specify the evaluated result type as you intended: </p>\n\n<pre><code>var now = CSharpScript.EvaluateAsync<string>(\"System.DateTime.Now.ToString()\").Result;\n</code></pre>\n\n<p>To evaluate more advanced code snippets, pass parameters, provide references, namespaces and whatnot, check the wiki linked above.</p>\n"
},
{
"answer_id": 52685808,
"author": "cdiggins",
"author_id": 184528,
"author_profile": "https://Stackoverflow.com/users/184528",
"pm_score": 4,
"selected": false,
"text": "<p>If you specifically want to call into code and assemblies in your own project I would advocate using the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.codedom.compiler.codedomprovider?view=netframework-4.7.2\" rel=\"noreferrer\">C# CodeDom CodeProvider</a>. </p>\n\n<p>Here is a list of the most popular approaches that I am aware of for evaluating string expressions dynamically in C#. </p>\n\n<h2>Microsoft Solutions</h2>\n\n<ul>\n<li><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.codedom.compiler.codedomprovider?view=netframework-4.7.2\" rel=\"noreferrer\">C# CodeDom CodeProvider</a>: \n\n<ul>\n<li>See <a href=\"https://stackoverflow.com/questions/5766373/how-does-linqpad-compile-code\">How LINQ used to work</a> and this <a href=\"https://www.codeproject.com/Articles/11939/Evaluate-C-Code-Eval-Function\" rel=\"noreferrer\">CodeProject article</a></li>\n</ul></li>\n<li><a href=\"https://github.com/dotnet/roslyn\" rel=\"noreferrer\">Roslyn</a>:\n\n<ul>\n<li>See this <a href=\"https://joshvarty.com/2016/01/16/learn-roslyn-now-part-16-the-emit-api\" rel=\"noreferrer\">article on Rosly Emit API</a> and this <a href=\"https://stackoverflow.com/a/43630318/184528\">StackOverflow answer</a></li>\n</ul></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.data.datatable.compute.aspx\" rel=\"noreferrer\">DataTable.Compute</a>:\n\n<ul>\n<li>See this <a href=\"https://stackoverflow.com/a/12431343/184528\">answer on StackOverflow</a></li>\n</ul></li>\n<li><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.htmldocument.invokescript?view=netframework-4.7.2\" rel=\"noreferrer\">Webbrowser.Document.InvokeScript</a>\n\n<ul>\n<li>See this <a href=\"https://stackoverflow.com/questions/7322420/calling-javascript-object-method-using-webbrowser-document-invokescript\">StackOverflow question</a></li>\n</ul></li>\n<li><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.databinder.eval?redirectedfrom=MSDN&view=netframework-4.7.2#overloads\" rel=\"noreferrer\">DataBinder.Eval</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-6.0/aa227400(v=vs.60)\" rel=\"noreferrer\">ScriptControl</a>\n\n<ul>\n<li>See <a href=\"https://stackoverflow.com/questions/12431286/calculate-result-from-a-string-expression-dynamically/12431435#12431435\">this answer on StackOverflow</a> and <a href=\"https://stackoverflow.com/questions/16075775/calling-the-javascript-functions-inside-c-sharp-for-a-64-bit-project?noredirect=1&lq=1\">this question</a></li>\n</ul></li>\n<li>Executing PowerShell:\n\n<ul>\n<li>See <a href=\"https://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C\" rel=\"noreferrer\">this CodeProject article</a></li>\n</ul></li>\n</ul>\n\n<h2>Non-Microsoft solutions (not that there is anything wrong with that)</h2>\n\n<ul>\n<li>Expression evaluation libraries:\n\n<ul>\n<li><a href=\"https://github.com/mparlak/Flee\" rel=\"noreferrer\">Flee</a></li>\n<li><a href=\"https://github.com/davideicardi/DynamicExpresso/\" rel=\"noreferrer\">DynamicExpresso</a></li>\n<li><a href=\"https://archive.codeplex.com/?p=ncalc\" rel=\"noreferrer\">NCalc</a></li>\n<li><a href=\"https://github.com/codingseb/ExpressionEvaluator\" rel=\"noreferrer\">CodingSeb.ExpressionEvaluator</a></li>\n<li><a href=\"https://github.com/zzzprojects/Eval-Expression.NET\" rel=\"noreferrer\">Eval-Expression.NET</a></li>\n</ul></li>\n<li>Javascript interpreter\n\n<ul>\n<li><a href=\"https://github.com/sebastienros/jint\" rel=\"noreferrer\">Jint</a></li>\n</ul></li>\n<li>To execute real C#\n\n<ul>\n<li><a href=\"https://github.com/oleg-shilo/cs-script\" rel=\"noreferrer\">CS-Script</a></li>\n</ul></li>\n<li>Roll your own a language building toolkit like:\n\n<ul>\n<li><a href=\"https://archive.codeplex.com/?p=irony\" rel=\"noreferrer\">Irony</a></li>\n<li><a href=\"https://www.codeproject.com/Articles/272494/Implementing-Programming-Languages-using-Csharp\" rel=\"noreferrer\">Jigsaw</a> </li>\n</ul></li>\n</ul>\n"
},
{
"answer_id": 68767842,
"author": "Binh",
"author_id": 8046877,
"author_profile": "https://Stackoverflow.com/users/8046877",
"pm_score": 1,
"selected": false,
"text": "<p>I have just written a similar library (<a href=\"https://github.com/matheval/expression-evaluator-c-sharp\" rel=\"nofollow noreferrer\">Matheval</a>) in pure C#.\nIt allows evaluating string and number expression like excel fomular.</p>\n<pre><code>using System;\nusing org.matheval;\n \npublic class Program\n{\n public static void Main()\n {\n Expression expression = new Expression("IF(time>8, (HOUR_SALARY*8) + (HOUR_SALARY*1.25*(time-8)), HOUR_SALARY*time)");\n //bind variable\n expression.Bind("HOUR_SALARY", 10);\n expression.Bind("time", 9);\n //eval\n Decimal salary = expression.Eval<Decimal>(); \n Console.WriteLine(salary);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 70491393,
"author": "Venugopal M",
"author_id": 2132005,
"author_profile": "https://Stackoverflow.com/users/2132005",
"pm_score": 0,
"selected": false,
"text": "<p>There is a nice piece of code here\n<a href=\"https://www.c-sharpcorner.com/article/codedom-calculator-evaluating-c-sharp-math-expressions-dynamica/\" rel=\"nofollow noreferrer\">https://www.c-sharpcorner.com/article/codedom-calculator-evaluating-c-sharp-math-expressions-dynamica/</a></p>\n<p>Download this and make it a class library which may be referenced in your project. This seems to be pretty fast and simple</p>\n<p>Perhaps this could help !</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] | I would like to do the equivalent of:
```
object result = Eval("1 + 3");
string now = Eval("System.DateTime.Now().ToString()") as string
```
Following Biri s [link](http://www.codeproject.com/KB/cs/evalcscode.aspx), I got this snippet (modified to remove obsolete method `ICodeCompiler.CreateCompiler()`:
```
private object Eval(string sExpression)
{
CSharpCodeProvider c = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.CompilerOptions = "/t:library";
cp.GenerateInMemory = true;
StringBuilder sb = new StringBuilder("");
sb.Append("using System;\n");
sb.Append("namespace CSCodeEvaler{ \n");
sb.Append("public class CSCodeEvaler{ \n");
sb.Append("public object EvalCode(){\n");
sb.Append("return " + sExpression + "; \n");
sb.Append("} \n");
sb.Append("} \n");
sb.Append("}\n");
CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());
if (cr.Errors.Count > 0)
{
throw new InvalidExpressionException(
string.Format("Error ({0}) evaluating: {1}",
cr.Errors[0].ErrorText, sExpression));
}
System.Reflection.Assembly a = cr.CompiledAssembly;
object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");
Type t = o.GetType();
MethodInfo mi = t.GetMethod("EvalCode");
object s = mi.Invoke(o, null);
return s;
}
``` | I have written an open source project, [Dynamic Expresso](https://github.com/davideicardi/DynamicExpresso/), that can convert text expression written using a C# syntax into delegates (or expression tree). Text expressions are parsed and transformed into [Expression Trees](http://msdn.microsoft.com/en-us/library/bb397951.aspx) without using compilation or reflection.
You can write something like:
```
var interpreter = new Interpreter();
var result = interpreter.Eval("8 / 2 + 2");
```
or
```
var interpreter = new Interpreter()
.SetVariable("service", new ServiceExample());
string expression = "x > 4 ? service.aMethod() : service.AnotherMethod()";
Lambda parsedExpression = interpreter.Parse(expression,
new Parameter("x", typeof(int)));
parsedExpression.Invoke(5);
```
My work is based on Scott Gu article <http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx> . |
53,849 | <p>Java has a convenient split method:</p>
<pre><code>String str = "The quick brown fox";
String[] results = str.split(" ");
</code></pre>
<p>Is there an easy way to do this in C++?</p>
| [
{
"answer_id": 53862,
"author": "vzczc",
"author_id": 224,
"author_profile": "https://Stackoverflow.com/users/224",
"pm_score": 5,
"selected": false,
"text": "<p>Here is a sample tokenizer class that might do what you want </p>\n\n<pre><code>//Header file\nclass Tokenizer \n{\n public:\n static const std::string DELIMITERS;\n Tokenizer(const std::string& str);\n Tokenizer(const std::string& str, const std::string& delimiters);\n bool NextToken();\n bool NextToken(const std::string& delimiters);\n const std::string GetToken() const;\n void Reset();\n protected:\n size_t m_offset;\n const std::string m_string;\n std::string m_token;\n std::string m_delimiters;\n};\n\n//CPP file\nconst std::string Tokenizer::DELIMITERS(\" \\t\\n\\r\");\n\nTokenizer::Tokenizer(const std::string& s) :\n m_string(s), \n m_offset(0), \n m_delimiters(DELIMITERS) {}\n\nTokenizer::Tokenizer(const std::string& s, const std::string& delimiters) :\n m_string(s), \n m_offset(0), \n m_delimiters(delimiters) {}\n\nbool Tokenizer::NextToken() \n{\n return NextToken(m_delimiters);\n}\n\nbool Tokenizer::NextToken(const std::string& delimiters) \n{\n size_t i = m_string.find_first_not_of(delimiters, m_offset);\n if (std::string::npos == i) \n {\n m_offset = m_string.length();\n return false;\n }\n\n size_t j = m_string.find_first_of(delimiters, i);\n if (std::string::npos == j) \n {\n m_token = m_string.substr(i);\n m_offset = m_string.length();\n return true;\n }\n\n m_token = m_string.substr(i, j - i);\n m_offset = j;\n return true;\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>std::vector <std::string> v;\nTokenizer s(\"split this string\", \" \");\nwhile (s.NextToken())\n{\n v.push_back(s.GetToken());\n}\n</code></pre>\n"
},
{
"answer_id": 53863,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 8,
"selected": true,
"text": "<p>C++ standard library algorithms are pretty universally based around iterators rather than concrete containers. Unfortunately this makes it hard to provide a Java-like <code>split</code> function in the C++ standard library, even though nobody argues that this would be convenient. But what would its return type be? <code>std::vector<std::basic_string<…>></code>? Maybe, but then we’re forced to perform (potentially redundant and costly) allocations.</p>\n\n<p>Instead, C++ offers a plethora of ways to split strings based on arbitrarily complex delimiters, but none of them is encapsulated as nicely as in other languages. The numerous ways <a href=\"https://www.fluentcpp.com/2017/04/21/how-to-split-a-string-in-c/\" rel=\"noreferrer\">fill whole blog posts</a>.</p>\n\n<p>At its simplest, you could iterate using <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/find\" rel=\"noreferrer\"><code>std::string::find</code></a> until you hit <code>std::string::npos</code>, and extract the contents using <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/substr\" rel=\"noreferrer\"><code>std::string::substr</code></a>.</p>\n\n<p>A more fluid (and idiomatic, but basic) version for splitting on whitespace would use a <a href=\"https://en.cppreference.com/w/cpp/io/basic_istringstream\" rel=\"noreferrer\"><code>std::istringstream</code></a>:</p>\n\n<pre><code>auto iss = std::istringstream{\"The quick brown fox\"};\nauto str = std::string{};\n\nwhile (iss >> str) {\n process(str);\n}\n</code></pre>\n\n<p>Using <a href=\"https://en.cppreference.com/w/cpp/iterator/istream_iterator\" rel=\"noreferrer\"><code>std::istream_iterator</code>s</a>, the contents of the string stream could also be copied into a vector using its iterator range constructor.</p>\n\n<p>Multiple libraries (such as <a href=\"https://www.boost.org/doc/libs/1_70_0/libs/tokenizer/doc/tokenizer.htm\" rel=\"noreferrer\">Boost.Tokenizer</a>) offer specific tokenisers.</p>\n\n<p>More advanced splitting require regular expressions. C++ provides the <a href=\"https://en.cppreference.com/w/cpp/regex/regex_token_iterator\" rel=\"noreferrer\"><code>std::regex_token_iterator</code></a> for this purpose in particular:</p>\n\n<pre><code>auto const str = \"The quick brown fox\"s;\nauto const re = std::regex{R\"(\\s+)\"};\nauto const vec = std::vector<std::string>(\n std::sregex_token_iterator{begin(str), end(str), re, -1},\n std::sregex_token_iterator{}\n);\n</code></pre>\n"
},
{
"answer_id": 53867,
"author": "On Freund",
"author_id": 2150,
"author_profile": "https://Stackoverflow.com/users/2150",
"pm_score": 2,
"selected": false,
"text": "<p>If you're willing to use C, you can use the <a href=\"http://www.cplusplus.com/reference/clibrary/cstring/strtok.html\" rel=\"nofollow noreferrer\">strtok</a> function. You should pay attention to multi-threading issues when using it.</p>\n"
},
{
"answer_id": 53878,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 7,
"selected": false,
"text": "<p>Here's a real simple one:</p>\n\n<pre><code>#include <vector>\n#include <string>\nusing namespace std;\n\nvector<string> split(const char *str, char c = ' ')\n{\n vector<string> result;\n\n do\n {\n const char *begin = str;\n\n while(*str != c && *str)\n str++;\n\n result.push_back(string(begin, str));\n } while (0 != *str++);\n\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 53915,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 2,
"selected": false,
"text": "<p>I thought that was what the <code>>></code> operator on string streams was for:</p>\n\n<pre><code>string word; sin >> word;\n</code></pre>\n"
},
{
"answer_id": 53921,
"author": "KeithB",
"author_id": 2298,
"author_profile": "https://Stackoverflow.com/users/2298",
"pm_score": 6,
"selected": false,
"text": "<p>You can use streams, iterators, and the copy algorithm to do this fairly directly.</p>\n\n<pre><code>#include <string>\n#include <vector>\n#include <iostream>\n#include <istream>\n#include <ostream>\n#include <iterator>\n#include <sstream>\n#include <algorithm>\n\nint main()\n{\n std::string str = \"The quick brown fox\";\n\n // construct a stream from the string\n std::stringstream strstr(str);\n\n // use stream iterators to copy the stream to the vector as whitespace separated strings\n std::istream_iterator<std::string> it(strstr);\n std::istream_iterator<std::string> end;\n std::vector<std::string> results(it, end);\n\n // send the vector to stdout.\n std::ostream_iterator<std::string> oit(std::cout);\n std::copy(results.begin(), results.end(), oit);\n}\n</code></pre>\n"
},
{
"answer_id": 54048,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 7,
"selected": false,
"text": "<p>Use strtok. In my opinion, there isn't a need to build a class around tokenizing unless strtok doesn't provide you with what you need. It might not, but in 15+ years of writing various parsing code in C and C++, I've always used strtok. Here is an example</p>\n\n<pre><code>char myString[] = \"The quick brown fox\";\nchar *p = strtok(myString, \" \");\nwhile (p) {\n printf (\"Token: %s\\n\", p);\n p = strtok(NULL, \" \");\n}\n</code></pre>\n\n<p>A few caveats (which might not suit your needs). The string is \"destroyed\" in the process, meaning that EOS characters are placed inline in the delimter spots. Correct usage might require you to make a non-const version of the string. You can also change the list of delimiters mid parse.</p>\n\n<p>In my own opinion, the above code is far simpler and easier to use than writing a separate class for it. To me, this is one of those functions that the language provides and it does it well and cleanly. It's simply a \"C based\" solution. It's appropriate, it's easy, and you don't have to write a lot of extra code :-)</p>\n"
},
{
"answer_id": 55680,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 8,
"selected": false,
"text": "<p>The <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/tokenizer/index.html\" rel=\"noreferrer\">Boost tokenizer</a> class can make this sort of thing quite simple:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <boost/foreach.hpp>\n#include <boost/tokenizer.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nint main(int, char**)\n{\n string text = \"token, test string\";\n\n char_separator<char> sep(\", \");\n tokenizer< char_separator<char> > tokens(text, sep);\n BOOST_FOREACH (const string& t, tokens) {\n cout << t << \".\" << endl;\n }\n}\n</code></pre>\n\n<p>Updated for C++11:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <boost/tokenizer.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nint main(int, char**)\n{\n string text = \"token, test string\";\n\n char_separator<char> sep(\", \");\n tokenizer<char_separator<char>> tokens(text, sep);\n for (const auto& t : tokens) {\n cout << t << \".\" << endl;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 59552,
"author": "Raz",
"author_id": 5661,
"author_profile": "https://Stackoverflow.com/users/5661",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Boost_C%2B%2B_Libraries\" rel=\"noreferrer\">Boost</a> has a strong split function: <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/boost/algorithm/split_id2965593.html\" rel=\"noreferrer\">boost::algorithm::split</a>.</p>\n\n<p>Sample program:</p>\n\n<pre><code>#include <vector>\n#include <boost/algorithm/string.hpp>\n\nint main() {\n auto s = \"a,b, c ,,e,f,\";\n std::vector<std::string> fields;\n boost::split(fields, s, boost::is_any_of(\",\"));\n for (const auto& field : fields)\n std::cout << \"\\\"\" << field << \"\\\"\\n\";\n return 0;\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>\"a\"\n\"b\"\n\" c \"\n\"\"\n\"e\"\n\"f\"\n\"\"\n</code></pre>\n"
},
{
"answer_id": 63946,
"author": "jilles de wit",
"author_id": 7531,
"author_profile": "https://Stackoverflow.com/users/7531",
"pm_score": 2,
"selected": false,
"text": "<p>For simple stuff I just use the following:</p>\n\n<pre><code>unsigned TokenizeString(const std::string& i_source,\n const std::string& i_seperators,\n bool i_discard_empty_tokens,\n std::vector<std::string>& o_tokens)\n{\n unsigned prev_pos = 0;\n unsigned pos = 0;\n unsigned number_of_tokens = 0;\n o_tokens.clear();\n pos = i_source.find_first_of(i_seperators, pos);\n while (pos != std::string::npos)\n {\n std::string token = i_source.substr(prev_pos, pos - prev_pos);\n if (!i_discard_empty_tokens || token != \"\")\n {\n o_tokens.push_back(i_source.substr(prev_pos, pos - prev_pos));\n number_of_tokens++;\n }\n\n pos++;\n prev_pos = pos;\n pos = i_source.find_first_of(i_seperators, pos);\n }\n\n if (prev_pos < i_source.length())\n {\n o_tokens.push_back(i_source.substr(prev_pos));\n number_of_tokens++;\n }\n\n return number_of_tokens;\n}\n</code></pre>\n\n<p>Cowardly disclaimer: I write real-time data processing software where the data comes in through binary files, sockets, or some API call (I/O cards, camera's). I never use this function for something more complicated or time-critical than reading external configuration files on startup.</p>\n"
},
{
"answer_id": 325000,
"author": "Mr.Ree",
"author_id": 37946,
"author_profile": "https://Stackoverflow.com/users/37946",
"pm_score": 6,
"selected": false,
"text": "<p>No offense folks, but for such a simple problem, you are making things <strong><em>way</em></strong> too complicated. There are a lot of reasons to use <a href=\"http://en.wikipedia.org/wiki/Boost_C%2B%2B_Libraries\" rel=\"nofollow noreferrer\">Boost</a>. But for something this simple, it's like hitting a fly with a 20# sledge.</p>\n\n<pre><code>void\nsplit( vector<string> & theStringVector, /* Altered/returned value */\n const string & theString,\n const string & theDelimiter)\n{\n UASSERT( theDelimiter.size(), >, 0); // My own ASSERT macro.\n\n size_t start = 0, end = 0;\n\n while ( end != string::npos)\n {\n end = theString.find( theDelimiter, start);\n\n // If at end, use length=maxLength. Else use length=end-start.\n theStringVector.push_back( theString.substr( start,\n (end == string::npos) ? string::npos : end - start));\n\n // If at end, use start=maxSize. Else use start=end+delimiter.\n start = ( ( end > (string::npos - theDelimiter.size()) )\n ? string::npos : end + theDelimiter.size());\n }\n}\n</code></pre>\n\n<p>For example (for Doug's case),</p>\n\n<pre><code>#define SHOW(I,X) cout << \"[\" << (I) << \"]\\t \" # X \" = \\\"\" << (X) << \"\\\"\" << endl\n\nint\nmain()\n{\n vector<string> v;\n\n split( v, \"A:PEP:909:Inventory Item\", \":\" );\n\n for (unsigned int i = 0; i < v.size(); i++)\n SHOW( i, v[i] );\n}\n</code></pre>\n\n<p>And yes, we could have split() return a new vector rather than passing one in. It's trivial to wrap and overload. But depending on what I'm doing, I often find it better to re-use pre-existing objects rather than always creating new ones. (Just as long as I don't forget to empty the vector in between!)</p>\n\n<p>Reference: <a href=\"http://en.cppreference.com/w/cpp/string/basic_string\" rel=\"nofollow noreferrer\">http://www.cplusplus.com/reference/string/string/</a>.</p>\n\n<p>(I was originally writing a response to Doug's question: <a href=\"https://stackoverflow.com/questions/324867/c-strings-modifying-and-extracting-based-on-separators\">C++ Strings Modifying and Extracting based on Separators (closed)</a>. But since Martin York closed that question with a pointer over here... I'll just generalize my code.)</p>\n"
},
{
"answer_id": 325042,
"author": "user35978",
"author_id": 35978,
"author_profile": "https://Stackoverflow.com/users/35978",
"pm_score": 7,
"selected": false,
"text": "<p>Another quick way is to use <code>getline</code>. Something like:</p>\n\n<pre><code>stringstream ss(\"bla bla\");\nstring s;\n\nwhile (getline(ss, s, ' ')) {\n cout << s << endl;\n}\n</code></pre>\n\n<p>If you want, you can make a simple <code>split()</code> method returning a <code>vector<string></code>, which is \nreally useful. </p>\n"
},
{
"answer_id": 670441,
"author": "Jim In Texas",
"author_id": 15079,
"author_profile": "https://Stackoverflow.com/users/15079",
"pm_score": 3,
"selected": false,
"text": "<p>MFC/ATL has a very nice tokenizer. From MSDN:</p>\n\n<pre><code>CAtlString str( \"%First Second#Third\" );\nCAtlString resToken;\nint curPos= 0;\n\nresToken= str.Tokenize(\"% #\",curPos);\nwhile (resToken != \"\")\n{\n printf(\"Resulting token: %s\\n\", resToken);\n resToken= str.Tokenize(\"% #\",curPos);\n};\n\nOutput\n\nResulting Token: First\nResulting Token: Second\nResulting Token: Third\n</code></pre>\n"
},
{
"answer_id": 3408134,
"author": "sivabudh",
"author_id": 65313,
"author_profile": "https://Stackoverflow.com/users/65313",
"pm_score": 5,
"selected": false,
"text": "<p>I know you asked for a C++ solution, but you might consider this helpful:</p>\n\n<p><strong>Qt</strong></p>\n\n<pre><code>#include <QString>\n\n...\n\nQString str = \"The quick brown fox\"; \nQStringList results = str.split(\" \"); \n</code></pre>\n\n<p>The advantage over Boost in this example is that it's a direct one to one mapping to your post's code.</p>\n\n<p>See more at <a href=\"https://doc.qt.io/qt-5/qstring.html#split\" rel=\"noreferrer\">Qt documentation</a></p>\n"
},
{
"answer_id": 4489586,
"author": "sohesado",
"author_id": 548600,
"author_profile": "https://Stackoverflow.com/users/548600",
"pm_score": 3,
"selected": false,
"text": "<p>Check this example. It might help you..</p>\n\n<pre><code>#include <iostream>\n#include <sstream>\n\nusing namespace std;\n\nint main ()\n{\n string tmps;\n istringstream is (\"the dellimiter is the space\");\n while (is.good ()) {\n is >> tmps;\n cout << tmps << \"\\n\";\n }\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 5751134,
"author": "Fawix",
"author_id": 706840,
"author_profile": "https://Stackoverflow.com/users/706840",
"pm_score": 2,
"selected": false,
"text": "<p>You can simply use a <a href=\"http://www.tropicsoft.com/Components/RegularExpression/\" rel=\"nofollow noreferrer\">regular expression library</a> and solve that using regular expressions.</p>\n\n<p>Use expression (\\w+) and the variable in \\1 (or $1 depending on the library implementation of regular expressions).</p>\n"
},
{
"answer_id": 6011144,
"author": "Angel Sinigersky",
"author_id": 754396,
"author_profile": "https://Stackoverflow.com/users/754396",
"pm_score": 0,
"selected": false,
"text": "<p>If the maximum length of the input string to be tokenized is known, one can exploit this and implement a very fast version. I am sketching the basic idea below, which was inspired by both strtok() and the \"suffix array\"-data structure described Jon Bentley's \"Programming Perls\" 2nd edition, chapter 15. The C++ class in this case only gives some organization and convenience of use. The implementation shown can be easily extended for removing leading and trailing whitespace characters in the tokens.</p>\n\n<p>Basically one can replace the separator characters with string-terminating '\\0'-characters and set pointers to the tokens withing the modified string. In the extreme case when the string consists only of separators, one gets string-length plus 1 resulting empty tokens. It is practical to duplicate the string to be modified.</p>\n\n<p>Header file:</p>\n\n<pre><code>class TextLineSplitter\n{\npublic:\n\n TextLineSplitter( const size_t max_line_len );\n\n ~TextLineSplitter();\n\n void SplitLine( const char *line,\n const char sep_char = ',',\n );\n\n inline size_t NumTokens( void ) const\n {\n return mNumTokens;\n }\n\n const char * GetToken( const size_t token_idx ) const\n {\n assert( token_idx < mNumTokens );\n return mTokens[ token_idx ];\n }\n\nprivate:\n const size_t mStorageSize;\n\n char *mBuff;\n char **mTokens;\n size_t mNumTokens;\n\n inline void ResetContent( void )\n {\n memset( mBuff, 0, mStorageSize );\n // mark all items as empty:\n memset( mTokens, 0, mStorageSize * sizeof( char* ) );\n // reset counter for found items:\n mNumTokens = 0L;\n }\n};\n</code></pre>\n\n<p>Implementattion file:</p>\n\n<pre><code>TextLineSplitter::TextLineSplitter( const size_t max_line_len ):\n mStorageSize ( max_line_len + 1L )\n{\n // allocate memory\n mBuff = new char [ mStorageSize ];\n mTokens = new char* [ mStorageSize ];\n\n ResetContent();\n}\n\nTextLineSplitter::~TextLineSplitter()\n{\n delete [] mBuff;\n delete [] mTokens;\n}\n\n\nvoid TextLineSplitter::SplitLine( const char *line,\n const char sep_char /* = ',' */,\n )\n{\n assert( sep_char != '\\0' );\n\n ResetContent();\n strncpy( mBuff, line, mMaxLineLen );\n\n size_t idx = 0L; // running index for characters\n\n do\n {\n assert( idx < mStorageSize );\n\n const char chr = line[ idx ]; // retrieve current character\n\n if( mTokens[ mNumTokens ] == NULL )\n {\n mTokens[ mNumTokens ] = &mBuff[ idx ];\n } // if\n\n if( chr == sep_char || chr == '\\0' )\n { // item or line finished\n // overwrite separator with a 0-terminating character:\n mBuff[ idx ] = '\\0';\n // count-up items:\n mNumTokens ++;\n } // if\n\n } while( line[ idx++ ] );\n}\n</code></pre>\n\n<p>A scenario of usage would be:</p>\n\n<pre><code>// create an instance capable of splitting strings up to 1000 chars long:\nTextLineSplitter spl( 1000 );\nspl.SplitLine( \"Item1,,Item2,Item3\" );\nfor( size_t i = 0; i < spl.NumTokens(); i++ )\n{\n printf( \"%s\\n\", spl.GetToken( i ) );\n}\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>Item1\n\nItem2\nItem3\n</code></pre>\n"
},
{
"answer_id": 6922744,
"author": "Arash",
"author_id": 551537,
"author_profile": "https://Stackoverflow.com/users/551537",
"pm_score": 1,
"selected": false,
"text": "<p>you can take advantage of boost::make_find_iterator. Something similar to this:</p>\n\n<pre><code>template<typename CH>\ninline vector< basic_string<CH> > tokenize(\n const basic_string<CH> &Input,\n const basic_string<CH> &Delimiter,\n bool remove_empty_token\n ) {\n\n typedef typename basic_string<CH>::const_iterator string_iterator_t;\n typedef boost::find_iterator< string_iterator_t > string_find_iterator_t;\n\n vector< basic_string<CH> > Result;\n string_iterator_t it = Input.begin();\n string_iterator_t it_end = Input.end();\n for(string_find_iterator_t i = boost::make_find_iterator(Input, boost::first_finder(Delimiter, boost::is_equal()));\n i != string_find_iterator_t();\n ++i) {\n if(remove_empty_token){\n if(it != i->begin())\n Result.push_back(basic_string<CH>(it,i->begin()));\n }\n else\n Result.push_back(basic_string<CH>(it,i->begin()));\n it = i->end();\n }\n if(it != it_end)\n Result.push_back(basic_string<CH>(it,it_end));\n\n return Result;\n}\n</code></pre>\n"
},
{
"answer_id": 8669587,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://github.com/imageworks/pystring\" rel=\"noreferrer\">pystring</a> is a small library which implements a bunch of Python's string functions, including the split method:</p>\n\n<pre><code>#include <string>\n#include <vector>\n#include \"pystring.h\"\n\nstd::vector<std::string> chunks;\npystring::split(\"this string\", chunks);\n\n// also can specify a separator\npystring::split(\"this-string\", chunks, \"-\");\n</code></pre>\n"
},
{
"answer_id": 11497058,
"author": "jochenleidner",
"author_id": 1527677,
"author_profile": "https://Stackoverflow.com/users/1527677",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.boost.org/doc/libs/1_50_0/libs/tokenizer/index.html\" rel=\"nofollow\"><code>boost::tokenizer</code></a> is your friend, but consider making your code portable with reference to internationalization (i18n) issues by using <code>wstring</code>/<code>wchar_t</code> instead of the legacy <code>string</code>/<code>char</code> types.</p>\n\n<pre><code>#include <iostream>\n#include <boost/tokenizer.hpp>\n#include <string>\n\nusing namespace std;\nusing namespace boost;\n\ntypedef tokenizer<char_separator<wchar_t>,\n wstring::const_iterator, wstring> Tok;\n\nint main()\n{\n wstring s;\n while (getline(wcin, s)) {\n char_separator<wchar_t> sep(L\" \"); // list of separator characters\n Tok tok(s, sep);\n for (Tok::iterator beg = tok.begin(); beg != tok.end(); ++beg) {\n wcout << *beg << L\"\\t\"; // output (or store in vector)\n }\n wcout << L\"\\n\";\n }\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 11753247,
"author": "David919",
"author_id": 1567655,
"author_profile": "https://Stackoverflow.com/users/1567655",
"pm_score": 2,
"selected": false,
"text": "<p>Many overly complicated suggestions here. Try this simple std::string solution:</p>\n\n<pre><code>using namespace std;\n\nstring someText = ...\n\nstring::size_type tokenOff = 0, sepOff = tokenOff;\nwhile (sepOff != string::npos)\n{\n sepOff = someText.find(' ', sepOff);\n string::size_type tokenLen = (sepOff == string::npos) ? sepOff : sepOff++ - tokenOff;\n string token = someText.substr(tokenOff, tokenLen);\n if (!token.empty())\n /* do something with token */;\n tokenOff = sepOff;\n}\n</code></pre>\n"
},
{
"answer_id": 13089627,
"author": "Darren Smith",
"author_id": 1776419,
"author_profile": "https://Stackoverflow.com/users/1776419",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an approach that allows you control over whether empty tokens are included (like strsep) or excluded (like strtok). </p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <string.h> // for strchr and strlen\n\n/*\n * want_empty_tokens==true : include empty tokens, like strsep()\n * want_empty_tokens==false : exclude empty tokens, like strtok()\n */\nstd::vector<std::string> tokenize(const char* src,\n char delim,\n bool want_empty_tokens)\n{\n std::vector<std::string> tokens;\n\n if (src and *src != '\\0') // defensive\n while( true ) {\n const char* d = strchr(src, delim);\n size_t len = (d)? d-src : strlen(src);\n\n if (len or want_empty_tokens)\n tokens.push_back( std::string(src, len) ); // capture token\n\n if (d) src += len+1; else break;\n }\n\n return tokens;\n}\n</code></pre>\n"
},
{
"answer_id": 16635277,
"author": "Karthik",
"author_id": 2398970,
"author_profile": "https://Stackoverflow.com/users/2398970",
"pm_score": -1,
"selected": false,
"text": "<p>This a simple loop to tokenise with only standard library files</p>\n\n<pre><code>#include <iostream.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include <conio.h>\nclass word\n {\n public:\n char w[20];\n word()\n {\n for(int j=0;j<=20;j++)\n {w[j]='\\0';\n }\n }\n\n\n\n};\n\nvoid main()\n {\n int i=1,n=0,j=0,k=0,m=1;\n char input[100];\n word ww[100];\n gets(input);\n\n n=strlen(input);\n\n\n for(i=0;i<=m;i++)\n {\n if(context[i]!=' ')\n {\n ww[k].w[j]=context[i];\n j++;\n\n }\n else\n {\n k++;\n j=0;\n m++;\n }\n\n }\n }\n</code></pre>\n"
},
{
"answer_id": 20590157,
"author": "vsoftco",
"author_id": 3093378,
"author_profile": "https://Stackoverflow.com/users/3093378",
"pm_score": 0,
"selected": false,
"text": "<p>Simple C++ code (standard C++98), accepts multiple delimiters (specified in a std::string), uses only vectors, strings and iterators.</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <string>\n#include <stdexcept> \n\nstd::vector<std::string> \nsplit(const std::string& str, const std::string& delim){\n std::vector<std::string> result;\n if (str.empty())\n throw std::runtime_error(\"Can not tokenize an empty string!\");\n std::string::const_iterator begin, str_it;\n begin = str_it = str.begin(); \n do {\n while (delim.find(*str_it) == std::string::npos && str_it != str.end())\n str_it++; // find the position of the first delimiter in str\n std::string token = std::string(begin, str_it); // grab the token\n if (!token.empty()) // empty token only when str starts with a delimiter\n result.push_back(token); // push the token into a vector<string>\n while (delim.find(*str_it) != std::string::npos && str_it != str.end())\n str_it++; // ignore the additional consecutive delimiters\n begin = str_it; // process the remaining tokens\n } while (str_it != str.end());\n return result;\n}\n\nint main() {\n std::string test_string = \".this is.a.../.simple;;test;;;END\";\n std::string delim = \"; ./\"; // string containing the delimiters\n std::vector<std::string> tokens = split(test_string, delim); \n for (std::vector<std::string>::const_iterator it = tokens.begin(); \n it != tokens.end(); it++)\n std::cout << *it << std::endl;\n}\n</code></pre>\n"
},
{
"answer_id": 20981311,
"author": "DannyK",
"author_id": 969968,
"author_profile": "https://Stackoverflow.com/users/969968",
"pm_score": 4,
"selected": false,
"text": "<p>I posted this answer for similar question.<br>\nDon't reinvent the wheel. I've used a number of libraries and the fastest and most flexible I have come across is: <a href=\"http://www.partow.net/programming/strtk/\" rel=\"nofollow noreferrer\">C++ String Toolkit Library</a>. </p>\n\n<p>Here is an example of how to use it that I've posted else where on the stackoverflow.</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <string>\n#include <strtk.hpp>\n\nconst char *whitespace = \" \\t\\r\\n\\f\";\nconst char *whitespace_and_punctuation = \" \\t\\r\\n\\f;,=\";\n\nint main()\n{\n { // normal parsing of a string into a vector of strings\n std::string s(\"Somewhere down the road\");\n std::vector<std::string> result;\n if( strtk::parse( s, whitespace, result ) )\n {\n for(size_t i = 0; i < result.size(); ++i )\n std::cout << result[i] << std::endl;\n }\n }\n\n { // parsing a string into a vector of floats with other separators\n // besides spaces\n\n std::string s(\"3.0, 3.14; 4.0\");\n std::vector<float> values;\n if( strtk::parse( s, whitespace_and_punctuation, values ) )\n {\n for(size_t i = 0; i < values.size(); ++i )\n std::cout << values[i] << std::endl;\n }\n }\n\n { // parsing a string into specific variables\n\n std::string s(\"angle = 45; radius = 9.9\");\n std::string w1, w2;\n float v1, v2;\n if( strtk::parse( s, whitespace_and_punctuation, w1, v1, w2, v2) )\n {\n std::cout << \"word \" << w1 << \", value \" << v1 << std::endl;\n std::cout << \"word \" << w2 << \", value \" << v2 << std::endl;\n }\n }\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 22006543,
"author": "Murphy78",
"author_id": 3331297,
"author_profile": "https://Stackoverflow.com/users/3331297",
"pm_score": 0,
"selected": false,
"text": "<pre><code>/// split a string into multiple sub strings, based on a separator string\n/// for example, if separator=\"::\",\n///\n/// s = \"abc\" -> \"abc\"\n///\n/// s = \"abc::def xy::st:\" -> \"abc\", \"def xy\" and \"st:\",\n///\n/// s = \"::abc::\" -> \"abc\"\n///\n/// s = \"::\" -> NO sub strings found\n///\n/// s = \"\" -> NO sub strings found\n///\n/// then append the sub-strings to the end of the vector v.\n/// \n/// the idea comes from the findUrls() function of \"Accelerated C++\", chapt7,\n/// findurls.cpp\n///\nvoid split(const string& s, const string& sep, vector<string>& v)\n{\n typedef string::const_iterator iter;\n iter b = s.begin(), e = s.end(), i;\n iter sep_b = sep.begin(), sep_e = sep.end();\n\n // search through s\n while (b != e){\n i = search(b, e, sep_b, sep_e);\n\n // no more separator found\n if (i == e){\n // it's not an empty string\n if (b != e)\n v.push_back(string(b, e));\n break;\n }\n else if (i == b){\n // the separator is found and right at the beginning\n // in this case, we need to move on and search for the\n // next separator\n b = i + sep.length();\n }\n else{\n // found the separator\n v.push_back(string(b, i));\n b = i;\n }\n }\n}\n</code></pre>\n\n<p>The boost library is good, but they are not always available. Doing this sort of things by hand is also a good brain exercise. Here we just use the std::search() algorithm from the STL, see the above code.</p>\n"
},
{
"answer_id": 22460450,
"author": "robcsi",
"author_id": 3257292,
"author_profile": "https://Stackoverflow.com/users/3257292",
"pm_score": 0,
"selected": false,
"text": "<p>I've been searching for a way to split a string by a separator of any length, so I started writing it from scratch, as existing solutions didn't suit me.</p>\n\n<p>Here is my little algorithm, using only STL:</p>\n\n<pre><code>//use like this\n//std::vector<std::wstring> vec = Split<std::wstring> (L\"Hello##world##!\", L\"##\");\n\ntemplate <typename valueType>\nstatic std::vector <valueType> Split (valueType text, const valueType& delimiter)\n{\n std::vector <valueType> tokens;\n size_t pos = 0;\n valueType token;\n\n while ((pos = text.find(delimiter)) != valueType::npos) \n {\n token = text.substr(0, pos);\n tokens.push_back (token);\n text.erase(0, pos + delimiter.length());\n }\n tokens.push_back (text);\n\n return tokens;\n}\n</code></pre>\n\n<p>It can be used with separator of any length and form, as far as I've tested. Instantiate with either string or wstring type.</p>\n\n<p>All the algorithm does is it searches for the delimiter, gets the part of the string that is up to the delimiter, deletes the delimiter and searches again until it finds it no more.</p>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 24971386,
"author": "odinthenerd",
"author_id": 893819,
"author_profile": "https://Stackoverflow.com/users/893819",
"pm_score": 2,
"selected": false,
"text": "<p>Seems odd to me that with all us speed conscious nerds here on SO no one has presented a version that uses a compile time generated look up table for the delimiter (example implementation further down). Using a look up table and iterators should beat std::regex in efficiency, if you don't need to beat regex, just use it, its standard as of C++11 and super flexible.</p>\n\n<p>Some have suggested regex already but for the noobs here is a packaged example that should do exactly what the OP expects:</p>\n\n<pre><code>std::vector<std::string> split(std::string::const_iterator it, std::string::const_iterator end, std::regex e = std::regex{\"\\\\w+\"}){\n std::smatch m{};\n std::vector<std::string> ret{};\n while (std::regex_search (it,end,m,e)) {\n ret.emplace_back(m.str()); \n std::advance(it, m.position() + m.length()); //next start position = match position + match length\n }\n return ret;\n}\nstd::vector<std::string> split(const std::string &s, std::regex e = std::regex{\"\\\\w+\"}){ //comfort version calls flexible version\n return split(s.cbegin(), s.cend(), std::move(e));\n}\nint main ()\n{\n std::string str {\"Some people, excluding those present, have been compile time constants - since puberty.\"};\n auto v = split(str);\n for(const auto&s:v){\n std::cout << s << std::endl;\n }\n std::cout << \"crazy version:\" << std::endl;\n v = split(str, std::regex{\"[^e]+\"}); //using e as delim shows flexibility\n for(const auto&s:v){\n std::cout << s << std::endl;\n }\n return 0;\n}\n</code></pre>\n\n<p>If we need to be faster and accept the constraint that all chars must be 8 bits we can make a look up table at compile time using metaprogramming:</p>\n\n<pre><code>template<bool...> struct BoolSequence{}; //just here to hold bools\ntemplate<char...> struct CharSequence{}; //just here to hold chars\ntemplate<typename T, char C> struct Contains; //generic\ntemplate<char First, char... Cs, char Match> //not first specialization\nstruct Contains<CharSequence<First, Cs...>,Match> :\n Contains<CharSequence<Cs...>, Match>{}; //strip first and increase index\ntemplate<char First, char... Cs> //is first specialization\nstruct Contains<CharSequence<First, Cs...>,First>: std::true_type {}; \ntemplate<char Match> //not found specialization\nstruct Contains<CharSequence<>,Match>: std::false_type{};\n\ntemplate<int I, typename T, typename U> \nstruct MakeSequence; //generic\ntemplate<int I, bool... Bs, typename U> \nstruct MakeSequence<I,BoolSequence<Bs...>, U>: //not last\n MakeSequence<I-1, BoolSequence<Contains<U,I-1>::value,Bs...>, U>{};\ntemplate<bool... Bs, typename U> \nstruct MakeSequence<0,BoolSequence<Bs...>,U>{ //last \n using Type = BoolSequence<Bs...>;\n};\ntemplate<typename T> struct BoolASCIITable;\ntemplate<bool... Bs> struct BoolASCIITable<BoolSequence<Bs...>>{\n /* could be made constexpr but not yet supported by MSVC */\n static bool isDelim(const char c){\n static const bool table[256] = {Bs...};\n return table[static_cast<int>(c)];\n } \n};\nusing Delims = CharSequence<'.',',',' ',':','\\n'>; //list your custom delimiters here\nusing Table = BoolASCIITable<typename MakeSequence<256,BoolSequence<>,Delims>::Type>;\n</code></pre>\n\n<p>With that in place making a <code>getNextToken</code> function is easy:</p>\n\n<pre><code>template<typename T_It>\nstd::pair<T_It,T_It> getNextToken(T_It begin,T_It end){\n begin = std::find_if(begin,end,std::not1(Table{})); //find first non delim or end\n auto second = std::find_if(begin,end,Table{}); //find first delim or end\n return std::make_pair(begin,second);\n}\n</code></pre>\n\n<p>Using it is also easy:</p>\n\n<pre><code>int main() {\n std::string s{\"Some people, excluding those present, have been compile time constants - since puberty.\"};\n auto it = std::begin(s);\n auto end = std::end(s);\n while(it != std::end(s)){\n auto token = getNextToken(it,end);\n std::cout << std::string(token.first,token.second) << std::endl;\n it = token.second;\n }\n return 0;\n}\n</code></pre>\n\n<p>Here is a live example: <a href=\"http://ideone.com/GKtkLQ\" rel=\"nofollow\">http://ideone.com/GKtkLQ</a> </p>\n"
},
{
"answer_id": 27468529,
"author": "w.b",
"author_id": 2720372,
"author_profile": "https://Stackoverflow.com/users/2720372",
"pm_score": 6,
"selected": false,
"text": "<p>A solution using <code>regex_token_iterator</code>s:</p>\n\n<pre><code>#include <iostream>\n#include <regex>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n string str(\"The quick brown fox\");\n\n regex reg(\"\\\\s+\");\n\n sregex_token_iterator iter(str.begin(), str.end(), reg, -1);\n sregex_token_iterator end;\n\n vector<string> vec(iter, end);\n\n for (auto a : vec)\n {\n cout << a << endl;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 27969097,
"author": "CATspellsDOG",
"author_id": 4308970,
"author_profile": "https://Stackoverflow.com/users/4308970",
"pm_score": 0,
"selected": false,
"text": "<p>I made a lexer/tokenizer before with the use of only standard libraries. Here's the code:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <vector>\n#include <sstream>\n\nusing namespace std;\n\nstring seps(string& s) {\n if (!s.size()) return \"\";\n stringstream ss;\n ss << s[0];\n for (int i = 1; i < s.size(); i++) {\n ss << '|' << s[i];\n }\n return ss.str();\n}\n\nvoid Tokenize(string& str, vector<string>& tokens, const string& delimiters = \" \")\n{\n seps(str);\n\n // Skip delimiters at beginning.\n string::size_type lastPos = str.find_first_not_of(delimiters, 0);\n // Find first \"non-delimiter\".\n string::size_type pos = str.find_first_of(delimiters, lastPos);\n\n while (string::npos != pos || string::npos != lastPos)\n {\n // Found a token, add it to the vector.\n tokens.push_back(str.substr(lastPos, pos - lastPos));\n // Skip delimiters. Note the \"not_of\"\n lastPos = str.find_first_not_of(delimiters, pos);\n // Find next \"non-delimiter\"\n pos = str.find_first_of(delimiters, lastPos);\n }\n}\n\nint main(int argc, char *argv[])\n{\n vector<string> t;\n string s = \"Tokens for everyone!\";\n\n Tokenize(s, t, \"|\");\n\n for (auto c : t)\n cout << c << endl;\n\n system(\"pause\");\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 28788127,
"author": "Parham",
"author_id": 1357387,
"author_profile": "https://Stackoverflow.com/users/1357387",
"pm_score": 5,
"selected": false,
"text": "<p>This is a simple STL-only solution (~5 lines!) using <code>std::find</code> and <code>std::find_first_not_of</code> that handles repetitions of the delimiter (like spaces or periods for instance), as well leading and trailing delimiters:</p>\n\n<pre><code>#include <string>\n#include <vector>\n\nvoid tokenize(std::string str, std::vector<string> &token_v){\n size_t start = str.find_first_not_of(DELIMITER), end=start;\n\n while (start != std::string::npos){\n // Find next occurence of delimiter\n end = str.find(DELIMITER, start);\n // Push back the token found into vector\n token_v.push_back(str.substr(start, end-start));\n // Skip all occurences of the delimiter to find new start\n start = str.find_first_not_of(DELIMITER, end);\n }\n}\n</code></pre>\n\n<p>Try it out <a href=\"http://coliru.stacked-crooked.com/a/652f29c0500cf195\"><em>live</em></a>!</p>\n"
},
{
"answer_id": 38595708,
"author": "Jonathan Mee",
"author_id": 2642059,
"author_profile": "https://Stackoverflow.com/users/2642059",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/53878/2642059\">Adam Pierce's answer</a> provides an hand-spun tokenizer taking in a <code>const char*</code>. It's a bit more problematic to do with iterators because <a href=\"https://stackoverflow.com/q/37209725/2642059\">incrementing a <code>string</code>'s end iterator is undefined</a>. That said, given <code>string str{ \"The quick brown fox\" }</code> we can certainly accomplish this:</p>\n\n<pre><code>auto start = find(cbegin(str), cend(str), ' ');\nvector<string> tokens{ string(cbegin(str), start) };\n\nwhile (start != cend(str)) {\n const auto finish = find(++start, cend(str), ' ');\n\n tokens.push_back(string(start, finish));\n start = finish;\n}\n</code></pre>\n\n<p><a href=\"http://ideone.com/8bGCbg\" rel=\"noreferrer\"><kbd>Live Example</kbd></a></p>\n\n<hr>\n\n<p>If you're looking to abstract complexity by using standard functionality, as <a href=\"https://stackoverflow.com/a/53867/2642059\">On Freund suggests</a> <a href=\"http://en.cppreference.com/w/cpp/string/byte/strtok\" rel=\"noreferrer\"><code>strtok</code></a> is a simple option: </p>\n\n<pre><code>vector<string> tokens;\n\nfor (auto i = strtok(data(str), \" \"); i != nullptr; i = strtok(nullptr, \" \")) tokens.push_back(i);\n</code></pre>\n\n<p>If you don't have access to C++17 you'll need to substitute <code>data(str)</code> as in this example: <a href=\"http://ideone.com/8kAGoa\" rel=\"noreferrer\">http://ideone.com/8kAGoa</a></p>\n\n<p>Though not demonstrated in the example, <code>strtok</code> need not use the same delimiter for each token. Along with this advantage though, there are several drawbacks:</p>\n\n<ol>\n<li><code>strtok</code> cannot be used on multiple <code>strings</code> at the same time: Either a <code>nullptr</code> must be passed to continue tokenizing the current <code>string</code> or a new <code>char*</code> to tokenize must be passed (there are some non-standard implementations which do support this however, such as: <a href=\"https://msdn.microsoft.com/en-us/library/ftsafwz3.aspx\" rel=\"noreferrer\"><code>strtok_s</code></a>)</li>\n<li>For the same reason <code>strtok</code> cannot be used on multiple threads simultaneously (this may however be implementation defined, for example: <a href=\"https://msdn.microsoft.com/en-us/library/2c8d19sb.aspx#Anchor_3\" rel=\"noreferrer\">Visual Studio's implementation is thread safe</a>)</li>\n<li>Calling <code>strtok</code> modifies the <code>string</code> it is operating on, so it cannot be used on <code>const string</code>s, <code>const char*</code>s, or literal strings, to tokenize any of these with <code>strtok</code> or to operate on a <code>string</code> who's contents need to be preserved, <code>str</code> would have to be copied, then the copy could be operated on</li>\n</ol>\n\n<hr>\n\n<p><a href=\"/questions/tagged/c%2b%2b20\" class=\"post-tag\" title=\"show questions tagged 'c++20'\" rel=\"tag\">c++20</a> provides us with <code>split_view</code> to tokenize strings, in a non-destructive manner: <a href=\"https://topanswers.xyz/cplusplus?q=749#a874\" rel=\"noreferrer\">https://topanswers.xyz/cplusplus?q=749#a874</a></p>\n\n<hr>\n\n<p>The previous methods cannot generate a tokenized <code>vector</code> in-place, meaning without abstracting them into a helper function they cannot initialize <code>const vector<string> tokens</code>. That functionality <em>and</em> the ability to accept <em>any</em> white-space delimiter can be harnessed using an <a href=\"http://en.cppreference.com/w/cpp/iterator/istream_iterator\" rel=\"noreferrer\"><code>istream_iterator</code></a>. For example given: <code>const string str{ \"The quick \\tbrown \\nfox\" }</code> we can do this:</p>\n\n<pre><code>istringstream is{ str };\nconst vector<string> tokens{ istream_iterator<string>(is), istream_iterator<string>() };\n</code></pre>\n\n<p><a href=\"http://ideone.com/gWmfV9\" rel=\"noreferrer\"><kbd>Live Example</kbd></a></p>\n\n<p>The required construction of an <code>istringstream</code> for this option has far greater cost than the previous 2 options, however this cost is typically hidden in the expense of <code>string</code> allocation.</p>\n\n<hr>\n\n<p>If none of the above options are flexable enough for your tokenization needs, the most flexible option is using a <a href=\"http://en.cppreference.com/w/cpp/regex/regex_token_iterator\" rel=\"noreferrer\"><code>regex_token_iterator</code></a> of course with this flexibility comes greater expense, but again this is likely hidden in the <code>string</code> allocation cost. Say for example we want to tokenize based on non-escaped commas, also eating white-space, given the following input: <code>const string str{ \"The ,qu\\\\,ick ,\\tbrown, fox\" }</code> we can do this:</p>\n\n<pre><code>const regex re{ \"\\\\s*((?:[^\\\\\\\\,]|\\\\\\\\.)*?)\\\\s*(?:,|$)\" };\nconst vector<string> tokens{ sregex_token_iterator(cbegin(str), cend(str), re, 1), sregex_token_iterator() };\n</code></pre>\n\n<p><a href=\"http://ideone.com/q58zoX\" rel=\"noreferrer\"><kbd>Live Example</kbd></a></p>\n"
},
{
"answer_id": 50247503,
"author": "NutCracker",
"author_id": 5517378,
"author_profile": "https://Stackoverflow.com/users/5517378",
"pm_score": 2,
"selected": false,
"text": "<p>I know this question is already answered but I want to contribute. Maybe my solution is a bit simple but this is what I came up with:</p>\n\n<pre><code>vector<string> get_words(string const& text, string const& separator)\n{\n vector<string> result;\n string tmp = text;\n\n size_t first_pos = 0;\n size_t second_pos = tmp.find(separator);\n\n while (second_pos != string::npos)\n {\n if (first_pos != second_pos)\n {\n string word = tmp.substr(first_pos, second_pos - first_pos);\n result.push_back(word);\n }\n tmp = tmp.substr(second_pos + separator.length());\n second_pos = tmp.find(separator);\n }\n\n result.push_back(tmp);\n\n return result;\n}\n</code></pre>\n\n<p>Please comment if there is a better approach to something in my code or if something is wrong.</p>\n\n<p><strong>UPDATE:</strong> added generic separator</p>\n"
},
{
"answer_id": 52436170,
"author": "kayleeFrye_onDeck",
"author_id": 3543437,
"author_profile": "https://Stackoverflow.com/users/3543437",
"pm_score": 1,
"selected": false,
"text": "<p>Here's my Swiss® Army Knife of string-tokenizers for splitting up strings by whitespace, accounting for single and double-quote wrapped strings as well as stripping those characters from the results. I used RegexBuddy 4.x to generate <em>most</em> of the code-snippet, but I added custom handling for stripping quotes and a few other things.</p>\n\n<pre><code>#include <string>\n#include <locale>\n#include <regex>\n\nstd::vector<std::wstring> tokenize_string(std::wstring string_to_tokenize) {\n std::vector<std::wstring> tokens;\n\n std::wregex re(LR\"((\"[^\"]*\"|'[^']*'|[^\"' ]+))\", std::regex_constants::collate);\n\n std::wsregex_iterator next( string_to_tokenize.begin(),\n string_to_tokenize.end(),\n re,\n std::regex_constants::match_not_null );\n\n std::wsregex_iterator end;\n const wchar_t single_quote = L'\\'';\n const wchar_t double_quote = L'\\\"';\n while ( next != end ) {\n std::wsmatch match = *next;\n const std::wstring token = match.str( 0 );\n next++;\n\n if (token.length() > 2 && (token.front() == double_quote || token.front() == single_quote))\n tokens.emplace_back( std::wstring(token.begin()+1, token.begin()+token.length()-1) );\n else\n tokens.emplace_back(token);\n }\n return tokens;\n}\n</code></pre>\n"
},
{
"answer_id": 63431488,
"author": "einpoklum",
"author_id": 1593077,
"author_profile": "https://Stackoverflow.com/users/1593077",
"pm_score": 3,
"selected": false,
"text": "<p>If you're using C++ ranges - the full <a href=\"https://github.com/ericniebler/range-v3/\" rel=\"nofollow noreferrer\">ranges-v3</a> library, not the limited functionality accepted into C++20 - you could do it this way:</p>\n<pre><code>auto results = str | ranges::views::tokenize(" ",1);\n</code></pre>\n<p>... and this is lazily-evaluated. You can alternatively set a vector to this range:</p>\n<pre><code>auto results = str | ranges::views::tokenize(" ",1) | ranges::to<std::vector>();\n</code></pre>\n<p>this will take O(m) space and O(n) time if <code>str</code> has n characters making up m words.</p>\n<p>See also the library's own tokenization example, <a href=\"https://github.com/ericniebler/range-v3/blob/5b492996048d1baad98b50ec074e783eb6086627/test/view/tokenize.cpp\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 71564188,
"author": "Tanzer",
"author_id": 3976739,
"author_profile": "https://Stackoverflow.com/users/3976739",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote a simplified version (and maybe a little bit efficient) of <a href=\"https://stackoverflow.com/a/50247503/3976739\">https://stackoverflow.com/a/50247503/3976739</a> for my own use. I hope it would help.</p>\n<pre><code>void StrTokenizer(string& source, const char* delimiter, vector<string>& Tokens)\n{ \n size_t new_index = 0;\n size_t old_index = 0;\n\n while (new_index != std::string::npos) \n {\n new_index = source.find(delimiter, old_index);\n Tokens.emplace_back(source.substr(old_index, new_index-old_index));\n\n if (new_index != std::string::npos)\n old_index = ++new_index;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 74347767,
"author": "leanid.chaika",
"author_id": 955508,
"author_profile": "https://Stackoverflow.com/users/955508",
"pm_score": 0,
"selected": false,
"text": "<p>I just read all the answers and can't find solution with next preconditions:</p>\n<ol>\n<li>no dynamic memory allocations</li>\n<li>no use of boost</li>\n<li>no use of regex</li>\n<li>c++17 standard only</li>\n</ol>\n<p>So here is my solution</p>\n<pre><code>#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <string_view>\n#include <utility>\n\nstruct split_by_spaces\n{\n std::string_view text;\n static constexpr char delim = ' ';\n\n struct iterator\n {\n const std::string_view& text;\n std::size_t cur_pos;\n std::size_t end_pos;\n\n std::string_view operator*() const\n {\n return { &text[cur_pos], end_pos - cur_pos };\n }\n bool operator==(const iterator& other) const\n {\n return cur_pos == other.cur_pos && end_pos == other.end_pos;\n }\n bool operator!=(const iterator& other) const\n {\n return !(*this == other);\n }\n iterator& operator++()\n {\n cur_pos = text.find_first_not_of(delim, end_pos);\n\n if (cur_pos == std::string_view::npos)\n {\n cur_pos = text.size();\n end_pos = cur_pos;\n return *this;\n }\n\n end_pos = text.find(delim, cur_pos);\n\n if (cur_pos == std::string_view::npos)\n {\n end_pos = text.size();\n }\n\n return *this;\n }\n };\n\n [[nodiscard]] iterator begin() const\n {\n auto start = text.find_first_not_of(delim);\n if (start == std::string_view::npos)\n {\n return iterator{ text, text.size(), text.size() };\n }\n auto end_word = text.find(delim, start);\n if (end_word == std::string_view::npos)\n {\n end_word = text.size();\n }\n return iterator{ text, start, end_word };\n }\n [[nodiscard]] iterator end() const\n {\n return iterator{ text, text.size(), text.size() };\n }\n};\n\nint main(int argc, char** argv)\n{\n using namespace std::literals;\n auto str = " there should be no memory allocation during parsing"\n " into words this line and you should'n create any"\n " contaner for intermediate words "sv;\n\n auto comma = "";\n for (std::string_view word : split_by_spaces{ str })\n {\n std::cout << std::exchange(comma, ",") << std::quoted(word);\n }\n\n auto only_spaces = " "sv;\n for (std::string_view word : split_by_spaces{ only_spaces })\n {\n std::cout << "you will not see this line in output" << std::endl;\n }\n}\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] | Java has a convenient split method:
```
String str = "The quick brown fox";
String[] results = str.split(" ");
```
Is there an easy way to do this in C++? | C++ standard library algorithms are pretty universally based around iterators rather than concrete containers. Unfortunately this makes it hard to provide a Java-like `split` function in the C++ standard library, even though nobody argues that this would be convenient. But what would its return type be? `std::vector<std::basic_string<…>>`? Maybe, but then we’re forced to perform (potentially redundant and costly) allocations.
Instead, C++ offers a plethora of ways to split strings based on arbitrarily complex delimiters, but none of them is encapsulated as nicely as in other languages. The numerous ways [fill whole blog posts](https://www.fluentcpp.com/2017/04/21/how-to-split-a-string-in-c/).
At its simplest, you could iterate using [`std::string::find`](http://en.cppreference.com/w/cpp/string/basic_string/find) until you hit `std::string::npos`, and extract the contents using [`std::string::substr`](https://en.cppreference.com/w/cpp/string/basic_string/substr).
A more fluid (and idiomatic, but basic) version for splitting on whitespace would use a [`std::istringstream`](https://en.cppreference.com/w/cpp/io/basic_istringstream):
```
auto iss = std::istringstream{"The quick brown fox"};
auto str = std::string{};
while (iss >> str) {
process(str);
}
```
Using [`std::istream_iterator`s](https://en.cppreference.com/w/cpp/iterator/istream_iterator), the contents of the string stream could also be copied into a vector using its iterator range constructor.
Multiple libraries (such as [Boost.Tokenizer](https://www.boost.org/doc/libs/1_70_0/libs/tokenizer/doc/tokenizer.htm)) offer specific tokenisers.
More advanced splitting require regular expressions. C++ provides the [`std::regex_token_iterator`](https://en.cppreference.com/w/cpp/regex/regex_token_iterator) for this purpose in particular:
```
auto const str = "The quick brown fox"s;
auto const re = std::regex{R"(\s+)"};
auto const vec = std::vector<std::string>(
std::sregex_token_iterator{begin(str), end(str), re, -1},
std::sregex_token_iterator{}
);
``` |
53,911 | <p>Programming in vim I often go search for something, yank it, then go back to where I was, insert it, modify it.</p>
<p>The problem is that after I search and find, I need to MANUALLY find my way back to where I was.</p>
<p>Is there an automatic way to go back to where I was when I initiated my last search?</p>
| [
{
"answer_id": 53924,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 6,
"selected": false,
"text": "<p>I've always done by it setting a mark.</p>\n\n<ol>\n<li><p>In command-mode, press <strong><kbd>m</kbd><em>[letter]</em></strong>. For example, <kbd>m</kbd><kbd>a</kbd> sets a mark at the current line using <strong>a</strong> as the mark identifier.</p></li>\n<li><p>To get back to the mark press <strong><kbd>'</kbd> [letter]</strong>. For example, <kbd>'</kbd><kbd>a</kbd> takes you back to the line mark set in step 1. To get back to the column position of the row where you marked the line, use <kbd>`</kbd><kbd>a</kbd> (<strong>back-tick <em>[letter]</em></strong>).</p></li>\n</ol>\n\n<p>To see all of the marks that currently set, type <strong><code>:marks</code></strong>.</p>\n\n<hr>\n\n<p>On a slightly unrelated note, I just discovered another nifty thing about marks.</p>\n\n<p>Let's say you jump to mark <strong>b</strong> by doing <kbd>m</kbd><kbd>b</kbd>. Vim automatically sets the mark <kbd>'</kbd> (that's a single-quote) to be whichever line you were on before jumping to mark <strong>b</strong>.</p>\n\n<p>That means you can do <kbd>'</kbd><kbd>b</kbd> to jump to that mark, then do <kbd>''</kbd> (2 single-quotes) to jump back to wherever you were before.</p>\n\n<p>I discovered this accidentally using the <code>:marks</code> command, which shows a list of all marks.</p>\n"
},
{
"answer_id": 53926,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 3,
"selected": false,
"text": "<p>The simplest way is to set a mark, with <code>m[letter]</code>, then go back to it with <code>'[letter]</code></p>\n"
},
{
"answer_id": 53929,
"author": "Agnel Kurian",
"author_id": 45603,
"author_profile": "https://Stackoverflow.com/users/45603",
"pm_score": 10,
"selected": true,
"text": "<p><kbd>Ctrl</kbd>+<kbd>O</kbd> takes me to the previous location. Don't know about location before the search.</p>\n\n<p>Edit: Also, <kbd>`</kbd><kbd>.</kbd> will take you to the last change you made.</p>\n"
},
{
"answer_id": 84117,
"author": "Max Cantor",
"author_id": 16034,
"author_profile": "https://Stackoverflow.com/users/16034",
"pm_score": 7,
"selected": false,
"text": "<p>Use <code>``</code> to jump back to the exact position you were in before you searched/jumped, or <code>''</code> to jump back to the start of the line you were on before you searched/jumped.</p>\n"
},
{
"answer_id": 138943,
"author": "André",
"author_id": 9683,
"author_profile": "https://Stackoverflow.com/users/9683",
"pm_score": 5,
"selected": false,
"text": "<p>You really should read <code>:help jumplist</code> it explains all of this very well.</p>\n"
},
{
"answer_id": 10392263,
"author": "Ethan Zhang",
"author_id": 619292,
"author_profile": "https://Stackoverflow.com/users/619292",
"pm_score": 3,
"selected": false,
"text": "<p>I use this one:</p>\n\n<pre><code>nnoremap / ms/\nnnoremap ? ms?\n</code></pre>\n\n<p>Then if I search something by using <code>/</code> or <code>?</code>, I can go back quickly by <code>`s</code>. You could replace the letter <code>s</code> to any letter you like.</p>\n"
},
{
"answer_id": 12706072,
"author": "sale",
"author_id": 1716702,
"author_profile": "https://Stackoverflow.com/users/1716702",
"pm_score": 5,
"selected": false,
"text": "<p><kbd>CTRL+O</kbd> and <kbd>CTRL+I</kbd>, for jumping back and forward.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] | Programming in vim I often go search for something, yank it, then go back to where I was, insert it, modify it.
The problem is that after I search and find, I need to MANUALLY find my way back to where I was.
Is there an automatic way to go back to where I was when I initiated my last search? | `Ctrl`+`O` takes me to the previous location. Don't know about location before the search.
Edit: Also, ````.` will take you to the last change you made. |
53,945 | <p>I am currently loading a lightbox style popup that loads it's HTML from an XHR call. This content is then displayed in a 'modal' popup using <code>element.innerHTML = content</code> This works like a charm.</p>
<p>In another section of this website I use a Flickr 'badge' (<a href="http://www.elliotswan.com/2006/08/06/custom-flickr-badge-api-documentation/" rel="noreferrer">http://www.elliotswan.com/2006/08/06/custom-flickr-badge-api-documentation/</a>) to load flickr images dynamically. This is done including a script tag that loads a flickr javascript, which in turn does some <code>document.write</code> statments.</p>
<p>Both of them work perfectly when included in the HTML. Only when loading the flickr badge code <em>inside</em> the lightbox, no content is rendered at all. It seems that using <code>innerHTML</code> to write <code>document.write</code> statements is taking it a step too far, but I cannot find any clue in the javascript implementations (FF2&3, IE6&7) of this behavior.</p>
<p>Can anyone clarify if this should or shouldn't work? Thanks.</p>
| [
{
"answer_id": 54002,
"author": "Jon Cram",
"author_id": 5343,
"author_profile": "https://Stackoverflow.com/users/5343",
"pm_score": 0,
"selected": false,
"text": "<p>Can I get some clarification first to make sure I get the problem?</p>\n\n<p><code>document.write</code> calls will add content to the markup at the point in the markup at which they occur. For example if you include <code>document.write</code> calls in a function but call the function elsewhere, the <code>document.write</code> output will happen at the point in the markup the function is <em>defined</em> not where it is <em>called</em>.</p>\n\n<p>Therefore for this to work at all the Flickr <code>document.write</code> statements will need to be part of the <code>content</code> in <code>element.innerHTML = content</code>. Is this definitely the case?</p>\n\n<p>You might quickly test if this should work at all by adding a single and simple <code>document.write</code> call in the content that is set as the <code>innerHTML</code> and see what this does:</p>\n\n<pre><code><script>\n var content = \"<p>1st para</p><script>document.write('<p>2nd para</p>');</script>\"\n element.innerHTML = content;\n</script>\n</code></pre>\n\n<p>If that works, the concept of <code>document.write</code> working in content set as the <code>innerHTML</code> of an element might just work.</p>\n\n<p>My gut feeling is that it won't work, but it should be pretty straightforward to test the concept.</p>\n"
},
{
"answer_id": 54026,
"author": "Kamiel Wanrooij",
"author_id": 4174,
"author_profile": "https://Stackoverflow.com/users/4174",
"pm_score": 3,
"selected": false,
"text": "<p>I created a simple test page that illustrates the problem:</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html>\n <head>\n <meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" />\n <title>Document Write Testcase</title>\n </head>\n <body>\n <div id=\"container\">\n </div>\n <div id=\"container2\">\n </div>\n\n <script>\n // This doesn't work!\n var container = document.getElementById('container');\n container.innerHTML = \"<script type='text/javascript'>alert('foo');document.write('bar');<\\/script>\";\n\n // This does!\n var container2 = document.getElementById('container2');\n var script = document.createElement(\"script\");\n script.type = 'text/javascript';\n script.innerHTML = \"alert('bar');document.write('foo');\";\n container.appendChild(script);\n </script>\n </body>\n</html>\n</code></pre>\n\n<p>This page alerts 'bar' and prints 'foo', while I expected it to also alert 'foo' and print 'bar'. But, unfortunately, since the <code>script</code> tag is part of a larger HTML page, I cannot single out that tag and append it like the example above. Well, I can, but that would require scanning <code>innerHTML</code> content for <code>script</code> tags, and replacing them in the string by placeholders, and then inserting them using the DOM. Sounds not <em>that</em> trivial.</p>\n"
},
{
"answer_id": 54079,
"author": "Jon Cram",
"author_id": 5343,
"author_profile": "https://Stackoverflow.com/users/5343",
"pm_score": 0,
"selected": false,
"text": "<p>So you're using a DOM method to create a <code>script</code> element and append that to an existing element and this then causes the content of the appended <code>script</code> element to execute? That sounds good.</p>\n\n<p>You say that the script tag is part of a larger HTML page and therefore cannot be singled out. Can you not give the script tag an ID and target it? I'm probably missing something obvious here.</p>\n"
},
{
"answer_id": 54110,
"author": "Kamiel Wanrooij",
"author_id": 4174,
"author_profile": "https://Stackoverflow.com/users/4174",
"pm_score": 0,
"selected": false,
"text": "<p>In theory, yes, I can single out a script tag that way. The problem is that we potentially have dozens of situations where this occurs, so I am trying to find some cause or documentation of this behavior.</p>\n\n<p>Also, the <code>script</code> tag does not seem to be a part of the DOM anymore after it gets loaded. In our environment, my <code>container</code> div remains empty, so I cannot fetch the <code>script</code> tag. It should work, though, because in my example above the script does not get executed, but is still part of the DOM.</p>\n"
},
{
"answer_id": 54114,
"author": "Mo.",
"author_id": 5560,
"author_profile": "https://Stackoverflow.com/users/5560",
"pm_score": 1,
"selected": false,
"text": "<p><code>document.write</code> is about as deprecated as they come. Thanks to the wonders of JavaScript, though, you can just assign your own function to the <code>write</code> method of the <code>document</code> object which uses <code>innerHTML</code> on an element of your choosing to append the supplied content.</p>\n"
},
{
"answer_id": 1863308,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": 5,
"selected": true,
"text": "<p>In general, script tags aren't executed when using innerHTML. In your case, this is good, because the <code>document.write</code> call would wipe out everything that's already in the page. However, that leaves you without whatever HTML document.write was supposed to add.</p>\n\n<p>jQuery's HTML manipulation methods will execute scripts in HTML for you, the trick is then capturing the calls to <code>document.write</code> and getting the HTML in the proper place. If it's simple enough, then something like this will do:</p>\n\n<pre><code>var content = '';\ndocument.write = function(s) {\n content += s;\n};\n// execute the script\n$('#foo').html(markupWithScriptInIt);\n$('#foo .whereverTheDocumentWriteContentGoes').html(content);\n</code></pre>\n\n<p>It gets complicated though. If the script is on another domain, it will be loaded asynchronously, so you'll have to wait until it's done to get the content. Also, what if it just writes the HTML into the middle of the fragment without a wrapper element that you can easily select? <a href=\"http://github.com/iamnoah/writeCapture\" rel=\"noreferrer\">writeCapture.js</a> (full disclosure: I wrote it) handles all of these problems. I'd recommend just using it, but at the very least you can look at the code to see how it handles everything.</p>\n\n<p>EDIT: Here is a <a href=\"http://iamnoah.github.com/writeCapture/lbFlickrDemo.html\" rel=\"noreferrer\">page</a> demonstrating what sounds like the effect you want.</p>\n"
},
{
"answer_id": 7175202,
"author": "David Refoua",
"author_id": 1454514,
"author_profile": "https://Stackoverflow.com/users/1454514",
"pm_score": 2,
"selected": false,
"text": "<p>Use <code>document.writeln(content);</code> instead of <code>document.write(content)</code>.</p>\n\n<p>However, the better method is using the concatenation of <code>innerHTML</code>, like this:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>element.innerHTML += content;\n</code></pre>\n\n<p>The <code>element.innerHTML = content;</code> method will replace the old content with the new one, which will overwrite your element's innerHTML!</p>\n\n<p>Whereas using the the <code>+=</code> operator in <code>element.innerHTML += content</code> will append your text after the old content. (similar to what <code>document.write</code> does.)</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4174/"
] | I am currently loading a lightbox style popup that loads it's HTML from an XHR call. This content is then displayed in a 'modal' popup using `element.innerHTML = content` This works like a charm.
In another section of this website I use a Flickr 'badge' (<http://www.elliotswan.com/2006/08/06/custom-flickr-badge-api-documentation/>) to load flickr images dynamically. This is done including a script tag that loads a flickr javascript, which in turn does some `document.write` statments.
Both of them work perfectly when included in the HTML. Only when loading the flickr badge code *inside* the lightbox, no content is rendered at all. It seems that using `innerHTML` to write `document.write` statements is taking it a step too far, but I cannot find any clue in the javascript implementations (FF2&3, IE6&7) of this behavior.
Can anyone clarify if this should or shouldn't work? Thanks. | In general, script tags aren't executed when using innerHTML. In your case, this is good, because the `document.write` call would wipe out everything that's already in the page. However, that leaves you without whatever HTML document.write was supposed to add.
jQuery's HTML manipulation methods will execute scripts in HTML for you, the trick is then capturing the calls to `document.write` and getting the HTML in the proper place. If it's simple enough, then something like this will do:
```
var content = '';
document.write = function(s) {
content += s;
};
// execute the script
$('#foo').html(markupWithScriptInIt);
$('#foo .whereverTheDocumentWriteContentGoes').html(content);
```
It gets complicated though. If the script is on another domain, it will be loaded asynchronously, so you'll have to wait until it's done to get the content. Also, what if it just writes the HTML into the middle of the fragment without a wrapper element that you can easily select? [writeCapture.js](http://github.com/iamnoah/writeCapture) (full disclosure: I wrote it) handles all of these problems. I'd recommend just using it, but at the very least you can look at the code to see how it handles everything.
EDIT: Here is a [page](http://iamnoah.github.com/writeCapture/lbFlickrDemo.html) demonstrating what sounds like the effect you want. |
53,965 | <pre><code>$output = preg_replace("|(/D)(/s+)(/d+)(;)|", "//1,//3;", $output);
</code></pre>
<p>I'm trying to replace all alphabetical character followed by one or more whitespace characters (tabs and/or spaces) followed by one or more numerical characters followed by a semicolon with the alphabetical character followed by a comma followed by the numerical digits and then the semicolon.</p>
<p>I'll provide an example:</p>
<p>Start:</p>
<pre><code>hello world 1007;
</code></pre>
<p>End:</p>
<pre><code>hello world,1007;
</code></pre>
| [
{
"answer_id": 53988,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 2,
"selected": false,
"text": "<p>Should those forward-slashes be backslashes? You'll need to escape them for PHP too unless you change your double-quotes to single-quotes.</p>\n"
},
{
"answer_id": 53993,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 4,
"selected": true,
"text": "<p>The two <code>|</code> at the start and end probably are incorrect - and should both be forward-slashes.</p>\n\n<p>All other forward slashes should be backward slashes (and need escaping).</p>\n\n<p>And since PHP 4.04 <code>$n</code> is the preferred way of referring to a capture group.</p>\n\n<pre><code>$output = preg_replace(\"/(\\\\D)\\\\s+(\\\\d+;)/\", \"$1,$2\", $output);\n</code></pre>\n\n<p>If you use single quotes you don't need to escape your backslashes:</p>\n\n<pre><code>$output = preg_replace('/(\\D)\\s+(\\d+;)/', '$1,$2', $output);\n</code></pre>\n"
},
{
"answer_id": 54018,
"author": "Alan Storm",
"author_id": 4668,
"author_profile": "https://Stackoverflow.com/users/4668",
"pm_score": 1,
"selected": false,
"text": "<p>You want backslashes in the regular expression, not forward slashes. The starting and ending pipes <strong>are</strong> needed (or another delimiter for the regex)</p>\n\n<pre><code>$x = \"hello world 1007;\"; \necho preg_replace('|(\\D)(\\s+)(\\d+)(;)|','$1,$3',$x);\necho preg_replace('/(\\D)(\\s+)(\\d+)(;)/','$1,$3',$x);\necho preg_replace('{(\\D)(\\s+)(\\d+)(;)}','$1,$3',$x);\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] | ```
$output = preg_replace("|(/D)(/s+)(/d+)(;)|", "//1,//3;", $output);
```
I'm trying to replace all alphabetical character followed by one or more whitespace characters (tabs and/or spaces) followed by one or more numerical characters followed by a semicolon with the alphabetical character followed by a comma followed by the numerical digits and then the semicolon.
I'll provide an example:
Start:
```
hello world 1007;
```
End:
```
hello world,1007;
``` | The two `|` at the start and end probably are incorrect - and should both be forward-slashes.
All other forward slashes should be backward slashes (and need escaping).
And since PHP 4.04 `$n` is the preferred way of referring to a capture group.
```
$output = preg_replace("/(\\D)\\s+(\\d+;)/", "$1,$2", $output);
```
If you use single quotes you don't need to escape your backslashes:
```
$output = preg_replace('/(\D)\s+(\d+;)/', '$1,$2', $output);
``` |
53,967 | <p>I have a class that map objects to objects, but unlike dictionary it maps them both ways. I am now trying to implement a custom <code>IEnumerator</code> interface that iterates through the values.</p>
<pre><code>public class Mapper<K,T> : IEnumerable<T>, IEnumerator<T>
{
C5.TreeDictionary<K,T> KToTMap = new TreeDictionary<K,T>();
C5.HashDictionary<T,K> TToKMap = new HashDictionary<T,K>();
public void Add(K key, T value)
{
KToTMap.Add(key, value);
TToKMap.Add(value, key);
}
public int Count
{
get { return KToTMap.Count; }
}
public K this[T obj]
{
get
{
return TToKMap[obj];
}
}
public T this[K obj]
{
get
{
return KToTMap[obj];
}
}
public IEnumerator<T> GetEnumerator()
{
return KToTMap.Values.GetEnumerator();
}
public T Current
{
get { throw new NotImplementedException(); }
}
public void Dispose()
{
throw new NotImplementedException();
}
object System.Collections.IEnumerator.Current
{
get { throw new NotImplementedException(); }
}
public bool MoveNext()
{
;
}
public void Reset()
{
throw new NotImplementedException();
}
}
</code></pre>
| [
{
"answer_id": 53986,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 2,
"selected": false,
"text": "<p>Use yield return.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/39476/what-is-the-yield-keyword-used-for-in-c#39496\">What is the yield keyword used for in C#?</a></p>\n"
},
{
"answer_id": 53999,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 3,
"selected": false,
"text": "<p>Just implement the <code>IEnumerable<T></code> interface. No need to implement the <code>IEnumerator<T></code> unless you want to do some special things in the enumerator, which for your case doesn't seem to be needed.</p>\n<pre><code>public class Mapper<K,T> : IEnumerable<T> {\n public IEnumerator<T> GetEnumerator()\n {\n return KToTMap.Values.GetEnumerator();\n }\n}\n</code></pre>\n<p>and that's it.</p>\n"
},
{
"answer_id": 54022,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 5,
"selected": true,
"text": "<p>First, don't make your collection object implement IEnumerator<>. This leads to bugs. (Consider the situation where two threads are iterating over the same collection). </p>\n\n<p>Implementing an enumerator correctly turns out to be non-trivial, so C# 2.0 added special language support for doing it, based on the 'yield return' statement.</p>\n\n<p>Raymond Chen's recent series of blog posts (\"The implementation of iterators in C# and its consequences\") is a good place to get up to speed. </p>\n\n<ul>\n<li>Part 1: <a href=\"https://web.archive.org/web/20081216071723/http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20081216071723/http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx</a></li>\n<li>Part 2: <a href=\"https://web.archive.org/web/20080907004812/http://blogs.msdn.com/oldnewthing/archive/2008/08/13/8854601.aspx\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20080907004812/http://blogs.msdn.com/oldnewthing/archive/2008/08/13/8854601.aspx</a></li>\n<li>Part 3: <a href=\"https://web.archive.org/web/20080824210655/http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20080824210655/http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx</a></li>\n<li>Part 4: <a href=\"https://web.archive.org/web/20090207130506/http://blogs.msdn.com/oldnewthing/archive/2008/08/15/8868267.aspx\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20090207130506/http://blogs.msdn.com/oldnewthing/archive/2008/08/15/8868267.aspx</a></li>\n</ul>\n"
},
{
"answer_id": 14999790,
"author": "Jack",
"author_id": 794594,
"author_profile": "https://Stackoverflow.com/users/794594",
"pm_score": 3,
"selected": false,
"text": "<p><code>CreateEnumerable()</code> returns an <code>IEnumerable</code> which implements <code>GetEnumerator()</code></p>\n\n<pre><code>public class EasyEnumerable : IEnumerable<int> {\n\n IEnumerable<int> CreateEnumerable() {\n yield return 123;\n yield return 456;\n for (int i = 0; i < 6; i++) {\n yield return i;\n }//for\n }//method\n\n public IEnumerator<int> GetEnumerator() {\n return CreateEnumerable().GetEnumerator();\n }//method\n\n IEnumerator IEnumerable.GetEnumerator() {\n return CreateEnumerable().GetEnumerator();\n }//method\n\n}//class\n</code></pre>\n"
},
{
"answer_id": 23442029,
"author": "Rezo Megrelidze",
"author_id": 2204040,
"author_profile": "https://Stackoverflow.com/users/2204040",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an example from the book \"Algorithms (4th Edition) by Robert Sedgewick\".</p>\n\n<p>It was written in java and i basically rewrote it in C#.</p>\n\n<pre><code>public class Stack<T> : IEnumerable<T>\n{\n private T[] array;\n\n public Stack(int n)\n {\n array = new T[n];\n }\n\n public Stack()\n {\n array = new T[16];\n }\n\n public void Push(T item)\n {\n if (Count == array.Length)\n {\n Grow(array.Length * 2);\n }\n\n array[Count++] = item;\n }\n\n public T Pop()\n {\n if (Count == array.Length/4)\n {\n Shrink(array.Length/2);\n }\n\n return array[--Count];\n }\n\n private void Grow(int size)\n {\n var temp = array;\n array = new T[size];\n Array.Copy(temp, array, temp.Length);\n }\n\n private void Shrink(int size)\n {\n Array temp = array;\n array = new T[size];\n Array.Copy(temp,0,array,0,size);\n }\n\n public int Count { get; private set; }\n public IEnumerator<T> GetEnumerator()\n {\n return new ReverseArrayIterator(Count,array);\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n\n // IEnumerator implementation\n private class ReverseArrayIterator : IEnumerator<T>\n {\n private int i;\n\n private readonly T[] array;\n\n public ReverseArrayIterator(int count,T[] array)\n {\n i = count;\n this.array = array;\n }\n\n public void Dispose()\n {\n\n }\n\n public bool MoveNext()\n {\n return i > 0;\n }\n\n public void Reset()\n {\n\n }\n\n public T Current { get { return array[--i]; } }\n\n object IEnumerator.Current\n {\n get { return Current; }\n }\n }\n}\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/53967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4694/"
] | I have a class that map objects to objects, but unlike dictionary it maps them both ways. I am now trying to implement a custom `IEnumerator` interface that iterates through the values.
```
public class Mapper<K,T> : IEnumerable<T>, IEnumerator<T>
{
C5.TreeDictionary<K,T> KToTMap = new TreeDictionary<K,T>();
C5.HashDictionary<T,K> TToKMap = new HashDictionary<T,K>();
public void Add(K key, T value)
{
KToTMap.Add(key, value);
TToKMap.Add(value, key);
}
public int Count
{
get { return KToTMap.Count; }
}
public K this[T obj]
{
get
{
return TToKMap[obj];
}
}
public T this[K obj]
{
get
{
return KToTMap[obj];
}
}
public IEnumerator<T> GetEnumerator()
{
return KToTMap.Values.GetEnumerator();
}
public T Current
{
get { throw new NotImplementedException(); }
}
public void Dispose()
{
throw new NotImplementedException();
}
object System.Collections.IEnumerator.Current
{
get { throw new NotImplementedException(); }
}
public bool MoveNext()
{
;
}
public void Reset()
{
throw new NotImplementedException();
}
}
``` | First, don't make your collection object implement IEnumerator<>. This leads to bugs. (Consider the situation where two threads are iterating over the same collection).
Implementing an enumerator correctly turns out to be non-trivial, so C# 2.0 added special language support for doing it, based on the 'yield return' statement.
Raymond Chen's recent series of blog posts ("The implementation of iterators in C# and its consequences") is a good place to get up to speed.
* Part 1: <https://web.archive.org/web/20081216071723/http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx>
* Part 2: <https://web.archive.org/web/20080907004812/http://blogs.msdn.com/oldnewthing/archive/2008/08/13/8854601.aspx>
* Part 3: <https://web.archive.org/web/20080824210655/http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx>
* Part 4: <https://web.archive.org/web/20090207130506/http://blogs.msdn.com/oldnewthing/archive/2008/08/15/8868267.aspx> |
54,010 | <p>I've recently been working on a beginner's project in Scala, and have a beginner question about Scala's Lists.</p>
<p>Say I have a list of tuples ( <code>List[Tuple2[String, String]]</code>, for example). Is there a convenience method to return the first occurence of a specified tuple from the List, or is it necessary to iterate through the list by hand?</p>
| [
{
"answer_id": 54123,
"author": "Tim Sullivan",
"author_id": 722,
"author_profile": "https://Stackoverflow.com/users/722",
"pm_score": 3,
"selected": false,
"text": "<p>You could try using <a href=\"http://www.scala-lang.org/api/current/index.html#scala.collection.parallel.ParIterableLike$Find\" rel=\"nofollow noreferrer\">find</a>. (Updated scala-doc location of find)</p>\n"
},
{
"answer_id": 56534,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 2,
"selected": false,
"text": "<p>If you're learning scala, I'd take a good look at the <a href=\"http://www.scala-lang.org/api/current/scala/collection/Seq.html\" rel=\"nofollow noreferrer\">Seq</a> trait. It provides the basis for much of scala's functional goodness.</p>\n"
},
{
"answer_id": 61497,
"author": "Binil Thomas",
"author_id": 3973,
"author_profile": "https://Stackoverflow.com/users/3973",
"pm_score": 4,
"selected": false,
"text": "<pre>\nscala> val list = List((\"A\", \"B\", 1), (\"C\", \"D\", 1), (\"E\", \"F\", 1), (\"C\", \"D\", 2), (\"G\", \"H\", 1))\nlist: List[(java.lang.String, java.lang.String, Int)] = List((A,B,1), (C,D,1), (E,F,1), (C,D,2), (G,H,1))\n\nscala> list find {e => e._1 == \"C\" && e._2 == \"D\"}\nres0: Option[(java.lang.String, java.lang.String, Int)] = Some((C,D,1))\n</pre>\n"
},
{
"answer_id": 66489,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 2,
"selected": false,
"text": "<p>As mentioned in a previous comment, <code>find</code> is probably the easiest way to do this. There are actually three different \"linear search\" methods in Scala's collections, each returning a slightly different value. Which one you use depends upon what you need the data for. For example, do you need an index, or do you just need a boolean <code>true</code>/<code>false</code>?</p>\n"
},
{
"answer_id": 392351,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You could also do this, which doesn't require knowing the field names in the Tuple2 class--it uses pattern matching instead:</p>\n\n<pre><code>list find { case (x,y,_) => x == \"C\" && y == \"D\" }\n</code></pre>\n\n<p>\"find\" is good when you know you only need one; if you want to find all matching elements you could either use \"filter\" or the equivalent sugary for comprehension:</p>\n\n<pre><code>for ( (x,y,z) <- list if x == \"C\" && y == \"D\") yield (x,y,z)\n</code></pre>\n"
},
{
"answer_id": 13305849,
"author": "akauppi",
"author_id": 14455,
"author_profile": "https://Stackoverflow.com/users/14455",
"pm_score": 1,
"selected": false,
"text": "<p>Here's code that may help you.</p>\n\n<p>I had a similar case, having a collection of base class entries (here, <code>A</code>) out of which I wanted to find a certain derived class's node, if any (here, <code>B</code>).</p>\n\n<pre><code>class A\n\ncase class B(val name: String) extends A\n\nobject TestX extends App {\n val states: List[A] = List( B(\"aa\"), new A, B(\"ccc\") )\n\n def findByName( name: String ): Option[B] = {\n states.find{\n case x: B if x.name == name => return Some(x)\n case _ => false\n }\n None\n }\n\n println( findByName(\"ccc\") ) // \"Some(B(ccc))\"\n}\n</code></pre>\n\n<p>The important part here (for my app) is that <code>findByName</code> does not return <code>Option[A]</code> but <code>Option[B]</code>.</p>\n\n<p>You can easily modify the behaviour to return <code>B</code> instead, and throw an exception if none was found. Hope this helps.</p>\n"
},
{
"answer_id": 32812857,
"author": "elm",
"author_id": 3189923,
"author_profile": "https://Stackoverflow.com/users/3189923",
"pm_score": 1,
"selected": false,
"text": "<p>Consider <code>collectFirst</code> which delivers <code>Some[(String,String)]</code> for the first matching tuple or <code>None</code> otherwise, for instance as follows,</p>\n\n<pre><code>xs collectFirst { case t@(a,_) if a == \"existing\" => t }\nSome((existing,str))\n\nscala> xs collectFirst { case t@(a,_) if a == \"nonExisting\" => t }\nNone\n</code></pre>\n\n<p>Using <code>@</code> we bind the value of the tuple to <code>t</code> so that a whole matching tuple can be collected.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I've recently been working on a beginner's project in Scala, and have a beginner question about Scala's Lists.
Say I have a list of tuples ( `List[Tuple2[String, String]]`, for example). Is there a convenience method to return the first occurence of a specified tuple from the List, or is it necessary to iterate through the list by hand? | ```
scala> val list = List(("A", "B", 1), ("C", "D", 1), ("E", "F", 1), ("C", "D", 2), ("G", "H", 1))
list: List[(java.lang.String, java.lang.String, Int)] = List((A,B,1), (C,D,1), (E,F,1), (C,D,2), (G,H,1))
scala> list find {e => e._1 == "C" && e._2 == "D"}
res0: Option[(java.lang.String, java.lang.String, Int)] = Some((C,D,1))
``` |
54,043 | <p>I would like to be able to do such things as</p>
<pre><code>var m1 = new UnitOfMeasureQuantityPair(123.00, UnitOfMeasure.Pounds);
var m2 = new UnitOfMeasureQuantityPair(123.00, UnitOfMeasure.Liters);
m1.ToKilograms();
m2.ToPounds(new Density(7.0, DensityType.PoundsPerGallon);
</code></pre>
<p>If there isn't something like this already, anybody interested in doing it as an os project?</p>
| [
{
"answer_id": 54049,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "<p>Check out the <a href=\"http://www.codeproject.com/KB/library/Measurement_Conversion.aspx\" rel=\"nofollow noreferrer\">Measurement Unit Conversion Library</a> on The Code Project.</p>\n"
},
{
"answer_id": 54067,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 2,
"selected": false,
"text": "<p>We actually built one in-house where I work. Unfortunately, it's not available for the public.</p>\n\n<p>This is actually a great project to work on and it's not that hard to do. If you plan on doing something by yourself, I suggest you read about <a href=\"http://en.wikipedia.org/wiki/Physical_quantity\" rel=\"nofollow noreferrer\">Quantity</a>, <a href=\"http://en.wikipedia.org/wiki/Dimensional_analysis\" rel=\"nofollow noreferrer\">Dimension</a> and <a href=\"http://en.wikipedia.org/wiki/Units_of_measurement\" rel=\"nofollow noreferrer\">Unit</a> (<a href=\"http://en.wikipedia.org/wiki/Fundamental_units\" rel=\"nofollow noreferrer\">fundamental units</a>).</p>\n\n<p>These helped us understand the domain of the problem clearly and helped a lot in designing the library.</p>\n"
},
{
"answer_id": 54150,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Also see the most recent F# release - it has static measurement domain/dimension analysis.</p>\n"
},
{
"answer_id": 54296,
"author": "rohancragg",
"author_id": 5351,
"author_profile": "https://Stackoverflow.com/users/5351",
"pm_score": 2,
"selected": false,
"text": "<p>In <a href=\"https://learning.oreilly.com/library/view/enterprise-patterns-and/032111230X/ch10.html\" rel=\"nofollow noreferrer\">Chapter 10. Quantity archetype pattern</a> of the book <a href=\"http://www.informit.com/store/product.aspx?isbn=9780321112309&aid=3B419801-6640-4A1F-A653-6CD00295FCDD\" rel=\"nofollow noreferrer\">Enterprise Patterns and MDA: Building Better Software with Archetype Patterns and UML</a> by Jim Arlow and Ila Neustadt\nthere is a really useful discussion of this topic and some general patterns you could use as a guide.</p>\n"
},
{
"answer_id": 6321253,
"author": "denis",
"author_id": 86643,
"author_profile": "https://Stackoverflow.com/users/86643",
"pm_score": 0,
"selected": false,
"text": "<p>Unix <a href=\"http://linux.die.net/man/1/units\" rel=\"nofollow\">units</a> is imho brilliant; source must be on the web somewhere.<br>\n(Under \"bugs\", the original doc said \"do not base your financial plans on the currency conversions\".)</p>\n"
},
{
"answer_id": 41745573,
"author": "Peter",
"author_id": 15349,
"author_profile": "https://Stackoverflow.com/users/15349",
"pm_score": 1,
"selected": false,
"text": "<p>There is an (old) article on <a href=\"https://www.codeproject.com/Articles/611731/Working-with-Units-and-Amounts\" rel=\"nofollow noreferrer\">CodeProject</a>. I've used it in a production environment previously and it worked great. We had some minor issues (performance amongst others), which I addressed. I put all this in a library you can find <a href=\"https://github.com/petermorlion/RedStar.Amounts\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p><strong>Disclaimer:</strong> I am the maintainer of this project, so this might be conceived as a shameless plug. The library is free (as in beer and as in speech) however.</p>\n\n<p>It includes the SI units, but also allows creating new units and conversions. </p>\n\n<p>So you can for example create a unit \"XP\" (experience points). You can then register a conversion to \"m\" (meter, makes no sense, but you can do it). You can also create an amount like 3 XP/min (3 experience points per minute). I believe it offers decent defaults, while allowing flexibility.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | I would like to be able to do such things as
```
var m1 = new UnitOfMeasureQuantityPair(123.00, UnitOfMeasure.Pounds);
var m2 = new UnitOfMeasureQuantityPair(123.00, UnitOfMeasure.Liters);
m1.ToKilograms();
m2.ToPounds(new Density(7.0, DensityType.PoundsPerGallon);
```
If there isn't something like this already, anybody interested in doing it as an os project? | Check out the [Measurement Unit Conversion Library](http://www.codeproject.com/KB/library/Measurement_Conversion.aspx) on The Code Project. |
54,059 | <p>Say I have a linked list of numbers of length <code>N</code>. <code>N</code> is very large and I don’t know in advance the exact value of <code>N</code>. </p>
<p>How can I most efficiently write a function that will return <code>k</code> completely <em>random numbers</em> from the list?</p>
| [
{
"answer_id": 54070,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest: First find your k random numbers. Sort them. Then traverse both the linked list and your random numbers once.</p>\n\n<p>If you somehow don't know the length of your linked list (how?), then you could grab the first k into an array, then for node r, generate a random number in [0, r), and if that is less than k, replace the rth item of the array. (Not entirely convinced that doesn't bias...)</p>\n\n<p>Other than that: \"If I were you, I wouldn't be starting from here.\" Are you sure linked list is right for your problem? Is there not a better data structure, such as a good old flat array list.</p>\n"
},
{
"answer_id": 54072,
"author": "Christian Oudard",
"author_id": 3757,
"author_profile": "https://Stackoverflow.com/users/3757",
"pm_score": -1,
"selected": false,
"text": "<p>Well, you do need to know what N is at runtime at least, even if this involves doing an extra pass over the list to count them. The simplest algorithm to do this is to just pick a random number in N and remove that item, repeated k times. Or, if it is permissible to return repeat numbers, don't remove the item.</p>\n\n<p>Unless you have a VERY large N, and very stringent performance requirements, this algorithm runs with <code>O(N*k)</code> complexity, which should be acceptable.</p>\n\n<p>Edit: Nevermind, Tom Hawtin's method is way better. Select the random numbers first, then traverse the list once. Same theoretical complexity, I think, but much better expected runtime.</p>\n"
},
{
"answer_id": 54083,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": -1,
"selected": false,
"text": "<p>Why can't you just do something like</p>\n\n<pre><code>List GetKRandomFromList(List input, int k)\n List ret = new List();\n for(i=0;i<k;i++)\n ret.Add(input[Math.Rand(0,input.Length)]);\n return ret;\n</code></pre>\n\n<p>I'm sure that you don't mean something that simple so can you specify further?</p>\n"
},
{
"answer_id": 54101,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 5,
"selected": false,
"text": "<p>This is called a <a href=\"http://gregable.com/2007/10/reservoir-sampling.html\" rel=\"noreferrer\">Reservoir Sampling</a> problem. The simple solution is to assign a random number to each element of the list as you see it, then keep the top (or bottom) k elements as ordered by the random number.</p>\n"
},
{
"answer_id": 54174,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't know the length of the list, then you will have to traverse it complete to ensure random picks. The method I've used in this case is the one described by Tom Hawtin (<a href=\"https://stackoverflow.com/questions/54059/efficiently-selecting-a-set-of-random-elements-from-a-linked-list#54070\">54070</a>). While traversing the list you keep <code>k</code> elements that form your random selection to that point. (Initially you just add the first <code>k</code> elements you encounter.) Then, with probability <code>k/i</code>, you replace a random element from your selection with the <code>i</code>th element of the list (i.e. the element you are at, at that moment).</p>\n\n<p>It's easy to show that this gives a random selection. After seeing <code>m</code> elements (<code>m > k</code>), we have that each of the first <code>m</code> elements of the list are part of you random selection with a probability <code>k/m</code>. That this initially holds is trivial. Then for each element <code>m+1</code>, you put it in your selection (replacing a random element) with probability <code>k/(m+1)</code>. You now need to show that all other elements also have probability <code>k/(m+1)</code> of being selected. We have that the probability is <code>k/m * (k/(m+1)*(1-1/k) + (1-k/(m+1)))</code> (i.e. probability that element was in the list times the probability that it is still there). With calculus you can straightforwardly show that this is equal to <code>k/(m+1)</code>.</p>\n"
},
{
"answer_id": 21201378,
"author": "Richard",
"author_id": 752843,
"author_profile": "https://Stackoverflow.com/users/752843",
"pm_score": 6,
"selected": true,
"text": "<p>There's a very nice and efficient algorithm for this using a method called <strong>reservoir sampling</strong>.</p>\n\n<p>Let me start by giving you its <strong>history</strong>:</p>\n\n<p><strong>Knuth</strong> calls this Algorithm R on p. 144 of his 1997 edition of Seminumerical Algorithms (volume 2 of The Art of Computer Programming), and provides some code for it there. Knuth attributes the algorithm to Alan G. Waterman. Despite a lengthy search, I haven't been able to find Waterman's original document, if it exists, which may be why you'll most often see Knuth quoted as the source of this algorithm.</p>\n\n<p><strong>McLeod and Bellhouse, 1983</strong> (1) provide a more thorough discussion than Knuth as well as the first published proof (that I'm aware of) that the algorithm works.</p>\n\n<p><strong>Vitter 1985</strong> (2) reviews Algorithm R and then presents an additional three algorithms which provide the same output, but with a twist. Rather than making a choice to include or skip each incoming element, his algorithm predetermines the number of incoming elements to be skipped. In his tests (which, admittedly, are out of date now) this decreased execution time dramatically by avoiding random number generation and comparisons on each in-coming number.</p>\n\n<p>In <strong>pseudocode</strong> the algorithm is:</p>\n\n<pre><code>Let R be the result array of size s\nLet I be an input queue\n\n> Fill the reservoir array\nfor j in the range [1,s]:\n R[j]=I.pop()\n\nelements_seen=s\nwhile I is not empty:\n elements_seen+=1\n j=random(1,elements_seen) > This is inclusive\n if j<=s:\n R[j]=I.pop()\n else:\n I.pop()\n</code></pre>\n\n<p>Note that I've specifically written the code to avoid specifying the size of the input. That's one of the cool properties of this algorithm: you can run it without needing to know the size of the input beforehand and it <em>still</em> assures you that each element you encounter has an equal probability of ending up in <code>R</code> (that is, there is no bias). Furthermore, <code>R</code> contains a fair and representative sample of the elements the algorithm has considered at all times. This means you can use this as an <a href=\"https://en.wikipedia.org/wiki/Online_algorithm\" rel=\"noreferrer\">online algorithm</a>.</p>\n\n<p><strong>Why does this work?</strong></p>\n\n<p>McLeod and Bellhouse (1983) provide a proof using the mathematics of combinations. It's pretty, but it would be a bit difficult to reconstruct it here. Therefore, I've generated an alternative proof which is easier to explain.</p>\n\n<p>We proceed via proof by induction.</p>\n\n<p>Say we want to generate a set of <code>s</code> elements and that we have already seen <code>n>s</code> elements.</p>\n\n<p>Let's assume that our current <code>s</code> elements have already each been chosen with probability <code>s/n</code>.</p>\n\n<p>By the definition of the algorithm, we choose element <code>n+1</code> with probability <code>s/(n+1)</code>.</p>\n\n<p>Each element already part of our result set has a probability <code>1/s</code> of being replaced.</p>\n\n<p>The probability that an element from the <code>n</code>-seen result set is replaced in the <code>n+1</code>-seen result set is therefore <code>(1/s)*s/(n+1)=1/(n+1)</code>. Conversely, the probability that an element is not replaced is <code>1-1/(n+1)=n/(n+1)</code>.</p>\n\n<p>Thus, the <code>n+1</code>-seen result set contains an element either if it was part of the <code>n</code>-seen result set and was not replaced---this probability is <code>(s/n)*n/(n+1)=s/(n+1)</code>---or if the element was chosen---with probability <code>s/(n+1)</code>.</p>\n\n<p>The definition of the algorithm tells us that the first <code>s</code> elements are automatically included as the first <code>n=s</code> members of the result set. Therefore, the <code>n-seen</code> result set includes each element with <code>s/n</code> (=1) probability giving us the necessary base case for the induction.</p>\n\n<p><strong>References</strong></p>\n\n<ol>\n<li><p>McLeod, A. Ian, and David R. Bellhouse. \"A convenient algorithm for drawing a simple random sample.\" Journal of the Royal Statistical Society. Series C (Applied Statistics) 32.2 (1983): 182-184. (<a href=\"http://www.jstor.org/stable/10.2307/2347297\" rel=\"noreferrer\">Link</a>)</p></li>\n<li><p>Vitter, Jeffrey S. \"Random sampling with a reservoir.\" ACM Transactions on Mathematical Software (TOMS) 11.1 (1985): 37-57. (<a href=\"http://www.mathcs.emory.edu/~cheung/Courses/584-StreamDB/Syllabus/papers/RandomSampling/1985-Vitter-Random-sampling-with-reservior.pdf\" rel=\"noreferrer\">Link</a>)</p></li>\n</ol>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | Say I have a linked list of numbers of length `N`. `N` is very large and I don’t know in advance the exact value of `N`.
How can I most efficiently write a function that will return `k` completely *random numbers* from the list? | There's a very nice and efficient algorithm for this using a method called **reservoir sampling**.
Let me start by giving you its **history**:
**Knuth** calls this Algorithm R on p. 144 of his 1997 edition of Seminumerical Algorithms (volume 2 of The Art of Computer Programming), and provides some code for it there. Knuth attributes the algorithm to Alan G. Waterman. Despite a lengthy search, I haven't been able to find Waterman's original document, if it exists, which may be why you'll most often see Knuth quoted as the source of this algorithm.
**McLeod and Bellhouse, 1983** (1) provide a more thorough discussion than Knuth as well as the first published proof (that I'm aware of) that the algorithm works.
**Vitter 1985** (2) reviews Algorithm R and then presents an additional three algorithms which provide the same output, but with a twist. Rather than making a choice to include or skip each incoming element, his algorithm predetermines the number of incoming elements to be skipped. In his tests (which, admittedly, are out of date now) this decreased execution time dramatically by avoiding random number generation and comparisons on each in-coming number.
In **pseudocode** the algorithm is:
```
Let R be the result array of size s
Let I be an input queue
> Fill the reservoir array
for j in the range [1,s]:
R[j]=I.pop()
elements_seen=s
while I is not empty:
elements_seen+=1
j=random(1,elements_seen) > This is inclusive
if j<=s:
R[j]=I.pop()
else:
I.pop()
```
Note that I've specifically written the code to avoid specifying the size of the input. That's one of the cool properties of this algorithm: you can run it without needing to know the size of the input beforehand and it *still* assures you that each element you encounter has an equal probability of ending up in `R` (that is, there is no bias). Furthermore, `R` contains a fair and representative sample of the elements the algorithm has considered at all times. This means you can use this as an [online algorithm](https://en.wikipedia.org/wiki/Online_algorithm).
**Why does this work?**
McLeod and Bellhouse (1983) provide a proof using the mathematics of combinations. It's pretty, but it would be a bit difficult to reconstruct it here. Therefore, I've generated an alternative proof which is easier to explain.
We proceed via proof by induction.
Say we want to generate a set of `s` elements and that we have already seen `n>s` elements.
Let's assume that our current `s` elements have already each been chosen with probability `s/n`.
By the definition of the algorithm, we choose element `n+1` with probability `s/(n+1)`.
Each element already part of our result set has a probability `1/s` of being replaced.
The probability that an element from the `n`-seen result set is replaced in the `n+1`-seen result set is therefore `(1/s)*s/(n+1)=1/(n+1)`. Conversely, the probability that an element is not replaced is `1-1/(n+1)=n/(n+1)`.
Thus, the `n+1`-seen result set contains an element either if it was part of the `n`-seen result set and was not replaced---this probability is `(s/n)*n/(n+1)=s/(n+1)`---or if the element was chosen---with probability `s/(n+1)`.
The definition of the algorithm tells us that the first `s` elements are automatically included as the first `n=s` members of the result set. Therefore, the `n-seen` result set includes each element with `s/n` (=1) probability giving us the necessary base case for the induction.
**References**
1. McLeod, A. Ian, and David R. Bellhouse. "A convenient algorithm for drawing a simple random sample." Journal of the Royal Statistical Society. Series C (Applied Statistics) 32.2 (1983): 182-184. ([Link](http://www.jstor.org/stable/10.2307/2347297))
2. Vitter, Jeffrey S. "Random sampling with a reservoir." ACM Transactions on Mathematical Software (TOMS) 11.1 (1985): 37-57. ([Link](http://www.mathcs.emory.edu/~cheung/Courses/584-StreamDB/Syllabus/papers/RandomSampling/1985-Vitter-Random-sampling-with-reservior.pdf)) |
54,068 | <p>I'm looking at a new computer which will probably have vista on it. But there are so many editions of vista; are there any weird restrictions on what you can run on the various editions? For instance you couldn't run IIS on Windows ME. Can you still run IIS on the home editions of vista? </p>
| [
{
"answer_id": 54070,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest: First find your k random numbers. Sort them. Then traverse both the linked list and your random numbers once.</p>\n\n<p>If you somehow don't know the length of your linked list (how?), then you could grab the first k into an array, then for node r, generate a random number in [0, r), and if that is less than k, replace the rth item of the array. (Not entirely convinced that doesn't bias...)</p>\n\n<p>Other than that: \"If I were you, I wouldn't be starting from here.\" Are you sure linked list is right for your problem? Is there not a better data structure, such as a good old flat array list.</p>\n"
},
{
"answer_id": 54072,
"author": "Christian Oudard",
"author_id": 3757,
"author_profile": "https://Stackoverflow.com/users/3757",
"pm_score": -1,
"selected": false,
"text": "<p>Well, you do need to know what N is at runtime at least, even if this involves doing an extra pass over the list to count them. The simplest algorithm to do this is to just pick a random number in N and remove that item, repeated k times. Or, if it is permissible to return repeat numbers, don't remove the item.</p>\n\n<p>Unless you have a VERY large N, and very stringent performance requirements, this algorithm runs with <code>O(N*k)</code> complexity, which should be acceptable.</p>\n\n<p>Edit: Nevermind, Tom Hawtin's method is way better. Select the random numbers first, then traverse the list once. Same theoretical complexity, I think, but much better expected runtime.</p>\n"
},
{
"answer_id": 54083,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": -1,
"selected": false,
"text": "<p>Why can't you just do something like</p>\n\n<pre><code>List GetKRandomFromList(List input, int k)\n List ret = new List();\n for(i=0;i<k;i++)\n ret.Add(input[Math.Rand(0,input.Length)]);\n return ret;\n</code></pre>\n\n<p>I'm sure that you don't mean something that simple so can you specify further?</p>\n"
},
{
"answer_id": 54101,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 5,
"selected": false,
"text": "<p>This is called a <a href=\"http://gregable.com/2007/10/reservoir-sampling.html\" rel=\"noreferrer\">Reservoir Sampling</a> problem. The simple solution is to assign a random number to each element of the list as you see it, then keep the top (or bottom) k elements as ordered by the random number.</p>\n"
},
{
"answer_id": 54174,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't know the length of the list, then you will have to traverse it complete to ensure random picks. The method I've used in this case is the one described by Tom Hawtin (<a href=\"https://stackoverflow.com/questions/54059/efficiently-selecting-a-set-of-random-elements-from-a-linked-list#54070\">54070</a>). While traversing the list you keep <code>k</code> elements that form your random selection to that point. (Initially you just add the first <code>k</code> elements you encounter.) Then, with probability <code>k/i</code>, you replace a random element from your selection with the <code>i</code>th element of the list (i.e. the element you are at, at that moment).</p>\n\n<p>It's easy to show that this gives a random selection. After seeing <code>m</code> elements (<code>m > k</code>), we have that each of the first <code>m</code> elements of the list are part of you random selection with a probability <code>k/m</code>. That this initially holds is trivial. Then for each element <code>m+1</code>, you put it in your selection (replacing a random element) with probability <code>k/(m+1)</code>. You now need to show that all other elements also have probability <code>k/(m+1)</code> of being selected. We have that the probability is <code>k/m * (k/(m+1)*(1-1/k) + (1-k/(m+1)))</code> (i.e. probability that element was in the list times the probability that it is still there). With calculus you can straightforwardly show that this is equal to <code>k/(m+1)</code>.</p>\n"
},
{
"answer_id": 21201378,
"author": "Richard",
"author_id": 752843,
"author_profile": "https://Stackoverflow.com/users/752843",
"pm_score": 6,
"selected": true,
"text": "<p>There's a very nice and efficient algorithm for this using a method called <strong>reservoir sampling</strong>.</p>\n\n<p>Let me start by giving you its <strong>history</strong>:</p>\n\n<p><strong>Knuth</strong> calls this Algorithm R on p. 144 of his 1997 edition of Seminumerical Algorithms (volume 2 of The Art of Computer Programming), and provides some code for it there. Knuth attributes the algorithm to Alan G. Waterman. Despite a lengthy search, I haven't been able to find Waterman's original document, if it exists, which may be why you'll most often see Knuth quoted as the source of this algorithm.</p>\n\n<p><strong>McLeod and Bellhouse, 1983</strong> (1) provide a more thorough discussion than Knuth as well as the first published proof (that I'm aware of) that the algorithm works.</p>\n\n<p><strong>Vitter 1985</strong> (2) reviews Algorithm R and then presents an additional three algorithms which provide the same output, but with a twist. Rather than making a choice to include or skip each incoming element, his algorithm predetermines the number of incoming elements to be skipped. In his tests (which, admittedly, are out of date now) this decreased execution time dramatically by avoiding random number generation and comparisons on each in-coming number.</p>\n\n<p>In <strong>pseudocode</strong> the algorithm is:</p>\n\n<pre><code>Let R be the result array of size s\nLet I be an input queue\n\n> Fill the reservoir array\nfor j in the range [1,s]:\n R[j]=I.pop()\n\nelements_seen=s\nwhile I is not empty:\n elements_seen+=1\n j=random(1,elements_seen) > This is inclusive\n if j<=s:\n R[j]=I.pop()\n else:\n I.pop()\n</code></pre>\n\n<p>Note that I've specifically written the code to avoid specifying the size of the input. That's one of the cool properties of this algorithm: you can run it without needing to know the size of the input beforehand and it <em>still</em> assures you that each element you encounter has an equal probability of ending up in <code>R</code> (that is, there is no bias). Furthermore, <code>R</code> contains a fair and representative sample of the elements the algorithm has considered at all times. This means you can use this as an <a href=\"https://en.wikipedia.org/wiki/Online_algorithm\" rel=\"noreferrer\">online algorithm</a>.</p>\n\n<p><strong>Why does this work?</strong></p>\n\n<p>McLeod and Bellhouse (1983) provide a proof using the mathematics of combinations. It's pretty, but it would be a bit difficult to reconstruct it here. Therefore, I've generated an alternative proof which is easier to explain.</p>\n\n<p>We proceed via proof by induction.</p>\n\n<p>Say we want to generate a set of <code>s</code> elements and that we have already seen <code>n>s</code> elements.</p>\n\n<p>Let's assume that our current <code>s</code> elements have already each been chosen with probability <code>s/n</code>.</p>\n\n<p>By the definition of the algorithm, we choose element <code>n+1</code> with probability <code>s/(n+1)</code>.</p>\n\n<p>Each element already part of our result set has a probability <code>1/s</code> of being replaced.</p>\n\n<p>The probability that an element from the <code>n</code>-seen result set is replaced in the <code>n+1</code>-seen result set is therefore <code>(1/s)*s/(n+1)=1/(n+1)</code>. Conversely, the probability that an element is not replaced is <code>1-1/(n+1)=n/(n+1)</code>.</p>\n\n<p>Thus, the <code>n+1</code>-seen result set contains an element either if it was part of the <code>n</code>-seen result set and was not replaced---this probability is <code>(s/n)*n/(n+1)=s/(n+1)</code>---or if the element was chosen---with probability <code>s/(n+1)</code>.</p>\n\n<p>The definition of the algorithm tells us that the first <code>s</code> elements are automatically included as the first <code>n=s</code> members of the result set. Therefore, the <code>n-seen</code> result set includes each element with <code>s/n</code> (=1) probability giving us the necessary base case for the induction.</p>\n\n<p><strong>References</strong></p>\n\n<ol>\n<li><p>McLeod, A. Ian, and David R. Bellhouse. \"A convenient algorithm for drawing a simple random sample.\" Journal of the Royal Statistical Society. Series C (Applied Statistics) 32.2 (1983): 182-184. (<a href=\"http://www.jstor.org/stable/10.2307/2347297\" rel=\"noreferrer\">Link</a>)</p></li>\n<li><p>Vitter, Jeffrey S. \"Random sampling with a reservoir.\" ACM Transactions on Mathematical Software (TOMS) 11.1 (1985): 37-57. (<a href=\"http://www.mathcs.emory.edu/~cheung/Courses/584-StreamDB/Syllabus/papers/RandomSampling/1985-Vitter-Random-sampling-with-reservior.pdf\" rel=\"noreferrer\">Link</a>)</p></li>\n</ol>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
] | I'm looking at a new computer which will probably have vista on it. But there are so many editions of vista; are there any weird restrictions on what you can run on the various editions? For instance you couldn't run IIS on Windows ME. Can you still run IIS on the home editions of vista? | There's a very nice and efficient algorithm for this using a method called **reservoir sampling**.
Let me start by giving you its **history**:
**Knuth** calls this Algorithm R on p. 144 of his 1997 edition of Seminumerical Algorithms (volume 2 of The Art of Computer Programming), and provides some code for it there. Knuth attributes the algorithm to Alan G. Waterman. Despite a lengthy search, I haven't been able to find Waterman's original document, if it exists, which may be why you'll most often see Knuth quoted as the source of this algorithm.
**McLeod and Bellhouse, 1983** (1) provide a more thorough discussion than Knuth as well as the first published proof (that I'm aware of) that the algorithm works.
**Vitter 1985** (2) reviews Algorithm R and then presents an additional three algorithms which provide the same output, but with a twist. Rather than making a choice to include or skip each incoming element, his algorithm predetermines the number of incoming elements to be skipped. In his tests (which, admittedly, are out of date now) this decreased execution time dramatically by avoiding random number generation and comparisons on each in-coming number.
In **pseudocode** the algorithm is:
```
Let R be the result array of size s
Let I be an input queue
> Fill the reservoir array
for j in the range [1,s]:
R[j]=I.pop()
elements_seen=s
while I is not empty:
elements_seen+=1
j=random(1,elements_seen) > This is inclusive
if j<=s:
R[j]=I.pop()
else:
I.pop()
```
Note that I've specifically written the code to avoid specifying the size of the input. That's one of the cool properties of this algorithm: you can run it without needing to know the size of the input beforehand and it *still* assures you that each element you encounter has an equal probability of ending up in `R` (that is, there is no bias). Furthermore, `R` contains a fair and representative sample of the elements the algorithm has considered at all times. This means you can use this as an [online algorithm](https://en.wikipedia.org/wiki/Online_algorithm).
**Why does this work?**
McLeod and Bellhouse (1983) provide a proof using the mathematics of combinations. It's pretty, but it would be a bit difficult to reconstruct it here. Therefore, I've generated an alternative proof which is easier to explain.
We proceed via proof by induction.
Say we want to generate a set of `s` elements and that we have already seen `n>s` elements.
Let's assume that our current `s` elements have already each been chosen with probability `s/n`.
By the definition of the algorithm, we choose element `n+1` with probability `s/(n+1)`.
Each element already part of our result set has a probability `1/s` of being replaced.
The probability that an element from the `n`-seen result set is replaced in the `n+1`-seen result set is therefore `(1/s)*s/(n+1)=1/(n+1)`. Conversely, the probability that an element is not replaced is `1-1/(n+1)=n/(n+1)`.
Thus, the `n+1`-seen result set contains an element either if it was part of the `n`-seen result set and was not replaced---this probability is `(s/n)*n/(n+1)=s/(n+1)`---or if the element was chosen---with probability `s/(n+1)`.
The definition of the algorithm tells us that the first `s` elements are automatically included as the first `n=s` members of the result set. Therefore, the `n-seen` result set includes each element with `s/n` (=1) probability giving us the necessary base case for the induction.
**References**
1. McLeod, A. Ian, and David R. Bellhouse. "A convenient algorithm for drawing a simple random sample." Journal of the Royal Statistical Society. Series C (Applied Statistics) 32.2 (1983): 182-184. ([Link](http://www.jstor.org/stable/10.2307/2347297))
2. Vitter, Jeffrey S. "Random sampling with a reservoir." ACM Transactions on Mathematical Software (TOMS) 11.1 (1985): 37-57. ([Link](http://www.mathcs.emory.edu/~cheung/Courses/584-StreamDB/Syllabus/papers/RandomSampling/1985-Vitter-Random-sampling-with-reservior.pdf)) |
54,138 | <p>I have a third-party app that creates HTML-based reports that I need to display. I have <em>some</em> control over how they look, but in general it's pretty primitive. I <em>can</em> inject some javascript, though. I'd like to try to inject some jQuery goodness into it to tidy it up some. One specific thing I would like to do is to take a table (an actual HTML <table>) that always contains one row and a variable number of columns and magically convert that into a tabbed view where the contents (always one <div> that I can supply an ID if necessary) of each original table cell represents a sheet in the tabbed view. I haven't found any good (read: simple) examples of re-parenting items like this, so I'm not sure where to begin. Can someone provide some hints on how I might try this?</p>
| [
{
"answer_id": 54145,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 0,
"selected": false,
"text": "<p>You could do this with jQuery but it may make additional maintenance a nightmare. I would recommend against doing this / screen scraping because if the source ever changes so does your work around.</p>\n"
},
{
"answer_id": 54190,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 0,
"selected": false,
"text": "<p>This certainly sounds possible. With a combination of jQuery.append and jQuery.fadeIn and fadeOut you should be able to create a nice little tabbed control.</p>\n\n<p>See the JQuery UI/Tabs for a simple way to create a set of tabs based on a <code><ul></code> element and a set of <code><div>'s</code>: <a href=\"http://docs.jquery.com/UI/Tabs\" rel=\"nofollow noreferrer\">http://docs.jquery.com/UI/Tabs</a></p>\n"
},
{
"answer_id": 76943,
"author": "Rich McCollister",
"author_id": 9306,
"author_profile": "https://Stackoverflow.com/users/9306",
"pm_score": 3,
"selected": true,
"text": "<p>Given a html page like this:</p>\n\n<pre><code><body><br/>\n <table id=\"my-table\">`<br/>\n <tr><br/>\n <td><div>This is the contents of Column One</div></td><br/>\n <td><div>This is the contents of Column Two</div></td><br/>\n <td><div>This is the contents of Column Three</div></td><br/>\n <td><div>Contents of Column Four blah blah</div></td><br/>\n <td><div>Column Five is here</div></td><br/>\n </tr><br/>\n </table><br/>\n</body><br/>\n</code></pre>\n\n<p>the following jQuery code converts the table cells into tabs (tested in FF 3 and IE 7)</p>\n\n<pre><code>$(document).ready(function() {\n var tabCounter = 1;\n $(\"#my-table\").after(\"<div id='tab-container' class='flora'><ul id='tab-list'></ul></div>\");\n $(\"#my-table div\").appendTo(\"#tab-container\").each(function() { \n var id = \"fragment-\" + tabCounter;\n $(this).attr(\"id\", id);\n $(\"#tab-list\").append(\"<li><span><a href='#\" + id + \"'>Tab \" + tabCounter + \"</a></span></li>\");\n tabCounter++;\n });\n $(\"#tab-container > ul\").tabs();\n});\n</code></pre>\n\n<p>To get this to work I referenced the following jQuery files</p>\n\n<ul>\n<li>jquery-latest.js</li>\n<li>ui.core.js</li>\n<li>ui.tabs.js</li>\n</ul>\n\n<p>And I referenced the flora.all.css stylesheet. Basically I copied the header section from the <a href=\"http://docs.jquery.com/UI/Tabs#Example\" rel=\"nofollow noreferrer\">jQuery tab example</a> </p>\n"
},
{
"answer_id": 892348,
"author": "Tom",
"author_id": 45350,
"author_profile": "https://Stackoverflow.com/users/45350",
"pm_score": 0,
"selected": false,
"text": "<p>I would also suggest injecting an additional stylesheet and use that to show/hide and style ugly elements.</p>\n"
},
{
"answer_id": 1091573,
"author": "fbuchinger",
"author_id": 113936,
"author_profile": "https://Stackoverflow.com/users/113936",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like you are not interested in a HTML cleanup as HTML Tidy does, but in an interactive enhancement of static HTML components (e.g. turning a static table in a tabbed interface).</p>\n\n<p>Some replies here already gave you hints, e.g. using Jquery Tabs, but i don't like the HTML rewrite approach in their answers.</p>\n\n<p>IMHO its better to extract the content of the table cells you want with a JQuery selector, like: </p>\n\n<pre><code>var mycontent = $('table tr[:first-child]').find('td[:first-child]').html()\n</code></pre>\n\n<p>then you can feed this data to the JQuery UI plugin by programmatically creating the tabs:</p>\n\n<pre><code>$('body').append($('<div></div>').attr('id','mytabs'));\n$('#mytabs').tabs({}); //specify tab preferences here\n$('#mytabs').tabs('add',mycontent);\n</code></pre>\n"
},
{
"answer_id": 8278645,
"author": "austincheney",
"author_id": 1065429,
"author_profile": "https://Stackoverflow.com/users/1065429",
"pm_score": 0,
"selected": false,
"text": "<p>Beautifying HTML is not such a simple process, because every line break between tags is a text node and arbitrary beautification creates and removes text nodes in manner that could be harmful to the document structure and likely harmful to the content. I recommend using a program that has already thought all these conditions through, such as <a href=\"http://prettydiff.com/?m=beautify\" rel=\"nofollow\">http://prettydiff.com/?m=beautify</a></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
] | I have a third-party app that creates HTML-based reports that I need to display. I have *some* control over how they look, but in general it's pretty primitive. I *can* inject some javascript, though. I'd like to try to inject some jQuery goodness into it to tidy it up some. One specific thing I would like to do is to take a table (an actual HTML <table>) that always contains one row and a variable number of columns and magically convert that into a tabbed view where the contents (always one <div> that I can supply an ID if necessary) of each original table cell represents a sheet in the tabbed view. I haven't found any good (read: simple) examples of re-parenting items like this, so I'm not sure where to begin. Can someone provide some hints on how I might try this? | Given a html page like this:
```
<body><br/>
<table id="my-table">`<br/>
<tr><br/>
<td><div>This is the contents of Column One</div></td><br/>
<td><div>This is the contents of Column Two</div></td><br/>
<td><div>This is the contents of Column Three</div></td><br/>
<td><div>Contents of Column Four blah blah</div></td><br/>
<td><div>Column Five is here</div></td><br/>
</tr><br/>
</table><br/>
</body><br/>
```
the following jQuery code converts the table cells into tabs (tested in FF 3 and IE 7)
```
$(document).ready(function() {
var tabCounter = 1;
$("#my-table").after("<div id='tab-container' class='flora'><ul id='tab-list'></ul></div>");
$("#my-table div").appendTo("#tab-container").each(function() {
var id = "fragment-" + tabCounter;
$(this).attr("id", id);
$("#tab-list").append("<li><span><a href='#" + id + "'>Tab " + tabCounter + "</a></span></li>");
tabCounter++;
});
$("#tab-container > ul").tabs();
});
```
To get this to work I referenced the following jQuery files
* jquery-latest.js
* ui.core.js
* ui.tabs.js
And I referenced the flora.all.css stylesheet. Basically I copied the header section from the [jQuery tab example](http://docs.jquery.com/UI/Tabs#Example) |
54,142 | <p>How does the comma operator work in C++?</p>
<p>For instance, if I do:</p>
<pre><code>a = b, c;
</code></pre>
<p>Does a end up equaling b or c? </p>
<p>(Yes, I know this is easy to test - just documenting on here for someone to find the answer quickly.)</p>
<p><strong>Update:</strong> This question has exposed a nuance when using the comma operator. Just to document this:</p>
<pre><code>a = b, c; // a is set to the value of b!
a = (b, c); // a is set to the value of c!
</code></pre>
<p>This question was actually inspired by a typo in code. What was intended to be</p>
<pre><code>a = b;
c = d;
</code></pre>
<p>Turned into</p>
<pre><code>a = b, // <- Note comma typo!
c = d;
</code></pre>
| [
{
"answer_id": 54146,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 7,
"selected": true,
"text": "<p>It would be equal to <code>b</code>.</p>\n\n<p>The comma operator has a lower precedence than assignment.</p>\n"
},
{
"answer_id": 54154,
"author": "prakash",
"author_id": 123,
"author_profile": "https://Stackoverflow.com/users/123",
"pm_score": 3,
"selected": false,
"text": "<p>b's value will be assigned to a.\nNothing will happen to c</p>\n"
},
{
"answer_id": 54172,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": false,
"text": "<p>Take care to notice that the comma operator may be overloaded in C++. The actual behaviour may thus be very different from the one expected.</p>\n\n<p>As an example, <a href=\"http://spirit.sourceforge.net/\" rel=\"noreferrer\">Boost.Spirit</a> uses the comma operator quite cleverly to implement list initializers for symbol tables. Thus, it makes the following syntax possible and meaningful:</p>\n\n<pre><code>keywords = \"and\", \"or\", \"not\", \"xor\";\n</code></pre>\n\n<p>Notice that due to operator precedence, the code is (intentionally!) identical to</p>\n\n<pre><code>(((keywords = \"and\"), \"or\"), \"not\"), \"xor\";\n</code></pre>\n\n<p>That is, the first operator called is <code>keywords.operator =(\"and\")</code> which returns a proxy object on which the remaining <code>operator,</code>s are invoked:</p>\n\n<pre><code>keywords.operator =(\"and\").operator ,(\"or\").operator ,(\"not\").operator ,(\"xor\");\n</code></pre>\n"
},
{
"answer_id": 54173,
"author": "Jason Carreiro",
"author_id": 5582,
"author_profile": "https://Stackoverflow.com/users/5582",
"pm_score": 2,
"selected": false,
"text": "<p>The value of a will be equal to b, since the comma operator has a lower precedence than the assignment operator.</p>\n"
},
{
"answer_id": 65438,
"author": "MobyDX",
"author_id": 3923,
"author_profile": "https://Stackoverflow.com/users/3923",
"pm_score": 5,
"selected": false,
"text": "<p>The value of <code>a</code> will be <code>b</code>, but the value of <em><strong>the expression</strong></em> will be <code>c</code>. That is, in</p>\n<pre><code>d = (a = b, c);\n</code></pre>\n<p><code>a</code> would be equal to <code>b</code>, and <code>d</code> would be equal to <code>c</code>.</p>\n"
},
{
"answer_id": 114404,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 7,
"selected": false,
"text": "<p>The comma operator has the <strong>lowest</strong> precedence of all C/C++ operators. Therefore it's always the last one to bind to an expression, meaning this:</p>\n\n<pre><code>a = b, c;\n</code></pre>\n\n<p>is equivalent to:</p>\n\n<pre><code>(a = b), c;\n</code></pre>\n\n<p>Another interesting fact is that the comma operator introduces a <a href=\"http://en.wikipedia.org/wiki/Sequence_point\" rel=\"noreferrer\">sequence point</a>. This means that the expression:</p>\n\n<pre><code>a+b, c(), d\n</code></pre>\n\n<p>is guaranteed to have its three subexpressions (<strong>a+b</strong>, <strong>c()</strong> and <strong>d</strong>) evaluated in order. This is significant if they have side-effects. Normally compilers are allowed to evaluate subexpressions in whatever order they find fit; for example, in a function call:</p>\n\n<pre><code>someFunc(arg1, arg2, arg3)\n</code></pre>\n\n<p>arguments can be evaluated in an arbitrary order. Note that the commas in the function call are <em>not</em> operators; they are separators.</p>\n"
},
{
"answer_id": 15861440,
"author": "Quonux",
"author_id": 388614,
"author_profile": "https://Stackoverflow.com/users/388614",
"pm_score": -1,
"selected": false,
"text": "<p><strong>First things first:</strong> Comma is actually not an operator, for the compiler it is just a token which gets a meaning <em>in context</em> with other tokens.</p>\n\n<h2>What does this mean and why bother?</h2>\n\n<p><strong>Example 1:</strong></p>\n\n<p>To understand the difference between the meaning of the same token in a different context we take a look at this example:</p>\n\n<pre><code>class Example {\n Foo<int, char*> ContentA;\n}\n</code></pre>\n\n<p>Usually a C++ beginner would think that this expression could/would compare things but it is absolutly wrong, the meaning of the <code><</code>, <code>></code> and <code>,</code> tokens depent on the context of use.</p>\n\n<p>The correct interpretation of the example above is of course that it is an instatiation of a template.</p>\n\n<p><strong>Example 2:</strong></p>\n\n<p>When we write a typically for loop with more than one initialisation variable and/or more than one expressions that should be done after each iteration of the loop we use comma too:</p>\n\n<pre><code>for(a=5,b=0;a<42;a++,b--)\n ...\n</code></pre>\n\n<p>The meaning of the comma depends on the context of use, here it is the context of the <code>for</code> construction.</p>\n\n<h2>What does a comma in context actually mean?</h2>\n\n<p>To complicate it even more (as always in C++) the comma operator can itself be overloaded (thanks to <a href=\"https://stackoverflow.com/users/1968/konrad-rudolph\">Konrad Rudolph</a> for pointing that out).</p>\n\n<p>To come back to the question, the Code</p>\n\n<pre><code>a = b, c;\n</code></pre>\n\n<p>means for the compiler something like</p>\n\n<pre><code>(a = b), c;\n</code></pre>\n\n<p>because the <a href=\"http://en.cppreference.com/w/cpp/language/operator_precedence\" rel=\"nofollow noreferrer\">priority</a> of the <code>=</code> token/operator is higher than the priority of the <code>,</code> token.</p>\n\n<p>and this is interpreted in context like</p>\n\n<pre><code>a = b;\nc;\n</code></pre>\n\n<p>(note that the interpretation depend on context, here it it neither a function/method call or a template instatiation.)</p>\n"
},
{
"answer_id": 19198977,
"author": "CygnusX1",
"author_id": 635654,
"author_profile": "https://Stackoverflow.com/users/635654",
"pm_score": 6,
"selected": false,
"text": "<p>The comma operator:</p>\n\n<ul>\n<li>has the lowest precedence</li>\n<li>is left-associative</li>\n</ul>\n\n<p>A default version of comma operator is defined for all types (built-in and custom), and it works as follows - given <code>exprA , exprB</code>:</p>\n\n<ul>\n<li><code>exprA</code> is evaluated</li>\n<li>the result of <code>exprA</code> is ignored</li>\n<li><code>exprB</code> is evaluated</li>\n<li>the result of <code>exprB</code> is returned as the result of the whole expression</li>\n</ul>\n\n<p>With most operators, the compiler is allowed to choose the order of execution and it is even required to skip the execution whatsoever if it does not affect the final result (e.g. <code>false && foo()</code> will skip the call to <code>foo</code>). This is however not the case for comma operator and the above steps will always happen<sup>*</sup>.</p>\n\n<p>In practice, the default comma operator works almost the same way as a semicolon. The difference is that two expressions separated by a semicolon form two separate statements, while comma-separation keeps all as a single expression. This is why comma operator is sometimes used in the following scenarios:</p>\n\n<ul>\n<li>C syntax requires an single <em>expression</em>, not a statement. e.g. in <code>if( HERE )</code></li>\n<li>C syntax requires a single statement, not more, e.g. in the initialization of the <code>for</code> loop <code>for ( HERE ; ; )</code></li>\n<li>When you want to skip curly braces and keep a single statement: <code>if (foo) HERE ;</code> (please don't do that, it's really ugly!)</li>\n</ul>\n\n<p>When a statement is not an expression, semicolon cannot be replaced by a comma. For example these are disallowed:</p>\n\n<ul>\n<li><code>(foo, if (foo) bar)</code> (<code>if</code> is not an expression)</li>\n<li>int x, int y (variable declaration is not an expression)</li>\n</ul>\n\n<hr>\n\n<p>In your case we have:</p>\n\n<ul>\n<li><code>a=b, c;</code>, equivalent to <code>a=b; c;</code>, assuming that <code>a</code> is of type that does not overload the comma operator.</li>\n<li><code>a = b, c = d;</code> equivalent to <code>a=b; c=d;</code>, assuming that <code>a</code> is of type that does not overload the comma operator.</li>\n</ul>\n\n<hr>\n\n<p>Do note that not every comma is actually a comma operator. Some commas which have a completely different meaning:</p>\n\n<ul>\n<li><code>int a, b;</code> --- variable declaration list is comma separated, but these are not comma operators</li>\n<li><code>int a=5, b=3;</code> --- this is also a comma separated variable declaration list</li>\n<li><code>foo(x,y)</code> --- comma-separated argument list. In fact, <code>x</code> and <code>y</code> can be evaluated in <em>any</em> order!</li>\n<li><code>FOO(x,y)</code> --- comma-separated macro argument list</li>\n<li><code>foo<a,b></code> --- comma-separated template argument list</li>\n<li><code>int foo(int a, int b)</code> --- comma-separated parameter list</li>\n<li><code>Foo::Foo() : a(5), b(3) {}</code> --- comma-separated initializer list in a class constructor</li>\n</ul>\n\n<hr>\n\n<p><sup>*</sup> This is not entirely true if you apply optimizations. If the compiler recognizes that certain piece of code has absolutely no impact on the rest, it will remove the unnecessary statements.</p>\n\n<p>Further reading: <a href=\"http://en.wikipedia.org/wiki/Comma_operator\">http://en.wikipedia.org/wiki/Comma_operator</a></p>\n"
},
{
"answer_id": 31221185,
"author": "Roopam",
"author_id": 3529776,
"author_profile": "https://Stackoverflow.com/users/3529776",
"pm_score": 2,
"selected": false,
"text": "<p>Yes Comma operator has low precedence than Assignment operator</p>\n\n<pre><code>#include<stdio.h>\nint main()\n{\n int i;\n i = (1,2,3);\n printf(\"i:%d\\n\",i);\n return 0;\n}\n</code></pre>\n\n<p>Output : i=3<br>\nBecause comma operator always return rightmost value.<br>\nIn case of comma operator with Assignment Operator:</p>\n\n<pre><code> int main()\n{\n int i;\n i = 1,2,3;\n printf(\"i:%d\\n\",i);\n return 0;\n}\n</code></pre>\n\n<p>Ouput: i=1\n<br>\nAs we know comma operator has lower precedence than assignment.....</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541/"
] | How does the comma operator work in C++?
For instance, if I do:
```
a = b, c;
```
Does a end up equaling b or c?
(Yes, I know this is easy to test - just documenting on here for someone to find the answer quickly.)
**Update:** This question has exposed a nuance when using the comma operator. Just to document this:
```
a = b, c; // a is set to the value of b!
a = (b, c); // a is set to the value of c!
```
This question was actually inspired by a typo in code. What was intended to be
```
a = b;
c = d;
```
Turned into
```
a = b, // <- Note comma typo!
c = d;
``` | It would be equal to `b`.
The comma operator has a lower precedence than assignment. |
54,147 | <p>I want to insert some special characters at the caret inside textboxes using javascript on a button. How can this be done?</p>
<p>The script needs to find the active textbox and insert the character at the caret in that textbox. The script also needs to work in IE and Firefox.</p>
<p><strong>EDIT:</strong> It is also ok to insert the character "last" in the previously active textbox.</p>
| [
{
"answer_id": 54162,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 0,
"selected": false,
"text": "<p>Note that if the user pushes a button, focus on the textbox will be lost and there will be no caret position!</p>\n"
},
{
"answer_id": 54164,
"author": "delux247",
"author_id": 5569,
"author_profile": "https://Stackoverflow.com/users/5569",
"pm_score": 0,
"selected": false,
"text": "<p>loop over all you input fields... \nfinding the one that has focus..\nthen once you have your text area...\nyou should be able to do something like...</p>\n\n<p>myTextArea.value = 'text to insert in the text area goes here';</p>\n"
},
{
"answer_id": 54167,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure if you can capture the caret position, but if you can, you can avoid Jason Cohen's concern by capturing the location (in relation to the string) using the text box's <code>onblur</code> event.</p>\n"
},
{
"answer_id": 54269,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 1,
"selected": false,
"text": "<p>In light of your update:</p>\n\n<pre><code>var inputs = document.getElementsByTagName('input');\nvar lastTextBox = null;\n\nfor(var i = 0; i < inputs.length; i++)\n{\n if(inputs[i].getAttribute('type') == 'text')\n {\n inputs[i].onfocus = function() {\n lastTextBox = this;\n }\n }\n}\n\nvar button = document.getElementById(\"YOURBUTTONID\");\nbutton.onclick = function() {\n lastTextBox.value += 'PUTYOURTEXTHERE';\n}\n</code></pre>\n"
},
{
"answer_id": 58369,
"author": "bmb",
"author_id": 5298,
"author_profile": "https://Stackoverflow.com/users/5298",
"pm_score": 2,
"selected": false,
"text": "<p>I think Jason Cohen is incorrect. The caret position is preserved when focus is lost.</p>\n\n<p>[<strong>Edit</strong>: Added code for FireFox that I didn't have originally.]</p>\n\n<p>[<strong>Edit</strong>: Added code to determine the most recent active text box.]</p>\n\n<p>First, you can use each text box's onBlur event to set a variable to \"this\" so you always know the most recent active text box.</p>\n\n<p>Then, there's an IE way to get the cursor position that also works in Opera, and an easier way in Firefox.</p>\n\n<p>In IE the basic concept is to use the document.selection object and <em>put</em> some text <em>into</em> the selection. Then, using indexOf, you can get the position of the text you added.</p>\n\n<p>In FireFox, there's a method called selectionStart that will give you the cursor position.</p>\n\n<p>Once you have the cursor position, you overwrite the whole text.value with</p>\n\n<p>text before the cursor position + the text you want to insert + the text after the cursor position</p>\n\n<p>Here is an example with separate links for IE and FireFox. You can use you favorite browser detection method to figure out which code to run.</p>\n\n<pre><code><html><head></head><body>\n\n<script language=\"JavaScript\">\n<!--\n\nvar lasttext;\n\nfunction doinsert_ie() {\n var oldtext = lasttext.value;\n var marker = \"##MARKER##\";\n lasttext.focus();\n var sel = document.selection.createRange();\n sel.text = marker;\n var tmptext = lasttext.value;\n var curpos = tmptext.indexOf(marker);\n pretext = oldtext.substring(0,curpos);\n posttest = oldtext.substring(curpos,oldtext.length);\n lasttext.value = pretext + \"|\" + posttest;\n}\n\nfunction doinsert_ff() {\n var oldtext = lasttext.value;\n var curpos = lasttext.selectionStart;\n pretext = oldtext.substring(0,curpos);\n posttest = oldtext.substring(curpos,oldtext.length);\n lasttext.value = pretext + \"|\" + posttest;\n}\n\n-->\n</script>\n\n\n<form name=\"testform\">\n<input type=\"text\" name=\"testtext1\" onBlur=\"lasttext=this;\">\n<input type=\"text\" name=\"testtext2\" onBlur=\"lasttext=this;\">\n<input type=\"text\" name=\"testtext3\" onBlur=\"lasttext=this;\">\n\n</form>\n<a href=\"#\" onClick=\"doinsert_ie();\">Insert IE</a>\n<br>\n<a href=\"#\" onClick=\"doinsert_ff();\">Insert FF</a>\n</body></html>\n</code></pre>\n\n<p>This will also work with textareas. I don't know how to reposition the cursor so it stays at the insertion point.</p>\n"
},
{
"answer_id": 14401812,
"author": "CraigDub",
"author_id": 1983541,
"author_profile": "https://Stackoverflow.com/users/1983541",
"pm_score": 0,
"selected": false,
"text": "<p>A butchered version of @bmb code in previous answer works well to reposition the cursor at end of inserted characters too:</p>\n\n<pre><code>var lasttext;\n\nfunction doinsert_ie() {\n var ttInsert = \"bla\";\n lasttext.focus();\n var sel = document.selection.createRange();\n sel.text = ttInsert;\n sel.select();\n}\n\nfunction doinsert_ff() {\n var oldtext = lasttext.value;\n var curposS = lasttext.selectionStart;\n var curposF = lasttext.selectionEnd;\n pretext = oldtext.substring(0,curposS);\n posttest = oldtext.substring(curposF,oldtext.length);\n var ttInsert='bla';\n lasttext.value = pretext + ttInsert + posttest;\n lasttext.selectionStart=curposS+ttInsert.length;\n lasttext.selectionEnd=curposS+ttInsert.length;\n}\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1523/"
] | I want to insert some special characters at the caret inside textboxes using javascript on a button. How can this be done?
The script needs to find the active textbox and insert the character at the caret in that textbox. The script also needs to work in IE and Firefox.
**EDIT:** It is also ok to insert the character "last" in the previously active textbox. | I think Jason Cohen is incorrect. The caret position is preserved when focus is lost.
[**Edit**: Added code for FireFox that I didn't have originally.]
[**Edit**: Added code to determine the most recent active text box.]
First, you can use each text box's onBlur event to set a variable to "this" so you always know the most recent active text box.
Then, there's an IE way to get the cursor position that also works in Opera, and an easier way in Firefox.
In IE the basic concept is to use the document.selection object and *put* some text *into* the selection. Then, using indexOf, you can get the position of the text you added.
In FireFox, there's a method called selectionStart that will give you the cursor position.
Once you have the cursor position, you overwrite the whole text.value with
text before the cursor position + the text you want to insert + the text after the cursor position
Here is an example with separate links for IE and FireFox. You can use you favorite browser detection method to figure out which code to run.
```
<html><head></head><body>
<script language="JavaScript">
<!--
var lasttext;
function doinsert_ie() {
var oldtext = lasttext.value;
var marker = "##MARKER##";
lasttext.focus();
var sel = document.selection.createRange();
sel.text = marker;
var tmptext = lasttext.value;
var curpos = tmptext.indexOf(marker);
pretext = oldtext.substring(0,curpos);
posttest = oldtext.substring(curpos,oldtext.length);
lasttext.value = pretext + "|" + posttest;
}
function doinsert_ff() {
var oldtext = lasttext.value;
var curpos = lasttext.selectionStart;
pretext = oldtext.substring(0,curpos);
posttest = oldtext.substring(curpos,oldtext.length);
lasttext.value = pretext + "|" + posttest;
}
-->
</script>
<form name="testform">
<input type="text" name="testtext1" onBlur="lasttext=this;">
<input type="text" name="testtext2" onBlur="lasttext=this;">
<input type="text" name="testtext3" onBlur="lasttext=this;">
</form>
<a href="#" onClick="doinsert_ie();">Insert IE</a>
<br>
<a href="#" onClick="doinsert_ff();">Insert FF</a>
</body></html>
```
This will also work with textareas. I don't know how to reposition the cursor so it stays at the insertion point. |
54,219 | <p>I'm working on an editor for files that are used by an important internal testing tool we use. The tool itself is large, complicated, and refactoring or rewriting would take more resources than we are able to devote to it for the forseeable future, so my hands are tied when it comes to large modifications. I must use a .NET language.</p>
<p>The files are XML serialized versions of four classes that are used by the tool (let's call them A, B, C, and D). The classes form a tree structure when all is well. Our editor works by loading a set of files, deserializing them, working out the relationships between them, and keeping track of any bad states it can find. The idea is for us to move away from hand-editing these files, which introduces tons of errors.</p>
<p>For a particular type of error, I'd like to maintain a collection of all files that have the problem. All four classes can have the problem, and I'd like to reduce duplication of code as much as possible. An important requirement is the user needs to be able to get the items in sets; for example, they need to get all A objects with an error, and telling them to iterate over the whole collection and pick out what they want is unacceptable compared to a <code>GetAs()</code> method. So, my first thought was to make a generic item that related the deserialized object and some metadata to indicate the error:</p>
<pre><code>public class ErrorItem<T>
{
public T Item { get; set; }
public Metadata Metadata { get; set; }
}
</code></pre>
<p>Then, I'd have a collection class that could hold all of the error items, with helper methods to extract the items of a specific class when the user needs them. This is where the trouble starts.</p>
<p>None of the classes inherit from a common ancestor (other than <code>Object</code>). This was probably a mistake of the initial design, but I've spent a few days thinking about it and the classes really don't have much in common other than a GUID property that uniquely identifies each item so I can see why the original designer did not relate them through inheritance. This means that the unified error collection would need to store <code>ErrorItem<Object></code> objects, since I don't have a base class or interface to restrict what comes in. However, this makes the idea of this unified collection a little sketchy to me:</p>
<pre><code>Public Class ErrorCollection
{
public ErrorItem<Object> AllItems { get; set; }
}
</code></pre>
<p>However, this has consequences on the public interface. What I really want is to return the appropriate <code>ErrorItem</code> generic type like this:</p>
<pre><code>public ErrorItem<A>[] GetA()
</code></pre>
<p>This is impossible because I can only store <code>ErrorItem<Object></code>! I've gone over some workarounds in my head; mostly they include creating a new <code>ErrorItem</code> of the appropriate type on-the-fly, but it just feels kind of ugly. Another thought has been using a <code>Dictionary</code> to keep items organized by type, but it still doesn't seem right.</p>
<p>Is there some kind of pattern that might help me here? I know the easiest way to solve this is to add a base class that A, B, C, and D derive from, but I'm trying to have as small an impact on the original tool as possible. Is the cost of any workaround great enough that I should push to change the initial tool?</p>
| [
{
"answer_id": 54258,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 1,
"selected": true,
"text": "<p>If A, B, C and D have nothing in common then adding a base class won't really get you anything. It will just be an empty class and in effect will be the same as object.</p>\n\n<p>I'd just create an ErrorItem class without the generics, make Item an object and do some casting when you want to use the objects referenced. If you want to use any of the properties or methods of the A, B, C or D class other than the Guid you would have had to cast them anyway.</p>\n"
},
{
"answer_id": 54287,
"author": "fryguybob",
"author_id": 4592,
"author_profile": "https://Stackoverflow.com/users/4592",
"pm_score": 1,
"selected": false,
"text": "<p>Is this what you are looking for?</p>\n\n<pre><code>private List<ErrorItem<object>> _allObjects = new List<ErrorItem<object>>();\n\npublic IEnumerable<ErrorItem<A>> ItemsOfA\n{\n get\n {\n foreach (ErrorItem<object> obj in _allObjects)\n {\n if (obj.Item is A)\n yield return new ErrorItem<A>((A)obj.Item, obj.MetaData);\n }\n }\n}\n</code></pre>\n\n<p>If you want to cache the <code>ItemsOfA</code> you can easily do that:</p>\n\n<pre><code>private List<ErrorItem<A>> _itemsOfA = null;\n\npublic IEnumerable<ErrorItem<A>> ItemsOfACached\n{\n if (_itemsOfA == null)\n _itemsOfA = new List<ErrorItem<A>>(ItemsOfA);\n return _itemsOfA;\n}\n</code></pre>\n"
},
{
"answer_id": 54649,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 1,
"selected": false,
"text": "<p>The answer I'm going with so far is a combination of the answers from fryguybob and Mendelt Siebenga.</p>\n\n<p>Adding a base class would just pollute the namespace and introduce a similar problem, as Mendelt Siebenga pointed out. I would get more control over what items can go into the collection, but I'd still need to store <code>ErrorItem<BaseClass></code> and still do some casting, so I'd have a slightly different problem with the same root cause. This is why I selected the post as the answer: it points out that I'm going to have to do some casts no matter what, and KISS would dictate that the extra base class and generics are too much.</p>\n\n<p>I like fryguybob's answer not for the solution itself but for reminding me about <code>yield return</code>, which will make a non-cached version easier to write (I was going to use LINQ). I think a cached version is a little bit more wise, though the expected performance parameters won't make the non-cached version noticably slower.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547/"
] | I'm working on an editor for files that are used by an important internal testing tool we use. The tool itself is large, complicated, and refactoring or rewriting would take more resources than we are able to devote to it for the forseeable future, so my hands are tied when it comes to large modifications. I must use a .NET language.
The files are XML serialized versions of four classes that are used by the tool (let's call them A, B, C, and D). The classes form a tree structure when all is well. Our editor works by loading a set of files, deserializing them, working out the relationships between them, and keeping track of any bad states it can find. The idea is for us to move away from hand-editing these files, which introduces tons of errors.
For a particular type of error, I'd like to maintain a collection of all files that have the problem. All four classes can have the problem, and I'd like to reduce duplication of code as much as possible. An important requirement is the user needs to be able to get the items in sets; for example, they need to get all A objects with an error, and telling them to iterate over the whole collection and pick out what they want is unacceptable compared to a `GetAs()` method. So, my first thought was to make a generic item that related the deserialized object and some metadata to indicate the error:
```
public class ErrorItem<T>
{
public T Item { get; set; }
public Metadata Metadata { get; set; }
}
```
Then, I'd have a collection class that could hold all of the error items, with helper methods to extract the items of a specific class when the user needs them. This is where the trouble starts.
None of the classes inherit from a common ancestor (other than `Object`). This was probably a mistake of the initial design, but I've spent a few days thinking about it and the classes really don't have much in common other than a GUID property that uniquely identifies each item so I can see why the original designer did not relate them through inheritance. This means that the unified error collection would need to store `ErrorItem<Object>` objects, since I don't have a base class or interface to restrict what comes in. However, this makes the idea of this unified collection a little sketchy to me:
```
Public Class ErrorCollection
{
public ErrorItem<Object> AllItems { get; set; }
}
```
However, this has consequences on the public interface. What I really want is to return the appropriate `ErrorItem` generic type like this:
```
public ErrorItem<A>[] GetA()
```
This is impossible because I can only store `ErrorItem<Object>`! I've gone over some workarounds in my head; mostly they include creating a new `ErrorItem` of the appropriate type on-the-fly, but it just feels kind of ugly. Another thought has been using a `Dictionary` to keep items organized by type, but it still doesn't seem right.
Is there some kind of pattern that might help me here? I know the easiest way to solve this is to add a base class that A, B, C, and D derive from, but I'm trying to have as small an impact on the original tool as possible. Is the cost of any workaround great enough that I should push to change the initial tool? | If A, B, C and D have nothing in common then adding a base class won't really get you anything. It will just be an empty class and in effect will be the same as object.
I'd just create an ErrorItem class without the generics, make Item an object and do some casting when you want to use the objects referenced. If you want to use any of the properties or methods of the A, B, C or D class other than the Guid you would have had to cast them anyway. |
54,227 | <p>I have an asp.net url path which is being generated in a web form, and is coming out something like "/foo/bar/../bar/path.aspx", and is coming out in the generated html like this too. It should be shortened to "/foo/bar/path.aspx". </p>
<p>Path.Combine didn't fix it. Is there a function to clean this path up? </p>
| [
{
"answer_id": 54273,
"author": "Compile This",
"author_id": 4048,
"author_profile": "https://Stackoverflow.com/users/4048",
"pm_score": 3,
"selected": true,
"text": "<p>You could create a helper class which wrapped the UriBuilder class in System.Net</p>\n\n<pre><code>public static class UriHelper\n{ \n public static string NormalizeRelativePath(string path)\n {\n UriBuilder _builder = new UriBuilder(\"http://localhost\");\n builder.Path = path;\n return builder.Uri.AbsolutePath;\n }\n}\n</code></pre>\n\n<p>which could then be used like this:</p>\n\n<pre><code>string url = \"foo/bar/../bar/path.aspx\";\nConsole.WriteLine(UriHelper.NormalizeRelativePath(url));\n</code></pre>\n\n<p>It is a bit hacky but it would work for the specific example you gave.</p>\n\n<p><strong>EDIT: Updated to reflect Andrew's comments.</strong></p>\n"
},
{
"answer_id": 54289,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 0,
"selected": false,
"text": "<p>Sarcastic's reply is so much better than mine, but if you were working with filesystem paths, my <strong>ugly hack below</strong> could turn out to be useful too. (Translation: I typed it, so I'll be damned if I don't post it :)</p>\n\n<p>Path.Combine just slaps two strings together, paying attention to leading or trailing slashes. As far as I know, the only Path method that does normalization is Path.GetFullPath. The following will give you the \"cleaned up\" version.</p>\n\n<pre><code>myPath = System.IO.Path.GetFullPath(myPath);\n</code></pre>\n\n<p>Of course, there is the small issue that the resulting path will be rooted and the forward slashes will be converted to back slashes (like \"C:\\foo\\bar\\path.aspx\"). But if you know the parent root of the original path, stripping out the root should not be a big problem.</p>\n"
},
{
"answer_id": 54297,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Whatever you do, don't use a static UriBuilder. This introduces all sorts of potential race conditions that you might not detect until you are under heavy load. </p>\n\n<p>If two different threads called UriHelper.NormalizeRelativePath at the same time, the return value for one could be passed back to the other caller arbitrarily.</p>\n\n<p>If you want to use UriBuilder to do this, just create a new one when you need it (it's not expensive to create). </p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5599/"
] | I have an asp.net url path which is being generated in a web form, and is coming out something like "/foo/bar/../bar/path.aspx", and is coming out in the generated html like this too. It should be shortened to "/foo/bar/path.aspx".
Path.Combine didn't fix it. Is there a function to clean this path up? | You could create a helper class which wrapped the UriBuilder class in System.Net
```
public static class UriHelper
{
public static string NormalizeRelativePath(string path)
{
UriBuilder _builder = new UriBuilder("http://localhost");
builder.Path = path;
return builder.Uri.AbsolutePath;
}
}
```
which could then be used like this:
```
string url = "foo/bar/../bar/path.aspx";
Console.WriteLine(UriHelper.NormalizeRelativePath(url));
```
It is a bit hacky but it would work for the specific example you gave.
**EDIT: Updated to reflect Andrew's comments.** |
54,237 | <p>I want to link to bookmark on a page (mysite.com/mypage.htm#bookmark) AND visually highlight the item that was bookmarked (maybe having a red border). Naturally, there would be multiple items bookmarked. So that if someone clicked on #bookmark2 then <em>that</em> other area would be highlighted). </p>
<p>I can see how to do that with .asp or .aspx but I'd like to do it more simply than that. I thought maybe there was a clever way to do it with CSS.</p>
<p>WHY I'm interested:
- I want to have our programs link to a shopping page that lists all the programs on it. I'm using a bookmark so they're jumping to the particular program area (site.com/shoppingpage#Programx) but just to make it <em>obvious</em> I'd like to actually highlight the page being linked to.</p>
| [
{
"answer_id": 54257,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<p>I guess if you could store this information with JavaScript and cookies for the functionality of remembering the bookmarks and even add a splash of Ajax if you wanted to interact with a database.</p>\n\n<p>CSS would only be able to do styling. You would have to give the bookmarked anchor a class found in your CSS file.</p>\n\n<p>CSS also has the a:visited selector which is used for styling links found in the browser's history.</p>\n"
},
{
"answer_id": 54278,
"author": "Kevin",
"author_id": 2678,
"author_profile": "https://Stackoverflow.com/users/2678",
"pm_score": 2,
"selected": false,
"text": "<p>Use your favorite JS toolkit to add a \"highlight\" (or whatever) class to the item containing (or contained in) the anchor.</p>\n\n<p>Something like:</p>\n\n<pre><code>jQuery(location.hash).addClass('highlight');\n</code></pre>\n\n<p>Of course, you'd need to call that onready or click if you want it triggered by other links on the page, and you'll want to have the .highlight class defined. You could also make your jQuery selector traverse up or down depending on the container you want highlighted.</p>\n"
},
{
"answer_id": 54326,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 4,
"selected": true,
"text": "<p>In your css you need to define </p>\n\n<pre class=\"lang-css prettyprint-override\"><code>a.highlight {border:1px solid red;}\n</code></pre>\n\n<p>or something similar</p>\n\n<p>Then using jQuery, </p>\n\n<pre><code>$(document).ready ( function () { //Work as soon as the DOM is ready for parsing\n var id = location.hash.substr(1); //Get the word after the hash from the url\n if (id) $('#'+id).addClass('highlight'); // add class highlight to element whose id is the word after the hash\n});\n</code></pre>\n\n<p>To highlight the targets on mouse over also add:</p>\n\n<pre><code>$(\"a[href^='#']\")\n .mouseover(function() {\n var id = $(this).attr('href').substr(1);\n $('#'+id).addClass('highlight');\n })\n .mouseout(function() {\n var id = $(this).attr('href').substr(1);\n $('#'+id).removeClass('highlight');\n });\n</code></pre>\n"
},
{
"answer_id": 55530,
"author": "chrisofspades",
"author_id": 2614,
"author_profile": "https://Stackoverflow.com/users/2614",
"pm_score": 3,
"selected": false,
"text": "<p>You can also use the <code>target</code> pseudo-class in CSS:</p>\n\n<pre><code><html>\n<head>\n\n<style type=\"text/css\">\ndiv#test:target {\n background-color: yellow;\n}\n</style>\n\n</head>\n<body>\n\n<p><b><a href=\"#test\">Link</a></b></p>\n\n<div id=\"test\">\nTarget\n</div>\n\n</body>\n</html>\n</code></pre>\n\n<p>Unfortunately the target pseudo class isn't supported by IE or Opera, so if you're looking for a universal solution here this might not be sufficient.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4906/"
] | I want to link to bookmark on a page (mysite.com/mypage.htm#bookmark) AND visually highlight the item that was bookmarked (maybe having a red border). Naturally, there would be multiple items bookmarked. So that if someone clicked on #bookmark2 then *that* other area would be highlighted).
I can see how to do that with .asp or .aspx but I'd like to do it more simply than that. I thought maybe there was a clever way to do it with CSS.
WHY I'm interested:
- I want to have our programs link to a shopping page that lists all the programs on it. I'm using a bookmark so they're jumping to the particular program area (site.com/shoppingpage#Programx) but just to make it *obvious* I'd like to actually highlight the page being linked to. | In your css you need to define
```css
a.highlight {border:1px solid red;}
```
or something similar
Then using jQuery,
```
$(document).ready ( function () { //Work as soon as the DOM is ready for parsing
var id = location.hash.substr(1); //Get the word after the hash from the url
if (id) $('#'+id).addClass('highlight'); // add class highlight to element whose id is the word after the hash
});
```
To highlight the targets on mouse over also add:
```
$("a[href^='#']")
.mouseover(function() {
var id = $(this).attr('href').substr(1);
$('#'+id).addClass('highlight');
})
.mouseout(function() {
var id = $(this).attr('href').substr(1);
$('#'+id).removeClass('highlight');
});
``` |
54,255 | <p>Using Vim I often want to replace a block of code with a block that I just yanked.</p>
<p>But when I delete the block of code that is to be replaced, that block itself goes into the register which erases the block I just yanked. So I've got in the habit of yanking, then inserting, then deleting what I didn't want, but with large blocks of code this gets messy trying to keep the inserted block and the block to delete separate.</p>
<p>So what is the slickest and quickest way to replace text in Vim?</p>
<ul>
<li>is there a way to delete text without putting it into the register?</li>
<li>is there a way to say e.g. "replace next word" or "replace up to next paragraph"</li>
<li>or is the best way to somehow use the multi-register feature?</li>
</ul>
| [
{
"answer_id": 54265,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 3,
"selected": false,
"text": "<p>Well, first do this command:</p>\n\n<pre><code>:h d\n</code></pre>\n\n<p>Then you will realize that you can delete into a specific register. That way you won't alter what is in your default register.</p>\n"
},
{
"answer_id": 54272,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 5,
"selected": false,
"text": "<p>For the specific example that you gave, if I understand the question then this might work:</p>\n\n<pre><code>*Highlight what you want to put somewhere else\n*delete (d)\n*Highlight the code that you want it to replace\n*paste (p)\n</code></pre>\n"
},
{
"answer_id": 54422,
"author": "maeghith",
"author_id": 5614,
"author_profile": "https://Stackoverflow.com/users/5614",
"pm_score": 3,
"selected": false,
"text": "<p>If you're using Vim then you'll have the visual mode, which is like selecting, but with the separating modes thing that's the basis of vi/vim.</p>\n\n<p>What you want to do is use visual mode to select the source, then yank, then use visual mode again to select the scope of the destination, and then paste to text from the default buffer.</p>\n\n<p>Example:</p>\n\n<p>In a text file with:</p>\n\n<pre>\n1| qwer\n2| asdf\n3| zxcv\n4| poiu\n</pre>\n\n<p>with the following sequence: <code>ggVjyGVkp</code> you'll end with:</p>\n\n<pre>\n1| qwer\n2| asdf\n3| qewr\n4| asdf\n</pre>\n\n<p>Explained:</p>\n\n<ul>\n<li><code>gg</code>: go to first line</li>\n<li><code>V</code>: start visual mode with whole lines</li>\n<li><code>j</code>: go down one line (with the selection started on the previous lines this grows the selection one line down)</li>\n<li><code>y</code>: yank to the default buffer (the two selected lines, and it automatically exits you from visual mode)</li>\n<li><code>G</code>: go to the last line</li>\n<li><code>V</code>: start visual mode (same as before)</li>\n<li><code>k</code>: go up one line (as before, with the visual mode enabled, this grows the selection one line up)</li>\n<li><code>p</code>: paste (with the selection on the two last lines, it will replace those lines with whatever there is in the buffer -- the 2 first lines in this case)</li>\n</ul>\n\n<p>This has the little inconvenient that puts the last block on the buffer, so it's somehow not desired for repeated pastings of the same thing, so you'll want to save the source to a named buffer with something like <code>\"ay</code> (to a buffer called \"a\") and paste with something like <code>\"ap</code> (but then if you're programming, you probably don't want to paste several times but to create a function and call it, right? <strong>RIGHT</strong>?).</p>\n\n<p>If you are only using vi, then youll have to use invisible marks instead the visual mode, <code>:he mark</code> for more on this, I'm sorry but I'm not very good with this invisible marks thing, I'm pretty contaminated with visual mode.</p>\n"
},
{
"answer_id": 54434,
"author": "Christian Berg",
"author_id": 5035,
"author_profile": "https://Stackoverflow.com/users/5035",
"pm_score": 10,
"selected": true,
"text": "<p>To delete something without saving it in a register, you can use the \"black hole register\":</p>\n\n<pre><code>\"_d\n</code></pre>\n\n<p>Of course you could also use any of the other registers that don't hold anything you are interested in.</p>\n"
},
{
"answer_id": 56186,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Text deleted, while in insert mode, doesn't go into default register.</p>\n"
},
{
"answer_id": 58607,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 3,
"selected": false,
"text": "<p>For 'replace word', try <code>cw</code> in normal mode.</p>\n\n<p>For 'replace paragraph', try <code>cap</code> in normal mode.</p>\n"
},
{
"answer_id": 58637,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 7,
"selected": false,
"text": "<p>Yep. It's slightly more convoluted than deleting the \"old\" text first, but:</p>\n\n<p>I start off with..</p>\n\n<pre><code>line1\nline2\nline3\nline4\n\nold1\nold2\nold3\nold4\n</code></pre>\n\n<p>I <kbd>shift</kbd>+<kbd>v</kbd> select the line1, line 2, 3 and 4, and delete them with the <kbd>d</kbd> command</p>\n\n<p>Then I delete the old 1-4 lines the same way.</p>\n\n<p>Then, do</p>\n\n<pre><code>\"2p\n</code></pre>\n\n<p>That'll paste the second-last yanked lines (line 1-4). <code>\"3p</code> will do the third-from-last, and so on..</p>\n\n<p>So I end up with</p>\n\n<pre><code>line1\nline2\nline3\nline4\n</code></pre>\n\n<p><strong>Reference:</strong>\n<a href=\"http://vimdoc.sourceforge.net/htmldoc/change.html#quote_number\" rel=\"noreferrer\">Vim documentation on numbered register</a></p>\n"
},
{
"answer_id": 62959,
"author": "JayG",
"author_id": 5823,
"author_profile": "https://Stackoverflow.com/users/5823",
"pm_score": 2,
"selected": false,
"text": "<p>In the windows version (probably in Linux also), you can yank into the system's copy/paste buffer using <code>\"*y</code> (i.e. preceding your yank command with double-quotes and asterisk).</p>\n\n<p>You can then delete the replaceable lines normally and paste the copied text using <code>\"*p</code>.</p>\n"
},
{
"answer_id": 509557,
"author": "alex2k8",
"author_id": 62192,
"author_profile": "https://Stackoverflow.com/users/62192",
"pm_score": 6,
"selected": false,
"text": "<p>VIM docs: <em>Numbered register 0 contains the text from the most recent yank command,\nunless the command specified another register with [\"x].</em></p>\n\n<p>E.g. we yank \"foo\" and delete \"bar\" - the registry 0 still contains \"foo\"! Hence \"foo\" can be pasted using <code>\"0p</code></p>\n"
},
{
"answer_id": 920139,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>It's handy to have an easy mapping which lets you replace the current selection with buffer.</p>\n<p>For example when you put this in your .vimrc</p>\n<pre><code>" it's a capital 'p' at the end\nvmap r "_dP\n</code></pre>\n<p>then, after copying something into register (i.e. with 'y'), you can just select the text which you want to be replaced, and simply hit 'r' on your keyboard. The selection will be substituted with your current register.</p>\n<p>Explanation:</p>\n<pre><code>vmap - mapping for visual mode\n"_d - delete current selection into "black hole register"\nP - paste\n</code></pre>\n"
},
{
"answer_id": 1290230,
"author": "Magnus",
"author_id": 136815,
"author_profile": "https://Stackoverflow.com/users/136815",
"pm_score": 5,
"selected": false,
"text": "<p>I put the following in my vimrc:</p>\n<pre><code>noremap y "*y\nnoremap Y "*Y\nnoremap p "*p\nnoremap P "*P\nvnoremap y "*y\nvnoremap Y "*Y\nvnoremap p "*p\nvnoremap P "*P\n</code></pre>\n<p>Now I yank to and put from the clipboard register, and don't have to care what happens with the default register. An added benefit is that I can paste from other apps with minimal hassle. I'm losing some functionality, I know (I am no longer able to manage different copied information for the clipboard register and the default register), but I just can't keep track of more than one register/clipboard anyway.</p>\n"
},
{
"answer_id": 1555850,
"author": "Clueless",
"author_id": 165876,
"author_profile": "https://Stackoverflow.com/users/165876",
"pm_score": 2,
"selected": false,
"text": "<p>I often make a mistake when following the commands to 'y'ank then '\"_d'elete into a black hole then 'p'aste. I prefer to 'y'ank, then delete however I like, then '\"0p' from the 0 register, which is where the last copied text gets pushed to.</p>\n"
},
{
"answer_id": 2557670,
"author": "idbrii",
"author_id": 79125,
"author_profile": "https://Stackoverflow.com/users/79125",
"pm_score": 4,
"selected": false,
"text": "<p>To emphasize what <a href=\"https://stackoverflow.com/questions/54255/in-vim-is-there-a-way-to-delete-without-putting-text-in-the-register/54272#54272\">EBGreen said</a>:</p>\n\n<p>If you paste while selecting text, the selected text is <strong>replaced</strong> with the pasted text.</p>\n\n<p>If you want to copy some text and then paste it in multiple locations, use <code>\"0p</code> to paste. Numbered register 0 contains the text from the most recent yank command.</p>\n\n<hr>\n\n<p>Also, you can list the contents of all of your registers:</p>\n\n<pre><code>:registers\n</code></pre>\n\n<p>That command makes it easier to figure out what register you want when doing something like <a href=\"https://stackoverflow.com/questions/54255/in-vim-is-there-a-way-to-delete-without-putting-text-in-the-register/58637#58637\">dbr's answer</a>. You'll also see the /,%,# registers. (See also <code>:help registers</code>)</p>\n\n<hr>\n\n<p>And finally, check out <code>cW</code> and <code>cW</code> to change a word including and not including an trailing space. (Using capital <code>W</code> includes punctuation.)</p>\n"
},
{
"answer_id": 5370718,
"author": "expelledboy",
"author_id": 644945,
"author_profile": "https://Stackoverflow.com/users/644945",
"pm_score": 2,
"selected": false,
"text": "<p>The two solutions I use in the right contexts are;</p>\n\n<ul>\n<li>highlight what you want to replace using Vims <code>VISUAL</code> mode then paste the register.</li>\n</ul>\n\n<p>I use this mostly out of habit as I only found the second solution much later, eg </p>\n\n<pre><code>yiw \" yank the whole word\nviwp \" replace any word with the default register\n</code></pre>\n\n<ul>\n<li><a href=\"http://www.vim.org/scripts/script.php?script_id=1234\" rel=\"nofollow\">YankRing</a>. With this plugin you can use the keybinding <code><ctrl>+<p></code> to replace the previous numbered register with the one you just pasted.</li>\n</ul>\n\n<p>Basically you go about pasting as you would, but when you realise that you have since overwritten the default register thus losing what you actually wanted to paste you can <code><C-P></code> to find and replace from the YankRing history!</p>\n\n<p>One of those must have plugins...</p>\n"
},
{
"answer_id": 8533710,
"author": "Vic Goldfeld",
"author_id": 985859,
"author_profile": "https://Stackoverflow.com/users/985859",
"pm_score": 2,
"selected": false,
"text": "<p>For Dvorak users, one very convenient method is to just delete unneeded text into the \"1 register instead of the \"_ black hole register, if only because you can press \" + 1 with the same shift press and a swift pinky motion since 1 is the key immediately above \" in Dvorak (PLUS d is in the other hand, which makes the whole command fast as hell).</p>\n\n<p>Then of course, the \"1 register could be used for other things because of it's convenience, but unless you have a purpose more common than replacing text I'd say it's a pretty good use of the register.</p>\n"
},
{
"answer_id": 28726374,
"author": "Hieu Nguyen",
"author_id": 1087430,
"author_profile": "https://Stackoverflow.com/users/1087430",
"pm_score": 2,
"selected": false,
"text": "<p>I found a very useful mapping for your purpose:</p>\n\n<pre><code>xnoremap p \"_dP\n</code></pre>\n\n<p>Deleted text is put in \"black hole register\", and the yanked text remains. </p>\n\n<p>Source: <a href=\"http://vim.wikia.com/wiki/Replace_a_word_with_yanked_text\" rel=\"nofollow\">http://vim.wikia.com/wiki/Replace_a_word_with_yanked_text</a></p>\n"
},
{
"answer_id": 32488853,
"author": "Torben",
"author_id": 398844,
"author_profile": "https://Stackoverflow.com/users/398844",
"pm_score": 4,
"selected": false,
"text": "<p><strong>A minimal invasive solution for the lazy ones:</strong></p>\n\n<p>Register <code>0</code> always contains the last yank (as <a href=\"/questions/54255/in-vim-is-there-a-way-to-delete-without-putting-text-in-the-register#comment-6335532\">Rafael</a>, <a href=\"/questions/54255/in-vim-is-there-a-way-to-delete-without-putting-text-in-the-register#answer-509557\">alex2k8</a> and <a href=\"/questions/54255/in-vim-is-there-a-way-to-delete-without-putting-text-in-the-register#answer-2557670\">idbrii</a> have already mentioned). Unfortunately selecting register <code>0</code> all the time can be quite annoying, so it would be nice if <code>p</code> uses <code>\"0</code> by default. This can be achieved by putting the following lines into your <code>.vimrc</code>:</p>\n\n<pre><code>noremap p \"0p\nnoremap P \"0P\nfor s:i in ['\"','*','+','-','.',':','%','/','=','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\n execute 'noremap \"'.s:i.'p \"'.s:i.'p'\n execute 'noremap \"'.s:i.'P \"'.s:i.'P'\nendfor\n</code></pre>\n\n<p>The first line maps each <code>p</code> stroke to <code>\"0p</code>. However, this prevents <code>p</code> from accessing any other registers. Therefore all <code>p</code> strokes with an explicitly selected register are mapped to the equivalent commandline expression within the for-loop. The same is done for <code>P</code>.</p>\n\n<p>This way the standard behaviour is preserved, except for the implicit <code>p</code> and <code>P</code> strokes, which now use register <code>0</code> by default.</p>\n\n<p><strong>Hint 1:</strong> The cut command is now <code>\"0d</code> instead of just <code>d</code>. But since I'm lazy this is way too long for me ;) Therefore I'm using the following mapping:</p>\n\n<pre><code>noremap <LEADER>d \"0d\nnoremap <LEADER>D \"0D\n</code></pre>\n\n<p>The leader key is <code>\\</code> by default, so you can easily cut text by typing <code>\\d</code> or <code>\\D</code>.</p>\n\n<p><strong>Hint 2:</strong> The default timeout for multi-key mappings is pretty short. You might want to increase it to have more time when selecting a register. See <code>:help timeoutlen</code> for details, I'm using:</p>\n\n<pre><code>set timeout timeoutlen=3000 ttimeoutlen=100\n</code></pre>\n"
},
{
"answer_id": 32954215,
"author": "Wayne",
"author_id": 592746,
"author_profile": "https://Stackoverflow.com/users/592746",
"pm_score": 5,
"selected": false,
"text": "<p>All yank and delete operations write to the unnamed register by default. However, the most recent yank and most recent delete are always stored (separately) in the numbered registers. The register <code>0</code> holds the most recent yank. The registers <code>1-9</code> hold the 9 most recent deletes (with <code>1</code> being the most recent). </p>\n\n<p>In other words, <strong>a delete overwrites the most recent yank in the unnamed register, but it's still there in the <code>0</code> register.</strong> The blackhole-register trick (<code>\"_dd</code>) mentioned in the other answers works because it prevents overwriting the unnamed register, but it's not necessary.</p>\n\n<p>You reference a register using double quotes, so pasting the most recently yanked text can be done like this:</p>\n\n<pre><code>\"0p\n</code></pre>\n\n<p>This is an excellent reference:</p>\n\n<ul>\n<li><a href=\"http://blog.sanctum.geek.nz/advanced-vim-registers/\">http://blog.sanctum.geek.nz/advanced-vim-registers/</a></li>\n</ul>\n"
},
{
"answer_id": 50424088,
"author": "snap",
"author_id": 8578684,
"author_profile": "https://Stackoverflow.com/users/8578684",
"pm_score": 1,
"selected": false,
"text": "<p>For those of you who are primary interested of not overwriting the unnamed register when you replace a text via virtual selection and paste.</p>\n\n<p>You could use the following solution which is easy and works best for me:</p>\n\n<p><code>xnoremap <expr> p 'pgv\"'.v:register.'y'</code></p>\n\n<p>It's from the answers (and comments) here:\n<a href=\"https://stackoverflow.com/questions/290465/how-to-paste-over-without-overwriting-register\">How to paste over without overwriting register</a></p>\n\n<p>It past the selection first, then the selection with the new text is selected again (gv). Now the register which was last used in visual mode (normally the unnamed register but works also side effect free if you use another register for pasting). And then yank the new value to the register again.</p>\n\n<p>PS: If you need a simpler variant which works also with intellj idea plugin vim-simulation you can take this one (downside: overwrite unnamed register even if another register was given for pasting):</p>\n\n<p><code>vnoremap p pgvy</code></p>\n"
},
{
"answer_id": 52913326,
"author": "Adrien Vakili",
"author_id": 9033536,
"author_profile": "https://Stackoverflow.com/users/9033536",
"pm_score": 2,
"selected": false,
"text": "<p>For emacs-evil users, the function <code>(evil-paste-pop)</code> can be triggered after pasting, and cycles through previous entries in the kill-ring. Assuming you bound it to <code><C-p></code> (default in Spacemacs), you would hit <code>p</code> followed by as many <code><C-p></code> as needed.</p>\n"
},
{
"answer_id": 53872985,
"author": "Victoria Stuart",
"author_id": 1904943,
"author_profile": "https://Stackoverflow.com/users/1904943",
"pm_score": 3,
"selected": false,
"text": "<p>My situation: in <code>Normal</code> mode, when I delete characters using the <code>x</code> keypress, those deletions overwrite my latest register -- complicating edits where I want to delete characters using <code>x</code> and paste something I have in my most recent register (e.g. pasting the same text at two or more places).</p>\n\n<p>I tried the suggestion in the accepted answer (<code>\"_d</code>), but it did not work.</p>\n\n<p>However, from the accepted answer/comments at <a href=\"https://vi.stackexchange.com/questions/122/performing-certain-operations-without-clearing-register\">https://vi.stackexchange.com/questions/122/performing-certain-operations-without-clearing-register</a>, I added this to my <code>~/.vimrc</code>, which works (you may have to restart Vim):</p>\n\n<pre><code>nnoremap x \"_x\n</code></pre>\n\n<p>That is, I can now do my normal yank (<code>y</code>), delete (<code>d</code>), and paste (<code>p</code>) commands -- and characters I delete using <code>x</code> no longer populate the most recent registers.</p>\n"
},
{
"answer_id": 58026614,
"author": "Eduard Kolosovskyi",
"author_id": 5385623,
"author_profile": "https://Stackoverflow.com/users/5385623",
"pm_score": 2,
"selected": false,
"text": "<p>For those who use JetBrans IDE (PhpStorm, WebStorm, IntelliJ IDEA) with IdeaVim. You may be experiencing problems with remapping like <code>nnoremap d \"_d</code> and using it to delete a line <code>dd</code>. Possible solution for you: <code>nnoremap dd \"_dd</code> </p>\n\n<p>There are issues on youtrack, please vote for them: \n<a href=\"https://youtrack.jetbrains.com/issue/VIM-1189\" rel=\"nofollow noreferrer\">https://youtrack.jetbrains.com/issue/VIM-1189</a>\n<a href=\"https://youtrack.jetbrains.com/issue/VIM-1363\" rel=\"nofollow noreferrer\">https://youtrack.jetbrains.com/issue/VIM-1363</a></p>\n"
},
{
"answer_id": 60119781,
"author": "gregory",
"author_id": 2057509,
"author_profile": "https://Stackoverflow.com/users/2057509",
"pm_score": 3,
"selected": false,
"text": "<p>Vim's occasional preference for complexity over practicality burdens the user with applying registers to copy/delete actions -- when more often than not, one just wants paste what was copied and \"forget\" what was deleted. </p>\n\n<p>However, instead of fighting vim's complicated registers, make them more convenient: choose a \"default\" register to store your latest delete. For example, send deletes to the d register (leaving a-c open for ad-hoc usage; d is a nice mnemonic): </p>\n\n<pre><code>nnoremap d \"dd \"send latest delete to d register\nnnoremap D \"dD \"send latest delete to d register \nnnoremap dd \"ddd \"send latest delete to d register\nnnoremap x \"_x \"send char deletes to black hole, not worth saving\nnnoremap <leader>p \"dp \"paste what was deleted\nnnoremap <leader>P \"dP \"paste what was deleted\n</code></pre>\n\n<p>This approach prevents deletes from clobbering yanks BUT doesn't forfeit registering the delete -- one can paste (back) what was deleted instead of losing it in a black hole (as in the accepted answer). In the example above, this recalling is done with two leader p mappings. A benefit of this approach, is that it gives you the ability to choose what to paste: (a) what was just yanked, or (b) what was just deleted. </p>\n"
},
{
"answer_id": 61975093,
"author": "bob",
"author_id": 13603321,
"author_profile": "https://Stackoverflow.com/users/13603321",
"pm_score": 1,
"selected": false,
"text": "<p>register 0 thru 9 are the latest things you yank or cut etc, and DO NOT include deleted things etc. So if you yank/cut something, it is in register 0 also, even if you say deleted stuff all day after that, register 0 is still the last stuff you yanked/cut.</p>\n<p>yiw #goes to both default register, and register 0</p>\n<h1>it yanks the word the cursor is in</h1>\n<h1>deleted stuff etc will go to default register, but NOT register 0</h1>\n<h1>in standard mode:</h1>\n<p>"0p #put the content of register 0</p>\n<h1>in insert mode:</h1>\n<p>ctrl-r 0 #put the content of register 0</p>\n<p>I also had a friend who always yanked/cut to register x lol.</p>\n"
},
{
"answer_id": 62951993,
"author": "mohammadreza berneti",
"author_id": 3464834,
"author_profile": "https://Stackoverflow.com/users/3464834",
"pm_score": 2,
"selected": false,
"text": "<p>The following vscode setting should allow e.g. dd and dw to become "_dd and "_dw, which work correctly now with our remapper.</p>\n<pre><code>{\n "vim.normalModeKeyBindingsNonRecursive": [\n {\n "before": ["d"],\n "after": [ "\\"", "_", "d" ]\n }\n ]\n}\n</code></pre>\n"
},
{
"answer_id": 64529113,
"author": "sebtheiler",
"author_id": 10226703,
"author_profile": "https://Stackoverflow.com/users/10226703",
"pm_score": 0,
"selected": false,
"text": "<p>You can make a simple macro with:\n<code>q"_dwq</code></p>\n<p>Now to delete the next word without overwriting the register, you can use <code>@d</code></p>\n"
},
{
"answer_id": 64641073,
"author": "ZhiyuanLck",
"author_id": 9514052,
"author_profile": "https://Stackoverflow.com/users/9514052",
"pm_score": 0,
"selected": false,
"text": "<p>The main problem is to use <code>p</code> when in visual mode. Following function will recover the content of unnamed register after you paste something in visual mode.</p>\n<pre><code> function! MyPaste(ex)\n let save_reg = @"\n let reg = v:register\n let l:count = v:count1\n let save_map = maparg('_', 'v', 0, 1)\n exec 'vnoremap _ '.a:ex\n exec 'normal gv"'.reg.l:count.'_'\n call mapset('v', 0, save_map)\n let @" = save_reg\nendfunction\n\nvmap p :<c-u>call MyPaste('p')<cr>\nvmap P :<c-u>call MyPaste('P')<cr>\n</code></pre>\n<p>Usage is the same as before and the content of register " is not changed.</p>\n"
},
{
"answer_id": 65785248,
"author": "Jacob Vanus",
"author_id": 1249891,
"author_profile": "https://Stackoverflow.com/users/1249891",
"pm_score": 0,
"selected": false,
"text": "<p>I find it easier to yank into the 'p' buffer to begin with.</p>\n<h3>Copy (aka: yank)</h3>\n<pre><code># highlight text you want to copy, then:\n"py\n</code></pre>\n<h3>Paste</h3>\n<pre><code># delete or highlight the text you want to replace, then:\n"pp\n</code></pre>\n<p>Pros (As opposed to deleting into a specific register):</p>\n<ul>\n<li><code>"pp</code> is easy on the fingers</li>\n<li>Not going to accidentally overwrite your paste buffer on delete.</li>\n</ul>\n"
},
{
"answer_id": 66926326,
"author": "WalksB",
"author_id": 6382242,
"author_profile": "https://Stackoverflow.com/users/6382242",
"pm_score": 0,
"selected": false,
"text": "<p><code>noremap mm m</code></p>\n<p>and</p>\n<p><code>noremap mx "_x</code></p>\n<p>is how I deal with it.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] | Using Vim I often want to replace a block of code with a block that I just yanked.
But when I delete the block of code that is to be replaced, that block itself goes into the register which erases the block I just yanked. So I've got in the habit of yanking, then inserting, then deleting what I didn't want, but with large blocks of code this gets messy trying to keep the inserted block and the block to delete separate.
So what is the slickest and quickest way to replace text in Vim?
* is there a way to delete text without putting it into the register?
* is there a way to say e.g. "replace next word" or "replace up to next paragraph"
* or is the best way to somehow use the multi-register feature? | To delete something without saving it in a register, you can use the "black hole register":
```
"_d
```
Of course you could also use any of the other registers that don't hold anything you are interested in. |
54,295 | <p>I'd like to store a properties file as XML. Is there a way to sort the keys when doing this so that the generated XML file will be in alphabetical order? </p>
<pre><code>String propFile = "/path/to/file";
Properties props = new Properties();
/*set some properties here*/
try {
FileOutputStream xmlStream = new FileOutputStream(propFile);
/*this comes out unsorted*/
props.storeToXML(xmlStream,"");
} catch (IOException e) {
e.printStackTrace();
}
</code></pre>
| [
{
"answer_id": 54303,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 1,
"selected": false,
"text": "<p>java.util.Properties is based on Hashtable, which does not store its values in alphabetical order, but in order of the hash of each item, that is why you are seeing the behaviour you are.</p>\n"
},
{
"answer_id": 54308,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 1,
"selected": false,
"text": "<p>java.util.Properties is a subclass of java.util.<strong>Hashtable</strong>. ('Hash', being the key here.)You'd have to come up with your own customer implementation based on something that keeps/defines order...like a TreeMap.</p>\n"
},
{
"answer_id": 54316,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 2,
"selected": false,
"text": "<p>You could sort the keys first, then loop through the items in the properties file and write them to the xml file.</p>\n\n<pre><code>public static void main(String[] args){\n String propFile = \"/tmp/test2.xml\";\n Properties props = new Properties();\n props.setProperty(\"key\", \"value\");\n props.setProperty(\"key1\", \"value1\");\n props.setProperty(\"key2\", \"value2\");\n props.setProperty(\"key3\", \"value3\");\n props.setProperty(\"key4\", \"value4\");\n\n try {\n BufferedWriter out = new BufferedWriter(new FileWriter(propFile));\n List<String> list = new ArrayList<String>();\n for(Object o : props.keySet()){\n list.add((String)o);\n }\n Collections.sort(list);\n out.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n out.write(\"<!DOCTYPE properties SYSTEM \\\"http://java.sun.com/dtd/properties.dtd\\\">\\n\");\n out.write(\"<properties>\\n\");\n out.write(\"<comment/>\\n\");\n for(String s : list){\n out.write(\"<entry key=\\\"\" + s + \"\\\">\" + props.getProperty(s) + \"</entry>\\n\");\n }\n out.write(\"</properties>\\n\");\n out.flush();\n out.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n</code></pre>\n"
},
{
"answer_id": 54382,
"author": "Jay R.",
"author_id": 5074,
"author_profile": "https://Stackoverflow.com/users/5074",
"pm_score": 0,
"selected": false,
"text": "<p>You could try this:</p>\n\n<p>Make a new class that does what java.util.XMLUtils does but in the save method change this:</p>\n\n<pre><code>Set keys = props.keySet();\nIterator i = keys.iterator();\n</code></pre>\n\n<p>to</p>\n\n<pre><code>Set keys = props.keySet();\nList<String> newKeys = new ArrayList<String>();\nfor(Object key : keys)\n{\n newKeys.add(key.toString());\n}\nCollections.sort(newKeys);\nIterator i = newKeys.iterator();\n</code></pre>\n\n<p>Extend properties and override the Properties class storeToXML method to call your new class's save method.</p>\n"
},
{
"answer_id": 54399,
"author": "Tim Frey",
"author_id": 1471,
"author_profile": "https://Stackoverflow.com/users/1471",
"pm_score": -1,
"selected": false,
"text": "<p>Why do you want the XML file to be sorted in the first place? Presumably, there is another piece of code that reads the file and puts the data in another Properties object. Do you want to do this so you can manually find and edit entries in the XML file?</p>\n"
},
{
"answer_id": 54402,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "<p>The simplest hack would be to override keySet. A bit of a hack, and not guaranteed to work in future implementations:</p>\n\n<pre><code>new Properties() {\n @Override Set<Object> keySet() {\n return new TreeSet<Object>(super.keySet());\n }\n}\n</code></pre>\n\n<p>(Disclaimer: I have not even tested that it compiles.)</p>\n\n<p>Alternatively, you could use something like XSLT to reformat the produced XML.</p>\n"
},
{
"answer_id": 54454,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 6,
"selected": true,
"text": "<p>Here's a quick and dirty way to do it:</p>\n\n<pre><code>String propFile = \"/path/to/file\";\nProperties props = new Properties();\n\n/* Set some properties here */\n\nProperties tmp = new Properties() {\n @Override\n public Set<Object> keySet() {\n return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet()));\n }\n};\n\ntmp.putAll(props);\n\ntry {\n FileOutputStream xmlStream = new FileOutputStream(propFile);\n /* This comes out SORTED! */\n tmp.storeToXML(xmlStream,\"\");\n} catch (IOException e) {\n e.printStackTrace();\n}\n</code></pre>\n\n<p>Here are the caveats:</p>\n\n<ul>\n<li>The tmp Properties (an anonymous\nsubclass) doesn't fulfill the\ncontract of Properties.</li>\n</ul>\n\n<p>For example, if you got its <code>keySet</code> and tried to remove an element from it, an exception would be raised. So, don't allow instances of this subclass to escape! In the snippet above, you are never passing it to another object or returning it to a caller who has a legitimate expectation that it fulfills the contract of Properties, so it is safe.</p>\n\n<ul>\n<li>The implementation of\nProperties.storeToXML could change,\ncausing it to ignore the keySet\nmethod.</li>\n</ul>\n\n<p>For example, a future release, or OpenJDK, could use the <code>keys()</code> method of <code>Hashtable</code> instead of <code>keySet</code>. This is one of the reasons why classes should always document their \"self-use\" (Effective Java Item 15). However, in this case, the worst that would happen is that your output would revert to unsorted.</p>\n\n<ul>\n<li>Remember that the Properties storage\nmethods ignore any \"default\"\nentries.</li>\n</ul>\n"
},
{
"answer_id": 3253071,
"author": "Espen",
"author_id": 392356,
"author_profile": "https://Stackoverflow.com/users/392356",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a way to produce sorted output for both store <code>Properties.store(OutputStream out, String comments)</code> and <code>Properties.storeToXML(OutputStream os, String comment)</code>:</p>\n\n<pre><code>Properties props = new Properties() {\n @Override\n public Set<Object> keySet(){\n return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet()));\n }\n\n @Override\n public synchronized Enumeration<Object> keys() {\n return Collections.enumeration(new TreeSet<Object>(super.keySet()));\n }\n};\nprops.put(\"B\", \"Should come second\");\nprops.put(\"A\", \"Should come first\");\nprops.storeToXML(new FileOutputStream(new File(\"sortedProps.xml\")), null);\nprops.store(new FileOutputStream(new File(\"sortedProps.properties\")), null);\n</code></pre>\n"
},
{
"answer_id": 17982586,
"author": "Serg",
"author_id": 105037,
"author_profile": "https://Stackoverflow.com/users/105037",
"pm_score": 0,
"selected": false,
"text": "<p>Here is another solution:</p>\n\n<pre><code>public static void save_sorted(Properties props, String filename) throws Throwable {\n FileOutputStream fos = new FileOutputStream(filename);\n Properties prop_sorted = new Properties() {\n @Override\n public Set<String> stringPropertyNames() {\n TreeSet<String> set = new TreeSet<String>();\n for (Object o : keySet()) {\n set.add((String) o);\n }\n return set;\n }\n };\n prop_sorted.putAll(props);\n prop_sorted.storeToXML(fos, \"test xml\");\n}\n</code></pre>\n"
},
{
"answer_id": 23092108,
"author": "trevorsky",
"author_id": 3203998,
"author_profile": "https://Stackoverflow.com/users/3203998",
"pm_score": 2,
"selected": false,
"text": "<p>In my testing, the other answers to this question don't work properly on AIX. My particular test machine is running this version:</p>\n\n<blockquote>\n <p>IBM J9 VM (build 2.4, JRE 1.6.0 IBM J9 2.4 AIX ppc64-64 jvmap6460sr9-20110624_85526</p>\n</blockquote>\n\n<p>After looking through the implementation of the <code>store</code> method, I found that it relies upon <code>entrySet</code>. This method works well for me.</p>\n\n<pre><code>public static void saveSorted(Properties props, FileWriter fw, String comment) throws IOException {\n Properties tmp = new Properties() {\n @Override\n public Set<Object> keySet() {\n return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet()));\n }\n\n @Override\n public Set<java.util.Map.Entry<Object,Object>> entrySet() {\n TreeSet<java.util.Map.Entry<Object,Object>> tmp = new TreeSet<java.util.Map.Entry<Object,Object>>(new Comparator<java.util.Map.Entry<Object,Object>>() {\n @Override\n public int compare(java.util.Map.Entry<Object, Object> entry1, java.util.Map.Entry<Object, Object> entry2) {\n String key1 = entry1.getKey().toString();\n String key2 = entry2.getKey().toString();\n return key1.compareTo(key2);\n }\n });\n\n tmp.addAll(super.entrySet());\n\n return Collections.unmodifiableSet(tmp);\n }\n\n @Override\n public synchronized Enumeration<Object> keys() {\n return Collections.enumeration(new TreeSet<Object>(super.keySet()));\n }\n\n @Override\n public Set<String> stringPropertyNames() {\n TreeSet<String> set = new TreeSet<String>();\n for(Object o : keySet()) {\n set.add((String)o);\n }\n return set;\n }\n };\n\n tmp.putAll(props);\n tmp.store(fw, comment);\n}\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5084/"
] | I'd like to store a properties file as XML. Is there a way to sort the keys when doing this so that the generated XML file will be in alphabetical order?
```
String propFile = "/path/to/file";
Properties props = new Properties();
/*set some properties here*/
try {
FileOutputStream xmlStream = new FileOutputStream(propFile);
/*this comes out unsorted*/
props.storeToXML(xmlStream,"");
} catch (IOException e) {
e.printStackTrace();
}
``` | Here's a quick and dirty way to do it:
```
String propFile = "/path/to/file";
Properties props = new Properties();
/* Set some properties here */
Properties tmp = new Properties() {
@Override
public Set<Object> keySet() {
return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet()));
}
};
tmp.putAll(props);
try {
FileOutputStream xmlStream = new FileOutputStream(propFile);
/* This comes out SORTED! */
tmp.storeToXML(xmlStream,"");
} catch (IOException e) {
e.printStackTrace();
}
```
Here are the caveats:
* The tmp Properties (an anonymous
subclass) doesn't fulfill the
contract of Properties.
For example, if you got its `keySet` and tried to remove an element from it, an exception would be raised. So, don't allow instances of this subclass to escape! In the snippet above, you are never passing it to another object or returning it to a caller who has a legitimate expectation that it fulfills the contract of Properties, so it is safe.
* The implementation of
Properties.storeToXML could change,
causing it to ignore the keySet
method.
For example, a future release, or OpenJDK, could use the `keys()` method of `Hashtable` instead of `keySet`. This is one of the reasons why classes should always document their "self-use" (Effective Java Item 15). However, in this case, the worst that would happen is that your output would revert to unsorted.
* Remember that the Properties storage
methods ignore any "default"
entries. |
54,334 | <p>The following SQL:</p>
<pre><code>SELECT notes + 'SomeText'
FROM NotesTable a
</code></pre>
<p>Give the error:</p>
<blockquote>
<p>The data types nvarchar and text are incompatible in the add operator.</p>
</blockquote>
| [
{
"answer_id": 54343,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 7,
"selected": true,
"text": "<p>The only way would be to convert your text field into an nvarchar field.</p>\n\n<pre><code>Select Cast(notes as nvarchar(4000)) + 'SomeText'\nFrom NotesTable a\n</code></pre>\n\n<p>Otherwise, I suggest doing the concatenation in your application.</p>\n"
},
{
"answer_id": 54357,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 3,
"selected": false,
"text": "<p>You have to explicitly cast the string types to the same in order to concatenate them, In your case you may solve the issue by simply addig an 'N' in front of 'SomeText' (N'SomeText'). If that doesn't work, try Cast('SomeText' as nvarchar(8)).</p>\n"
},
{
"answer_id": 57061,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 4,
"selected": false,
"text": "<p>If you are using SQL Server 2005 or greater, depending on the size of the data in the Notes field, you may want to consider casting to nvarchar(max) instead of casting to a specific length which could result in string truncation. </p>\n\n<pre><code>Select Cast(notes as nvarchar(max)) + 'SomeText' From NotesTable a\n</code></pre>\n"
},
{
"answer_id": 62119,
"author": "edosoft",
"author_id": 6399,
"author_profile": "https://Stackoverflow.com/users/6399",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using SQL Server 2005 (or greater) you might want to consider switching to NVARCHAR(MAX) in your table definition; TEXT, NTEXT, and IMAGE data types of SQL Server 2000 will be deprecated in future versions of SQL Server. SQL Server 2005 provides backward compatibility to data types, but you should probably be using VARCHAR(MAX), NVARCHAR(MAX), and VARBINARY(MAX) instead.</p>\n"
},
{
"answer_id": 77130,
"author": "Chris Wuestefeld",
"author_id": 10082,
"author_profile": "https://Stackoverflow.com/users/10082",
"pm_score": 5,
"selected": false,
"text": "<p>You might want to consider NULL values as well. In your example, if the column <strong>notes</strong> has a null value, then the resulting value will be NULL. If you want the null values to behave as empty strings (so that the answer comes out 'SomeText'), then use the IsNull function: </p>\n\n<pre><code>Select IsNull(Cast(notes as nvarchar(4000)),'') + 'SomeText' From NotesTable a\n</code></pre>\n"
},
{
"answer_id": 48540394,
"author": "David Gausmann",
"author_id": 1800813,
"author_profile": "https://Stackoverflow.com/users/1800813",
"pm_score": 2,
"selected": false,
"text": "<p>Another option is the <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/concat-transact-sql\" rel=\"noreferrer\" title=\"CONCAT\">CONCAT</a> command:</p>\n\n<pre><code>SELECT CONCAT(MyTable.TextColumn, 'Text') FROM MyTable\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2017/"
] | The following SQL:
```
SELECT notes + 'SomeText'
FROM NotesTable a
```
Give the error:
>
> The data types nvarchar and text are incompatible in the add operator.
>
>
> | The only way would be to convert your text field into an nvarchar field.
```
Select Cast(notes as nvarchar(4000)) + 'SomeText'
From NotesTable a
```
Otherwise, I suggest doing the concatenation in your application. |
54,365 | <p>This is probably <a href="http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/x13320.html" rel="noreferrer">a complex solution</a>.</p>
<p>I am looking for a simple operator like ">>", but for prepending.</p>
<p>I am afraid it does not exist. I'll have to do something like </p>
<pre>
mv myfile tmp
cat myheader tmp > myfile
</pre>
<p>Anything smarter?</p>
| [
{
"answer_id": 54381,
"author": "Jason Navarrete",
"author_id": 3920,
"author_profile": "https://Stackoverflow.com/users/3920",
"pm_score": 7,
"selected": false,
"text": "<p>This still uses a temp file, but at least it is on one line:</p>\n\n<pre><code>echo \"text\" | cat - yourfile > /tmp/out && mv /tmp/out yourfile\n</code></pre>\n\n<p>Credit: <a href=\"http://www.cyberciti.biz/faq/bash-prepend-text-lines-to-file/\" rel=\"noreferrer\">BASH: Prepend A Text / Lines To a File</a></p>\n"
},
{
"answer_id": 54384,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "<p>Not possible without a temp file, but here goes a oneliner</p>\n\n<pre><code>{ echo foo; cat oldfile; } > newfile && mv newfile oldfile\n</code></pre>\n\n<p>You can use other tools such as ed or perl to do it without temp files.</p>\n"
},
{
"answer_id": 55826,
"author": "Tim Kennedy",
"author_id": 5699,
"author_profile": "https://Stackoverflow.com/users/5699",
"pm_score": 1,
"selected": false,
"text": "<p>If you're scripting in BASH, actually, you can just issue:</p>\n\n<pre>\ncat - yourfile /tmp/out && mv /tmp/out yourfile\n</pre>\n\n<p>That's actually in the Complex Example you yourself posted in your own question.</p>\n"
},
{
"answer_id": 59504,
"author": "Eric Hansander",
"author_id": 5039,
"author_profile": "https://Stackoverflow.com/users/5039",
"pm_score": 4,
"selected": false,
"text": "<p>It may be worth noting that it often is a <a href=\"http://www.linuxsecurity.com/content/view/115462/81/\" rel=\"noreferrer\" title=\"Safely Creating Temporary Files in Shell Scripts, by Stefan Nordhausen at LinuxSecurity\">good idea</a> to safely generate the temporary file using a utility like <a href=\"http://www.mktemp.org/\" rel=\"noreferrer\" title=\"mktemp homepage\">mktemp</a>, at least if the script will ever be executed with root privileges. You could for example do the following (again in bash):</p>\n\n<pre><code>(tmpfile=`mktemp` && { echo \"prepended text\" | cat - yourfile > $tmpfile && mv $tmpfile yourfile; } )\n</code></pre>\n"
},
{
"answer_id": 61713,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 3,
"selected": false,
"text": "<p>When you start trying to do things that become difficult in shell-script, I would strongly suggest looking into rewriting the script in a \"proper\" scripting language (Python/Perl/Ruby/etc)</p>\n\n<p>As for prepending a line to a file, it's not possible to do this via piping, as when you do anything like <code>cat blah.txt | grep something > blah.txt</code>, it inadvertently blanks the file. There is a small utility command called <code>sponge</code> you can install (you do <code>cat blah.txt | grep something | sponge blah.txt</code> and it buffers the contents of the file, then writes it to the file). It is similar to a temp file but you dont have to do that explicitly. but I would say that's a \"worse\" requirement than, say, Perl.</p>\n\n<p>There may be a way to do it via awk, or similar, but if you have to use shell-script, I think a temp file is by far the easiest(/only?) way..</p>\n"
},
{
"answer_id": 621786,
"author": "John Mee",
"author_id": 75033,
"author_profile": "https://Stackoverflow.com/users/75033",
"pm_score": 6,
"selected": true,
"text": "<p>The <strong>hack</strong> below was a quick off-the-cuff answer which worked and received lots of upvotes. Then, as the question became more popular and more time passed, people started reporting that it sorta worked but weird things could happen, or it just didn't work at all. Such fun.</p>\n<p>I recommend <a href=\"https://stackoverflow.com/a/15721194/75033\">the 'sponge' solution posted by user222</a> as Sponge is part of 'moreutils' and probably on your system by default.\n<code>(echo 'foo' && cat yourfile) | sponge yourfile</code></p>\n<p>The solution below exploits the exact implementation of file descriptors on your system and, because implementation varies significantly between nixes, it's success is entirely system dependent, definitively non-portable, and should not be relied upon for anything even vaguely important. Sponge uses the /tmp filesystem but condenses the task to a single command.</p>\n<p>Now, with all that out of the way the original answer was:</p>\n<hr>\n<p>Creating another file descriptor for the file (<code>exec 3<> yourfile</code>) thence writing to that (<code>>&3</code>) seems to overcome the read/write on same file dilemma. Works for me on 600K files with awk. However trying the same trick using 'cat' fails.<br></p>\n<p>Passing the prependage as a variable to awk (<code>-v TEXT="$text"</code>) overcomes the literal quotes problem which prevents doing this trick with 'sed'.</p>\n<pre><code>#!/bin/bash\ntext="Hello world\nWhat's up?"\n\nexec 3<> yourfile && awk -v TEXT="$text" 'BEGIN {print TEXT}{print}' yourfile >&3\n</code></pre>\n"
},
{
"answer_id": 1137872,
"author": "cb0",
"author_id": 85737,
"author_profile": "https://Stackoverflow.com/users/85737",
"pm_score": 3,
"selected": false,
"text": "<p>assuming that the file you want to edit is my.txt</p>\n\n<pre><code>$cat my.txt \nthis is the regular file\n</code></pre>\n\n<p>And the file you want to prepend is header</p>\n\n<pre><code>$ cat header\nthis is the header\n</code></pre>\n\n<p>Be sure to have a final blank line in the header file.<br>\nNow you can prepend it with</p>\n\n<pre><code>$cat header <(cat my.txt) > my.txt\n</code></pre>\n\n<p>You end up with</p>\n\n<pre><code>$ cat my.txt\nthis is the header\nthis is the regular file\n</code></pre>\n\n<p>As far as I know this only works in 'bash'. </p>\n"
},
{
"answer_id": 2362886,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>A variant on cb0's solution for \"no temp file\" to prepend fixed text:</p>\n\n<pre><code>echo \"text to prepend\" | cat - file_to_be_modified | ( cat > file_to_be_modified ) \n</code></pre>\n\n<p>Again this relies on sub-shell execution - the (..) - to avoid the cat refusing to have the same file for input and output.</p>\n\n<p>Note: Liked this solution. However, in my Mac the original file is lost (thought it shouldn't but it does). That could be fixed by writing your solution as: \necho \"text to prepend\" | cat - file_to_be_modified | cat > tmp_file; mv tmp_file file_to_be_modified</p>\n"
},
{
"answer_id": 2652178,
"author": "user318396",
"author_id": 318396,
"author_profile": "https://Stackoverflow.com/users/318396",
"pm_score": -1,
"selected": false,
"text": "<p>Bah! No one cared to mention about <em>tac</em>.</p>\n\n<pre><code>endor@grid ~ $ tac --help\nUsage: tac [OPTION]... [FILE]...\nWrite each FILE to standard output, last line first.\nWith no FILE, or when FILE is -, read standard input.\n\nMandatory arguments to long options are mandatory for short options too.\n -b, --before attach the separator before instead of after\n -r, --regex interpret the separator as a regular expression\n -s, --separator=STRING use STRING as the separator instead of newline\n --help display this help and exit\n --version output version information and exit\n\nReport tac bugs to bug-coreutils@gnu.org\nGNU coreutils home page: <http://www.gnu.org/software/coreutils/>\nGeneral help using GNU software: <http://www.gnu.org/gethelp/>\nReport tac translation bugs to <http://translationproject.org/team/>\n</code></pre>\n"
},
{
"answer_id": 2731521,
"author": "vinyll",
"author_id": 328117,
"author_profile": "https://Stackoverflow.com/users/328117",
"pm_score": 0,
"selected": false,
"text": "<pre><code>current=`cat my_file` && echo 'my_string' > my_file && echo $current >> my_file\n</code></pre>\n\n<p>where \"my_file\" is the file to prepend \"my_string\" to.</p>\n"
},
{
"answer_id": 2754039,
"author": "anonymous",
"author_id": 330877,
"author_profile": "https://Stackoverflow.com/users/330877",
"pm_score": 4,
"selected": false,
"text": "<p>John Mee: your method is not guaranteed to work, and will probably fail if you prepend more than 4096 byte of stuff (at least that's what happens with gnu awk, but I suppose other implementations will have similar constraints). Not only will it fail in that case, but it will enter an endless loop where it will read its own output, thereby making the file grow until all the available space is filled.</p>\n\n<p>Try it for yourself:</p>\n\n<pre><code>exec 3<>myfile && awk 'BEGIN{for(i=1;i<=1100;i++)print i}{print}' myfile >&3\n</code></pre>\n\n<p>(warning: kill it after a while or it will fill the filesystem)</p>\n\n<p>Moreover, it's very dangerous to edit files that way, and it's very bad advice, as if something happens while the file is being edited (crash, disk full) you're almost guaranteed to be left with the file in an inconsistent state.</p>\n"
},
{
"answer_id": 3272296,
"author": "fluffle",
"author_id": 394737,
"author_profile": "https://Stackoverflow.com/users/394737",
"pm_score": 5,
"selected": false,
"text": "<pre><code>echo '0a\nyour text here\n.\nw' | ed some_file\n</code></pre>\n\n<p>ed is the Standard Editor! <a href=\"http://www.gnu.org/fun/jokes/ed.msg.html\" rel=\"noreferrer\">http://www.gnu.org/fun/jokes/ed.msg.html</a></p>\n"
},
{
"answer_id": 3835300,
"author": "shixilun",
"author_id": 463357,
"author_profile": "https://Stackoverflow.com/users/463357",
"pm_score": 3,
"selected": false,
"text": "<pre><code>sed -i -e \"1s/^/new first line\\n/\" old_file.txt\n</code></pre>\n"
},
{
"answer_id": 4027421,
"author": "Daniel",
"author_id": 243238,
"author_profile": "https://Stackoverflow.com/users/243238",
"pm_score": 3,
"selected": false,
"text": "<p><strong>EDIT: This is broken. See <a href=\"https://stackoverflow.com/questions/25334938/weird-behavior-when-prepending-to-a-file-with-cat-and-tee\">Weird behavior when prepending to a file with cat and tee</a></strong></p>\n\n<p>The workaround to the overwrite problem is using <code>tee</code>:</p>\n\n<pre><code>cat header main | tee main > /dev/null\n</code></pre>\n"
},
{
"answer_id": 5209427,
"author": "hobs",
"author_id": 623735,
"author_profile": "https://Stackoverflow.com/users/623735",
"pm_score": 2,
"selected": false,
"text": "<p>WARNING: this needs a bit more work to meet the OP's needs.</p>\n\n<p>There should be a way to make the sed approach by @shixilun work despite his misgivings. There must be a bash command to escape whitespace when reading a file into a sed substitute string (e.g. replace newline characters with '\\n'. Shell commands <code>vis</code> and <code>cat</code> can deal with nonprintable characters, but not whitespace, so this won't solve the OP's problem:</p>\n\n<pre><code>sed -i -e \"1s/^/$(cat file_with_header.txt)/\" file_to_be_prepended.txt\n</code></pre>\n\n<p>fails due to the raw newlines in the substitute script, which need to be prepended with a line continuation character () and perhaps followed by an &, to keep the shell and sed happy, like <a href=\"https://stackoverflow.com/a/723164/623735\">this SO answer</a></p>\n\n<p><code>sed</code> has a size limit of 40K for non-global search-replace commands (no trailing /g after the pattern) so would likely avoid the scary buffer overrun problems of awk that anonymous warned of. </p>\n"
},
{
"answer_id": 5593088,
"author": "torf",
"author_id": 698365,
"author_profile": "https://Stackoverflow.com/users/698365",
"pm_score": 2,
"selected": false,
"text": "<p>Why not simply use the ed command (as already suggested by fluffle here)?</p>\n\n<p>ed reads the whole file into memory and automatically performs an in-place file edit!</p>\n\n<p>So, if your file is not that huge ...</p>\n\n<pre><code># cf. \"Editing files with the ed text editor from scripts.\",\n# http://wiki.bash-hackers.org/doku.php?id=howto:edit-ed\n\nprepend() {\n printf '%s\\n' H 1i \"${1}\" . wq | ed -s \"${2}\"\n}\n\necho 'Hello, world!' > myfile\nprepend 'line to prepend' myfile\n</code></pre>\n\n<p>Yet another workaround would be using open file handles as suggested by Jürgen Hötzel in <a href=\"https://stackoverflow.com/questions/2585438/redirect-output-from-sed-s-c-d-myfile-to-myfile\">Redirect output from sed 's/c/d/' myFile to myFile</a></p>\n\n<pre><code>echo cat > manipulate.txt\nexec 3<manipulate.txt\n# Prevent open file from being truncated:\nrm manipulate.txt\nsed 's/cat/dog/' <&3 > manipulate.txt\n</code></pre>\n\n<p>All this could be put on a single line, of course.</p>\n"
},
{
"answer_id": 6108287,
"author": "nemisj",
"author_id": 219703,
"author_profile": "https://Stackoverflow.com/users/219703",
"pm_score": 2,
"selected": false,
"text": "<p>The one which I use. This one allows you to specify order, extra chars, etc in the way you like it:</p>\n\n<pre><code>echo -e \"TEXTFIRSt\\n$(< header)\\n$(< my.txt)\" > my.txt\n</code></pre>\n\n<p>P.S: only it's not working if files contains text with backslash, cause it gets interpreted as escape characters</p>\n"
},
{
"answer_id": 7050051,
"author": "lkraav",
"author_id": 35946,
"author_profile": "https://Stackoverflow.com/users/35946",
"pm_score": 0,
"selected": false,
"text": "<p>I'm liking <a href=\"https://stackoverflow.com/questions/54365/prepend-to-a-file-one-liner-shell/3272296#3272296\">@fluffle's <strong>ed</strong> approach</a> the best. After all, any tool's command line switches vs scripted editor commands are essentially the same thing here; not seeing a scripted editor solution \"cleanliness\" being any lesser or whatnot.</p>\n\n<p>Here's my one-liner appended to <code>.git/hooks/prepare-commit-msg</code> to prepend an in-repo <code>.gitmessage</code> file to commit messages:</p>\n\n<pre><code>echo -e \"1r $PWD/.gitmessage\\n.\\nw\" | ed -s \"$1\"\n</code></pre>\n\n<p>Example <code>.gitmessage</code>:</p>\n\n<pre><code># Commit message formatting samples:\n# runlevels: boot +consolekit -zfs-fuse\n#\n</code></pre>\n\n<p>I'm doing <code>1r</code> instead of <code>0r</code>, because that will leave the empty ready-to-write line on top of the file from the original template. Don't put an empty line on top of your <code>.gitmessage</code> then, you will end up with two empty lines. <code>-s</code> suppresses diagnostic info output of ed.</p>\n\n<p>In connection with going through this, I <a href=\"http://shawnbiddle.com/devblog/archive/git-commit-templates-vim-and-you\" rel=\"nofollow noreferrer\">discovered</a> that for vim-buffs it is also good to have:</p>\n\n<pre><code>[core]\n editor = vim -c ':normal gg'\n</code></pre>\n"
},
{
"answer_id": 7091228,
"author": "Jayen",
"author_id": 192798,
"author_profile": "https://Stackoverflow.com/users/192798",
"pm_score": 0,
"selected": false,
"text": "<p>variables, ftw?</p>\n\n<pre><code>NEWFILE=$(echo deb http://mirror.csesoc.unsw.edu.au/ubuntu/ $(lsb_release -cs) main universe restricted multiverse && cat /etc/apt/sources.list)\necho \"$NEWFILE\" | sudo tee /etc/apt/sources.list\n</code></pre>\n"
},
{
"answer_id": 8208478,
"author": "Hammad Akhwand",
"author_id": 1057325,
"author_profile": "https://Stackoverflow.com/users/1057325",
"pm_score": 2,
"selected": false,
"text": "<p>Here's what I discovered:</p>\n\n<pre><code>echo -e \"header \\n$(cat file)\" >file\n</code></pre>\n"
},
{
"answer_id": 9485338,
"author": "Max Tsepkov",
"author_id": 1035328,
"author_profile": "https://Stackoverflow.com/users/1035328",
"pm_score": 3,
"selected": false,
"text": "<p>Like Daniel Velkov suggests, use tee.<br>\nTo me, that's simple smart solution:</p>\n\n<pre><code>{ echo foo; cat bar; } | tee bar > /dev/null\n</code></pre>\n"
},
{
"answer_id": 10471758,
"author": "weakish",
"author_id": 222893,
"author_profile": "https://Stackoverflow.com/users/222893",
"pm_score": 2,
"selected": false,
"text": "<pre><code>sed -i -e '1rmyheader' -e '1{h;d}' -e '2{x;G}' myfile\n</code></pre>\n"
},
{
"answer_id": 14077361,
"author": "Dave Butler",
"author_id": 693869,
"author_profile": "https://Stackoverflow.com/users/693869",
"pm_score": 0,
"selected": false,
"text": "<p>I think this is the cleanest variation of ed:</p>\n\n<pre><code>cat myheader | { echo '0a'; cat ; echo -e \".\\nw\";} | ed myfile\n</code></pre>\n\n<p>as a function:</p>\n\n<pre><code>function prepend() { { echo '0a'; cat ; echo -e \".\\nw\";} | ed $1; }\n\ncat myheader | prepend myfile\n</code></pre>\n"
},
{
"answer_id": 15721194,
"author": "user2227573",
"author_id": 2227573,
"author_profile": "https://Stackoverflow.com/users/2227573",
"pm_score": 4,
"selected": false,
"text": "<p>If you need this on computers you control, install the package \"moreutils\" and use \"sponge\". Then you can do:</p>\n\n<pre><code>cat header myfile | sponge myfile\n</code></pre>\n"
},
{
"answer_id": 17532487,
"author": "benjwadams",
"author_id": 1914300,
"author_profile": "https://Stackoverflow.com/users/1914300",
"pm_score": 2,
"selected": false,
"text": "<p>Mostly for fun/shell golf, but</p>\n\n<pre><code>ex -c '0r myheader|x' myfile\n</code></pre>\n\n<p>will do the trick, and there are no pipelines or redirections. Of course, vi/ex isn't really for noninteractive use, so vi will flash up briefly.</p>\n"
},
{
"answer_id": 20931105,
"author": "JuSchu",
"author_id": 1738535,
"author_profile": "https://Stackoverflow.com/users/1738535",
"pm_score": 2,
"selected": false,
"text": "<p>With <strong>$( command )</strong> you can write the output of a command into a variable.\nSo I did it in three commands in one line and no temp file.</p>\n\n<pre><code>originalContent=$(cat targetfile) && echo \"text to prepend\" > targetfile && echo \"$originalContent\" >> targetfile\n</code></pre>\n"
},
{
"answer_id": 25340907,
"author": "jaybee",
"author_id": 837676,
"author_profile": "https://Stackoverflow.com/users/837676",
"pm_score": 0,
"selected": false,
"text": "<p>IMHO there is no shell solution (and will never be one) that would work consistently and reliably whatever the sizes of the two files <code>myheader</code> and <code>myfile</code>. The reason is that if you want to do that without recurring to a temporary file (and without letting the shell recur silently to a temporary file, e.g. through constructs like <code>exec 3<>myfile</code>, piping to <code>tee</code>, etc.</p>\n\n<p>The \"real\" solution you are looking for needs to fiddle with the filesystem, and so it's not available in userspace and would be platform-dependent: you're asking to modify the filesystem pointer in use by <code>myfile</code> to the current value of the filesystem pointer for <code>myheader</code> and replace in the filesystem the <code>EOF</code> of <code>myheader</code> with a chained link to the current filesystem address pointed by <code>myfile</code>. This is not trivial and obviously can not be done by a non-superuser, and probably not by the superuser either... Play with inodes, etc.</p>\n\n<p>You can more or less fake this using loop devices, though. See for instance <a href=\"https://stackoverflow.com/questions/5893531/fast-concatenate-multiple-files-on-linux\">this SO thread</a>.</p>\n"
},
{
"answer_id": 26330293,
"author": "crizCraig",
"author_id": 134077,
"author_profile": "https://Stackoverflow.com/users/134077",
"pm_score": 1,
"selected": false,
"text": "<p>If you have a large file (few hundred kilobytes in my case) and access to python, this is much quicker than <code>cat</code> pipe solutions:</p>\n\n<p><code>python -c 'f = \"filename\"; t = open(f).read(); open(f, \"w\").write(\"text to prepend \" + t)'</code></p>\n"
},
{
"answer_id": 28504431,
"author": "Eric Woodruff",
"author_id": 1139784,
"author_profile": "https://Stackoverflow.com/users/1139784",
"pm_score": 4,
"selected": false,
"text": "<p>Using a bash heredoc you can avoid the need for a tmp file:</p>\n\n<pre><code>cat <<-EOF > myfile\n $(echo this is prepended)\n $(cat myfile)\nEOF\n</code></pre>\n\n<p>This works because $(cat myfile) is evaluated when the bash script is evaluated, before the cat with redirect is executed.</p>\n"
},
{
"answer_id": 30663695,
"author": "jozxyqk",
"author_id": 1888983,
"author_profile": "https://Stackoverflow.com/users/1888983",
"pm_score": 0,
"selected": false,
"text": "<p>Quick and dirty, buffer everything in memory with python:</p>\n\n<pre><code>$ echo two > file\n$ echo one | python -c \"import sys; f=open(sys.argv[1]).read(); open(sys.argv[1],'w').write(sys.stdin.read()+f)\" file\n$ cat file\none\ntwo\n$ # or creating a shortcut...\n$ alias prepend='python -c \"import sys; f=open(sys.argv[1]).read(); open(sys.argv[1],\\\"w\\\").write(sys.stdin.read()+f)\"'\n$ echo zero | prepend file\n$ cat file\nzero\none\ntwo\n</code></pre>\n"
},
{
"answer_id": 31106873,
"author": "user137369",
"author_id": 1661012,
"author_profile": "https://Stackoverflow.com/users/1661012",
"pm_score": 1,
"selected": false,
"text": "<p>A solution with <code>printf</code>:</p>\n\n<pre><code>new_line='the line you want to add'\ntarget_file='/file you/want to/write to'\n\nprintf \"%s\\n$(cat ${target_file})\" \"${new_line}\" > \"${target_file}\"\n</code></pre>\n\n<p>You could also do:</p>\n\n<pre><code>printf \"${new_line}\\n$(cat ${target_file})\" > \"${target_file}\"\n</code></pre>\n\n<p>But in that case you have to be sure there aren’t any <code>%</code> anywhere, including the contents of target file, as that can be interpreted and screw up your results.</p>\n"
},
{
"answer_id": 34645273,
"author": "user5704481",
"author_id": 5704481,
"author_profile": "https://Stackoverflow.com/users/5704481",
"pm_score": 2,
"selected": false,
"text": "<p>You can use perl command line:</p>\n\n<pre><code>perl -i -0777 -pe 's/^/my_header/' tmp\n</code></pre>\n\n<p>Where -i will create an inline replacement of the file and \n-0777 will slurp the whole file and make ^ match only the beginning.\n-pe will print all the lines</p>\n\n<p>Or if my_header is a file:</p>\n\n<pre><code>perl -i -0777 -pe 's/^/`cat my_header`/e' tmp\n</code></pre>\n\n<p>Where the /e will allow an eval of code in the substitution.</p>\n"
},
{
"answer_id": 69520112,
"author": "123",
"author_id": 5563327,
"author_profile": "https://Stackoverflow.com/users/5563327",
"pm_score": 0,
"selected": false,
"text": "<p>for dash / ash:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>echo "hello\\n$(cat myfile)" > myfile\n</code></pre>\n<p>example:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>$ echo "line" > myfile\n$ cat myfile\nline\n$ echo "line1\\n$(cat myfile)" > myfile\n$ cat myfile\nline1\nline\n</code></pre>\n"
},
{
"answer_id": 70582884,
"author": "Murilo Perrone",
"author_id": 7626061,
"author_profile": "https://Stackoverflow.com/users/7626061",
"pm_score": 1,
"selected": false,
"text": "<p>The simplest solution I found is:</p>\n<pre><code>cat myHeader myFile | tee myFile\n</code></pre>\n<p>or</p>\n<pre><code>echo "<line to add>" | cat - myFile | tee myFile\n</code></pre>\n<p>Notes:</p>\n<ul>\n<li>Use <code>echo -n</code> if you want to append just a piece of text (not a full line).</li>\n<li>Add <code>&> /dev/null</code> to the end if you don't want to see the output (the generated file).</li>\n<li>This can be used to append a shebang to the file. Example:\n<pre><code># make it executable (use u+x to allow only current user)\nchmod +x cropImage.ts\n# append the shebang\necho '#''!'/usr/bin/env ts-node | cat - cropImage.ts | tee cropImage.ts &> /dev/null\n# execute it\n./cropImage.ts myImage.png\n</code></pre>\n</li>\n</ul>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1277510/"
] | This is probably [a complex solution](http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/x13320.html).
I am looking for a simple operator like ">>", but for prepending.
I am afraid it does not exist. I'll have to do something like
```
mv myfile tmp
cat myheader tmp > myfile
```
Anything smarter? | The **hack** below was a quick off-the-cuff answer which worked and received lots of upvotes. Then, as the question became more popular and more time passed, people started reporting that it sorta worked but weird things could happen, or it just didn't work at all. Such fun.
I recommend [the 'sponge' solution posted by user222](https://stackoverflow.com/a/15721194/75033) as Sponge is part of 'moreutils' and probably on your system by default.
`(echo 'foo' && cat yourfile) | sponge yourfile`
The solution below exploits the exact implementation of file descriptors on your system and, because implementation varies significantly between nixes, it's success is entirely system dependent, definitively non-portable, and should not be relied upon for anything even vaguely important. Sponge uses the /tmp filesystem but condenses the task to a single command.
Now, with all that out of the way the original answer was:
---
Creating another file descriptor for the file (`exec 3<> yourfile`) thence writing to that (`>&3`) seems to overcome the read/write on same file dilemma. Works for me on 600K files with awk. However trying the same trick using 'cat' fails.
Passing the prependage as a variable to awk (`-v TEXT="$text"`) overcomes the literal quotes problem which prevents doing this trick with 'sed'.
```
#!/bin/bash
text="Hello world
What's up?"
exec 3<> yourfile && awk -v TEXT="$text" 'BEGIN {print TEXT}{print}' yourfile >&3
``` |
54,380 | <p>I am adding a ADO.Net Data Service lookup feature to an existing web page. Everything works great when running from visual studio, but when I roll it out to IIS, I get the following error:</p>
<blockquote>
<p><strong>Request Error</strong><br>The server encountered an error processing the request. See server logs for more details.</p>
</blockquote>
<p>I get this even when trying to display the default page, i.e.:</p>
<blockquote>
<p><a href="http://server/FFLookup.svc" rel="noreferrer">http://server/FFLookup.svc</a></p>
</blockquote>
<p>I have 3.5 SP1 installed on the server.</p>
<p>What am I missing, and which "Server Logs" is it refering to? I can't find any further error messages.</p>
<p>There is nothing in the Event Viewer logs (System or Application), and nothing in the IIS logs other than the GET:</p>
<blockquote>
<p>2008-09-10 15:20:19 10.7.131.71 GET /FFLookup.svc - 8082 - 10.7.131.86 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US)+AppleWebKit/525.13+(KHTML,+like+Gecko)+Chrome/0.2.149.29+Safari/525.13 401 2 2148074254</p>
</blockquote>
<p>There is no stack trace returned. The only response I get is the "Request Error" as noted above.</p>
<p>Thanks</p>
<p>Patrick</p>
| [
{
"answer_id": 55557,
"author": "Patrick Connelly",
"author_id": 5431,
"author_profile": "https://Stackoverflow.com/users/5431",
"pm_score": 4,
"selected": false,
"text": "<p>Well I found the \"Server Logs\" mentioned in the error above.</p>\n\n<p>You need to turn on tracing in the web.config file by adding the following tags:</p>\n\n<pre><code> <system.diagnostics>\n <sources>\n <source name=\"System.ServiceModel.MessageLogging\" switchValue=\"Warning, ActivityTracing\" >\n <listeners>\n <add name=\"ServiceModelTraceListener\"/>\n </listeners>\n </source>\n\n <source name=\"System.ServiceModel\" switchValue=\"Verbose,ActivityTracing\" >\n <listeners>\n <add name=\"ServiceModelTraceListener\"/>\n </listeners>\n </source>\n <source name=\"System.Runtime.Serialization\" switchValue=\"Verbose,ActivityTracing\">\n <listeners>\n <add name=\"ServiceModelTraceListener\"/>\n </listeners>\n </source>\n </sources>\n <sharedListeners>\n <add initializeData=\"App_tracelog.svclog\" \n type=\"System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"\n name=\"ServiceModelTraceListener\" traceOutputOptions=\"Timestamp\"/>\n </sharedListeners>\n</system.diagnostics>\n</code></pre>\n\n<p>This will create a file called app_tracelog.svclog in your website directory.</p>\n\n<p>You then use the SvcTraceViewer.exe utility to view this file. The viewer does a good job of highlighting the errors (along with lots of other information about the communications).</p>\n\n<p><strong>Beware: The log file created with the above parameters grows very quickly. Only turn it on during debuging!</strong></p>\n\n<p>In this particular case, the problem ended up being the incorrect version of OraDirect.Net, our Oracle Data Provider. The version we were using did not support 3.5 SP1.</p>\n"
},
{
"answer_id": 277112,
"author": "James_2195",
"author_id": 36086,
"author_profile": "https://Stackoverflow.com/users/36086",
"pm_score": 5,
"selected": false,
"text": "<p>In order to verbosely display the errors resulting from your data service you can place the following tag above your dataservice definition:</p>\n\n<pre><code>[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)] \n</code></pre>\n\n<p>This will then display the error in your browser window as well as a stack trace.</p>\n\n<p>In addition to this dataservices throws all exceptions to the HandleException method so if you implement this method on your dataservice class you can put a break point on it and see the exception:</p>\n\n<pre><code>protected override void HandleException(HandleExceptionArgs e)\n{\n try\n {\n e.UseVerboseErrors = true;\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.Message);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3182489,
"author": "chitza",
"author_id": 2073,
"author_profile": "https://Stackoverflow.com/users/2073",
"pm_score": 0,
"selected": false,
"text": "<p>For me the error was caused by two methods having the same name (unintended overloading).</p>\n\n<blockquote>\n <p>Overloading is not supported but type 'abc' has an overloaded method 'Void SubmitCart(System.String, Int32)'.</p>\n</blockquote>\n\n<p>I found out by running the service in debug mode.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5431/"
] | I am adding a ADO.Net Data Service lookup feature to an existing web page. Everything works great when running from visual studio, but when I roll it out to IIS, I get the following error:
>
> **Request Error**
> The server encountered an error processing the request. See server logs for more details.
>
>
>
I get this even when trying to display the default page, i.e.:
>
> <http://server/FFLookup.svc>
>
>
>
I have 3.5 SP1 installed on the server.
What am I missing, and which "Server Logs" is it refering to? I can't find any further error messages.
There is nothing in the Event Viewer logs (System or Application), and nothing in the IIS logs other than the GET:
>
> 2008-09-10 15:20:19 10.7.131.71 GET /FFLookup.svc - 8082 - 10.7.131.86 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US)+AppleWebKit/525.13+(KHTML,+like+Gecko)+Chrome/0.2.149.29+Safari/525.13 401 2 2148074254
>
>
>
There is no stack trace returned. The only response I get is the "Request Error" as noted above.
Thanks
Patrick | In order to verbosely display the errors resulting from your data service you can place the following tag above your dataservice definition:
```
[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
```
This will then display the error in your browser window as well as a stack trace.
In addition to this dataservices throws all exceptions to the HandleException method so if you implement this method on your dataservice class you can put a break point on it and see the exception:
```
protected override void HandleException(HandleExceptionArgs e)
{
try
{
e.UseVerboseErrors = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
``` |
54,387 | <p>I have a set of calculation methods sitting in a .Net DLL. I would like to make those methods available to Excel (2003+) users so they can use them in their spreadsheets.</p>
<p>For example, my .net method:</p>
<pre><code>public double CalculateSomethingReallyComplex(double a, double b) {...}
</code></pre>
<p>I would like enable them to call this method just by typing a formula in a random cell:</p>
<pre><code>=CalculateSomethingReallyComplex(A1, B1)
</code></pre>
<p>What would be the best way to accomplish this?</p>
| [
{
"answer_id": 54429,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 3,
"selected": true,
"text": "<p>There are two methods - you can used Visual Studio Tools for Office (VSTO):</p>\n\n<p><a href=\"http://blogs.msdn.com/pstubbs/archive/2004/12/31/344964.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/pstubbs/archive/2004/12/31/344964.aspx</a></p>\n\n<p>or you can use COM:</p>\n\n<p><a href=\"http://blogs.msdn.com/eric_carter/archive/2004/12/01/273127.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/eric_carter/archive/2004/12/01/273127.aspx</a></p>\n\n<p>I'm not sure if the VSTO method would work in older versions of Excel, but the COM method should work fine.</p>\n"
},
{
"answer_id": 428190,
"author": "Govert",
"author_id": 44264,
"author_profile": "https://Stackoverflow.com/users/44264",
"pm_score": 3,
"selected": false,
"text": "<p>You should also have a look at ExcelDna (<a href=\"http://www.codeplex.com/exceldna\" rel=\"noreferrer\">http://www.codeplex.com/exceldna</a>). ExcelDna is an open-source project (also free for commercial use) that allows you to create native .xll add-ins using .Net. Both user-defined functions (UDFs) and macros can be created. Your add-in code can be in text-based script files containing VB, C# or F# code, or in managed .dlls.</p>\n\n<p>Since the native Excel SDK interfaces are used, rather than COM-based automation, add-ins based on ExcelDna can be easily deployed and require no registration. ExcelDna supports Excel versions from Excel '97 to Excel 2007, and includes support for the Excel 2007 data types (large sheet and Unicode strings), as well as multi-threaded recalculation under Excel 2007.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1324220/"
] | I have a set of calculation methods sitting in a .Net DLL. I would like to make those methods available to Excel (2003+) users so they can use them in their spreadsheets.
For example, my .net method:
```
public double CalculateSomethingReallyComplex(double a, double b) {...}
```
I would like enable them to call this method just by typing a formula in a random cell:
```
=CalculateSomethingReallyComplex(A1, B1)
```
What would be the best way to accomplish this? | There are two methods - you can used Visual Studio Tools for Office (VSTO):
<http://blogs.msdn.com/pstubbs/archive/2004/12/31/344964.aspx>
or you can use COM:
<http://blogs.msdn.com/eric_carter/archive/2004/12/01/273127.aspx>
I'm not sure if the VSTO method would work in older versions of Excel, but the COM method should work fine. |
54,401 | <p>As I develop more with vim, I find myself wanting to copy in blocks of useful code, similar to "templates" in Eclipse. </p>
<p>I was thinking of making a separate file for each code chunk and just reading them in with</p>
<pre><code>:r code-fornext
</code></pre>
<p>but that just seems kind of primitive. Googling around I find vim macros mentioned and something about "maps" but nothing that seems straightforward.</p>
<p>What I am looking for are e.g. something like Eclipse's "Templates" so I pop in a code chunk with the cursor sitting in the middle of it.
Or JEdit's "Macros" which I can record doing complicated deletes and renaming on one line, then I can play it again on 10 other lines so it does the same to them.</p>
<p>Does vim have anything like these two functionalities?</p>
| [
{
"answer_id": 54527,
"author": "brian newman",
"author_id": 3210,
"author_profile": "https://Stackoverflow.com/users/3210",
"pm_score": 4,
"selected": true,
"text": "<p>To record macros in Vim, in the command mode, hit the <code>q</code> key and another key you want to assign the macro to. For quick throw away macros I usually just hit <code>qq</code> and assign the macro to the <code>q</code> key. Once you are in recording mode, run through your key strokes. When you are done make sure you are back in command mode and hit <code>q</code> again to stop recording. Then to replay the macro manually, you can type <code>@q</code>. To replay the previously run macro you can type <code>@@</code> or to run it 10 times you could type <code>10@q</code> or <code>20@q</code>, etc..</p>\n\n<p>In summary:</p>\n\n<pre><code>+----------------------------------+-------------------------------------+\n| start recording a macro | qX (X = key to assign macro to) |\n+----------------------------------+-------------------------------------+\n| stop recording a macro | q | \n+----------------------------------+-------------------------------------+\n| playback macro | @X (X = key macro was assigned to) |\n+----------------------------------+-------------------------------------+\n| replay previously played macro | @@ |\n+----------------------------------+-------------------------------------+\n</code></pre>\n\n<p>In regards to code chunks, I have found and started using a Vim plug-in called snipMate, which mimics TextMate's snippets feature. You can get the plug-in here:</p>\n\n<p><a href=\"http://www.vim.org/scripts/script.php?script_id=2540\" rel=\"nofollow noreferrer\">http://www.vim.org/scripts/script.php?script_id=2540</a></p>\n\n<p>And a short article on using snipMate (along with a short screencast showing it in use):</p>\n\n<p><a href=\"http://www.catonmat.net/blog/vim-plugins-snipmate-vim/\" rel=\"nofollow noreferrer\">http://www.catonmat.net/blog/vim-plugins-snipmate-vim/</a></p>\n\n<p>Hope you find this helpful! </p>\n"
},
{
"answer_id": 83345,
"author": "Luc Hermitte",
"author_id": 15934,
"author_profile": "https://Stackoverflow.com/users/15934",
"pm_score": 0,
"selected": false,
"text": "<p>On vim.wikia, you will find a <a href=\"http://vim.wikia.com/wiki/Category:Automated_Text_Insertion\" rel=\"nofollow noreferrer\" title=\"Automated Text Insertion category\">category of tips</a> dedicated to snippets and abbreviations expansion. You will also see a list of plugins that ease the definition of complex snippets/templates-files.</p>\n\n<p>HTH,</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] | As I develop more with vim, I find myself wanting to copy in blocks of useful code, similar to "templates" in Eclipse.
I was thinking of making a separate file for each code chunk and just reading them in with
```
:r code-fornext
```
but that just seems kind of primitive. Googling around I find vim macros mentioned and something about "maps" but nothing that seems straightforward.
What I am looking for are e.g. something like Eclipse's "Templates" so I pop in a code chunk with the cursor sitting in the middle of it.
Or JEdit's "Macros" which I can record doing complicated deletes and renaming on one line, then I can play it again on 10 other lines so it does the same to them.
Does vim have anything like these two functionalities? | To record macros in Vim, in the command mode, hit the `q` key and another key you want to assign the macro to. For quick throw away macros I usually just hit `qq` and assign the macro to the `q` key. Once you are in recording mode, run through your key strokes. When you are done make sure you are back in command mode and hit `q` again to stop recording. Then to replay the macro manually, you can type `@q`. To replay the previously run macro you can type `@@` or to run it 10 times you could type `10@q` or `20@q`, etc..
In summary:
```
+----------------------------------+-------------------------------------+
| start recording a macro | qX (X = key to assign macro to) |
+----------------------------------+-------------------------------------+
| stop recording a macro | q |
+----------------------------------+-------------------------------------+
| playback macro | @X (X = key macro was assigned to) |
+----------------------------------+-------------------------------------+
| replay previously played macro | @@ |
+----------------------------------+-------------------------------------+
```
In regards to code chunks, I have found and started using a Vim plug-in called snipMate, which mimics TextMate's snippets feature. You can get the plug-in here:
<http://www.vim.org/scripts/script.php?script_id=2540>
And a short article on using snipMate (along with a short screencast showing it in use):
<http://www.catonmat.net/blog/vim-plugins-snipmate-vim/>
Hope you find this helpful! |
54,418 | <p>I need to retrieve all rows from a table where 2 columns combined are all different. So I want all the sales that do not have any other sales that happened on the same day for the same price. The sales that are unique based on day and price will get updated to an active status.</p>
<p>So I'm thinking:</p>
<pre><code>UPDATE sales
SET status = 'ACTIVE'
WHERE id IN (SELECT DISTINCT (saleprice, saledate), id, count(id)
FROM sales
HAVING count = 1)
</code></pre>
<p>But my brain hurts going any farther than that.</p>
| [
{
"answer_id": 54430,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 10,
"selected": true,
"text": "<pre><code>SELECT DISTINCT a,b,c FROM t\n</code></pre>\n\n<p>is <em>roughly</em> equivalent to: </p>\n\n<pre><code>SELECT a,b,c FROM t GROUP BY a,b,c\n</code></pre>\n\n<p>It's a good idea to get used to the GROUP BY syntax, as it's more powerful. </p>\n\n<p>For your query, I'd do it like this:</p>\n\n<pre><code>UPDATE sales\nSET status='ACTIVE'\nWHERE id IN\n(\n SELECT id\n FROM sales S\n INNER JOIN\n (\n SELECT saleprice, saledate\n FROM sales\n GROUP BY saleprice, saledate\n HAVING COUNT(*) = 1 \n ) T\n ON S.saleprice=T.saleprice AND s.saledate=T.saledate\n )\n</code></pre>\n"
},
{
"answer_id": 54557,
"author": "Christian Berg",
"author_id": 5035,
"author_profile": "https://Stackoverflow.com/users/5035",
"pm_score": 5,
"selected": false,
"text": "<p>The problem with your query is that when using a GROUP BY clause (which you essentially do by using distinct) you can only use columns that you group by or aggregate functions. You cannot use the column id because there are potentially different values. In your case there is always only one value because of the HAVING clause, but most RDBMS are not smart enough to recognize that.</p>\n\n<p>This should work however (and doesn't need a join):</p>\n\n<pre><code>UPDATE sales\nSET status='ACTIVE'\nWHERE id IN (\n SELECT MIN(id) FROM sales\n GROUP BY saleprice, saledate\n HAVING COUNT(id) = 1\n)\n</code></pre>\n\n<p>You could also use MAX or AVG instead of MIN, it is only important to use a function that returns the value of the column if there is only one matching row.</p>\n"
},
{
"answer_id": 12632129,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 9,
"selected": false,
"text": "<p>If you put together the answers so far, clean up and improve, you would arrive at this superior query:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>UPDATE sales\nSET status = 'ACTIVE'\nWHERE (saleprice, saledate) IN (\n SELECT saleprice, saledate\n FROM sales\n GROUP BY saleprice, saledate\n HAVING count(*) = 1 \n );\n</code></pre>\n<p>Which is <em>much</em> faster than either of them. Nukes the performance of the currently accepted answer by factor 10 - 15 (in my tests on PostgreSQL 8.4 and 9.1).</p>\n<p>But this is still far from optimal. Use a <a href=\"https://www.postgresql.org/docs/current/functions-subquery.html#FUNCTIONS-SUBQUERY-EXISTS\" rel=\"noreferrer\"><strong><code>NOT EXISTS</code></strong></a> (anti-)semi-join for even better performance. <code>EXISTS</code> is standard SQL, has been around forever (at least since PostgreSQL 7.2, long before this question was asked) and fits the presented requirements perfectly:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>UPDATE sales s\nSET status = 'ACTIVE'\nWHERE NOT EXISTS (\n SELECT FROM sales s1 -- SELECT list can be empty for EXISTS\n WHERE s.saleprice = s1.saleprice\n AND s.saledate = s1.saledate\n AND s.id <> s1.id -- except for row itself\n )\nAND s.status IS DISTINCT FROM 'ACTIVE'; -- avoid empty updates. see below\n</code></pre>\n<p><em>db<>fiddle <a href=\"https://dbfiddle.uk/?rdbms=postgres_11&fiddle=26c7eb96c3a22330a9c271d554c869fe\" rel=\"noreferrer\">here</a></em><br />\n<sub>Old <a href=\"http://sqlfiddle.com/#!17/6b5ef/1\" rel=\"noreferrer\">sqlfiddle</a></sub></p>\n<h3>Unique key to identify row</h3>\n<p>If you don't have a primary or unique key for the table (<code>id</code> in the example), you can substitute with the system column <code>ctid</code> for the purpose of this query (but not for some other purposes):</p>\n<pre><code> AND s1.ctid <> s.ctid\n</code></pre>\n<p><sub>Every table should have a primary key. Add one if you didn't have one, yet. I suggest a <code>serial</code> or an <code>IDENTITY</code> column in Postgres 10+.</sub></p>\n<p>Related:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/17500013/in-order-sequence-generation/17503095#17503095\">In-order sequence generation</a></li>\n<li><a href=\"https://stackoverflow.com/questions/9875223/auto-increment-table-column/9875517#9875517\">Auto increment table column</a></li>\n</ul>\n<h3>How is this faster?</h3>\n<p>The subquery in the <code>EXISTS</code> anti-semi-join can stop evaluating as soon as the first dupe is found (no point in looking further). For a base table with few duplicates this is only mildly more efficient. With lots of duplicates this becomes <em>way</em> more efficient.</p>\n<h3>Exclude empty updates</h3>\n<p>For rows that already have <code>status = 'ACTIVE'</code> this update would not change anything, but still insert a new row version at full cost (minor exceptions apply). Normally, you do not want this. Add another <code>WHERE</code> condition like demonstrated above to avoid this and make it even faster:</p>\n<p>If <code>status</code> is defined <code>NOT NULL</code>, you can simplify to:</p>\n<pre><code>AND status <> 'ACTIVE';\n</code></pre>\n<p>The data type of the column must support the <code><></code> operator. Some types like <code>json</code> don't. See:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/24292575/how-to-query-a-json-column-for-empty-objects/24296054#24296054\">How to query a json column for empty objects?</a></li>\n</ul>\n<h3>Subtle difference in NULL handling</h3>\n<p>This query (unlike the <a href=\"https://stackoverflow.com/a/54430/939860\">currently accepted answer by Joel</a>) does not treat NULL values as equal. The following two rows for <code>(saleprice, saledate)</code> would qualify as "distinct" (though looking identical to the human eye):</p>\n<pre><code>(123, NULL)\n(123, NULL)\n</code></pre>\n<p>Also passes in a unique index and almost anywhere else, since NULL values do not compare equal according to the SQL standard. See:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/8289100/create-unique-constraint-with-null-columns/8289253#8289253\">Create unique constraint with null columns</a></li>\n</ul>\n<p>OTOH, <code>GROUP BY</code>, <code>DISTINCT</code> or <code>DISTINCT ON ()</code> treat NULL values as equal. Use an appropriate query style depending on what you want to achieve. You can still use this faster query with <a href=\"https://www.postgresql.org/docs/current/functions-comparison.html#FUNCTIONS-COMPARISON-PRED-TABLE\" rel=\"noreferrer\"><code>IS NOT DISTINCT FROM</code></a> instead of <code>=</code> for any or all comparisons to make NULL compare equal. More:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/26769454/how-to-delete-duplicate-rows-without-unique-identifier/26773018#26773018\">How to delete duplicate rows without unique identifier</a></li>\n</ul>\n<p>If all columns being compared are defined <code>NOT NULL</code>, there is no room for disagreement.</p>\n"
},
{
"answer_id": 48238006,
"author": "frans eilering",
"author_id": 4962958,
"author_profile": "https://Stackoverflow.com/users/4962958",
"pm_score": 2,
"selected": false,
"text": "<p>I want to select the distinct values from one column 'GrondOfLucht' but they should be sorted in the order as given in the column 'sortering'. I cannot get the distinct values of just one column using</p>\n\n<pre><code>Select distinct GrondOfLucht,sortering\nfrom CorWijzeVanAanleg\norder by sortering\n</code></pre>\n\n<p>It will also give the column 'sortering' and because 'GrondOfLucht' AND 'sortering' is not unique, the result will be ALL rows.</p>\n\n<p>use the GROUP to select the records of 'GrondOfLucht' in the order given by 'sortering</p>\n\n<pre><code>SELECT GrondOfLucht\nFROM dbo.CorWijzeVanAanleg\nGROUP BY GrondOfLucht, sortering\nORDER BY MIN(sortering)\n</code></pre>\n"
},
{
"answer_id": 54456645,
"author": "Abdulhafeth Sartawi",
"author_id": 4385453,
"author_profile": "https://Stackoverflow.com/users/4385453",
"pm_score": 3,
"selected": false,
"text": "<p>If your DBMS doesn't support distinct with multiple columns like this:</p>\n\n<pre><code>select distinct(col1, col2) from table\n</code></pre>\n\n<p>Multi select in general can be executed safely as follows:</p>\n\n<pre><code>select distinct * from (select col1, col2 from table ) as x\n</code></pre>\n\n<p>As this can work on most of the DBMS and this is expected to be faster than group by solution as you are avoiding the grouping functionality.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4915/"
] | I need to retrieve all rows from a table where 2 columns combined are all different. So I want all the sales that do not have any other sales that happened on the same day for the same price. The sales that are unique based on day and price will get updated to an active status.
So I'm thinking:
```
UPDATE sales
SET status = 'ACTIVE'
WHERE id IN (SELECT DISTINCT (saleprice, saledate), id, count(id)
FROM sales
HAVING count = 1)
```
But my brain hurts going any farther than that. | ```
SELECT DISTINCT a,b,c FROM t
```
is *roughly* equivalent to:
```
SELECT a,b,c FROM t GROUP BY a,b,c
```
It's a good idea to get used to the GROUP BY syntax, as it's more powerful.
For your query, I'd do it like this:
```
UPDATE sales
SET status='ACTIVE'
WHERE id IN
(
SELECT id
FROM sales S
INNER JOIN
(
SELECT saleprice, saledate
FROM sales
GROUP BY saleprice, saledate
HAVING COUNT(*) = 1
) T
ON S.saleprice=T.saleprice AND s.saledate=T.saledate
)
``` |
54,419 | <p>I have a WCF application that has two Services that I am trying to host in a single Windows Service using net.tcp. I can run either of the services just fine, but as soon as I try to put them both in the Windows Service only the first one loads up. I have determined that the second services ctor is being called but the OnStart never fires. This tells me that WCF is finding something wrong with loading up that second service.</p>
<p>Using net.tcp I know I need to turn on port sharing and start the port sharing service on the server. This all seems to be working properly. I have tried putting the services on different tcp ports and still no success.</p>
<p>My service installer class looks like this:</p>
<pre><code> [RunInstaller(true)]
public class ProjectInstaller : Installer
{
private ServiceProcessInstaller _process;
private ServiceInstaller _serviceAdmin;
private ServiceInstaller _servicePrint;
public ProjectInstaller()
{
_process = new ServiceProcessInstaller();
_process.Account = ServiceAccount.LocalSystem;
_servicePrint = new ServiceInstaller();
_servicePrint.ServiceName = "PrintingService";
_servicePrint.StartType = ServiceStartMode.Automatic;
_serviceAdmin = new ServiceInstaller();
_serviceAdmin.ServiceName = "PrintingAdminService";
_serviceAdmin.StartType = ServiceStartMode.Automatic;
Installers.AddRange(new Installer[] { _process, _servicePrint, _serviceAdmin });
}
}
</code></pre>
<p>and both services looking very similar</p>
<pre><code> class PrintService : ServiceBase
{
public ServiceHost _host = null;
public PrintService()
{
ServiceName = "PCTSPrintingService";
CanStop = true;
AutoLog = true;
}
protected override void OnStart(string[] args)
{
if (_host != null) _host.Close();
_host = new ServiceHost(typeof(Printing.ServiceImplementation.PrintingService));
_host.Faulted += host_Faulted;
_host.Open();
}
}
</code></pre>
| [
{
"answer_id": 54424,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>you probably just need 2 service hosts.</p>\n\n<p>_host1 and _host2.</p>\n"
},
{
"answer_id": 77401,
"author": "Jeremy McGee",
"author_id": 3546,
"author_profile": "https://Stackoverflow.com/users/3546",
"pm_score": 1,
"selected": false,
"text": "<p>If you want one Windows service to start two WCF services, you'll need one ServiceInstaller that has two ServiceHost instances, both of which are started in the (single) OnStart method.</p>\n\n<p>You might want to follow the pattern for ServiceInstaller that's in the template code when you choose to create a new Windows Service in Visual Studio - in general this is a good place to start.</p>\n"
},
{
"answer_id": 90870,
"author": "Wiren",
"author_id": 2538222,
"author_profile": "https://Stackoverflow.com/users/2538222",
"pm_score": 5,
"selected": true,
"text": "<p>Base your service on this <a href=\"http://msdn.microsoft.com/en-us/library/ms733069.aspx\" rel=\"nofollow noreferrer\">MSDN article</a> and create two service hosts. \nBut instead of actually calling each service host directly, you can break it out to as many classes as you want which defines each service you want to run:</p>\n\n<pre><code>internal class MyWCFService1\n{\n internal static System.ServiceModel.ServiceHost serviceHost = null;\n\n internal static void StartService()\n {\n if (serviceHost != null)\n {\n serviceHost.Close();\n }\n\n // Instantiate new ServiceHost.\n serviceHost = new System.ServiceModel.ServiceHost(typeof(MyService1));\n // Open myServiceHost.\n serviceHost.Open();\n }\n\n internal static void StopService()\n {\n if (serviceHost != null)\n {\n serviceHost.Close();\n serviceHost = null;\n }\n }\n};\n</code></pre>\n\n<p>In the body of the windows service host, call the different classes:</p>\n\n<pre><code> // Start the Windows service.\n protected override void OnStart( string[] args )\n {\n // Call all the set up WCF services...\n MyWCFService1.StartService();\n //MyWCFService2.StartService();\n //MyWCFService3.StartService();\n\n\n }\n</code></pre>\n\n<p>Then you can add as many WCF services as you like to one windows service host.</p>\n\n<p>REMEBER to call the stop methods as well....</p>\n"
},
{
"answer_id": 9159152,
"author": "Eswararao",
"author_id": 1192102,
"author_profile": "https://Stackoverflow.com/users/1192102",
"pm_score": 2,
"selected": false,
"text": "<pre><code> Type serviceAServiceType = typeof(AfwConfigure);\n Type serviceAContractType = typeof(IAfwConfigure);\n\n Type serviceBServiceType = typeof(ConfigurationConsole);\n Type serviceBContractType = typeof(IConfigurationConsole);\n\n Type serviceCServiceType = typeof(ConfigurationAgent);\n Type serviceCContractType = typeof(IConfigurationAgent);\n\n ServiceHost serviceAHost = new ServiceHost(serviceAServiceType);\n ServiceHost serviceBHost = new ServiceHost(serviceBServiceType);\n ServiceHost serviceCHost = new ServiceHost(serviceCServiceType);\n Debug.WriteLine(\"Enter1\");\n serviceAHost.Open();\n Debug.WriteLine(\"Enter2\");\n serviceBHost.Open();\n Debug.WriteLine(\"Enter3\");\n serviceCHost.Open();\n Debug.WriteLine(\"Opened!!!!!!!!!\");\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5408/"
] | I have a WCF application that has two Services that I am trying to host in a single Windows Service using net.tcp. I can run either of the services just fine, but as soon as I try to put them both in the Windows Service only the first one loads up. I have determined that the second services ctor is being called but the OnStart never fires. This tells me that WCF is finding something wrong with loading up that second service.
Using net.tcp I know I need to turn on port sharing and start the port sharing service on the server. This all seems to be working properly. I have tried putting the services on different tcp ports and still no success.
My service installer class looks like this:
```
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
private ServiceProcessInstaller _process;
private ServiceInstaller _serviceAdmin;
private ServiceInstaller _servicePrint;
public ProjectInstaller()
{
_process = new ServiceProcessInstaller();
_process.Account = ServiceAccount.LocalSystem;
_servicePrint = new ServiceInstaller();
_servicePrint.ServiceName = "PrintingService";
_servicePrint.StartType = ServiceStartMode.Automatic;
_serviceAdmin = new ServiceInstaller();
_serviceAdmin.ServiceName = "PrintingAdminService";
_serviceAdmin.StartType = ServiceStartMode.Automatic;
Installers.AddRange(new Installer[] { _process, _servicePrint, _serviceAdmin });
}
}
```
and both services looking very similar
```
class PrintService : ServiceBase
{
public ServiceHost _host = null;
public PrintService()
{
ServiceName = "PCTSPrintingService";
CanStop = true;
AutoLog = true;
}
protected override void OnStart(string[] args)
{
if (_host != null) _host.Close();
_host = new ServiceHost(typeof(Printing.ServiceImplementation.PrintingService));
_host.Faulted += host_Faulted;
_host.Open();
}
}
``` | Base your service on this [MSDN article](http://msdn.microsoft.com/en-us/library/ms733069.aspx) and create two service hosts.
But instead of actually calling each service host directly, you can break it out to as many classes as you want which defines each service you want to run:
```
internal class MyWCFService1
{
internal static System.ServiceModel.ServiceHost serviceHost = null;
internal static void StartService()
{
if (serviceHost != null)
{
serviceHost.Close();
}
// Instantiate new ServiceHost.
serviceHost = new System.ServiceModel.ServiceHost(typeof(MyService1));
// Open myServiceHost.
serviceHost.Open();
}
internal static void StopService()
{
if (serviceHost != null)
{
serviceHost.Close();
serviceHost = null;
}
}
};
```
In the body of the windows service host, call the different classes:
```
// Start the Windows service.
protected override void OnStart( string[] args )
{
// Call all the set up WCF services...
MyWCFService1.StartService();
//MyWCFService2.StartService();
//MyWCFService3.StartService();
}
```
Then you can add as many WCF services as you like to one windows service host.
REMEBER to call the stop methods as well.... |
54,421 | <p>If you are writing a program that is executable from the command line, you often want to offer the user several options or flags, along with possibly more than one argument. I have stumbled my way through this many times, but is there some sort of design pattern for looping through args and calling the appropriate handler functions?</p>
<p>Consider:</p>
<pre><code>myprogram -f filename -d directory -r regex
</code></pre>
<p>How do you organize the handler functions after you retrieve the arguments using whatever built-ins for your language? (language-specific answers welcomed, if that helps you articulate an answer)</p>
| [
{
"answer_id": 54457,
"author": "Peter Ritchie",
"author_id": 5620,
"author_profile": "https://Stackoverflow.com/users/5620",
"pm_score": 5,
"selected": true,
"text": "<p>I don't know of any documented \"patterns\" for processing.</p>\n\n<p>I believe one of the oldest libraries/APIs for handling arguments is getopt. Googling \"getopt\" shows lots of man pages and links to implementations.</p>\n\n<p>Generally, I have a preferences or settings service in my application that the argument processor knows how to communicate with. Arguments are then translated into something in this service that the application than then query. This could be as simple as a dictionary of settings (like a string setting named \"filename\").</p>\n"
},
{
"answer_id": 54460,
"author": "Kilhoffer",
"author_id": 5469,
"author_profile": "https://Stackoverflow.com/users/5469",
"pm_score": 1,
"selected": false,
"text": "<p>I would recommend using a command line processor library. <a href=\"http://netcode.ru/dotnet/?lang=&katID=30&skatID=268&artID=7379\" rel=\"nofollow noreferrer\">Some Russian guy</a> created a decent one, but there are tons of them out there. Will save you some time so you can concentrate on the purpose of your app rather than parsing command line switches!</p>\n"
},
{
"answer_id": 54464,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 3,
"selected": false,
"text": "<p>You didn't mention the language, but for Java we've loved <a href=\"http://commons.apache.org/cli/\" rel=\"noreferrer\">Apache Commons CLI</a>. For C/C++, getopt.</p>\n"
},
{
"answer_id": 54479,
"author": "Dave Verwer",
"author_id": 4496,
"author_profile": "https://Stackoverflow.com/users/4496",
"pm_score": 0,
"selected": false,
"text": "<p>You don't mention a language for this but if you are looking for a really nice Objective-C wrapper around getopt then Dave Dribin's DDCLI framework is really nice.</p>\n\n<p><a href=\"http://www.dribin.org/dave/blog/archives/2008/04/29/ddcli\" rel=\"nofollow noreferrer\">http://www.dribin.org/dave/blog/archives/2008/04/29/ddcli</a></p>\n"
},
{
"answer_id": 54480,
"author": "Xetius",
"author_id": 274,
"author_profile": "https://Stackoverflow.com/users/274",
"pm_score": 0,
"selected": false,
"text": "<p>I use the <a href=\"http://perldoc.perl.org/Getopt/Std.html\" rel=\"nofollow noreferrer\">Getopts::std</a> and <a href=\"http://perldoc.perl.org/Getopt/Long.html\" rel=\"nofollow noreferrer\">Getopts::long</a> in perl and also the <a href=\"http://www.gnu.org/software/libc/manual/html_node/Getopt.html#Getopt\" rel=\"nofollow noreferrer\">Getopt</a> function in C. This standardises the parsing and format of parameters. Other languages have different mechanisms for handling these.</p>\n\n<p>Hope this helps</p>\n"
},
{
"answer_id": 54481,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "<p>The standard design usually follows what getopt does, there are getopt libraries for many languages, .NET, python, C, Perl, PHP, etc.</p>\n\n<p>The basic design is to have a command line parser which returns part by part the arguments passed to be checked in a loop.</p>\n\n<p><a href=\"http://www-128.ibm.com/developerworks/aix/library/au-unix-getopt.html\" rel=\"nofollow noreferrer\">This</a> article discusses it in some more detail.</p>\n"
},
{
"answer_id": 54491,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 1,
"selected": false,
"text": "<p>Getopt is the only way to go.</p>\n\n<p><a href=\"http://sourceforge.net/projects/csharpoptparse\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/csharpoptparse</a></p>\n"
},
{
"answer_id": 54543,
"author": "argv0",
"author_id": 5595,
"author_profile": "https://Stackoverflow.com/users/5595",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/program_options.html\" rel=\"nofollow noreferrer\">boost::program_options</a> library is nice if you're in C++ and have the luxury of using Boost.</p>\n"
},
{
"answer_id": 54690,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming you have a \"config\" object that you aim to setup with the flags and a suitable command line parser that takes care of parsing the command line and supply a constant stream of the options, here goes a block of pseudocode</p>\n\n<pre><code>while (current_argument = cli_parser_next()) {\n switch(current_argument) {\n case \"f\": //Parser strips the dashes\n case \"force\":\n config->force = true;\n break;\n case \"d\":\n case \"delete\":\n config->delete = true;\n break;\n //So on and so forth\n default:\n printUsage();\n exit;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 54883,
"author": "Martin Del Vecchio",
"author_id": 5397,
"author_profile": "https://Stackoverflow.com/users/5397",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer options like \"-t text\" and \"-i 44\"; I don't like \"-fname\" or \"--very-long-argument=some_value\".</p>\n\n<p>And \"-?\", \"-h\", and \"/h\" all produce a help screen.</p>\n\n<p>Here's how my code looks:</p>\n\n<pre><code>int main (int argc, char *argv[])\n { int i;\n char *Arg;\n int ParamX, ParamY;\n char *Text, *Primary;\n\n // Initialize...\n ParamX = 1;\n ParamY = 0;\n Text = NULL;\n Primary = NULL;\n\n // For each argument...\n for (i = 0; i < argc; i++)\n {\n // Get the next argument and see what it is\n Arg = argv[i];\n switch (Arg[0])\n {\n case '-':\n case '/':\n // It's an argument; which one?\n switch (Arg[1])\n {\n case '?':\n case 'h':\n case 'H':\n // A cry for help\n printf (\"Usage: whatever...\\n\\n\");\n return (0);\n break;\n\n case 't':\n case 'T':\n // Param T requires a value; is it there?\n i++;\n if (i >= argc)\n {\n printf (\"Error: missing value after '%s'.\\n\\n\", Arg);\n return (1);\n }\n\n // Just remember this\n Text = Arg;\n\n break;\n\n case 'x':\n case 'X':\n // Param X requires a value; is it there?\n i++;\n if (i >= argc)\n {\n printf (\"Error: missing value after '%s'.\\n\\n\", Arg);\n return (1);\n }\n\n // The value is there; get it and convert it to an int (1..10)\n Arg = argv[i];\n ParamX = atoi (Arg);\n if ((ParamX == 0) || (ParamX > 10))\n {\n printf (\"Error: invalid value for '%s'; must be between 1 and 10.\\n\\n\", Arg);\n return (1);\n }\n\n break;\n\n case 'y':\n case 'Y':\n // Param Y doesn't expect a value after it\n ParamY = 1;\n break;\n\n default:\n // Unexpected argument\n printf (\"Error: unexpected parameter '%s'; type 'command -?' for help.\\n\\n\", Arg);\n return (1);\n break;\n }\n\n break;\n\n default:\n // It's not a switch that begins with '-' or '/', so it's the primary option\n Primary = Arg;\n\n break;\n }\n }\n\n // Done\n return (0);\n }\n</code></pre>\n"
},
{
"answer_id": 78034,
"author": "mes5k",
"author_id": 1359466,
"author_profile": "https://Stackoverflow.com/users/1359466",
"pm_score": 2,
"selected": false,
"text": "<p>A few comments on this...</p>\n\n<p>First, while there aren't any patterns per se, writing a parser is essentially a mechanical exercise, since given a grammar, a parser can be easily generated. Tools like Bison, and ANTLR come to mind.</p>\n\n<p>That said, parser generators are usually overkill for the command line. So the usual pattern is to write one yourself (as others have demonstrated) a few times until you get sick of dealing with the tedious detail and find a library to do it for you. </p>\n\n<p>I wrote one for C++ that saves a bunch of effort that getopt imparts and makes nice use of templates: <a href=\"http://tclap.sourceforge.net\" rel=\"nofollow noreferrer\"><code>TCLAP</code></a></p>\n"
},
{
"answer_id": 111359,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 2,
"selected": false,
"text": "<p>I'm riffing on the ANTLR answer by mes5k. This <a href=\"http://www.codeproject.com/KB/recipes/sota_expression_evaluator.aspx\" rel=\"nofollow noreferrer\">link to Codeproject</a> is for an article that discusses ANLTR and using the visit pattern to implement the actions you want you app to take. It's well written and worth reviewing.</p>\n"
},
{
"answer_id": 7529952,
"author": "Lindsay Morsillo",
"author_id": 945525,
"author_profile": "https://Stackoverflow.com/users/945525",
"pm_score": 4,
"selected": false,
"text": "<p>I think the following answer is more along the lines of what you are looking for:</p>\n\n<p>You should look at applying the Template Pattern (Template Method in \"Design Patterns\" [Gamma, el al]) </p>\n\n<p>In short it's overall processing looks like this:</p>\n\n<pre><code>If the arguments to the program are valid then\n Do necessary pre-processing\n For every line in the input\n Do necessary input processing\n Do necessary post-processing\nOtherwise\n Show the user a friendly usage message\n</code></pre>\n\n<p>In short, implement a ConsoleEngineBase class that has methods for:</p>\n\n<pre><code>PreProcess()\nProcessLine()\nPostProcess()\nUsage()\nMain()\n</code></pre>\n\n<p>Then create a chassis, that instantiates a ConsoleEngine() instance and sends the Main() message to kick it off.</p>\n\n<p>To see a good example of how to apply this to a console or command line program check out the following link:\n<a href=\"http://msdn.microsoft.com/en-us/magazine/cc164014.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc164014.aspx</a></p>\n\n<p>The example is in C#, but the ideas are easily implemented in any other environment.</p>\n\n<p>You would look at the GetOpt() as just the part that fit's into the argument handling (pre-processing).</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 23583280,
"author": "amarnath chatterjee",
"author_id": 1178966,
"author_profile": "https://Stackoverflow.com/users/1178966",
"pm_score": 3,
"selected": false,
"text": "<p>Well, its an old post but i would still like to contribute. The question was intended on choice of design patterns however i could see a lot of discussion on which library to use. I have checked out microsoft link as per lindsay which talks about template design pattern to use.</p>\n\n<p>However, i am not convinced with the post. Template pattern's intent is to define a template which will be implemented by various other classes to have uniform behavior. I don't think parsing command line fits into it. </p>\n\n<p>I would rather go with \"Command\" design pattern. This pattern is best fit for menu driven options.</p>\n\n<p><a href=\"http://www.blackwasp.co.uk/Command.aspx\" rel=\"noreferrer\">http://www.blackwasp.co.uk/Command.aspx</a></p>\n\n<p>so in your case, -f, -d and -r all becomes commands which has common or separate receiver defined. That way more receivers can be defined in future. The next step will be to chain these responsibilities of commands, in case there a processing chain required. For which i would choose.</p>\n\n<p><a href=\"http://www.blackwasp.co.uk/ChainOfResponsibility.aspx\" rel=\"noreferrer\">http://www.blackwasp.co.uk/ChainOfResponsibility.aspx</a></p>\n\n<p>I guess the combination of these two are best to organize the code for command line processing or any menu driven approach.</p>\n"
},
{
"answer_id": 38641650,
"author": "Meadock",
"author_id": 1013794,
"author_profile": "https://Stackoverflow.com/users/1013794",
"pm_score": 1,
"selected": false,
"text": "<p>How about the interpreter pattern?\n<a href=\"http://www.dofactory.com/net/interpreter-design-pattern\" rel=\"nofollow\">http://www.dofactory.com/net/interpreter-design-pattern</a></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577/"
] | If you are writing a program that is executable from the command line, you often want to offer the user several options or flags, along with possibly more than one argument. I have stumbled my way through this many times, but is there some sort of design pattern for looping through args and calling the appropriate handler functions?
Consider:
```
myprogram -f filename -d directory -r regex
```
How do you organize the handler functions after you retrieve the arguments using whatever built-ins for your language? (language-specific answers welcomed, if that helps you articulate an answer) | I don't know of any documented "patterns" for processing.
I believe one of the oldest libraries/APIs for handling arguments is getopt. Googling "getopt" shows lots of man pages and links to implementations.
Generally, I have a preferences or settings service in my application that the argument processor knows how to communicate with. Arguments are then translated into something in this service that the application than then query. This could be as simple as a dictionary of settings (like a string setting named "filename"). |
54,426 | <p>Like the Delicious submission bookmark-let, I'd like to have some standard JavaScript I can use to submit any visited URL to a 3rd party site when that's possible by URL. Suggestions?</p>
<p>For example, I've been using </p>
<pre><code>javascript:void(location.href="http://www.yacktrack.com/home?query="+encodeURI(location.href))
</code></pre>
<p>so far but wonder if there's something more sophisticated I could use or better practice.</p>
| [
{
"answer_id": 54446,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 1,
"selected": false,
"text": "<pre><code>document.location = \"http://url_submitting_to.com?query_string_param=\" + window.location;\n</code></pre>\n"
},
{
"answer_id": 54470,
"author": "Justin Voss",
"author_id": 5616,
"author_profile": "https://Stackoverflow.com/users/5616",
"pm_score": 3,
"selected": true,
"text": "<p>Do you want something exactly like the Delicious bookmarklet (as in, something the user actively clicks on to submit the URL)? If so, you could probably just copy their code and replace the target URL:</p>\n\n<pre><code>javascript:(function(){\n location.href='http://example.com/your-script.php?url='+\n encodeURIComponent(window.location.href)+\n '&title='+encodeURIComponent(document.title)\n})()\n</code></pre>\n\n<p>You may need to change the query string names, etc., to match what your script expects.</p>\n\n<p>If you want to track a user through your website automatically, this probably won't be possible. You'd need to request the URL with AJAX, but the web browser won't allow Javascript to make a request outside of the originating domain. Maybe it's possible with <code>iframe</code> trickery.</p>\n\n<p><strong>Edit:</strong> John beat me to it.</p>\n"
},
{
"answer_id": 54531,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 0,
"selected": false,
"text": "<p>Another option would be to something like this:</p>\n\n<pre><code><form action=\"http://www.yacktrack.com/home\" method=\"get\" name=\"f\">\n <input type=\"hidden\" name=\"query\" />\n</form>\n</code></pre>\n\n<p>then your javascript would be:</p>\n\n<pre><code>f.query.value=location.href; f.submit();\n</code></pre>\n\n<p>or you could combine the [save link] with the submit like this:</p>\n\n<pre><code><form action=\"http://www.yacktrack.com/home\" method=\"get\" name=\"f\" onsubmit=\"f.query.value=location.href;\">\n <input type=\"hidden\" name=\"query\" />\n <input type=\"submit\" name=\"Save Link\" />\n</form>\n</code></pre>\n\n<p>and if you're running server-side code, you can plug in the location so you can be JavaScript-free:</p>\n\n<pre><code><form action=\"http://www.yacktrack.com/home\" method=\"get\" name=\"f\">\n <input type=\"hidden\" name=\"query\" value=\"<%=Response.Url%>\" />\n <input type=\"submit\" name=\"Save Link\" />\n</form>\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5613/"
] | Like the Delicious submission bookmark-let, I'd like to have some standard JavaScript I can use to submit any visited URL to a 3rd party site when that's possible by URL. Suggestions?
For example, I've been using
```
javascript:void(location.href="http://www.yacktrack.com/home?query="+encodeURI(location.href))
```
so far but wonder if there's something more sophisticated I could use or better practice. | Do you want something exactly like the Delicious bookmarklet (as in, something the user actively clicks on to submit the URL)? If so, you could probably just copy their code and replace the target URL:
```
javascript:(function(){
location.href='http://example.com/your-script.php?url='+
encodeURIComponent(window.location.href)+
'&title='+encodeURIComponent(document.title)
})()
```
You may need to change the query string names, etc., to match what your script expects.
If you want to track a user through your website automatically, this probably won't be possible. You'd need to request the URL with AJAX, but the web browser won't allow Javascript to make a request outside of the originating domain. Maybe it's possible with `iframe` trickery.
**Edit:** John beat me to it. |
54,440 | <p>I want to add the selected item from the <code>TreeView</code> to the <code>ListBox</code> control using <code>DataBinding</code> (If it can work with <code>DataBinding</code>). </p>
<pre><code><TreeView HorizontalAlignment="Left"
Margin="30,32,0,83"
Name="treeView1"
Width="133" >
</TreeView>
<ListBox VerticalAlignment="Top"
Margin="208,36,93,0"
Name="listBox1"
Height="196" >
</ListBox>
</code></pre>
<p><code>TreeView</code> is populated from the code behind page with some dummy data. </p>
| [
{
"answer_id": 54665,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 0,
"selected": false,
"text": "<p>I'm pretty sure it is possible, since WPF is really flexible with data binding, but I haven't done that specific scenario yet.</p>\n\n<p>I've been following a <a href=\"http://blogs.msdn.com/wpfsdk/archive/2006/10/19/wpf-basic-data-binding-faq.aspx\" rel=\"nofollow noreferrer\">WPF Databinding FAQ</a> from the MSDN blogs as of late and it provides a lot of insights that might help.</p>\n"
},
{
"answer_id": 55830,
"author": "Dylan",
"author_id": 4580,
"author_profile": "https://Stackoverflow.com/users/4580",
"pm_score": 1,
"selected": false,
"text": "<p>You can bind to an element using ElementName, so if you wanted to bind the selected tree item to the ItemsSource of a ListBox:</p>\n\n<pre><code>ItemsSource=\"{Binding SelectedItem, ElementName=treeView1}\"\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3797/"
] | I want to add the selected item from the `TreeView` to the `ListBox` control using `DataBinding` (If it can work with `DataBinding`).
```
<TreeView HorizontalAlignment="Left"
Margin="30,32,0,83"
Name="treeView1"
Width="133" >
</TreeView>
<ListBox VerticalAlignment="Top"
Margin="208,36,93,0"
Name="listBox1"
Height="196" >
</ListBox>
```
`TreeView` is populated from the code behind page with some dummy data. | You can bind to an element using ElementName, so if you wanted to bind the selected tree item to the ItemsSource of a ListBox:
```
ItemsSource="{Binding SelectedItem, ElementName=treeView1}"
``` |
54,475 | <p>I've run into a problem where I make changes to a few JavaScript files that are referenced in an HTML file, but the browser doesn't see the changes. It holds onto the copy cached in the browser, even though the web server has a newer version.</p>
<p>Not until I force the browser to clear the cache do I see the changes.</p>
<p>Is this a web-server configuration? Do I need to set my JavaScript files to never cache? I've seen some interesting techniques in the <a href="http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5&t=FAQ_GWTApplicationFiles" rel="noreferrer">Google Web Toolkit</a> where they actually create a <strong>new</strong> JavaScript file name any time an update is made. I believe this is to prevent proxies and browsers from keeping old versions of the JavaScript files with the same names.</p>
<p>Is there a list of best practices somewhere?</p>
| [
{
"answer_id": 54483,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<p>I am also of the method of just renaming things. It never fails, and is fairly easy to do.</p>\n"
},
{
"answer_id": 54486,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 6,
"selected": true,
"text": "<p>We append a product build number to the end of all Javascript (and CSS etc.) like so:</p>\n\n<pre><code><script src=\"MyScript.js?4.0.8243\">\n</code></pre>\n\n<p>Browsers ignore everything after the question mark but upgrades cause a new URL which means cache-reload.</p>\n\n<p>This has the additional benefit that you can set HTTP headers that mean \"never cache!\"</p>\n"
},
{
"answer_id": 54490,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>is your webserver sending the right headers to tell the browser it has a new version? I've also added the date to the querystring before. ie myscripts.js?date=4/14/2008 12:45:03 (only the date would be encoded)</p>\n"
},
{
"answer_id": 54506,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": false,
"text": "<p>@Jason and Darren</p>\n\n<p><strike>IE6</strike> treats anything with a query string as uncacheable. You should find another way to get the version number into the url, such as a fake directory:</p>\n\n<pre><code><script src=\"/js/version/MyScript.js\"/>\n</code></pre>\n\n<p>and just remove that first directory level after js on the server side before fulfilling the request.</p>\n\n<p>EDIT: Sorry all; it is Squid, not IE6, that won't cache with a query string. More info <a href=\"http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 54526,
"author": "argv0",
"author_id": 5595,
"author_profile": "https://Stackoverflow.com/users/5595",
"pm_score": 0,
"selected": false,
"text": "<p>With every release, we simply prepend a monotonically increasing integer to the root path of all our static assets, which forces the client to reload (we've seen the query string method break in IE6 before). For example:</p>\n\n<ul>\n<li>Release 1: http://www.foo.com/1/js/foo.js</li>\n<li>Release 2: http://www.foo.com/2/js/foo.js</li>\n</ul>\n\n<p>It requires rejiggering links with each release, but we've built functionality to automatically change the links into our deployment tools.</p>\n\n<p>Once you do this, you can use Expires/Cache-Control headers that let the client cache JS resources \"forever\", since the path changes with each release, which i think is what @JasonCohen was getting at. </p>\n"
},
{
"answer_id": 54538,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n<p>It holds onto the copy cached in the browser, even though the web server has a newer version.</p>\n</blockquote>\n<p>This is probably because the HTTP Expires / Cache-Control headers are set.</p>\n<p><a href=\"http://developer.yahoo.com/performance/rules.html#expires\" rel=\"noreferrer\">http://developer.yahoo.com/performance/rules.html#expires</a></p>\n<p>I wrote about this here:</p>\n<p><a href=\"http://www.codinghorror.com/blog/archives/000932.html\" rel=\"noreferrer\">http://www.codinghorror.com/blog/archives/000932.html</a></p>\n<blockquote>\n<p>This isn't bad advice, per se, but it can cause huge problems if you get it wrong. In Microsoft's IIS, for example, the Expires header is always turned off by default, probably for that very reason. By setting an Expires header on HTTP resources, you're telling the client to <em>never check for new versions of that resource</em> -- at least not until the expiration date on the Expires header. <strong>When I say never, I mean it -- the browser won't even <em>ask</em> for a new version; it'll just assume its cached version is good to go until the client clears the cache, or the cache reaches the expiration date.</strong> Yahoo notes that they change the filename of these resources when they need them refreshed.</p>\n<p>All you're really saving here is the cost of the client pinging the server for a new version and getting a 304 not modified header back in the common case that the resource hasn't changed. That's not much overhead.. unless you're Yahoo. Sure, if you have a set of images or scripts that almost never change, definitely exploit client caching and turn on the Cache-Control header. Caching is critical to browser performance; every web developer should have a deep understanding of how HTTP caching works. But only use it in a surgical, limited way for those specific folders or files that can benefit. For anything else, the risk outweighs the benefit. It's certainly not something you want turned on as a blanket default for your entire website.. unless you like changing filenames every time the content changes.</p>\n</blockquote>\n"
},
{
"answer_id": 54540,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 0,
"selected": false,
"text": "<p>Some very useful techniques in <a href=\"http://www.codeproject.com/KB/install/DeploySite.aspx\" rel=\"nofollow noreferrer\">here</a> even if you are not planning to use powershell to automate deployment.</p>\n"
},
{
"answer_id": 311153,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>For what it is worth, I saw <a href=\"http://PhiLho.deviantART.com/\" rel=\"nofollow noreferrer\" title=\"deviantART: where ART meets application!\">deviantART</a> site, quite a big one, serving their JS files as 54504.js. I just checked and see they now serve them as v6core.css?-5855446573 v6core_jc.js?4150339741 etc.</p>\n\n<p>If the problem of query string comes from the server, I suppose you can control that more or less.</p>\n"
},
{
"answer_id": 1208994,
"author": "Chris Roberts",
"author_id": 475,
"author_profile": "https://Stackoverflow.com/users/475",
"pm_score": 3,
"selected": false,
"text": "<p>I've written a blog post about how we overcame this problem here:</p>\n\n<p><a href=\"http://solutionmania.com/2009/7/30/avoiding-javascript-and-css-stylesheet-caching-problems-in-asp.net\" rel=\"noreferrer\">Avoiding JavaScript and CSS Stylesheet Caching Problems in ASP.NET</a></p>\n\n<p>Basically, during development you can add a random number to a query string after the filename of your CSS file. When you do a release build, the code switches to using your assembly's revision number instead. This means that in your production environment, your clients can cache the stylesheet, but whenever you release a new version of the site they'll be forced to re-load the file.</p>\n"
},
{
"answer_id": 71866372,
"author": "Stephen Duffy",
"author_id": 12894605,
"author_profile": "https://Stackoverflow.com/users/12894605",
"pm_score": 0,
"selected": false,
"text": "<p>I've resorted to dunking the class I'm working on into the main script which does not seem to suffer from the same aggressive cacheing problems as those called from main script. (For some reason? - Using Firefox). Can't see anyway to send a cache header without making things more complex like javascripts served as an asp/php page with a cache header.</p>\n<p>I'm sure it makes browsers work faster and more efficiently but it's a real PITA for development. Anyone who wants and knows how to do an RFC for HTML6, it would be good if we could go:</p>\n<pre><code><script src='script.js' max-age=0 nocache />\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5079/"
] | I've run into a problem where I make changes to a few JavaScript files that are referenced in an HTML file, but the browser doesn't see the changes. It holds onto the copy cached in the browser, even though the web server has a newer version.
Not until I force the browser to clear the cache do I see the changes.
Is this a web-server configuration? Do I need to set my JavaScript files to never cache? I've seen some interesting techniques in the [Google Web Toolkit](http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5&t=FAQ_GWTApplicationFiles) where they actually create a **new** JavaScript file name any time an update is made. I believe this is to prevent proxies and browsers from keeping old versions of the JavaScript files with the same names.
Is there a list of best practices somewhere? | We append a product build number to the end of all Javascript (and CSS etc.) like so:
```
<script src="MyScript.js?4.0.8243">
```
Browsers ignore everything after the question mark but upgrades cause a new URL which means cache-reload.
This has the additional benefit that you can set HTTP headers that mean "never cache!" |
54,482 | <p>I need to enumerate all the user defined types created in a <code>SQL Server</code> database with <code>CREATE TYPE</code>, and/or find out whether they have already been defined.</p>
<p>With tables or stored procedures I'd do something like this:</p>
<pre><code>if exists (select * from dbo.sysobjects where name='foobar' and xtype='U')
drop table foobar
</code></pre>
<p>However I can't find the equivalent (or a suitable alternative) for user defined types! I definitely can't see them anywhere in <code>sysobjects</code>. </p>
<p>Can anyone enlighten me?</p>
| [
{
"answer_id": 54496,
"author": "jwolly2",
"author_id": 5202,
"author_profile": "https://Stackoverflow.com/users/5202",
"pm_score": 7,
"selected": true,
"text": "<p>Types and UDTs don't appear in sys.objects.\nYou should be able to get what you're looking for with the following:</p>\n\n<pre><code>select * from sys.types\nwhere is_user_defined = 1\n</code></pre>\n"
},
{
"answer_id": 31549846,
"author": "Ron Sanderson",
"author_id": 3034283,
"author_profile": "https://Stackoverflow.com/users/3034283",
"pm_score": 4,
"selected": false,
"text": "<p>Although the post is old, I found it useful to use a query similar to this. \nYou may not find some of the formatting useful, but I wanted the fully qualified type name and I wanted to see the columns listed in order. You can just remove all of the SUBSTRING stuff to just get the column name by itself.</p>\n\n<pre><code>SELECT USER_NAME(TYPE.schema_id) + '.' + TYPE.name AS \"Type Name\",\n COL.column_id,\n SUBSTRING(CAST(COL.column_id + 100 AS char(3)), 2, 2) + ': ' + COL.name AS \"Column\",\n ST.name AS \"Data Type\",\n CASE COL.Is_Nullable\n WHEN 1 THEN ''\n ELSE 'NOT NULL' \n END AS \"Nullable\",\n COL.max_length AS \"Length\",\n COL.[precision] AS \"Precision\",\n COL.scale AS \"Scale\",\n ST.collation AS \"Collation\"\nFROM sys.table_types TYPE\nJOIN sys.columns COL\n ON TYPE.type_table_object_id = COL.object_id\nJOIN sys.systypes AS ST \n ON ST.xtype = COL.system_type_id\nwhere TYPE.is_user_defined = 1\nORDER BY \"Type Name\",\n COL.column_id\n</code></pre>\n"
},
{
"answer_id": 48426414,
"author": "Ton Plooij",
"author_id": 4490706,
"author_profile": "https://Stackoverflow.com/users/4490706",
"pm_score": 3,
"selected": false,
"text": "<p>To expand on jwolly2's answer, here's how you get a list of definitions including the standard data type:</p>\n\n<pre><code>-- User Defined Type definitions TP 20180124\nselect t1.name, t2.name, t1.precision, t1.scale, t1.max_length as bytes, t1.is_nullable\nfrom sys.types t1\njoin sys.types t2 on t2.system_type_id = t1.system_type_id and t2.is_user_defined = 0\nwhere t1.is_user_defined = 1 and t2.name <> 'sysname'\norder by t1.name\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/886/"
] | I need to enumerate all the user defined types created in a `SQL Server` database with `CREATE TYPE`, and/or find out whether they have already been defined.
With tables or stored procedures I'd do something like this:
```
if exists (select * from dbo.sysobjects where name='foobar' and xtype='U')
drop table foobar
```
However I can't find the equivalent (or a suitable alternative) for user defined types! I definitely can't see them anywhere in `sysobjects`.
Can anyone enlighten me? | Types and UDTs don't appear in sys.objects.
You should be able to get what you're looking for with the following:
```
select * from sys.types
where is_user_defined = 1
``` |
54,487 | <p>How can I format Floats in Java so that the float component is displayed only if it's not zero? For example:</p>
<pre>
123.45 -> 123.45
99.0 -> 99
23.2 -> 23.2
45.0 -> 45
</pre>
<p>Edit: I forgot to mention - I'm still on Java 1.4 - sorry!</p>
| [
{
"answer_id": 54502,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 4,
"selected": true,
"text": "<p>If you use <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/text/DecimalFormat.html\" rel=\"nofollow noreferrer\">DecimalFormat</a> and specify # in the pattern it only displays the value if it is not zero.</p>\n\n<p>See my question <a href=\"https://stackoverflow.com/questions/50532/how-do-i-format-a-number-in-java\">How do I format a number in java?</a></p>\n\n<p>Sample Code</p>\n\n<pre><code> DecimalFormat format = new DecimalFormat(\"###.##\");\n\n double[] doubles = {123.45, 99.0, 23.2, 45.0};\n for(int i=0;i<doubles.length;i++){\n System.out.println(format.format(doubles[i]));\n }\n</code></pre>\n"
},
{
"answer_id": 54509,
"author": "Andy Whitfield",
"author_id": 4805,
"author_profile": "https://Stackoverflow.com/users/4805",
"pm_score": 2,
"selected": false,
"text": "<p>Check out the <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html\" rel=\"nofollow noreferrer\">DecimalFormat</a> class, e.g. new DecimalFormat(\"0.##\").format(99.0) will return \"99\".</p>\n"
},
{
"answer_id": 54511,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 0,
"selected": false,
"text": "<pre><code>new Formatter().format( \"%f\", myFloat )\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How can I format Floats in Java so that the float component is displayed only if it's not zero? For example:
```
123.45 -> 123.45
99.0 -> 99
23.2 -> 23.2
45.0 -> 45
```
Edit: I forgot to mention - I'm still on Java 1.4 - sorry! | If you use [DecimalFormat](http://java.sun.com/j2se/1.4.2/docs/api/java/text/DecimalFormat.html) and specify # in the pattern it only displays the value if it is not zero.
See my question [How do I format a number in java?](https://stackoverflow.com/questions/50532/how-do-i-format-a-number-in-java)
Sample Code
```
DecimalFormat format = new DecimalFormat("###.##");
double[] doubles = {123.45, 99.0, 23.2, 45.0};
for(int i=0;i<doubles.length;i++){
System.out.println(format.format(doubles[i]));
}
``` |
54,503 | <p>I'm working on a .net post-commit hook to feed data into OnTime via their Soap SDK. My hook works on Windows fine, but on our production RHEL4 subversion server, it won't work when called from a shell script.</p>
<pre>
#!/bin/sh
/usr/bin/mono $1/hooks/post-commit.exe "$@"
</pre>
<p>When I execute it with parameters from the command line, it works properly. When executed via the shell script, I get the following error: (looks like there is some problem with the process execution of SVN that I use to get the log data for the revision):</p>
<pre>
Unhandled Exception: System.InvalidOperationException: The process must exit before getting the requested information.
at System.Diagnostics.Process.get_ExitCode () [0x0003f] in /tmp/monobuild/build/BUILD/mono-1.9.1/mcs/class/System/System.Diagnostics/Process.cs:149
at (wrapper remoting-invoke-with-check) System.Diagnostics.Process:get_ExitCode ()
at SVNLib.SVN.Execute (System.String sCMD, System.String sParams, System.String sComment, System.String sUserPwd, SVNLib.SVNCallback callback) [0x00000]
at SVNLib.SVN.Log (System.String sUrl, Int32 nRevLow, Int32 nRevHigh, SVNLib.SVNCallback callback) [0x00000]
at SVNLib.SVN.LogAsString (System.String sUrl, Int32 nRevLow, Int32 nRevHigh) [0x00000]
at SVNCommit2OnTime.Program.Main (System.String[] args) [0x00000]
</pre>
<p>I've tried using <code>mkbundle</code> and <code>mkbundle2</code> to make a stand alone that could be named <code>post-commit</code>, but I get a different error message:</p>
<pre>
Unhandled Exception: System.ArgumentNullException: Argument cannot be null.
Parameter name: Value cannot be null.
at System.Guid.CheckNull (System.Object o) [0x00000]
at System.Guid..ctor (System.String g) [0x00000]
at SVNCommit2OnTime.Program.Main (System.String[] args) [0x00000]
</pre>
<p>Any ideas why it might be failing from a shell script or what might be wrong with the bundled version?</p>
<p><b>Edit:</b> <a href="https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54537">@Herms</a>, I've already tried it with an echo, and it looks right. As for the <code>$1/hooks/post-commit.exe</code>, I've tried the script with and without a full path to the .net assembly with the same results.</p>
<p><b>Edit:</b> <a href="https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54545">@Leon</a>, I've tried both <code>$1 $2</code> and <code>"$@"</code> with the same results. It is a subversion post commit hook, and it takes two parameters, so those need to be passed along to the .net assembly. The <code>"$@"</code> was what was recommended at the mono site for calling a .net assembly from a shell script. The shell script <i>is</i> executing the .net assembly and with the correct parameters, but it is throwing an exception that does not get thrown when run directly from the command line.</p>
<p><b>Edit:</b> <a href="https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54568">@Vinko</a>, I don't see any differences in the environment other than things like <code>BASH_LINENO</code> and <code>BASH_SOURCE</code></p>
<p><b>Edit:</b> <a href="https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54818">@Luke</a>, I tired it, but that makes no difference either. I first noticed the problem when testing from TortoiseSVN on my machine (when it runs as a sub-process of the subversion daemon), but also found that I get the same results when executing the script from the hooks directory (i.e. <code>./post-commit REPOS REV</code>, where <code>post-commit</code> is the above sh script. Doing <code>mono post-commit.exe REPOS REV</code> works fine. The main problem is that to execute, I need to have something of the name <code>post-commit</code> so that it will be called. But it does not work from a shell script, and as noted above, the <code>mkbundle</code> is not working with a different problem.</p>
| [
{
"answer_id": 54537,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 0,
"selected": false,
"text": "<p>Just a random thought that might help with debugging. Try changing your shell script to:</p>\n\n<pre><code>#!/bin/sh\necho /usr/bin/mono $1/hooks/post-commit.exe \"$@\"\n</code></pre>\n\n<p>Check and see if the line it prints matches the command you're expecting it to run. It's possible your command line argument handling in the shell script isn't doing what you want it to do.</p>\n\n<p>I don't know what your input to the script is expected to be, but the $1 before the path looks a bit out of place to me.</p>\n"
},
{
"answer_id": 54545,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 0,
"selected": false,
"text": "<p>Are you sure you want to do</p>\n\n<pre><code>/usr/bin/mono $1/hooks/post-commit.exe \"$@\"</code></pre>\n\n<p>$@ expands to ALL arguments. \"$@\" expands to all arguments join by spaces. I suspect you shell script is incorrect. You didn't state exactly what you wanted the script to do, so that does limit our possibilities to make suggestions.</p>\n"
},
{
"answer_id": 54568,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "<p>Compare the environment variables in your shell and from within the script.</p>\n"
},
{
"answer_id": 54818,
"author": "Luke",
"author_id": 327,
"author_profile": "https://Stackoverflow.com/users/327",
"pm_score": 0,
"selected": false,
"text": "<p>Try putting \"cd $1/hooks/\" before the line that runs mono. You may have some assemblies in that folder that are found when you run mono from that folder in the shell but are not being found when you run your script.</p>\n"
},
{
"answer_id": 55119,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 0,
"selected": false,
"text": "<p>After having verified that my code <i>did</i> work from the command line, I found that it was no longer working! I went looking into my .net code to see if anything made sense.</p>\n\n<p>Here is what I had:</p>\n\n<pre>\n static public int Execute(string sCMD, string sParams, string sComment,\n string sUserPwd, SVNCallback callback)\n {\n System.Diagnostics.Process proc = new System.Diagnostics.Process();\n proc.EnableRaisingEvents = false;\n proc.StartInfo.RedirectStandardOutput = true;\n proc.StartInfo.CreateNoWindow = true;\n proc.StartInfo.UseShellExecute = false;\n proc.StartInfo.Verb = \"open\";\n proc.StartInfo.FileName = \"svn\";\n proc.StartInfo.Arguments = Cmd(sCMD, sParams, sComment, UserPass());\n proc.Start();\n int nLine = 0;\n string sLine = \"\";\n while ((sLine = proc.StandardOutput.ReadLine()) != null)\n {\n ++nLine;\n if (callback != null)\n {\n callback.Invoke(nLine, sLine);\n }\n }\n int errorCode = proc.ExitCode;\n proc.Close();\n return errorCode;\n }\n</pre>\n\n<p>I changed this:</p>\n\n<pre>\n while (!proc.HasExited)\n {\n sLine = proc.StandardOutput.ReadLine();\n if (sLine != null)\n {\n ++nLine;\n if (callback != null)\n {\n callback.Invoke(nLine, sLine);\n }\n }\n }\n int errorCode = proc.ExitCode;\n</pre>\n\n<p>It looks like the Process is hanging around a bit longer than I'm getting output, and thus the <code>proc.ExitCode</code> is throwing an error.</p>\n"
},
{
"answer_id": 65070,
"author": "apenwarr",
"author_id": 42219,
"author_profile": "https://Stackoverflow.com/users/42219",
"pm_score": 3,
"selected": true,
"text": "<p>It is normal for some processes to hang around for a while after they close their stdout (ie. you get an end-of-file reading from them). You need to call <code>proc.WaitForExit()</code> after reading all the data but before checking ExitCode.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1441/"
] | I'm working on a .net post-commit hook to feed data into OnTime via their Soap SDK. My hook works on Windows fine, but on our production RHEL4 subversion server, it won't work when called from a shell script.
```
#!/bin/sh
/usr/bin/mono $1/hooks/post-commit.exe "$@"
```
When I execute it with parameters from the command line, it works properly. When executed via the shell script, I get the following error: (looks like there is some problem with the process execution of SVN that I use to get the log data for the revision):
```
Unhandled Exception: System.InvalidOperationException: The process must exit before getting the requested information.
at System.Diagnostics.Process.get_ExitCode () [0x0003f] in /tmp/monobuild/build/BUILD/mono-1.9.1/mcs/class/System/System.Diagnostics/Process.cs:149
at (wrapper remoting-invoke-with-check) System.Diagnostics.Process:get_ExitCode ()
at SVNLib.SVN.Execute (System.String sCMD, System.String sParams, System.String sComment, System.String sUserPwd, SVNLib.SVNCallback callback) [0x00000]
at SVNLib.SVN.Log (System.String sUrl, Int32 nRevLow, Int32 nRevHigh, SVNLib.SVNCallback callback) [0x00000]
at SVNLib.SVN.LogAsString (System.String sUrl, Int32 nRevLow, Int32 nRevHigh) [0x00000]
at SVNCommit2OnTime.Program.Main (System.String[] args) [0x00000]
```
I've tried using `mkbundle` and `mkbundle2` to make a stand alone that could be named `post-commit`, but I get a different error message:
```
Unhandled Exception: System.ArgumentNullException: Argument cannot be null.
Parameter name: Value cannot be null.
at System.Guid.CheckNull (System.Object o) [0x00000]
at System.Guid..ctor (System.String g) [0x00000]
at SVNCommit2OnTime.Program.Main (System.String[] args) [0x00000]
```
Any ideas why it might be failing from a shell script or what might be wrong with the bundled version?
**Edit:** [@Herms](https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54537), I've already tried it with an echo, and it looks right. As for the `$1/hooks/post-commit.exe`, I've tried the script with and without a full path to the .net assembly with the same results.
**Edit:** [@Leon](https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54545), I've tried both `$1 $2` and `"$@"` with the same results. It is a subversion post commit hook, and it takes two parameters, so those need to be passed along to the .net assembly. The `"$@"` was what was recommended at the mono site for calling a .net assembly from a shell script. The shell script *is* executing the .net assembly and with the correct parameters, but it is throwing an exception that does not get thrown when run directly from the command line.
**Edit:** [@Vinko](https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54568), I don't see any differences in the environment other than things like `BASH_LINENO` and `BASH_SOURCE`
**Edit:** [@Luke](https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54818), I tired it, but that makes no difference either. I first noticed the problem when testing from TortoiseSVN on my machine (when it runs as a sub-process of the subversion daemon), but also found that I get the same results when executing the script from the hooks directory (i.e. `./post-commit REPOS REV`, where `post-commit` is the above sh script. Doing `mono post-commit.exe REPOS REV` works fine. The main problem is that to execute, I need to have something of the name `post-commit` so that it will be called. But it does not work from a shell script, and as noted above, the `mkbundle` is not working with a different problem. | It is normal for some processes to hang around for a while after they close their stdout (ie. you get an end-of-file reading from them). You need to call `proc.WaitForExit()` after reading all the data but before checking ExitCode. |
54,536 | <p>How do I create a windows application that does the following:</p>
<ul>
<li>it's a regular GUI app when invoked with no command line arguments</li>
<li>specifying the optional "--help" command line argument causes the app to write usage text to stdout then terminate</li>
<li>it must be a single executable. No cheating by making a console app exec a 2nd executable.</li>
<li>assume the main application code is written in C/C++</li>
<li>bonus points if no GUI window is created when "--help" is specified. (i.e., no flicker from a short-lived window)</li>
</ul>
<p>In my experience the standard visual studio template for console app has no GUI capability, and the normal win32 template does not send its stdout to the parent cmd shell.</p>
| [
{
"answer_id": 113032,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 5,
"selected": false,
"text": "<p>Microsoft designed console and GUI apps to be mutually exclusive.\nThis bit of short-sightedness means that there is no perfect solution.\nThe most popular approach is to have two executables (eg. cscript / wscript,\njava / javaw, devenv.com / devenv.exe etc) however you've indicated that you consider this \"cheating\".</p>\n\n<p>You've got two options - to make a \"console executable\" or a \"gui executable\",\nand then use code to try to provide the other behaviour.</p>\n\n<ul>\n<li>GUI executable:</li>\n</ul>\n\n<p><code>cmd.exe</code> will assume that your program does no console I/O so won't wait for it to terminate\nbefore continuing, which in interactive mode (ie not a batch) means displaying the next (\"<code>C:\\></code>\") prompt\nand reading from the keyboard. So even if you use AttachConsole your output will be mixed\nwith <code>cmd</code>'s output, and the situation gets worse if you try to do input. This is basically a non-starter.</p>\n\n<ul>\n<li>Console executable:</li>\n</ul>\n\n<p>Contrary to belief, there is nothing to stop a console executable from displaying a GUI, but there are two problems.</p>\n\n<p>The first is that if you run it from the command line with no arguments (so you want the GUI),\n<code>cmd</code> will still wait for it to terminate before continuing, so that particular\nconsole will be unusable for the duration. This can be overcome by launching\na second process of the same executable (do you consider this cheating?), \npassing the DETACHED_PROCESS flag to CreateProcess() and immediately exiting.\nThe new process can then detect that it has no console and display the GUI.</p>\n\n<p>Here's C code to illustrate this approach:</p>\n\n<pre><code>#include <stdio.h>\n#include <windows.h>\n\nint main(int argc, char *argv[])\n{\n if (GetStdHandle(STD_OUTPUT_HANDLE) == 0) // no console, we must be the child process\n {\n MessageBox(0, \"Hello GUI world!\", \"\", 0);\n }\n else if (argc > 1) // we have command line args\n {\n printf(\"Hello console world!\\n\");\n }\n else // no command line args but a console - launch child process\n {\n DWORD dwCreationFlags = CREATE_DEFAULT_ERROR_MODE | DETACHED_PROCESS;\n STARTUPINFO startinfo;\n PROCESS_INFORMATION procinfo;\n ZeroMemory(&startinfo, sizeof(startinfo));\n startinfo.cb = sizeof(startinfo);\n if (!CreateProcess(NULL, argv[0], NULL, NULL, FALSE, dwCreationFlags, NULL, NULL, &startinfo, &procinfo))\n MessageBox(0, \"CreateProcess() failed :(\", \"\", 0);\n }\n exit(0);\n}\n</code></pre>\n\n<p>I compiled it with cygwin's gcc - YMMV with MSVC.</p>\n\n<p>The second problem is that when run from Explorer, your program will for a split second\ndisplay a console window. There's no programmatic way around this because the console is\ncreated by Windows when the app is launched, before it starts executing. The only thing you can\ndo is, in your installer, make the shortcut to your program with a \"show command\" of\nSW_HIDE (ie. 0). This will only affect the console unless you deliberately honour the wShowWindow field of STARTUPINFO\nin your program, so don't do that.</p>\n\n<p>I've tested this by hacking cygwin's \"mkshortcut.exe\". How you accomplish\nit in your install program of choice is up to you.</p>\n\n<p>The user can still of course run your program by finding the executable in Explorer and\ndouble-clicking it, bypassing the console-hiding shortcut and seeing the brief black flash of a console window. There's nothing you can do about it.</p>\n"
},
{
"answer_id": 1098259,
"author": "gabeiscoding",
"author_id": 68535,
"author_profile": "https://Stackoverflow.com/users/68535",
"pm_score": 2,
"selected": false,
"text": "<p>I know my answer is coming in late, but I think the preferred technique for the situation here is the \".com\" and \".exe\" method. </p>\n\n<p>This may be considered \"cheating\" by your definition of two executables, but it requires very little change on the programmers part and can be done one and forgot about. Also this solution does not have the disadvantages of Hugh's solution where you have a console windows displayed for a split second.</p>\n\n<p>In windows from the command line, if you run a program and don't specify an extension, the order of precedence in locating the executable will prefer a .com over a .exe.</p>\n\n<p>Then you can use tricks to have that \".com\" be a proxy for the stdin/stdout/stderr and launch the same-named .exe file. This give the behavior of allowing the program to preform in a command line mode when called form a console (potentially only when certain command line args are detected) while still being able to launch as a GUI application free of a console.</p>\n\n<p>There are various articles describing this like \"How to make an application as both GUI and Console application?\" (see references in link below).</p>\n\n<p>I hosted a project called <a href=\"http://code.google.com/p/dualsubsystem/\" rel=\"nofollow noreferrer\" title=\"dualsubsystem\">dualsubsystem on google code</a> that updates an old codeguru solution of this technique and provides the source code and working example binaries.</p>\n\n<p>I hope that is helpful!</p>\n"
},
{
"answer_id": 26087606,
"author": "Dmitry Markin",
"author_id": 1675481,
"author_profile": "https://Stackoverflow.com/users/1675481",
"pm_score": 4,
"selected": false,
"text": "<p>You can use <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms681944(v=vs.85).aspx\" rel=\"noreferrer\"><code>AllocConsole()</code></a> WinApi function to allocate a console for GUI application. You can also try attaching to a console of a parent process with <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms681952(v=vs.85).aspx\" rel=\"noreferrer\"><code>AttachConsole()</code></a>, this makes sense if it already has one. The complete code with redirecting <code>stdout</code> and <code>stderr</code> to this console will be like this:</p>\n\n<pre><code>if(AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole()){\n freopen(\"CONOUT$\", \"w\", stdout);\n freopen(\"CONOUT$\", \"w\", stderr);\n}\n</code></pre>\n\n<p>I found this approach in the <a href=\"https://www.pidgin.im/\" rel=\"noreferrer\">Pidgin</a> sources (see <code>WinMain()</code> in pidgin/win32/winpidgin.c)</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5429/"
] | How do I create a windows application that does the following:
* it's a regular GUI app when invoked with no command line arguments
* specifying the optional "--help" command line argument causes the app to write usage text to stdout then terminate
* it must be a single executable. No cheating by making a console app exec a 2nd executable.
* assume the main application code is written in C/C++
* bonus points if no GUI window is created when "--help" is specified. (i.e., no flicker from a short-lived window)
In my experience the standard visual studio template for console app has no GUI capability, and the normal win32 template does not send its stdout to the parent cmd shell. | Microsoft designed console and GUI apps to be mutually exclusive.
This bit of short-sightedness means that there is no perfect solution.
The most popular approach is to have two executables (eg. cscript / wscript,
java / javaw, devenv.com / devenv.exe etc) however you've indicated that you consider this "cheating".
You've got two options - to make a "console executable" or a "gui executable",
and then use code to try to provide the other behaviour.
* GUI executable:
`cmd.exe` will assume that your program does no console I/O so won't wait for it to terminate
before continuing, which in interactive mode (ie not a batch) means displaying the next ("`C:\>`") prompt
and reading from the keyboard. So even if you use AttachConsole your output will be mixed
with `cmd`'s output, and the situation gets worse if you try to do input. This is basically a non-starter.
* Console executable:
Contrary to belief, there is nothing to stop a console executable from displaying a GUI, but there are two problems.
The first is that if you run it from the command line with no arguments (so you want the GUI),
`cmd` will still wait for it to terminate before continuing, so that particular
console will be unusable for the duration. This can be overcome by launching
a second process of the same executable (do you consider this cheating?),
passing the DETACHED\_PROCESS flag to CreateProcess() and immediately exiting.
The new process can then detect that it has no console and display the GUI.
Here's C code to illustrate this approach:
```
#include <stdio.h>
#include <windows.h>
int main(int argc, char *argv[])
{
if (GetStdHandle(STD_OUTPUT_HANDLE) == 0) // no console, we must be the child process
{
MessageBox(0, "Hello GUI world!", "", 0);
}
else if (argc > 1) // we have command line args
{
printf("Hello console world!\n");
}
else // no command line args but a console - launch child process
{
DWORD dwCreationFlags = CREATE_DEFAULT_ERROR_MODE | DETACHED_PROCESS;
STARTUPINFO startinfo;
PROCESS_INFORMATION procinfo;
ZeroMemory(&startinfo, sizeof(startinfo));
startinfo.cb = sizeof(startinfo);
if (!CreateProcess(NULL, argv[0], NULL, NULL, FALSE, dwCreationFlags, NULL, NULL, &startinfo, &procinfo))
MessageBox(0, "CreateProcess() failed :(", "", 0);
}
exit(0);
}
```
I compiled it with cygwin's gcc - YMMV with MSVC.
The second problem is that when run from Explorer, your program will for a split second
display a console window. There's no programmatic way around this because the console is
created by Windows when the app is launched, before it starts executing. The only thing you can
do is, in your installer, make the shortcut to your program with a "show command" of
SW\_HIDE (ie. 0). This will only affect the console unless you deliberately honour the wShowWindow field of STARTUPINFO
in your program, so don't do that.
I've tested this by hacking cygwin's "mkshortcut.exe". How you accomplish
it in your install program of choice is up to you.
The user can still of course run your program by finding the executable in Explorer and
double-clicking it, bypassing the console-hiding shortcut and seeing the brief black flash of a console window. There's nothing you can do about it. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.